diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 926b2a9a..0195b150 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -118,7 +118,7 @@ jobs: path: | target/wasm-fixtures/wasm32-wasip2/debug/*.wasm target/wasm-fixtures/wasm32-wasip2/debug/.fixtures-stamp - key: v0-wasm-fixtures-${{ runner.os }}-${{ hashFiles('rust-toolchain.toml', 'Cargo.toml', '.cargo/config.toml', 'wit/**', 'crates/plugin-sdk/**', 'crates/plugin-host/tests/fixtures/**') }} + key: v0-wasm-fixtures-${{ runner.os }}-${{ hashFiles('rust-toolchain.toml', 'Cargo.toml', '.cargo/config.toml', 'wit/**', 'crates/plugin-sdk/**', 'crates/plugin-host/tests/fixtures/**', 'crates/plugin-host/wit-legacy/**') }} - id: go run: echo "version=$(go env GOVERSION)" >> "$GITHUB_OUTPUT" - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 @@ -346,7 +346,7 @@ jobs: path: | target/wasm-fixtures/wasm32-wasip2/debug/*.wasm target/wasm-fixtures/wasm32-wasip2/debug/.fixtures-stamp - key: v0-wasm-fixtures-${{ runner.os }}-${{ hashFiles('rust-toolchain.toml', 'Cargo.toml', '.cargo/config.toml', 'wit/**', 'crates/plugin-sdk/**', 'crates/plugin-host/tests/fixtures/**') }} + key: v0-wasm-fixtures-${{ runner.os }}-${{ hashFiles('rust-toolchain.toml', 'Cargo.toml', '.cargo/config.toml', 'wit/**', 'crates/plugin-sdk/**', 'crates/plugin-host/tests/fixtures/**', 'crates/plugin-host/wit-legacy/**') }} - uses: ./.github/actions/gitleaks - uses: ./.github/actions/lychee - id: go diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b37808c6..496c5038 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -57,7 +57,8 @@ The planted-defect suite runs with the other tests: `cargo test --locked -p code ## Adding a Language or Metric plugin -Read [docs/plugins.md](./docs/plugins.md) to build an external WebAssembly Plugin against `codeint:plugin@0.5.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. +Inspect `plugins/languages/` for built-in implementations of the Code model contract. ## Code of Conduct diff --git a/README.md b/README.md index 2a496376..101f3921 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ Beyond static snapshots, codeint helps humans and coding agents understand how f codeint is written in safe Rust (`#![forbid(unsafe_code)]` on every host, core, CLI, and built-in Plugin crate, [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.5.0` WIT contract with mandatory SHA-256 verification, zero host capabilities, and configurable memory and time caps, using `codeint-plugin-sdk` for safe Rust builds on `wasm32-wasip2` (`no_std`, zero extra tools) or `wasm32-unknown-unknown` (`std` plus `wasm-tools component new`) with zero WASI imports ([ADR 0027](./docs/adr/0027-plugin-sdk-guest-runtime-unsafe.md)). +External WebAssembly Plugins implement the versioned `codeint:plugin@0.6.0` WIT contract with mandatory SHA-256 verification, zero host capabilities, and configurable memory and time caps, using `codeint-plugin-sdk` for safe Rust builds on `wasm32-wasip2` (`no_std`, zero extra tools) or `wasm32-unknown-unknown` (`std` plus `wasm-tools component new`) with zero WASI imports ([ADR 0027](./docs/adr/0027-plugin-sdk-guest-runtime-unsafe.md)). 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/tests.rs b/crates/cli/src/check/tests.rs index 08e2b75b..c1582325 100644 --- a/crates/cli/src/check/tests.rs +++ b/crates/cli/src/check/tests.rs @@ -1405,7 +1405,9 @@ fn no_imports_language_plugin_never_has_import_manifest_or_entry_point_functions guest_lower!(|_path, text| { let mut model = lines_of(&text)?; - model.runtime_imports.push("./never-resolved".to_owned()); + model + .runtime_imports + .push("./never-resolved".to_owned().into()); model.program_start = true; Ok(model) }); diff --git a/crates/cli/src/doctor.rs b/crates/cli/src/doctor.rs index c3476265..9f9b0a6c 100644 --- a/crates/cli/src/doctor.rs +++ b/crates/cli/src/doctor.rs @@ -608,13 +608,13 @@ fn plugin_component_error( 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" + "External Wasm Plugin {name:?} at {label} is not loadable: component does not satisfy the Plugin 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." - )), + .with_remedy( + "Ensure the Plugin exports a supported Language or Metric interface and imports no host capabilities.", + ), _ => DoctorCheck::error( id, format!("External Wasm Plugin {name:?} at {label} is not loadable: {error}"), diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 8f92451b..6036bfe0 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -7,7 +7,7 @@ use codeint_config::{ use codeint_git::GitError; use codeint_metrics::ImpactError; use codeint_model::{LanguagePluginError, MetricPluginError, WorkspaceError}; -use codeint_plugin_host::PluginHostError; +use codeint_plugin_host::{PLUGIN_INTERFACE_VERSION, PluginHostError}; use codeint_report::{SavedReportError, TraceError}; use crate::CliError; @@ -851,14 +851,14 @@ fn plugin_load_remedy(error: &PluginHostError, file: ConfigFileKind) -> Option Cow::Borrowed( - "Build the plugin as a WebAssembly component targeting codeint:plugin@0.5.0.", - ), + PluginHostError::Compile { .. } => Cow::Owned(format!( + "Build the plugin as a WebAssembly component targeting codeint:plugin@{PLUGIN_INTERFACE_VERSION}." + )), PluginHostError::Instantiate { .. } => Cow::Borrowed( - "Ensure the plugin exports codeint:plugin/language@0.5.0 or codeint:plugin/metric@0.5.0 and imports no host capabilities.", + "Ensure the plugin exports a supported Language or Metric interface and imports no host capabilities.", ), PluginHostError::IncompatibleContractVersion { .. } => Cow::Owned(format!( - "Rebuild the plugin against codeint:plugin@0.5.0 and update its sha256 in {file}." + "Rebuild the plugin against codeint:plugin@{PLUGIN_INTERFACE_VERSION} and update its sha256 in {file}." )), _ => return None, }) diff --git a/crates/cli/tests/integration/diff.rs b/crates/cli/tests/integration/diff.rs index 5b2a1733..84123d51 100644 --- a/crates/cli/tests/integration/diff.rs +++ b/crates/cli/tests/integration/diff.rs @@ -1702,7 +1702,7 @@ fn a_result_cached_under_plugin_interface_0_2_0_or_cache_version_7_is_not_reused assert_eq!(entries, 2); } - assert_eq!(current_settings["plugin_interface_version"], json!("0.5.0")); + assert_eq!(current_settings["plugin_interface_version"], json!("0.6.0")); assert_eq!(current_settings["cache_version"], json!(10)); } @@ -1759,7 +1759,7 @@ fn a_result_cached_under_plugin_interface_0_5_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.5.0")); + assert_eq!(settings["plugin_interface_version"], json!("0.6.0")); fixture.forget_committed_file("main:src/removed.ts"); let second = fixture.diff_json("main"); diff --git a/crates/cli/tests/integration/doctor.rs b/crates/cli/tests/integration/doctor.rs index 66b88199..c4ace949 100644 --- a/crates/cli/tests/integration/doctor.rs +++ b/crates/cli/tests/integration/doctor.rs @@ -528,7 +528,7 @@ fn doctor_reports_v0_2_0_and_v0_3_0_language_and_metric_plugins_as_not_loadable( "legacy_v0_2_0_language_plugin.wasm", "codeint:plugin/language@0.2.0", "0.2.0", - "codeint:plugin/language@0.5.0", + "codeint:plugin/language@0.6.0", ), ( "legacy-v02-metric", @@ -536,7 +536,7 @@ fn doctor_reports_v0_2_0_and_v0_3_0_language_and_metric_plugins_as_not_loadable( "legacy_v0_2_0_metric_plugin.wasm", "codeint:plugin/metric@0.2.0", "0.2.0", - "codeint:plugin/metric@0.5.0", + "codeint:plugin/metric@0.6.0", ), ( "legacy-v03-lang", @@ -544,7 +544,7 @@ fn doctor_reports_v0_2_0_and_v0_3_0_language_and_metric_plugins_as_not_loadable( "legacy_v0_3_0_language_plugin.wasm", "codeint:plugin/language@0.3.0", "0.3.0", - "codeint:plugin/language@0.5.0", + "codeint:plugin/language@0.6.0", ), ( "legacy-v03-metric", @@ -552,7 +552,7 @@ fn doctor_reports_v0_2_0_and_v0_3_0_language_and_metric_plugins_as_not_loadable( "legacy_v0_3_0_metric_plugin.wasm", "codeint:plugin/metric@0.3.0", "0.3.0", - "codeint:plugin/metric@0.5.0", + "codeint:plugin/metric@0.6.0", ), ( "legacy-v04-lang", @@ -560,7 +560,7 @@ fn doctor_reports_v0_2_0_and_v0_3_0_language_and_metric_plugins_as_not_loadable( "legacy_v0_4_0_language_plugin.wasm", "codeint:plugin/language@0.4.0", "0.4.0", - "codeint:plugin/language@0.5.0", + "codeint:plugin/language@0.6.0", ), ( "legacy-v04-metric", @@ -568,7 +568,7 @@ fn doctor_reports_v0_2_0_and_v0_3_0_language_and_metric_plugins_as_not_loadable( "legacy_v0_4_0_metric_plugin.wasm", "codeint:plugin/metric@0.4.0", "0.4.0", - "codeint:plugin/metric@0.5.0", + "codeint:plugin/metric@0.6.0", ), ]; @@ -596,13 +596,13 @@ fn doctor_reports_v0_2_0_and_v0_3_0_language_and_metric_plugins_as_not_loadable( && summary.contains(found_interface) && summary.contains(found_version) && summary.contains(expected_interface) - && summary.contains("0.5.0"), + && summary.contains("0.6.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.5.0"), - "expected remedy to instruct rebuilding against 0.5.0, got: {remedy:?}" + remedy.to_ascii_lowercase().contains("rebuild") && remedy.contains("0.6.0"), + "expected remedy to instruct rebuilding against 0.6.0, got: {remedy:?}" ); } diff --git a/crates/cli/tests/integration/plugins.rs b/crates/cli/tests/integration/plugins.rs index 68031849..dc9b2995 100644 --- a/crates/cli/tests/integration/plugins.rs +++ b/crates/cli/tests/integration/plugins.rs @@ -1204,13 +1204,13 @@ fn assert_legacy_plugin_stops_check( && lines[0].contains(found_interface) && lines[0].contains(found_version) && lines[0].contains(expected_interface) - && lines[0].contains("0.5.0"), + && lines[0].contains("0.6.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.5.0"), - "expected stderr line 2 to instruct rebuilding against 0.5.0, got: {}", + lines[1].to_ascii_lowercase().contains("rebuild") && lines[1].contains("0.6.0"), + "expected stderr line 2 to instruct rebuilding against 0.6.0, got: {}", lines[1] ); } @@ -1223,7 +1223,7 @@ fn v0_2_0_through_v0_4_0_language_plugins_stop_check_with_exit_2_and_rebuild_rem "legacy_v0_2_0_language_plugin.wasm", "codeint:plugin/language@0.2.0", "0.2.0", - "codeint:plugin/language@0.5.0", + "codeint:plugin/language@0.6.0", ); assert_legacy_plugin_stops_check( "legacy-v03-lang", @@ -1231,7 +1231,7 @@ fn v0_2_0_through_v0_4_0_language_plugins_stop_check_with_exit_2_and_rebuild_rem "legacy_v0_3_0_language_plugin.wasm", "codeint:plugin/language@0.3.0", "0.3.0", - "codeint:plugin/language@0.5.0", + "codeint:plugin/language@0.6.0", ); assert_legacy_plugin_stops_check( "legacy-v04-lang", @@ -1239,7 +1239,7 @@ fn v0_2_0_through_v0_4_0_language_plugins_stop_check_with_exit_2_and_rebuild_rem "legacy_v0_4_0_language_plugin.wasm", "codeint:plugin/language@0.4.0", "0.4.0", - "codeint:plugin/language@0.5.0", + "codeint:plugin/language@0.6.0", ); } @@ -1251,7 +1251,7 @@ fn v0_2_0_through_v0_4_0_metric_plugins_stop_check_with_exit_2_and_rebuild_remed "legacy_v0_2_0_metric_plugin.wasm", "codeint:plugin/metric@0.2.0", "0.2.0", - "codeint:plugin/metric@0.5.0", + "codeint:plugin/metric@0.6.0", ); assert_legacy_plugin_stops_check( "legacy-v03-metric", @@ -1259,7 +1259,7 @@ fn v0_2_0_through_v0_4_0_metric_plugins_stop_check_with_exit_2_and_rebuild_remed "legacy_v0_3_0_metric_plugin.wasm", "codeint:plugin/metric@0.3.0", "0.3.0", - "codeint:plugin/metric@0.5.0", + "codeint:plugin/metric@0.6.0", ); assert_legacy_plugin_stops_check( "legacy-v04-metric", @@ -1267,7 +1267,7 @@ fn v0_2_0_through_v0_4_0_metric_plugins_stop_check_with_exit_2_and_rebuild_remed "legacy_v0_4_0_metric_plugin.wasm", "codeint:plugin/metric@0.4.0", "0.4.0", - "codeint:plugin/metric@0.5.0", + "codeint:plugin/metric@0.6.0", ); } diff --git a/crates/cli/tests/integration/trace.rs b/crates/cli/tests/integration/trace.rs index 507df508..a2959e82 100644 --- a/crates/cli/tests/integration/trace.rs +++ b/crates/cli/tests/integration/trace.rs @@ -1,3 +1,5 @@ +mod package_conditions; + use std::fs; use std::path::Path; use std::process::Output; diff --git a/crates/cli/tests/integration/trace/package_conditions.rs b/crates/cli/tests/integration/trace/package_conditions.rs new file mode 100644 index 00000000..46709b0b --- /dev/null +++ b/crates/cli/tests/integration/trace/package_conditions.rs @@ -0,0 +1,46 @@ +use serde_json::json; + +use super::{init_git_repo, trace_json}; + +#[test] +fn trace_selects_package_exports_by_runtime_import_kind() { + let repo = init_git_repo(&[ + ( + "package.json", + r#"{"private":true,"workspaces":["packages/*"]}"#, + ), + ( + "packages/dual/package.json", + r#"{"name":"dual","exports":{ + ".":{"require":"./c.cjs","import":"./e.mjs"}, + "./reverse":{"import":"./e.mjs","require":"./c.cjs"} + }}"#, + ), + ("packages/dual/e.mjs", "export default 'esm';"), + ("packages/dual/c.cjs", "module.exports = 'cjs';"), + ("main.mjs", "import 'dual';"), + ("main.cjs", "require('dual/reverse');"), + ( + "mixed.mjs", + "import { createRequire } from 'node:module';\n\ + const require = createRequire(import.meta.url);\n\ + import('dual');\n\ + require('dual');", + ), + ]); + + for (source, target, connected) in [ + ("main.mjs", "packages/dual/e.mjs", true), + ("main.mjs", "packages/dual/c.cjs", false), + ("main.cjs", "packages/dual/c.cjs", true), + ("main.cjs", "packages/dual/e.mjs", false), + ("mixed.mjs", "packages/dual/e.mjs", true), + ("mixed.mjs", "packages/dual/c.cjs", true), + ] { + let trace = trace_json(repo.path(), &[source, target]); + assert_eq!(trace["connected"], connected, "{source} to {target}"); + if connected { + assert_eq!(trace["paths"], json!([[source, target]])); + } + } +} diff --git a/crates/model/HOW-TO.md b/crates/model/HOW-TO.md index 590324d5..eb7101e3 100644 --- a/crates/model/HOW-TO.md +++ b/crates/model/HOW-TO.md @@ -155,7 +155,7 @@ impl LanguagePlugin for Plain { } ``` -- The interface is defined once, in [wit/language.wit](../../wit/language.wit), as the versioned package `codeint:plugin@0.5.0`. +- The interface is defined once, in [wit/language.wit](../../wit/language.wit), as the versioned package `codeint:plugin@0.6.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 `LanguagePlugin` directly and borrows `&RepoPath`, `&str`, and `&[RepoPath]` to avoid per-file clones. @@ -213,8 +213,9 @@ impl LanguagePlugin for Plain { 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`; six of the eight built-in Language plugins always return an empty list (`sql` and `shell` declare Hazard line rules). -- `runtime_imports` lists the specifiers of imports that run when the file runs. +- `runtime_imports` lists the specifier and import kind of each runtime import. Leave out type-only imports. + Use `ImportKind::Unknown` for languages without import and require forms. The Language plugin can normalize specifiers and group imported names from the same module. - `program_start` is `false` unless the source text marks the file as a program start, such as a Go `package main` file. Seven of the eight built-in Language plugins always set `program_start` to `false` (`go` sets it for `package main` files). diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index 5daf89e1..348607be 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -15,6 +15,33 @@ mod tests; mod tooling; mod workspace; +impl FileModel { + pub fn runtime_import_specifiers(&self) -> impl Iterator { + self.runtime_imports + .iter() + .map(|edge| edge.specifier.as_str()) + } +} + +impl language::ImportRequest { + pub fn new(importer: impl Into, specifier: impl Into) -> Self { + Self { + importer: importer.into(), + specifier: specifier.into(), + kind: language::ImportKind::Unknown, + } + } +} + +impl From for language::ImportEdge { + fn from(specifier: String) -> Self { + Self { + specifier, + kind: language::ImportKind::Unknown, + } + } +} + mod bindings { wit_bindgen::generate!({ world: "language-plugin", diff --git a/crates/model/src/runtime_imports.rs b/crates/model/src/runtime_imports.rs index e85178c0..9e556a06 100644 --- a/crates/model/src/runtime_imports.rs +++ b/crates/model/src/runtime_imports.rs @@ -84,13 +84,13 @@ pub fn resolve_runtime_imports( if !plugin.has_imports() { return Ok(Vec::new()); } - let pending: Vec<(&RepoPath, &String)> = importers + let pending: Vec<(&RepoPath, &language::ImportEdge)> = importers .iter() .flat_map(|file| { file.model .runtime_imports .iter() - .map(|specifier| (&file.path, specifier)) + .map(|edge| (&file.path, edge)) }) .collect(); if pending.is_empty() { @@ -98,9 +98,10 @@ pub fn resolve_runtime_imports( } let requests = pending .iter() - .map(|(importer, specifier)| language::ImportRequest { + .map(|(importer, edge)| language::ImportRequest { importer: importer.as_str().to_owned(), - specifier: (*specifier).clone(), + specifier: edge.specifier.clone(), + kind: edge.kind, }) .collect(); let resolutions = @@ -115,7 +116,8 @@ pub fn resolve_runtime_imports( pending .into_iter() .zip(resolutions) - .map(|((importer, specifier), resolution)| { + .map(|((importer, edge), resolution)| { + let specifier = &edge.specifier; let resolution = validate_resolution(importer, specifier, resolution, &known_paths)?; Ok(RuntimeImport { importer: importer.clone(), diff --git a/crates/model/src/runtime_imports/tests.rs b/crates/model/src/runtime_imports/tests.rs index ff020fb5..ae834a29 100644 --- a/crates/model/src/runtime_imports/tests.rs +++ b/crates/model/src/runtime_imports/tests.rs @@ -123,7 +123,10 @@ fn importer(name: &str, specifiers: &[&str]) -> SourceFile { path: path(name), model: FileModel { source_lines: 1, - runtime_imports: specifiers.iter().map(|text| (*text).to_owned()).collect(), + runtime_imports: specifiers + .iter() + .map(|text| (*text).to_owned().into()) + .collect(), ..empty_file_model(SourceSet::Production) }, } diff --git a/crates/model/wit/language.wit b/crates/model/wit/language.wit index 81891560..d4be90cb 100644 --- a/crates/model/wit/language.wit +++ b/crates/model/wit/language.wit @@ -1,6 +1,6 @@ /// The Plugin interface of codeint. /// A change that breaks a Plugin built against this version needs a new version. -package codeint:plugin@0.5.0; +package codeint:plugin@0.6.0; /// The interface a Language plugin exports: the file extensions it reads, and the Code model of each such file. interface language { @@ -99,6 +99,19 @@ interface language { message: string, } + /// The runtime loading operation used by an import. + enum import-kind { + unknown, + %import, + require, + } + + /// One import that runs when the source file runs. + record import-edge { + specifier: string, + kind: import-kind, + } + /// The Code model of one source file. record file-model { /// The Source set of the file, chosen by the rules of the Language plugin. @@ -114,10 +127,10 @@ interface language { /// Each Hazard line with the rule it matched; a line that matches two rules appears once per rule. /// Empty when `has-hazard-rules` returns false. hazard-lines: list, - /// The module specifiers of the imports that run when the file runs, such as `./greet`. + /// The imports that run when the file runs, such as `./greet`. /// A Language plugin can normalize specifiers and group imported names from the same module. /// Type-only imports are left out. - runtime-imports: list, + runtime-imports: list, /// Whether the file starts a program as shown by its source text, such as a Go `package main` file. /// False unless the Language plugin sets it. program-start: bool, @@ -131,12 +144,14 @@ interface language { scope-artifact: option>, } - /// One runtime import to resolve: the file that imports, and the specifier it names. + /// One runtime import to resolve. record import-request { /// The importing file, relative to the repository root, with forward slashes. importer: string, /// The module specifier supplied by the Language plugin, which may be normalized. specifier: string, + /// The runtime loading operation used by the import. + kind: import-kind, } /// Where a runtime import leads. diff --git a/crates/model/wit/metric.wit b/crates/model/wit/metric.wit index 4aafe224..4f0aacea 100644 --- a/crates/model/wit/metric.wit +++ b/crates/model/wit/metric.wit @@ -1,4 +1,4 @@ -package codeint:plugin@0.5.0; +package codeint:plugin@0.6.0; /// The interface a Metric plugin exports: metadata for one Metric and a function that measures a Code model. interface metric { diff --git a/crates/plugin-host/Cargo.toml b/crates/plugin-host/Cargo.toml index f701c180..084699c4 100644 --- a/crates/plugin-host/Cargo.toml +++ b/crates/plugin-host/Cargo.toml @@ -9,7 +9,7 @@ homepage.workspace = true keywords = ["codeint", "wasm", "plugin", "static-analysis", "metrics"] categories = ["development-tools", "wasm"] publish = true -include = ["src/**", "wit/**", "Cargo.toml"] +include = ["src/**", "wit/**", "wit-legacy/**", "Cargo.toml"] [lib] diff --git a/crates/plugin-host/HOW-TO.md b/crates/plugin-host/HOW-TO.md index 6a613229..164babc8 100644 --- a/crates/plugin-host/HOW-TO.md +++ b/crates/plugin-host/HOW-TO.md @@ -33,7 +33,7 @@ let ts_plugin = built_in_language_plugin("typescript-javascript"); ## Resolve Framework profiles -- Built-in and external Language plugins resolve package-level Framework profiles, convention entry points, framework-generated Source set paths, and framework Reference ranges through `LanguagePlugin::known_framework_profiles` and `LanguagePlugin::resolve_framework_profiles` (`codeint:plugin@0.5.0`). +- Built-in and external Language plugins resolve package-level Framework profiles, convention entry points, framework-generated Source set paths, and framework Reference ranges through `LanguagePlugin::known_framework_profiles` and `LanguagePlugin::resolve_framework_profiles` (`codeint:plugin@0.6.0`). - Resolved active profile names are passed per package (`Vec`) into `LanguagePlugin::resolve_imports` so fallback import hints stay coupled to each package's active profiles. ## Load external plugins declared in configuration @@ -52,7 +52,8 @@ let external = load_language_plugins(repository.root(), &configuration.plugins, - `PluginSource::HttpsUrl` downloads through `curl` with `--proto =https --tlsv1.2 --proto-redir =https --max-filesize ` and a bounded streaming reader (50 MiB default via `PluginHostConfig::max_download_bytes`, overridden by `CODEINT_PLUGIN_MAX_DOWNLOAD_MB`), 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.5.0` before instantiation; an incompatible version (such as `codeint:plugin@0.4.0`, `codeint:plugin@0.3.0`, or `codeint:plugin@0.2.0`) fails with `PluginHostError::IncompatibleContractVersion`. +- Before instantiation, the host checks that each plugin exports the matching WIT interface at `0.6.0` or `0.5.0`. + An incompatible version fails with `PluginHostError::IncompatibleContractVersion`. - Every `WasmMetricPlugin` also validates its `version()` export at load time through `validate_metric_version`, rejecting `0` with `PluginHostError::InvalidMetricVersion`. - `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`, host lifted-size budget via `enforce_lifted_budget`, and wall-clock time limit via `wasmtime` epoch interruption). diff --git a/crates/plugin-host/src/compatibility.rs b/crates/plugin-host/src/compatibility.rs new file mode 100644 index 00000000..23c994f8 --- /dev/null +++ b/crates/plugin-host/src/compatibility.rs @@ -0,0 +1,106 @@ +use wasmtime::Store; +use wasmtime::component::InstancePre; + +use crate::limits::PluginStoreState; + +macro_rules! legacy_file_model { + ($guest:ident) => { + #[derive( + wasmtime::component::ComponentType, + wasmtime::component::Lift, + wasmtime::component::Lower, + )] + #[component(record)] + struct LegacyFileModel { + #[component(name = "source-set")] + source_set: $guest::SourceSet, + #[component(name = "source-lines")] + source_lines: u32, + functions: Vec<$guest::Function>, + tokens: Vec<$guest::Token>, + #[component(name = "flagged-lines")] + flagged_lines: Vec<$guest::FlaggedLine>, + #[component(name = "hazard-lines")] + hazard_lines: Vec<$guest::HazardLine>, + #[component(name = "runtime-imports")] + runtime_imports: Vec, + #[component(name = "program-start")] + program_start: bool, + #[component(name = "is-tooling-file")] + is_tooling_file: bool, + diagnostics: Vec<$guest::FileDiagnostic>, + #[component(name = "scope-artifact")] + scope_artifact: Option>, + } + }; +} + +macro_rules! versioned_component { + ($pre:ident, $bindings:ident, $plugin_pre:ident, $plugin:ident) => { + type $pre = Versioned< + bindings::$plugin_pre, + legacy_bindings::$plugin_pre, + >; + type $bindings = Versioned; + + fn bind_versioned_component( + pre: wasmtime::component::InstancePre, + interface: PluginInterface, + ) -> wasmtime::Result<$pre> { + interface.bind( + pre, + bindings::$plugin_pre::new, + legacy_bindings::$plugin_pre::new, + ) + } + + fn instantiate_versioned_component( + pre: &$pre, + store: &mut Store, + ) -> wasmtime::Result<$bindings> { + pre.instantiate( + store, + |pre, store| pre.instantiate(store), + |pre, store| pre.instantiate(store), + ) + } + }; +} + +pub(crate) enum PluginInterface { + Current, + Legacy, +} + +pub(crate) enum Versioned { + Current(Current), + Legacy(Legacy), +} + +impl PluginInterface { + pub(crate) fn bind( + self, + pre: InstancePre, + bind_current: impl FnOnce(InstancePre) -> wasmtime::Result, + bind_legacy: impl FnOnce(InstancePre) -> wasmtime::Result, + ) -> wasmtime::Result> { + match self { + Self::Current => bind_current(pre).map(Versioned::Current), + Self::Legacy => bind_legacy(pre).map(Versioned::Legacy), + } + } +} + +impl Versioned { + pub(crate) fn instantiate( + &self, + store: &mut Store, + current: impl FnOnce(&C, &mut Store) -> wasmtime::Result, + legacy: impl FnOnce(&L, &mut Store) -> wasmtime::Result, + ) -> wasmtime::Result> { + match self { + Self::Current(pre) => current(pre, store).map(Versioned::Current), + Self::Legacy(pre) => legacy(pre, store).map(Versioned::Legacy), + } + } +} diff --git a/crates/plugin-host/src/conformance.rs b/crates/plugin-host/src/conformance.rs index fbb213ce..c00d59c9 100644 --- a/crates/plugin-host/src/conformance.rs +++ b/crates/plugin-host/src/conformance.rs @@ -299,7 +299,7 @@ fn pass_structural_checks(report: &mut ConformanceReport) { fn pass_load_check(report: &mut ConformanceReport, id: &'static str) { let message = match id { "component" => "valid WebAssembly component", - "wit-contract" => "WIT contract matches codeint:plugin@0.5.0", + "wit-contract" => "WIT contract matches a supported codeint:plugin interface", "zero-imports" => "no WASI or host imports", "metric-key" => "the key is valid and unique", _ => "the version is valid", @@ -380,7 +380,7 @@ fn record_load_failure(report: &mut ConformanceReport, error: &PluginHostError, "component", error.to_string(), format!( - "build a WebAssembly component that exports codeint:plugin/{expected_kind}@0.5.0; check that --kind matches the kind of the Plugin" + "build a WebAssembly component that exports codeint:plugin/{expected_kind}@0.6.0; check that --kind matches the kind of the Plugin" ), ); } @@ -1267,10 +1267,10 @@ fn probe_importers(extensions: &[String]) -> Vec { path: repo_path(&format!("{prefix}/main.{extension}")), model: FileModel { runtime_imports: vec![ - "./lib".to_owned(), - "./missing".to_owned(), - "left-pad".to_owned(), - "fs".to_owned(), + "./lib".to_owned().into(), + "./missing".to_owned().into(), + "left-pad".to_owned().into(), + "fs".to_owned().into(), ], ..empty_file_model(SourceSet::Production) }, @@ -1929,7 +1929,11 @@ fn probe_file(path: &str, source_set: SourceSet) -> SourceFile { line: 3, rule: "probe-hazard".to_owned(), }], - runtime_imports: vec!["./util".to_owned(), "left-pad".to_owned(), "fs".to_owned()], + runtime_imports: vec![ + "./util".to_owned().into(), + "left-pad".to_owned().into(), + "fs".to_owned().into(), + ], ..empty_file_model(source_set) }, } diff --git a/crates/plugin-host/src/lib.rs b/crates/plugin-host/src/lib.rs index 47078f0a..87a5c692 100644 --- a/crates/plugin-host/src/lib.rs +++ b/crates/plugin-host/src/lib.rs @@ -12,6 +12,8 @@ use codeint_model::{ }; mod builtins; +#[macro_use] +mod compatibility; mod conformance; mod fetch; mod limits; @@ -34,7 +36,7 @@ pub use sha256::{format_hex as sha256_hex, sha256}; pub use wasm::WasmLanguagePlugin; pub use wasm_metric::{WasmMetricPlugin, validate_metric_key, validate_metric_version}; -pub const PLUGIN_INTERFACE_VERSION: &str = "0.5.0"; +pub const PLUGIN_INTERFACE_VERSION: &str = "0.6.0"; #[derive(Debug, thiserror::Error)] pub enum PluginHostError { diff --git a/crates/plugin-host/src/wasm.rs b/crates/plugin-host/src/wasm.rs index e43c049d..c6e36e65 100644 --- a/crates/plugin-host/src/wasm.rs +++ b/crates/plugin-host/src/wasm.rs @@ -13,10 +13,13 @@ use codeint_model::{ validate_flagged_lines, validate_framework_profile_result, validate_manifest_analysis, validate_scope_analysis, }; -use wasmtime::component::{Component, Linker}; +use wasmtime::component::{ + Component, ComponentNamedList, InstancePre, Lift, Linker, Lower, TypedFunc, +}; use wasmtime::{Cache, CacheConfig, Config, Engine, Store}; use crate::PluginHostError; +use crate::compatibility::{PluginInterface, Versioned}; use crate::limits::{ EpochTicker, LiftedBudget, LiftedSize, LimitTrap, PluginStoreState, arm_call_deadline, classify_trap, enforce_lifted_budget, new_limited_store, slice_budget, @@ -128,14 +131,60 @@ mod bindings { use bindings::exports::codeint::plugin::language as guest; +mod legacy_bindings { + wasmtime::component::bindgen!({ + world: "language-plugin", + path: "wit-legacy", + }); +} + +use legacy_bindings::exports::codeint::plugin::language as legacy_guest; + +versioned_component!( + LanguagePre, + LanguageBindings, + LanguagePluginPre, + LanguagePlugin +); + +pub(crate) fn call_wire( + func: &TypedFunc, + store: &mut Store, + params: P, +) -> wasmtime::Result +where + P: ComponentNamedList + Lower, + R: Lift, + LegacyP: ComponentNamedList + Lower, + LegacyR: ComponentNamedList + Lift, +{ + let result: (R,) = func.func().typed(&*store)?.call(store, params)?; + Ok(result.0) +} + +macro_rules! language_call { + ($bindings:expr, $store:expr, $func:ident $(, $arg:expr)* $(,)?) => { + match $bindings { + LanguageBindings::Current(bindings) => { + bindings.codeint_plugin_language().$func().call($store, ($($arg,)*)).map(|(value,)| value) + } + LanguageBindings::Legacy(bindings) => { + call_wire(&bindings.codeint_plugin_language().$func(), $store, ($($arg,)*)) + } + } + }; +} + pub(crate) struct ContractSpec { pub(crate) interface_prefix: &'static str, pub(crate) expected_interface: &'static str, + pub(crate) legacy_interface: &'static str, } const LANGUAGE_CONTRACT: ContractSpec = ContractSpec { interface_prefix: "codeint:plugin/language@", - expected_interface: "codeint:plugin/language@0.5.0", + expected_interface: "codeint:plugin/language@0.6.0", + legacy_interface: "codeint:plugin/language@0.5.0", }; pub(crate) fn check_contract_version( @@ -144,17 +193,22 @@ pub(crate) fn check_contract_version( engine: &Engine, component: &Component, spec: ContractSpec, -) -> Result<(), PluginHostError> { +) -> Result { let component_type = component.component_type(); let mut incompatible: Option = None; + let mut accepts_legacy = false; for (export_name, _) in component_type.exports(engine) { if export_name == spec.expected_interface { - return Ok(()); + return Ok(PluginInterface::Current); } + accepts_legacy |= export_name == spec.legacy_interface; if export_name.starts_with(spec.interface_prefix) && incompatible.is_none() { incompatible = Some(export_name.to_owned()); } } + if accepts_legacy { + return Ok(PluginInterface::Legacy); + } if let Some(found) = incompatible { return Err(PluginHostError::IncompatibleContractVersion { name: name.to_owned(), @@ -163,7 +217,7 @@ pub(crate) fn check_contract_version( found, }); } - Ok(()) + Ok(PluginInterface::Current) } pub(crate) struct SandboxedComponent
 {
@@ -239,7 +293,7 @@ pub struct WasmLanguagePlugin {
     hazard_rules_set: HashSet,
     has_imports: bool,
     has_scope_analysis: bool,
-    component: SandboxedComponent>,
+    component: SandboxedComponent,
 }
 
 fn compile_component(
@@ -272,13 +326,11 @@ pub(crate) fn prepare_sandboxed_component
(
     verified: &VerifiedBytes<'_>,
     compiled_plugin_cache: Option<&Path>,
     spec: ContractSpec,
-    bind: impl FnOnce(
-        wasmtime::component::InstancePre,
-    ) -> Result,
+    bind: impl FnOnce(InstancePre, PluginInterface) -> Result,
 ) -> Result<(Engine, Pre), PluginHostError> {
     let (name, path) = (verified.name, verified.path);
     let (engine, component) = compile_component(verified, compiled_plugin_cache)?;
-    check_contract_version(name, path, &engine, &component, spec)?;
+    let interface = check_contract_version(name, path, &engine, &component, spec)?;
     let linker: Linker = Linker::new(&engine);
     let instance_pre =
         linker
@@ -288,7 +340,7 @@ pub(crate) fn prepare_sandboxed_component
(
                 path: path.to_path_buf(),
                 reason: error.to_string(),
             })?;
-    let pre = bind(instance_pre).map_err(|error| PluginHostError::Instantiate {
+    let pre = bind(instance_pre, interface).map_err(|error| PluginHostError::Instantiate {
         name: name.to_owned(),
         path: path.to_path_buf(),
         reason: error.to_string(),
@@ -304,7 +356,7 @@ pub(crate) fn verify_language_component(
         verified,
         compiled_plugin_cache,
         LANGUAGE_CONTRACT,
-        bindings::LanguagePluginPre::new,
+        bind_versioned_component,
     )?;
     Ok(())
 }
@@ -328,9 +380,7 @@ pub(crate) struct VerifiedComponent<'a> {
 pub(crate) fn instantiate_sandboxed_component(
     verified: VerifiedComponent<'_>,
     spec: ContractSpec,
-    bind: impl FnOnce(
-        wasmtime::component::InstancePre,
-    ) -> Result,
+    bind: impl FnOnce(InstancePre, PluginInterface) -> Result,
     instantiate: impl FnOnce(&Pre, &mut Store) -> Result,
 ) -> Result, PluginHostError> {
     let (engine, pre) = prepare_sandboxed_component(
@@ -434,34 +484,30 @@ impl WasmLanguagePlugin {
                 compiled_plugin_cache,
             },
             LANGUAGE_CONTRACT,
-            bindings::LanguagePluginPre::new,
-            |pre, store| pre.instantiate(store),
+            bind_versioned_component,
+            instantiate_versioned_component,
         )?;
         let mut init = component.init_session(&name, path, limits);
-        let extensions = init.call_lifted("extensions", |b, s| {
-            b.codeint_plugin_language().call_extensions(s)
-        })?;
-        let known_dialects = init.call_lifted("known-dialects", |b, s| {
-            b.codeint_plugin_language().call_known_dialects(s)
-        })?;
-        let flagged_line_rules = init.call_lifted("flagged-line-rules", |b, s| {
-            b.codeint_plugin_language().call_flagged_line_rules(s)
-        })?;
-        let known_framework_profiles = init.call_lifted("known-framework-profiles", |b, s| {
-            b.codeint_plugin_language().call_known_framework_profiles(s)
-        })?;
-        let has_hazard_rules = init.call("has-hazard-rules", |b, s| {
-            b.codeint_plugin_language().call_has_hazard_rules(s)
-        })?;
-        let hazard_rules = init.call_lifted("hazard-rules", |b, s| {
-            b.codeint_plugin_language().call_hazard_rules(s)
-        })?;
-        let has_imports = init.call("has-imports", |b, s| {
-            b.codeint_plugin_language().call_has_imports(s)
-        })?;
-        let has_scope_analysis = init.call("has-scope-analysis", |b, s| {
-            b.codeint_plugin_language().call_has_scope_analysis(s)
-        })?;
+        macro_rules! metadata {
+            ($method:ident, $name:literal, $func:ident) => {
+                init.$method($name, |bindings, store| {
+                    language_call!(bindings, store, $func)
+                })
+            };
+        }
+        let extensions = metadata!(call_lifted, "extensions", func_extensions)?;
+        let known_dialects = metadata!(call_lifted, "known-dialects", func_known_dialects)?;
+        let flagged_line_rules =
+            metadata!(call_lifted, "flagged-line-rules", func_flagged_line_rules)?;
+        let known_framework_profiles = metadata!(
+            call_lifted,
+            "known-framework-profiles",
+            func_known_framework_profiles
+        )?;
+        let has_hazard_rules = metadata!(call, "has-hazard-rules", func_has_hazard_rules)?;
+        let hazard_rules = metadata!(call_lifted, "hazard-rules", func_hazard_rules)?;
+        let has_imports = metadata!(call, "has-imports", func_has_imports)?;
+        let has_scope_analysis = metadata!(call, "has-scope-analysis", func_has_scope_analysis)?;
         let flagged_line_rules_set: HashSet = flagged_line_rules.iter().cloned().collect();
         let hazard_rules_set: HashSet = hazard_rules.iter().cloned().collect();
         Ok(WasmLanguagePlugin {
@@ -488,14 +534,14 @@ impl WasmLanguagePlugin {
         &self,
         call: &'static str,
         operation: impl FnOnce(
-            &guest::Guest,
+            &LanguageBindings,
             &mut Store,
         ) -> Result,
     ) -> Result {
         let limits = self.component.limits();
         let value = self.component.call_fresh(
-            |pre, store| pre.instantiate(store),
-            |bindings, store| operation(bindings.codeint_plugin_language(), store),
+            instantiate_versioned_component,
+            operation,
             |store, error| map_call_trap(&self.name, "instantiate", limits, store, error),
             |store, error| map_call_trap(&self.name, call, limits, store, error),
         )?;
@@ -542,8 +588,18 @@ impl WasmLanguagePlugin {
         dialect: Option<&str>,
     ) -> Result {
         let lowered = self
-            .call_checked("lower", |api, store| {
-                api.call_lower(store, path.as_str(), text, dialect)
+            .call_checked("lower", |api, store| match api {
+                LanguageBindings::Current(bindings) => bindings
+                    .codeint_plugin_language()
+                    .call_lower(store, path.as_str(), text, dialect),
+                LanguageBindings::Legacy(bindings) => {
+                    let lowered: Result = call_wire(
+                        &bindings.codeint_plugin_language().func_lower(),
+                        store,
+                        (path.as_str(), text, dialect),
+                    )?;
+                    Ok(lowered.map(Into::into))
+                }
             })
             .map_err(|error| match error {
                 PluginHostError::MemoryLimitExceeded { name, memory_mb } => {
@@ -593,7 +649,7 @@ impl WasmLanguagePlugin {
     ) -> Result, PluginHostError> {
         let paths = owned_paths(repository_paths);
         self.call_checked("manifest-paths", |api, store| {
-            api.call_manifest_paths(store, &paths)
+            language_call!(api, store, func_manifest_paths, paths.as_slice())
         })
     }
 
@@ -613,7 +669,12 @@ impl WasmLanguagePlugin {
     ) -> Result {
         let host_manifests = to_guest_manifests(manifests);
         let analysis = self.call_checked("analyze-manifests", |api, store| {
-            api.call_analyze_manifests(store, &host_manifests)
+            language_call!(
+                api,
+                store,
+                func_analyze_manifests,
+                host_manifests.as_slice()
+            )
         })?;
         Ok(convert_manifest_analysis(analysis))
     }
@@ -632,6 +693,7 @@ impl WasmLanguagePlugin {
             .map(|request| guest::ImportRequest {
                 importer: request.importer,
                 specifier: request.specifier,
+                kind: to_guest_import_kind(request.kind),
             })
             .collect();
         let host_profiles: Vec = package_profiles
@@ -642,14 +704,35 @@ impl WasmLanguagePlugin {
             })
             .collect();
         let resolutions = self
-            .call_checked("resolve-imports", |api, store| {
-                api.call_resolve_imports(
-                    store,
-                    &paths,
-                    &host_manifests,
-                    &host_requests,
-                    &host_profiles,
-                )
+            .call_checked("resolve-imports", |api, store| match api {
+                LanguageBindings::Current(bindings) => {
+                    bindings.codeint_plugin_language().call_resolve_imports(
+                        store,
+                        paths.as_slice(),
+                        host_manifests.as_slice(),
+                        &host_requests,
+                        &host_profiles,
+                    )
+                }
+                LanguageBindings::Legacy(bindings) => {
+                    let requests: Vec = host_requests
+                        .iter()
+                        .map(|request| legacy_guest::ImportRequest {
+                            importer: request.importer.clone(),
+                            specifier: request.specifier.clone(),
+                        })
+                        .collect();
+                    call_wire(
+                        &bindings.codeint_plugin_language().func_resolve_imports(),
+                        store,
+                        (
+                            paths.as_slice(),
+                            host_manifests.as_slice(),
+                            requests.as_slice(),
+                            host_profiles.as_slice(),
+                        ),
+                    )
+                }
             })
             .map_err(map_language_plugin_error)?;
         Ok(resolutions.into_iter().map(convert_resolution).collect())
@@ -664,7 +747,13 @@ impl WasmLanguagePlugin {
         let host_manifests = to_guest_manifests(&manifests);
         let entries = self
             .call_checked("entry-points", |api, store| {
-                api.call_entry_points(store, &paths, &host_manifests)
+                language_call!(
+                    api,
+                    store,
+                    func_entry_points,
+                    paths.as_slice(),
+                    host_manifests.as_slice()
+                )
             })
             .map_err(map_language_plugin_error)?;
         validate_entry_points(repository_paths, entries)
@@ -673,7 +762,7 @@ impl WasmLanguagePlugin {
     pub(crate) fn reference_ranges_impl(&self) -> Result {
         let ranges = self
             .call_checked("reference-ranges", |api, store| {
-                api.call_reference_ranges(store)
+                language_call!(api, store, func_reference_ranges)
             })
             .map_err(map_language_plugin_error)?
             .into_iter()
@@ -694,11 +783,13 @@ impl WasmLanguagePlugin {
         let guest_selection = to_guest_framework_profile_selection(selection);
         let resolved = self
             .call_checked("resolve-framework-profiles", |api, store| {
-                api.call_resolve_framework_profiles(
+                language_call!(
+                    api,
                     store,
+                    func_resolve_framework_profiles,
                     package_root,
-                    &file_paths,
-                    &host_manifests,
+                    file_paths.as_slice(),
+                    host_manifests.as_slice(),
                     &guest_selection,
                 )
             })
@@ -745,7 +836,14 @@ impl WasmLanguagePlugin {
             })
             .collect();
         let analysis = self.call_checked("analyze-scope", |api, store| {
-            api.call_analyze_scope(store, package_root, dialect, &guest_artifacts)
+            language_call!(
+                api,
+                store,
+                func_analyze_scope,
+                package_root,
+                dialect,
+                guest_artifacts.as_slice()
+            )
         })?;
         Ok(convert_scope_analysis(analysis))
     }
@@ -886,7 +984,9 @@ impl LiftedSize for Result {
                     .saturating_add(tokens)
                     .saturating_add(flagged)
                     .saturating_add(hazards)
-                    .saturating_add(model.runtime_imports.lifted_budget())
+                    .saturating_add(slice_budget(&model.runtime_imports, |edge| {
+                        edge.specifier.len()
+                    }))
                     .saturating_add(diagnostics)
                     .saturating_add(artifact)
             }
@@ -945,6 +1045,41 @@ fn owned_paths(repository_paths: &[RepoPath]) -> Vec {
         .collect()
 }
 
+fn to_guest_import_kind(kind: language::ImportKind) -> guest::ImportKind {
+    match kind {
+        language::ImportKind::Unknown => guest::ImportKind::Unknown,
+        language::ImportKind::Import => guest::ImportKind::Import,
+        language::ImportKind::Require => guest::ImportKind::Require,
+    }
+}
+
+legacy_file_model!(guest);
+
+impl From for guest::FileModel {
+    fn from(model: LegacyFileModel) -> Self {
+        Self {
+            source_set: model.source_set,
+            source_lines: model.source_lines,
+            functions: model.functions,
+            tokens: model.tokens,
+            flagged_lines: model.flagged_lines,
+            hazard_lines: model.hazard_lines,
+            runtime_imports: model
+                .runtime_imports
+                .into_iter()
+                .map(|specifier| guest::ImportEdge {
+                    specifier,
+                    kind: guest::ImportKind::Unknown,
+                })
+                .collect(),
+            program_start: model.program_start,
+            is_tooling_file: model.is_tooling_file,
+            diagnostics: model.diagnostics,
+            scope_artifact: model.scope_artifact,
+        }
+    }
+}
+
 fn convert_file_model(model: guest::FileModel) -> FileModel {
     FileModel {
         source_set: convert_source_set(model.source_set),
@@ -989,7 +1124,18 @@ fn convert_file_model(model: guest::FileModel) -> FileModel {
             .into_iter()
             .map(convert_hazard_line)
             .collect(),
-        runtime_imports: model.runtime_imports,
+        runtime_imports: model
+            .runtime_imports
+            .into_iter()
+            .map(|edge| language::ImportEdge {
+                specifier: edge.specifier,
+                kind: match edge.kind {
+                    guest::ImportKind::Unknown => language::ImportKind::Unknown,
+                    guest::ImportKind::Import => language::ImportKind::Import,
+                    guest::ImportKind::Require => language::ImportKind::Require,
+                },
+            })
+            .collect(),
         program_start: model.program_start,
         is_tooling_file: model.is_tooling_file,
         diagnostics: model
diff --git a/crates/plugin-host/src/wasm_metric.rs b/crates/plugin-host/src/wasm_metric.rs
index cc9cd3b7..c1ff74ad 100644
--- a/crates/plugin-host/src/wasm_metric.rs
+++ b/crates/plugin-host/src/wasm_metric.rs
@@ -6,20 +6,23 @@ use codeint_model::{
     MetricPluginError, RepoPath, SourceSet, TokenKind, is_reserved_report_key,
 };
 use wasmtime::Store;
+use wasmtime::component::{ComponentType, Lower};
 
 use crate::PluginHostError;
+use crate::compatibility::{PluginInterface, Versioned};
 use crate::limits::{
     LiftedBudget, LiftedSize, LimitTrap, PluginStoreState, classify_trap, enforce_lifted_budget,
     slice_budget,
 };
 use crate::wasm::{
-    ContractSpec, SandboxedComponent, VerifiedBytes, VerifiedComponent,
+    ContractSpec, SandboxedComponent, VerifiedBytes, VerifiedComponent, call_wire,
     instantiate_sandboxed_component, prepare_sandboxed_component,
 };
 
 const METRIC_CONTRACT: ContractSpec = ContractSpec {
     interface_prefix: "codeint:plugin/metric@",
-    expected_interface: "codeint:plugin/metric@0.5.0",
+    expected_interface: "codeint:plugin/metric@0.6.0",
+    legacy_interface: "codeint:plugin/metric@0.5.0",
 };
 
 pub(crate) fn verify_metric_component(
@@ -30,7 +33,7 @@ pub(crate) fn verify_metric_component(
         verified,
         compiled_plugin_cache,
         METRIC_CONTRACT,
-        bindings::MetricPluginPre::new,
+        bind_versioned_component,
     )?;
     Ok(())
 }
@@ -42,6 +45,23 @@ mod bindings {
     });
 }
 
+mod legacy_bindings {
+    wasmtime::component::bindgen!({
+        world: "metric-plugin",
+        path: "wit-legacy",
+    });
+}
+
+versioned_component!(MetricPre, MetricBindings, MetricPluginPre, MetricPlugin);
+
+macro_rules! metric_metadata {
+    ($bindings:expr, $store:expr, $call:ident) => {
+        match $bindings {
+            MetricBindings::Current(bindings) => bindings.codeint_plugin_metric().$call($store),
+            MetricBindings::Legacy(bindings) => bindings.codeint_plugin_metric().$call($store),
+        }
+    };
+}
 use bindings::codeint::plugin::language as guest_language;
 use bindings::exports::codeint::plugin::metric as guest_metric;
 
@@ -57,7 +77,7 @@ pub struct WasmMetricPlugin {
     description: String,
     version: u32,
     declared_name_is_blank: bool,
-    component: SandboxedComponent>,
+    component: SandboxedComponent,
 }
 
 impl WasmMetricPlugin {
@@ -78,8 +98,8 @@ impl WasmMetricPlugin {
         let mut component = instantiate_sandboxed_component(
             verified,
             METRIC_CONTRACT,
-            bindings::MetricPluginPre::new,
-            |pre, store| pre.instantiate(store),
+            bind_versioned_component,
+            instantiate_versioned_component,
         )?;
         let (key, display_name, description, version, declared_name_is_blank) =
             read_metric_metadata(&mut component, &plugin_name, path, limits)?;
@@ -125,11 +145,19 @@ impl WasmMetricPlugin {
         let guest_model = to_guest_code_model(model);
         let limits = self.component.limits();
         let measurement = self.component.call_fresh(
-            |pre, store| pre.instantiate(store),
-            |bindings, store| {
-                bindings
+            instantiate_versioned_component,
+            |bindings, store| match bindings {
+                MetricBindings::Current(bindings) => bindings
                     .codeint_plugin_metric()
-                    .call_measure(store, &guest_model)
+                    .call_measure(store, &guest_model),
+                MetricBindings::Legacy(bindings) => {
+                    let legacy = LegacyCodeModel::from(guest_model);
+                    call_wire(
+                        &bindings.codeint_plugin_metric().func_measure(),
+                        store,
+                        (&legacy,),
+                    )
+                }
             },
             |store, error| map_metric_trap(&self.plugin_name, limits, store, error),
             |store, error| map_metric_trap(&self.plugin_name, limits, store, error),
@@ -173,22 +201,19 @@ pub(crate) fn enforce_metric_lifted_budget(
 }
 
 fn read_metric_metadata(
-    component: &mut crate::wasm::InstantiatedComponent<
-        bindings::MetricPluginPre,
-        bindings::MetricPlugin,
-    >,
+    component: &mut crate::wasm::InstantiatedComponent,
     plugin_name: &str,
     path: &Path,
     limits: PluginLimits,
 ) -> Result<(String, String, String, u32, bool), PluginHostError> {
     let mut init = component.init_session(plugin_name, path, limits);
-    let key = init.call_lifted("key", |b, s| b.codeint_plugin_metric().call_key(s))?;
+    let key = init.call_lifted("key", |b, s| metric_metadata!(b, s, call_key))?;
     validate_metric_key(plugin_name, &key)?;
-    let raw_name = init.call_lifted("name", |b, s| b.codeint_plugin_metric().call_name(s))?;
+    let raw_name = init.call_lifted("name", |b, s| metric_metadata!(b, s, call_name))?;
     let description = init.call_lifted("description", |b, s| {
-        b.codeint_plugin_metric().call_description(s)
+        metric_metadata!(b, s, call_description)
     })?;
-    let version = init.call("version", |b, s| b.codeint_plugin_metric().call_version(s))?;
+    let version = init.call("version", |b, s| metric_metadata!(b, s, call_version))?;
     validate_metric_version(plugin_name, version)?;
     let name_is_blank = raw_name.trim().is_empty();
     let display_name = if name_is_blank { key.clone() } else { raw_name };
@@ -309,6 +334,66 @@ fn to_guest_code_model(model: &CodeModel) -> guest_metric::CodeModel {
     }
 }
 
+legacy_file_model!(guest_language);
+
+impl From for LegacyFileModel {
+    fn from(model: guest_language::FileModel) -> Self {
+        Self {
+            source_set: model.source_set,
+            source_lines: model.source_lines,
+            functions: model.functions,
+            tokens: model.tokens,
+            flagged_lines: model.flagged_lines,
+            hazard_lines: model.hazard_lines,
+            runtime_imports: model
+                .runtime_imports
+                .into_iter()
+                .map(|edge| edge.specifier)
+                .collect(),
+            program_start: model.program_start,
+            is_tooling_file: model.is_tooling_file,
+            diagnostics: model.diagnostics,
+            scope_artifact: model.scope_artifact,
+        }
+    }
+}
+
+#[derive(ComponentType, Lower)]
+#[component(record)]
+struct LegacySourceFile {
+    path: String,
+    model: LegacyFileModel,
+}
+
+#[derive(ComponentType, Lower)]
+#[component(record)]
+struct LegacyCodeModel {
+    files: Vec,
+    #[component(name = "runtime-imports")]
+    runtime_imports: Vec,
+    #[component(name = "workspace-packages")]
+    workspace_packages: Vec,
+    languages: Vec,
+}
+
+impl From for LegacyCodeModel {
+    fn from(model: guest_metric::CodeModel) -> Self {
+        Self {
+            files: model
+                .files
+                .into_iter()
+                .map(|file| LegacySourceFile {
+                    path: file.path,
+                    model: file.model.into(),
+                })
+                .collect(),
+            runtime_imports: model.runtime_imports,
+            workspace_packages: model.workspace_packages,
+            languages: model.languages,
+        }
+    }
+}
+
 fn to_guest_file_model(model: &FileModel) -> guest_language::FileModel {
     guest_language::FileModel {
         source_set: match model.source_set {
@@ -366,7 +451,24 @@ fn to_guest_file_model(model: &FileModel) -> guest_language::FileModel {
                 rule: hazard.rule.clone(),
             })
             .collect(),
-        runtime_imports: model.runtime_imports.clone(),
+        runtime_imports: model
+            .runtime_imports
+            .iter()
+            .map(|edge| guest_language::ImportEdge {
+                specifier: edge.specifier.clone(),
+                kind: match edge.kind {
+                    codeint_model::language::ImportKind::Unknown => {
+                        guest_language::ImportKind::Unknown
+                    }
+                    codeint_model::language::ImportKind::Import => {
+                        guest_language::ImportKind::Import
+                    }
+                    codeint_model::language::ImportKind::Require => {
+                        guest_language::ImportKind::Require
+                    }
+                },
+            })
+            .collect(),
         program_start: model.program_start,
         is_tooling_file: model.is_tooling_file,
         diagnostics: model
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 131f47b1..63612063 100644
--- a/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs
+++ b/crates/plugin-host/tests/fixtures/sample-plugin/src/lib.rs
@@ -514,7 +514,7 @@ impl LanguagePlugin for SampleMiniPlugin {
             functions: state.functions,
             tokens: state.tokens,
             flagged_lines: state.flagged_lines,
-            runtime_imports: state.runtime_imports,
+            runtime_imports: state.runtime_imports.into_iter().map(Into::into).collect(),
             ..FileModel::empty(source_set_of(&path))
         })
     }
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
index 03dcaabf..abd42568 100644
--- 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
@@ -15,8 +15,8 @@ wit_bindgen::generate!({
 
 use exports::codeint::plugin::language::{
     DeclaredDep, FileModel, FrameworkProfileResult, FrameworkProfileSelection, Function, Guest,
-    ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, Token, TokenKind,
-    WorkspaceError,
+    ImportEdge, ImportKind, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution,
+    SourceSet, Token, TokenKind, WorkspaceError,
 };
 
 struct FolderImportLanguagePlugin;
@@ -27,7 +27,7 @@ struct LowerAccumulator {
     source_lines: u32,
     functions: Vec,
     tokens: Vec,
-    runtime_imports: Vec,
+    runtime_imports: Vec,
     program_start: bool,
 }
 
@@ -57,7 +57,10 @@ impl LowerAccumulator {
         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());
+                self.runtime_imports.push(ImportEdge {
+                    specifier: spec.to_string(),
+                    kind: ImportKind::Unknown,
+                });
             }
             TokenKind::ImportOrExport
         } else {
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
index ba38b388..431a01d2 100644
--- 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
@@ -8,7 +8,7 @@ use alloc::vec::Vec;
 
 wit_bindgen::generate!({
     world: "metric-plugin",
-    path: "../../../../../../wit",
+    path: "../../../../wit-legacy",
 });
 
 use self::codeint::plugin::language::Resolution;
@@ -33,6 +33,9 @@ impl Guest for ImportsReaderMetricPlugin {
 
         for import in &model.runtime_imports {
             if let Resolution::Resolved(targets) = &import.resolution {
+                assert!(model.files.iter().any(|file| {
+                    file.path == import.importer && file.model.runtime_imports.contains(&import.specifier)
+                }));
                 resolved_imports += 1;
                 if targets.len() > 1 {
                     multi_target_imports += 1;
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
index 696d9efd..92c197bd 100644
--- 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
@@ -15,7 +15,8 @@ wit_bindgen::generate!({
 
 use exports::codeint::plugin::language::{
     DeclaredDep, FileModel, FrameworkProfileResult, FrameworkProfileSelection, Guest,
-    ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, SourceSet, WorkspaceError,
+    ImportEdge, ImportKind, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution,
+    SourceSet, WorkspaceError,
 };
 
 struct ProgramStartLanguagePlugin;
@@ -34,8 +35,12 @@ impl Guest for ProgramStartLanguagePlugin {
         let runtime_imports = text
             .lines()
             .filter_map(|line| line.trim().strip_prefix("use "))
-            .map(|spec| spec.trim().to_string())
+            .map(str::trim)
             .filter(|spec| !spec.is_empty())
+            .map(|specifier| ImportEdge {
+                specifier: specifier.to_string(),
+                kind: ImportKind::Unknown,
+            })
             .collect();
         Ok(probe_runtime::blank_file_model!(
             source_set,
diff --git a/crates/plugin-host/tests/fixtures/sandbox-probes/v0-5-0-features-language/src/lib.rs b/crates/plugin-host/tests/fixtures/sandbox-probes/v0-5-0-features-language/src/lib.rs
index 199abbee..719d4256 100644
--- a/crates/plugin-host/tests/fixtures/sandbox-probes/v0-5-0-features-language/src/lib.rs
+++ b/crates/plugin-host/tests/fixtures/sandbox-probes/v0-5-0-features-language/src/lib.rs
@@ -10,7 +10,7 @@ use alloc::vec::Vec;
 
 wit_bindgen::generate!({
     world: "language-plugin",
-    path: "../../../../../../wit",
+    path: "../../../../wit-legacy",
 });
 
 use exports::codeint::plugin::language::{
diff --git a/crates/plugin-host/tests/integration/common/wasm_fixtures.rs b/crates/plugin-host/tests/integration/common/wasm_fixtures.rs
index 930968fd..ee08f745 100644
--- a/crates/plugin-host/tests/integration/common/wasm_fixtures.rs
+++ b/crates/plugin-host/tests/integration/common/wasm_fixtures.rs
@@ -38,10 +38,11 @@ const STD_CORE_MODULE_BUILDS: [(&str, &str, &str); 2] = [
 
 const STAMP_INPUT_FILES: [&str; 3] = ["rust-toolchain.toml", "Cargo.toml", ".cargo/config.toml"];
 
-const STAMP_INPUT_DIRS: [&str; 3] = [
+const STAMP_INPUT_DIRS: [&str; 4] = [
     "wit",
     "crates/plugin-sdk",
     "crates/plugin-host/tests/fixtures",
+    "crates/plugin-host/wit-legacy",
 ];
 
 static FIXTURES_DIR: OnceLock = OnceLock::new();
diff --git a/crates/plugin-host/tests/integration/conformance.rs b/crates/plugin-host/tests/integration/conformance.rs
index 235a377a..dd409ca7 100644
--- a/crates/plugin-host/tests/integration/conformance.rs
+++ b/crates/plugin-host/tests/integration/conformance.rs
@@ -139,10 +139,7 @@ fn assert_import_conformance(
     let requests: Vec = imports
         .import_requests
         .iter()
-        .map(|(importer, specifier)| ImportRequest {
-            importer: (*importer).to_owned(),
-            specifier: (*specifier).to_owned(),
-        })
+        .map(|(importer, specifier)| ImportRequest::new(*importer, *specifier))
         .collect();
     let resolutions = plugin
         .resolve_imports(&repo_paths, valid_manifest.clone(), requests, &[])
diff --git a/crates/plugin-host/tests/integration/load.rs b/crates/plugin-host/tests/integration/load.rs
index f530709a..0d31c08a 100644
--- a/crates/plugin-host/tests/integration/load.rs
+++ b/crates/plugin-host/tests/integration/load.rs
@@ -82,7 +82,10 @@ fn loads_sample_external_plugin_with_zero_capabilities_and_valid_hash() {
     assert_eq!(model.functions[0].name.as_deref(), Some("main"));
     assert_eq!(model.functions[0].decision_points, 1);
     assert_eq!(model.functions[0].cognitive_complexity, 1);
-    assert_eq!(model.runtime_imports, vec!["./util"]);
+    assert_eq!(
+        model.runtime_import_specifiers().collect::>(),
+        vec!["./util"]
+    );
     assert_eq!(model.flagged_lines.len(), 1);
     assert_eq!(model.flagged_lines[0].rule, "redundant-pass");
 
@@ -119,10 +122,7 @@ fn loads_sample_external_plugin_with_zero_capabilities_and_valid_hash() {
 
     let requests: Vec = ["./util", "external-pkg", "std:io"]
         .into_iter()
-        .map(|specifier| ImportRequest {
-            importer: "src/app.mini".to_owned(),
-            specifier: specifier.to_owned(),
-        })
+        .map(|specifier| ImportRequest::new("src/app.mini", specifier))
         .collect();
     let resolutions = plugin
         .resolve_imports(&repo_paths, Vec::new(), requests, &[])
@@ -547,12 +547,12 @@ fn built_in_and_sample_plugins_fit_comfortably_within_default_limits() {
 }
 
 #[test]
-fn verifies_0_5_0_contract_fields_and_methods_across_wasm_boundary() {
-    assert_eq!(PLUGIN_INTERFACE_VERSION, "0.5.0");
+fn verifies_0_6_0_contract_fields_and_methods_across_wasm_boundary() {
+    assert_eq!(PLUGIN_INTERFACE_VERSION, "0.6.0");
     let wasm_path = sample_plugin_wasm();
     let declaration = declaration_for("sample-mini", wasm_path);
     let plugin = load_language_plugin(Path::new("."), &declaration, &shared_host_config())
-        .expect("0.5.0 sample plugin loads");
+        .expect("0.6.0 sample plugin loads");
 
     assert_eq!(
         plugin.flagged_line_rules(),
@@ -628,22 +628,10 @@ fn verifies_0_5_0_contract_fields_and_methods_across_wasm_boundary() {
                 &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(),
-                    },
+                    ImportRequest::new("src/main.mini", "./util"),
+                    ImportRequest::new("src/main.mini", "serde"),
+                    ImportRequest::new("src/main.mini", "std:fs"),
+                    ImportRequest::new("src/main.mini", "./missing"),
                 ],
                 &[],
             )
@@ -733,10 +721,7 @@ fn verifies_0_5_0_contract_fields_and_methods_across_wasm_boundary() {
         Err(LanguagePluginError::FrameworkProfile { ref message }) if message.contains("nonexistent")
     ));
 
-    let alias_request = vec![ImportRequest {
-        importer: "pages/home.mini".to_owned(),
-        specifier: "@/util".to_owned(),
-    }];
+    let alias_request = vec![ImportRequest::new("pages/home.mini", "@/util")];
     assert_eq!(
         plugin
             .resolve_imports(&fw_paths, Vec::new(), alias_request.clone(), &[])
@@ -764,7 +749,7 @@ fn verifies_0_5_0_contract_fields_and_methods_across_wasm_boundary() {
         &declaration_with_kind("sample-metric", PluginKind::Metric, metric_wasm),
         &shared_host_config(),
     )
-    .expect("0.5.0 sample metric plugin loads");
+    .expect("0.6.0 sample metric plugin loads");
     assert_eq!(metric_plugin.version(), 1);
 }
 
@@ -805,12 +790,12 @@ fn rejects_v0_1_0_language_plugin_with_actionable_version_mismatch_error() {
 
     let error = load_language_plugin(Path::new("."), &declaration, &shared_host_config())
         .err()
-        .expect("0.1.0 Language plugin must be rejected by 0.5.0 host");
+        .expect("0.1.0 Language plugin must be rejected by 0.6.0 host");
 
     assert_incompatible_contract_error(
         error,
         "legacy-lang",
-        "codeint:plugin/language@0.5.0",
+        "codeint:plugin/language@0.6.0",
         "codeint:plugin/language@0.1.0",
     );
 }
@@ -822,12 +807,12 @@ fn rejects_v0_1_0_metric_plugin_with_actionable_version_mismatch_error() {
 
     let error = load_metric_plugin(Path::new("."), &declaration, &shared_host_config())
         .err()
-        .expect("0.1.0 Metric plugin must be rejected by 0.5.0 host");
+        .expect("0.1.0 Metric plugin must be rejected by 0.6.0 host");
 
     assert_incompatible_contract_error(
         error,
         "legacy-metric",
-        "codeint:plugin/metric@0.5.0",
+        "codeint:plugin/metric@0.6.0",
         "codeint:plugin/metric@0.1.0",
     );
 }
@@ -850,11 +835,11 @@ fn rejects_v0_2_0_and_v0_3_0_language_and_metric_plugins_with_actionable_version
         let lang_decl = declaration_for(label, &lang_path);
         let lang_err = load_language_plugin(Path::new("."), &lang_decl, &shared_host_config())
             .err()
-            .expect("legacy Language plugin must be rejected by 0.5.0 host");
+            .expect("legacy Language plugin must be rejected by 0.6.0 host");
         assert_incompatible_contract_error(
             lang_err,
             label,
-            "codeint:plugin/language@0.5.0",
+            "codeint:plugin/language@0.6.0",
             expected_found,
         );
         let legacy_lang_bytes = std::fs::read(&lang_path).expect("read legacy language wasm");
@@ -864,7 +849,7 @@ fn rejects_v0_2_0_and_v0_3_0_language_and_metric_plugins_with_actionable_version
         assert_incompatible_contract_error(
             verify_lang_err,
             label,
-            "codeint:plugin/language@0.5.0",
+            "codeint:plugin/language@0.6.0",
             expected_found,
         );
     }
@@ -885,11 +870,11 @@ fn rejects_v0_2_0_and_v0_3_0_language_and_metric_plugins_with_actionable_version
         let metric_decl = declaration_with_kind(label, PluginKind::Metric, &metric_path);
         let metric_err = load_metric_plugin(Path::new("."), &metric_decl, &shared_host_config())
             .err()
-            .expect("legacy Metric plugin must be rejected by 0.5.0 host");
+            .expect("legacy Metric plugin must be rejected by 0.6.0 host");
         assert_incompatible_contract_error(
             metric_err,
             label,
-            "codeint:plugin/metric@0.5.0",
+            "codeint:plugin/metric@0.6.0",
             expected_found,
         );
         let legacy_metric_bytes = std::fs::read(&metric_path).expect("read legacy metric wasm");
@@ -903,7 +888,7 @@ fn rejects_v0_2_0_and_v0_3_0_language_and_metric_plugins_with_actionable_version
         assert_incompatible_contract_error(
             verify_metric_err,
             label,
-            "codeint:plugin/metric@0.5.0",
+            "codeint:plugin/metric@0.6.0",
             expected_found,
         );
     }
@@ -937,7 +922,7 @@ fn rejects_v0_4_0_language_and_metric_plugins_with_actionable_version_mismatch_e
     let lang_decl = declaration_for("legacy-v04-lang", &lang_path);
     let lang_err = load_language_plugin(Path::new("."), &lang_decl, &shared_host_config())
         .err()
-        .expect("0.4.0 Language plugin must be rejected by 0.5.0 host");
+        .expect("0.4.0 Language plugin must be rejected by 0.6.0 host");
     let lang_rendered = lang_err.to_string();
     assert!(
         !lang_rendered.contains("codeint.json"),
@@ -946,7 +931,7 @@ fn rejects_v0_4_0_language_and_metric_plugins_with_actionable_version_mismatch_e
     assert_incompatible_contract_error(
         lang_err,
         "legacy-v04-lang",
-        "codeint:plugin/language@0.5.0",
+        "codeint:plugin/language@0.6.0",
         "codeint:plugin/language@0.4.0",
     );
 
@@ -954,7 +939,7 @@ fn rejects_v0_4_0_language_and_metric_plugins_with_actionable_version_mismatch_e
     let metric_decl = declaration_with_kind("legacy-v04-metric", PluginKind::Metric, &metric_path);
     let metric_err = load_metric_plugin(Path::new("."), &metric_decl, &shared_host_config())
         .err()
-        .expect("0.4.0 Metric plugin must be rejected by 0.5.0 host");
+        .expect("0.4.0 Metric plugin must be rejected by 0.6.0 host");
     let metric_rendered = metric_err.to_string();
     assert!(
         !metric_rendered.contains("codeint.json"),
@@ -963,7 +948,7 @@ fn rejects_v0_4_0_language_and_metric_plugins_with_actionable_version_mismatch_e
     assert_incompatible_contract_error(
         metric_err,
         "legacy-v04-metric",
-        "codeint:plugin/metric@0.5.0",
+        "codeint:plugin/metric@0.6.0",
         "codeint:plugin/metric@0.4.0",
     );
 }
@@ -1684,7 +1669,7 @@ fn metric_plugin_reads_per_language_hazard_rules_statement() {
 }
 
 #[test]
-fn language_plugin_resolves_multi_file_imports_and_metric_plugin_reads_them() {
+fn language_plugin_resolves_multi_file_imports_and_v05_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");
 
@@ -2480,11 +2465,18 @@ fn v05_wasm_plugin_round_trips_new_fields_and_enforces_host_and_conformance_guar
     let model = plugin
         .lower(
             &RepoPath::new("src/app.config.v05").expect("valid path"),
-            "DIAG_NOTE\nNOOP_FLAG\nSCOPE_RISK\n",
+            "DIAG_NOTE\nNOOP_FLAG\nSCOPE_RISK\nimport ./util\n",
             Some("alpha"),
         )
         .expect("v0.5.0 lower succeeds");
     assert!(model.is_tooling_file);
+    assert_eq!(
+        model.runtime_imports,
+        [codeint_model::language::ImportEdge {
+            specifier: "./util".to_owned(),
+            kind: codeint_model::language::ImportKind::Unknown,
+        }]
+    );
     assert_eq!(model.diagnostics.len(), 1);
     assert_eq!(model.diagnostics[0].kind, "note");
     assert_eq!(model.flagged_lines.len(), 1);
diff --git a/crates/plugin-host/tests/integration/sdk_build_paths.rs b/crates/plugin-host/tests/integration/sdk_build_paths.rs
index 889f382c..ccc091aa 100644
--- a/crates/plugin-host/tests/integration/sdk_build_paths.rs
+++ b/crates/plugin-host/tests/integration/sdk_build_paths.rs
@@ -19,7 +19,7 @@ fn componentize_std_core_module(core_module_file: &str, component_file: &str) ->
     let component_bytes = wit_component::ComponentEncoder::default()
         .validate(true)
         .module(&core_bytes)
-        .expect("std core module carries codeint:plugin@0.5.0 component metadata")
+        .expect("std core module carries codeint:plugin@0.6.0 component metadata")
         .encode()
         .expect("encode std core module as a component without a WASI adapter");
     let component_path = core_path.with_file_name(component_file);
@@ -110,7 +110,7 @@ fn sdk_std_unknown_unknown_plugins_load_and_match_no_std_wasip2_results() {
         PluginKind::Language,
         &std_language_bytes,
     )
-    .expect("std language component exports codeint:plugin/language@0.5.0");
+    .expect("std language component exports codeint:plugin/language@0.6.0");
     let std_metric_bytes = std::fs::read(&std_metric_path).expect("read std metric");
     verify_plugin_component(
         "long-functions-std",
@@ -118,7 +118,7 @@ fn sdk_std_unknown_unknown_plugins_load_and_match_no_std_wasip2_results() {
         PluginKind::Metric,
         &std_metric_bytes,
     )
-    .expect("std metric component exports codeint:plugin/metric@0.5.0");
+    .expect("std metric component exports codeint:plugin/metric@0.6.0");
 
     let host_config = shared_host_config();
     let no_std_language = load_language_plugin(
diff --git a/crates/plugin-host/wit-legacy/language.wit b/crates/plugin-host/wit-legacy/language.wit
new file mode 100644
index 00000000..070e1125
--- /dev/null
+++ b/crates/plugin-host/wit-legacy/language.wit
@@ -0,0 +1,406 @@
+/// The Plugin interface of codeint.
+/// A change that breaks a Plugin built against this version needs a new version.
+package codeint:plugin@0.5.0;
+
+/// The interface a Language plugin exports: the file extensions it reads, and the Code model of each such file.
+interface language {
+    /// Coverage counts for one function from Coverage reports.
+    record function-coverage {
+        /// The count of the function's lines listed by a Coverage report.
+        listed-lines: u32,
+        /// The count of those listed lines executed by tests.
+        executed-lines: u32,
+    }
+
+    /// One function of a source file.
+    /// A nested function is a function of its own and adds no decision points to the function around it.
+    record function {
+        /// The line where the function starts, counted from 1.
+        line: u32,
+        /// The line where the function ends, counted from 1; the same as `line` for a function on one line.
+        end-line: u32,
+        /// The decision points of the function, not counting those of nested functions.
+        decision-points: u32,
+        /// The source lines of the function, not counting lines of nested functions.
+        source-lines: u32,
+        /// The optional name of the function or method; `none` for anonymous lambdas and closures.
+        name: option,
+        /// The nesting-weighted cognitive complexity of the function, not counting nested functions.
+        cognitive-complexity: u32,
+        /// Coverage counts for the function from Coverage reports; `none` when no Coverage report covers the function.
+        /// A Language plugin always returns `none`; codeint fills this in before Metrics run.
+        coverage: option,
+    }
+
+    /// What a token is to clone detection, by the rules of the Language plugin.
+    enum token-kind {
+        /// A name the code chooses, such as a variable, function, parameter, type, or property name.
+        /// Clone detection treats every identifier as the same token.
+        identifier,
+        /// A literal value, such as a string, number, boolean, null, regular expression, or template text.
+        /// Clone detection treats every literal as the same token.
+        literal,
+        /// Any other token, such as a keyword, an operator, or punctuation.
+        /// Clone detection compares these by their text hash.
+        other,
+        /// Any token of a declaration that only imports or exports names, such as a TypeScript `import`, `export { a } from`, or `export { a }` declaration.
+        /// Which declarations count is a rule of the Language plugin.
+        /// Clone detection never matches these tokens, because a list of names repeats only its shape.
+        import-or-export,
+    }
+
+    /// The group a source file belongs to.
+    /// Every source file belongs to exactly one Source set, and every Metric reports each Source set separately.
+    enum source-set {
+        /// Code that ships, the default for a file that no other rule claims.
+        production,
+        /// Code that only tests run, such as a TypeScript `*.test.ts` file.
+        test,
+        /// Code that a tool writes, such as build output.
+        generated,
+        /// Third-party code copied into the repository.
+        vendored,
+    }
+
+    /// One token of a source file, so never whitespace or a comment.
+    record token {
+        /// Whether the token is an identifier, a literal, another token, or a token of an import or export declaration.
+        kind: token-kind,
+        /// The 64-bit FNV-1a hash of the token's UTF-8 text as written.
+        text-hash: u64,
+        /// The 1-based line on which the token starts.
+        line: u32,
+    }
+
+    /// A source line that matches a Flagged-line rule of the Language plugin.
+    record flagged-line {
+        /// The line number, counted from 1.
+        line: u32,
+        /// The stable identifier of the rule the line matched, such as `else-after-return`.
+        rule: string,
+    }
+
+    /// A source line that matches a Hazard-line rule of the Language plugin.
+    /// Never holds source text.
+    record hazard-line {
+        /// The line number, counted from 1.
+        line: u32,
+        /// The stable identifier of the rule the line matched, listed in `hazard-rules`.
+        rule: string,
+    }
+
+    /// One non-fatal diagnostic emitted while lowering a source file.
+    record file-diagnostic {
+        /// The 1-based line number where the diagnostic applies.
+        line: u32,
+        /// A stable machine-readable category for the diagnostic, such as `rejected-statement`.
+        kind: string,
+        /// A human-readable description of the diagnostic.
+        message: string,
+    }
+
+    /// The Code model of one source file.
+    record file-model {
+        /// The Source set of the file, chosen by the rules of the Language plugin.
+        source-set: source-set,
+        /// The lines that hold code, so not a blank line or a line with only comments.
+        source-lines: u32,
+        /// Every function of the file, in the order their first lines appear.
+        functions: list,
+        /// Every token of the file, in source order.
+        tokens: list,
+        /// Each Flagged line with the rule it matched; a line that matches two rules appears once per rule.
+        flagged-lines: list,
+        /// Each Hazard line with the rule it matched; a line that matches two rules appears once per rule.
+        /// Empty when `has-hazard-rules` returns false.
+        hazard-lines: list,
+        /// The module specifiers of the imports that run when the file runs, in source order, such as `./greet`.
+        /// Type-only imports are left out.
+        runtime-imports: list,
+        /// Whether the file starts a program as shown by its source text, such as a Go `package main` file.
+        /// False unless the Language plugin sets it.
+        program-start: bool,
+        /// Whether the file is a language-specific Tooling file, such as a config or build script.
+        /// False unless the Language plugin sets it.
+        is-tooling-file: bool,
+        /// Non-fatal per-file diagnostics collected while lowering this file.
+        diagnostics: list,
+        /// Optional opaque bytes passed back into `analyze-scope` for cross-file analysis.
+        /// `none` unless `has-scope-analysis` returns true.
+        scope-artifact: option>,
+    }
+
+    /// One runtime import to resolve: the file that imports, and the specifier it names.
+    record import-request {
+        /// The importing file, relative to the repository root, with forward slashes.
+        importer: string,
+        /// The module specifier exactly as the file writes it.
+        specifier: string,
+    }
+
+    /// Where a runtime import leads.
+    variant resolution {
+        /// The import names one or more files of the repository, relative to the root, with forward slashes.
+        /// An empty list is a Plugin error.
+        resolved(list),
+        /// The import names a third-party package outside the repository; the payload is the canonical package name.
+        external(string),
+        /// The import names a standard-library or runtime built-in module.
+        builtin,
+        /// The import should name a file of the repository, but none matches; the payload says why.
+        unresolved(string),
+    }
+
+    /// How a package manifest declares an external dependency.
+    enum dep-kind {
+        /// A dependency required at runtime in production.
+        runtime,
+        /// A dependency used only during development or testing.
+        dev,
+        /// An optional or peer dependency.
+        optional,
+    }
+
+    /// One external dependency declared in a package manifest.
+    record declared-dep {
+        /// The package root folder relative to the repository root, with forward slashes, or empty for the repository root.
+        package-root: string,
+        /// The normalized package name as declared by the manifest.
+        name: string,
+        /// Whether the dependency is declared as runtime, dev, or optional.
+        kind: dep-kind,
+    }
+
+    /// Why a Language plugin cannot lower a file.
+    variant lower-error {
+        /// The file does not parse; the payload is the parser's message.
+        unparsable(string),
+        /// No rule of the Language plugin covers the file; the payload says why.
+        unsupported-file(string),
+        /// The file has more source lines than a `u32` holds.
+        too-large,
+        /// The file only declares types and holds no code to measure, such as a TypeScript `.d.ts` file.
+        declaration-only,
+    }
+
+    /// A file that a Language plugin reads to find workspace packages and resolve imports, such as a `package.json` or `tsconfig.json` file, as the host read it.
+    record manifest {
+        /// The path of the file, relative to the repository root, with forward slashes.
+        path: string,
+        /// The whole file.
+        text: string,
+    }
+
+    /// Why a Language plugin could not parse one manifest.
+    record workspace-error {
+        /// The path of the manifest that holds the problem, relative to the repository root.
+        path: string,
+        /// What is wrong with the manifest.
+        message: string,
+    }
+
+    /// Ownership mapping between a dependency manifest file and its Workspace package root.
+    record dependency-manifest-owner {
+        /// The package root folder relative to the repository root, with forward slashes, or empty for the repository root.
+        package-root: string,
+        /// The manifest path relative to the repository root, with forward slashes.
+        path: string,
+    }
+
+    /// An external dependency referenced inside a manifest or script rather than a source-file import.
+    record package-dependency {
+        /// The package root folder relative to the repository root, with forward slashes, or empty for the repository root.
+        package-root: string,
+        /// The normalized external package name referenced by the manifest.
+        name: string,
+    }
+
+    /// Consolidated manifest analysis for one repository snapshot in a single pass.
+    record manifest-analysis {
+        /// The root folder of each workspace member package, relative to the repository root, with forward slashes.
+        /// The repository root is never in the list; an empty list means the repository is one package.
+        workspace-packages: list,
+        /// Manifests that could not be parsed and were skipped during analysis, with their exact paths and reasons.
+        invalid-manifests: list,
+        /// Manifest files that own dependencies for a package root.
+        dependency-manifests: list,
+        /// External dependencies declared in the valid manifests.
+        declared-dependencies: list,
+        /// External dependencies used by manifest scripts or configuration rather than source imports.
+        manifest-used-dependencies: list,
+        /// Package roots whose dependencies inherit from the repository root package, such as npm workspace hoisting.
+        root-dependency-inheritance: list,
+    }
+
+    /// Active Framework profiles for one Workspace package.
+    record package-framework-profiles {
+        /// The package root folder relative to the repository root, with forward slashes, or empty for the repository root.
+        package-root: string,
+        /// The active Framework profile names for this Workspace package.
+        active-profiles: list,
+    }
+
+    /// One file's opaque scope artifact passed back into `analyze-scope`.
+    record file-scope-artifact {
+        /// The path of the file, relative to the repository root, with forward slashes.
+        path: string,
+        /// The settled Source set of the file.
+        source-set: source-set,
+        /// The opaque byte artifact returned by `lower` for this file.
+        artifact: list,
+    }
+
+    /// Extra Hazard lines discovered for one file during cross-file scope analysis.
+    record file-hazards {
+        /// The path of the file, relative to the repository root, with forward slashes.
+        path: string,
+        /// Additional Hazard lines for this file, each naming a rule in `hazard-rules`.
+        hazard-lines: list,
+    }
+
+    /// One key-value field in a language-neutral scope summary.
+    record summary-field {
+        /// The stable machine-readable field key, such as `tables`.
+        key: string,
+        /// The string-encoded field value.
+        value: string,
+    }
+
+    /// A language-neutral summary emitted by cross-file scope analysis.
+    record scope-summary {
+        /// A stable kind identifier for this summary, such as `sql-schema`.
+        kind: string,
+        /// Key-value metadata fields for this summary.
+        fields: list,
+    }
+
+    /// Result of cross-file scope analysis for one `(package-root, dialect)` group.
+    record scope-analysis {
+        /// Additional Hazard lines discovered across files in the scope.
+        extra-hazards: list,
+        /// Language-neutral summaries for this scope.
+        summaries: list,
+    }
+
+    /// The file extensions the Language plugin reads, each without its leading dot, such as `ts`.
+    extensions: func() -> list;
+
+    /// The stable names of Dialects this Language plugin accepts in `lower`, such as `postgresql` or `sqlite`.
+    /// Empty when the Language plugin has no selectable Dialects.
+    known-dialects: func() -> list;
+
+    /// Lowers one file into its Code model.
+    /// `path` is relative to the repository root and uses forward slashes.
+    /// `text` is the whole file.
+    /// `dialect` is an optional Dialect name from `known-dialects`, or `none` for the plugin's default Dialect.
+    lower: func(path: string, text: string, dialect: option) -> result;
+
+    /// The stable names of the Flagged line rules this Language plugin may emit.
+    flagged-line-rules: func() -> list;
+
+    /// Chooses the files of one repository snapshot that the host reads once and passes to `analyze-manifests`, `resolve-imports`, and `entry-points`, because a Plugin cannot read files.
+    /// `repository-paths` lists every file of the snapshot, relative to the root, with forward slashes.
+    /// The result names only paths from `repository-paths`, such as each `package.json` and `tsconfig.json` file.
+    manifest-paths: func(repository-paths: list) -> list;
+
+    /// Analyzes the selected manifests in a single pass to discover workspace packages, skipped invalid manifests, dependency ownership, declared dependencies, manifest-used dependencies, and root-dependency inheritance.
+    /// `manifests` holds each file that `manifest-paths` chose, with its text.
+    analyze-manifests: func(manifests: list) -> manifest-analysis;
+
+    /// Resolves runtime imports against the files of one repository snapshot.
+    /// `repository-paths` lists every file of the snapshot, relative to the root, with forward slashes.
+    /// `manifests` holds each file that `manifest-paths` chose, with its text.
+    /// `requests` lists the runtime imports to resolve.
+    /// `package-profiles` lists the active Framework profile names per Workspace package, so monorepos resolve imports in one pass.
+    /// The result holds one resolution per request, in request order.
+    resolve-imports: func(repository-paths: list, manifests: list, requests: list, package-profiles: list) -> list;
+
+    /// Discovers standard entry-point source files from the repository paths and selected manifests.
+    /// `repository-paths` lists every file of the snapshot, relative to the root, with forward slashes.
+    /// `manifests` holds each file that `manifest-paths` chose, with its text.
+    /// Every returned path must come from `repository-paths`.
+    entry-points: func(repository-paths: list, manifests: list) -> list;
+
+    /// The published typical value of one Metric for codebases in the language of the Language plugin.
+    record reference-range {
+        /// The Metric, by its key in the report: `erosion`, `verbosity`, `duplication`, or `import_cycles`.
+        metric: string,
+        /// The positive integer version of the Metric that this Reference range was calibrated against.
+        metric-version: u32,
+        /// The lowest typical ratio, from 0 to 1.
+        low: f64,
+        /// The highest typical ratio, from `low` to 1.
+        high: f64,
+        /// Where the range was published and what it measured, shown next to the range.
+        source: string,
+    }
+
+    /// The Reference ranges measured in the language of this Language plugin, at most one per Metric.
+    /// A Metric without an entry has no published Reference range for this language.
+    /// codeint shows a range only next to values that this Language plugin measured.
+    reference-ranges: func() -> list;
+
+    /// How the host asks a Language plugin to select Framework profiles for one Workspace package.
+    variant framework-profile-selection {
+        /// Auto-detect every matching Framework profile from files and manifests.
+        auto,
+        /// Disable all Framework profiles for this Workspace package.
+        disabled,
+        /// Auto-detect Framework profiles, leaving out the named profiles.
+        exclude(list),
+        /// Activate only the named Framework profiles for this Workspace package.
+        only(list),
+    }
+
+    /// The resolved Framework profiles and package-level conventions for one Workspace package.
+    record framework-profile-result {
+        /// The stable names of the active Framework profiles for this Workspace package, each listed in `known-framework-profiles`.
+        active-profiles: list,
+        /// Framework convention entry-point source files, each coming from `files`.
+        entry-points: list,
+        /// Framework convention generated file paths, each coming from `files`.
+        generated-paths: list,
+        /// Framework-specific Reference ranges for this Workspace package; empty means use the language's default `reference-ranges`.
+        reference-ranges: list,
+        /// An optional note explaining why framework Reference ranges were selected or fell back.
+        reference-range-note: option,
+    }
+
+    /// The stable names of the Framework profiles this Language plugin knows.
+    /// Empty when the Language plugin defines no Framework profiles.
+    known-framework-profiles: func() -> list;
+
+    /// Resolves active Framework profiles and package-level conventions for one Workspace package.
+    /// `package-root` is the package root folder relative to the repository root, with forward slashes, or empty for the repository root.
+    /// `files` lists the repository-relative file paths belonging to this Workspace package, with forward slashes.
+    /// `manifests` holds the manifests relevant to this Workspace package, with their text.
+    /// `selection` chooses automatic detection or an explicit per-package override.
+    resolve-framework-profiles: func(package-root: string, files: list, manifests: list, selection: framework-profile-selection) -> result;
+
+    /// Whether this Language plugin defines Hazard line rules.
+    /// When false, the Hazards Metric is absent for this language rather than 0.
+    has-hazard-rules: func() -> bool;
+
+    /// The stable names of the Hazard line rules this Language plugin may emit.
+    /// Empty when `has-hazard-rules` returns false.
+    hazard-rules: func() -> list;
+
+    /// Whether this language has runtime imports, manifests, and entry points.
+    /// When false, codeint never calls `manifest-paths`, `analyze-manifests`, `resolve-imports`,
+    /// or `entry-points`, and import Metrics are absent for this language.
+    has-imports: func() -> bool;
+
+    /// Whether this Language plugin performs cross-file scope analysis over opaque `scope-artifact` bytes.
+    has-scope-analysis: func() -> bool;
+
+    /// Runs cross-file scope analysis over one `(package-root, dialect)` group of lowered files.
+    /// `package-root` is the package root folder relative to the repository root, with forward slashes, or empty for the repository root.
+    /// `dialect` is the optional Dialect name active for this group.
+    /// `artifacts` holds each file's path, settled Source set, and opaque artifact bytes from `lower`.
+    analyze-scope: func(package-root: string, dialect: option, artifacts: list) -> scope-analysis;
+}
+
+/// A Language plugin exports `language` and imports nothing.
+world language-plugin {
+    export language;
+}
diff --git a/crates/plugin-host/wit-legacy/metric.wit b/crates/plugin-host/wit-legacy/metric.wit
new file mode 100644
index 00000000..4fc17bc1
--- /dev/null
+++ b/crates/plugin-host/wit-legacy/metric.wit
@@ -0,0 +1,94 @@
+package codeint:plugin@0.5.0;
+
+/// The interface a Metric plugin exports: metadata for one Metric and a function that measures a Code model.
+interface metric {
+    use language.{file-model, resolution};
+
+    /// One lowered source file in the Code model.
+    record source-file {
+        /// The path of the file, relative to the repository root, with forward slashes.
+        path: string,
+        /// The lowered Code model of the file.
+        model: file-model,
+    }
+
+    /// One resolved runtime import in the Code model.
+    record runtime-import {
+        /// The importing file, relative to the repository root, with forward slashes.
+        importer: string,
+        /// The module specifier exactly as written in the importing file.
+        specifier: string,
+        /// Where the runtime import leads.
+        resolution: resolution,
+    }
+
+    /// Per-language facts attached to a Code model for Metric plugins.
+    record language-facts {
+        /// The Language plugin name, such as `typescript-javascript` or `rust`.
+        language: string,
+        /// Whether at least one Coverage report covers at least one file of this language.
+        has-coverage: bool,
+        /// Whether this Language plugin defines Hazard line rules.
+        has-hazard-rules: bool,
+        /// Whether this language has runtime imports, manifests, and entry points.
+        has-imports: bool,
+    }
+
+    /// The language-neutral Code model of one Source set that a Metric plugin reads.
+    record code-model {
+        /// Every measured source file in this Source set, sorted by path.
+        files: list,
+        /// Every runtime import of the files in this Source set.
+        runtime-imports: list,
+        /// The workspace package roots of the repository, relative to the repository root.
+        workspace-packages: list,
+        /// Per-language facts for every language represented in this Code model, sorted by language name.
+        languages: list,
+    }
+
+    /// One located piece of evidence behind a Metric value.
+    record finding {
+        /// A stable identifier for this Finding across runs, used by `codeint diff` to classify new, resolved, and unchanged Findings.
+        id: string,
+        /// The primary file of the Finding, relative to the repository root, with forward slashes.
+        path: string,
+        /// The 1-based line where the Finding starts.
+        line: u32,
+        /// The optional 1-based line where the Finding ends.
+        end-line: option,
+        /// A human-readable description of the Finding.
+        message: string,
+    }
+
+    /// The measurement of one Metric for a Code model.
+    record measurement {
+        /// The Metric value, a ratio from 0 to 1.
+        ratio: f64,
+        /// The numerator behind the ratio, used by Regression checks.
+        numerator: f64,
+        /// The denominator behind the ratio.
+        denominator: f64,
+        /// The Findings behind the Metric value, ordered worst first.
+        findings: list,
+    }
+
+    /// The key of the Metric in reports, Budgets, and Regression limits, such as `long_functions`.
+    key: func() -> string;
+
+    /// The display name of the Metric in human-readable reports, such as `Long functions`.
+    name: func() -> string;
+
+    /// A short description of what the Metric measures, used in SARIF rule metadata.
+    description: func() -> string;
+
+    /// The positive integer version of this Metric's measurement semantics, starting at 1.
+    version: func() -> u32;
+
+    /// Measures the Code model of one Source set and returns the Metric value and its Findings.
+    measure: func(model: code-model) -> measurement;
+}
+
+/// A Metric plugin exports `metric` and imports nothing.
+world metric-plugin {
+    export metric;
+}
diff --git a/crates/plugin-host/wit/language.wit b/crates/plugin-host/wit/language.wit
index 81891560..d4be90cb 100644
--- a/crates/plugin-host/wit/language.wit
+++ b/crates/plugin-host/wit/language.wit
@@ -1,6 +1,6 @@
 /// The Plugin interface of codeint.
 /// A change that breaks a Plugin built against this version needs a new version.
-package codeint:plugin@0.5.0;
+package codeint:plugin@0.6.0;
 
 /// The interface a Language plugin exports: the file extensions it reads, and the Code model of each such file.
 interface language {
@@ -99,6 +99,19 @@ interface language {
         message: string,
     }
 
+    /// The runtime loading operation used by an import.
+    enum import-kind {
+        unknown,
+        %import,
+        require,
+    }
+
+    /// One import that runs when the source file runs.
+    record import-edge {
+        specifier: string,
+        kind: import-kind,
+    }
+
     /// The Code model of one source file.
     record file-model {
         /// The Source set of the file, chosen by the rules of the Language plugin.
@@ -114,10 +127,10 @@ interface language {
         /// Each Hazard line with the rule it matched; a line that matches two rules appears once per rule.
         /// Empty when `has-hazard-rules` returns false.
         hazard-lines: list,
-        /// The module specifiers of the imports that run when the file runs, such as `./greet`.
+        /// The imports that run when the file runs, such as `./greet`.
         /// A Language plugin can normalize specifiers and group imported names from the same module.
         /// Type-only imports are left out.
-        runtime-imports: list,
+        runtime-imports: list,
         /// Whether the file starts a program as shown by its source text, such as a Go `package main` file.
         /// False unless the Language plugin sets it.
         program-start: bool,
@@ -131,12 +144,14 @@ interface language {
         scope-artifact: option>,
     }
 
-    /// One runtime import to resolve: the file that imports, and the specifier it names.
+    /// One runtime import to resolve.
     record import-request {
         /// The importing file, relative to the repository root, with forward slashes.
         importer: string,
         /// The module specifier supplied by the Language plugin, which may be normalized.
         specifier: string,
+        /// The runtime loading operation used by the import.
+        kind: import-kind,
     }
 
     /// Where a runtime import leads.
diff --git a/crates/plugin-host/wit/metric.wit b/crates/plugin-host/wit/metric.wit
index 4aafe224..4f0aacea 100644
--- a/crates/plugin-host/wit/metric.wit
+++ b/crates/plugin-host/wit/metric.wit
@@ -1,4 +1,4 @@
-package codeint:plugin@0.5.0;
+package codeint:plugin@0.6.0;
 
 /// The interface a Metric plugin exports: metadata for one Metric and a function that measures a Code model.
 interface metric {
diff --git a/crates/plugin-sdk/HOW-TO.md b/crates/plugin-sdk/HOW-TO.md
index 0cd06bf7..c5b0a6fe 100644
--- a/crates/plugin-sdk/HOW-TO.md
+++ b/crates/plugin-sdk/HOW-TO.md
@@ -71,7 +71,7 @@ codeint_plugin_sdk::export_metric_plugin!(MyMetric);
 
 ## Rules and Cargo features
 
-- `codeint-plugin-sdk` wraps the `codeint:plugin@0.5.0` WIT contract (`wit/language.wit` and `wit/metric.wit`) behind safe `LanguagePlugin` and `MetricPlugin` traits with sensible defaults.
+- `codeint-plugin-sdk` wraps the `codeint:plugin@0.6.0` WIT contract (`wit/language.wit` and `wit/metric.wit`) behind safe `LanguagePlugin` and `MetricPlugin` traits with sensible defaults.
 - Default features (`default-allocator`, `panic-handler`) supply a freeing `dlmalloc::GlobalDlmalloc` allocator, panic handler, `cabi_realloc`, and C `mem*` shims on `wasm32-wasip2` with zero WASI imports.
 - Enable `features = ["std"]` (with `default-features = false`) only when targeting `wasm32-unknown-unknown` plus `wasm-tools component new`; enabling the SDK `std` feature on `wasm32-wasip2` fails at compile time, because WASI imports violate codeint's empty-`Linker` sandbox.
 - The SDK cannot see whether your own crate uses `std`: with `default-features = false` and no `no_std` attribute, a `wasm32-wasip2` build compiles and imports `wasi:*` interfaces, and codeint rejects that component at load time.
diff --git a/crates/plugin-sdk/src/language.rs b/crates/plugin-sdk/src/language.rs
index 7e3a07ce..3452c028 100644
--- a/crates/plugin-sdk/src/language.rs
+++ b/crates/plugin-sdk/src/language.rs
@@ -6,11 +6,20 @@ use alloc::vec::Vec;
 pub use crate::runtime::__bindings::language::exports::codeint::plugin::language::{
     DeclaredDep, DepKind, DependencyManifestOwner, FileDiagnostic, FileHazards, FileModel,
     FileScopeArtifact, FlaggedLine, FrameworkProfileResult, FrameworkProfileSelection, Function,
-    FunctionCoverage, HazardLine, ImportRequest, LowerError, Manifest, ManifestAnalysis,
-    PackageDependency, PackageFrameworkProfiles, ReferenceRange, Resolution, ScopeAnalysis,
-    ScopeSummary, SourceSet, SummaryField, Token, TokenKind, WorkspaceError,
+    FunctionCoverage, HazardLine, ImportEdge, ImportKind, ImportRequest, LowerError, Manifest,
+    ManifestAnalysis, PackageDependency, PackageFrameworkProfiles, ReferenceRange, Resolution,
+    ScopeAnalysis, ScopeSummary, SourceSet, SummaryField, Token, TokenKind, WorkspaceError,
 };
 
+impl From for ImportEdge {
+    fn from(specifier: String) -> Self {
+        Self {
+            specifier,
+            kind: ImportKind::Unknown,
+        }
+    }
+}
+
 impl FileModel {
     pub fn empty(source_set: SourceSet) -> FileModel {
         FileModel {
diff --git a/crates/plugin-sdk/src/lib.rs b/crates/plugin-sdk/src/lib.rs
index cdc4b447..5a154211 100644
--- a/crates/plugin-sdk/src/lib.rs
+++ b/crates/plugin-sdk/src/lib.rs
@@ -27,7 +27,7 @@ pub use runtime::link_runtime_symbols as __link_runtime_symbols;
 #[doc(hidden)]
 pub use wit_bindgen as __wit_bindgen;
 
-pub const PLUGIN_INTERFACE_VERSION: &str = "0.5.0";
+pub const PLUGIN_INTERFACE_VERSION: &str = "0.6.0";
 
 #[macro_export]
 macro_rules! export_language_plugin {
diff --git a/crates/plugin-sdk/src/metric.rs b/crates/plugin-sdk/src/metric.rs
index 2525ba86..a735846c 100644
--- a/crates/plugin-sdk/src/metric.rs
+++ b/crates/plugin-sdk/src/metric.rs
@@ -4,8 +4,8 @@ use alloc::string::String;
 use alloc::vec::Vec;
 
 pub use crate::runtime::__bindings::metric::codeint::plugin::language::{
-    FileDiagnostic, FileModel, FlaggedLine, Function, FunctionCoverage, HazardLine, Resolution,
-    SourceSet, Token, TokenKind,
+    FileDiagnostic, FileModel, FlaggedLine, Function, FunctionCoverage, HazardLine, ImportEdge,
+    ImportKind, Resolution, SourceSet, Token, TokenKind,
 };
 pub use crate::runtime::__bindings::metric::exports::codeint::plugin::metric::{
     CodeModel, Finding, LanguageFacts, Measurement, RuntimeImport, SourceFile,
diff --git a/crates/plugin-sdk/src/tests.rs b/crates/plugin-sdk/src/tests.rs
index 97a8ffd1..b8a5265a 100644
--- a/crates/plugin-sdk/src/tests.rs
+++ b/crates/plugin-sdk/src/tests.rs
@@ -99,7 +99,7 @@ fn language_plugin_trait_provides_safe_sensible_defaults() {
 
 #[test]
 fn metric_plugin_trait_defaults_version_to_one_and_builds_measurements() {
-    assert_eq!(PLUGIN_INTERFACE_VERSION, "0.5.0");
+    assert_eq!(PLUGIN_INTERFACE_VERSION, "0.6.0");
     assert_eq!(MinimalMetric::key(), "tiny_metric");
     assert_eq!(MinimalMetric::name(), "Tiny metric");
     assert_eq!(MinimalMetric::version(), 1);
diff --git a/crates/plugin-sdk/wit/language.wit b/crates/plugin-sdk/wit/language.wit
index 81891560..d4be90cb 100644
--- a/crates/plugin-sdk/wit/language.wit
+++ b/crates/plugin-sdk/wit/language.wit
@@ -1,6 +1,6 @@
 /// The Plugin interface of codeint.
 /// A change that breaks a Plugin built against this version needs a new version.
-package codeint:plugin@0.5.0;
+package codeint:plugin@0.6.0;
 
 /// The interface a Language plugin exports: the file extensions it reads, and the Code model of each such file.
 interface language {
@@ -99,6 +99,19 @@ interface language {
         message: string,
     }
 
+    /// The runtime loading operation used by an import.
+    enum import-kind {
+        unknown,
+        %import,
+        require,
+    }
+
+    /// One import that runs when the source file runs.
+    record import-edge {
+        specifier: string,
+        kind: import-kind,
+    }
+
     /// The Code model of one source file.
     record file-model {
         /// The Source set of the file, chosen by the rules of the Language plugin.
@@ -114,10 +127,10 @@ interface language {
         /// Each Hazard line with the rule it matched; a line that matches two rules appears once per rule.
         /// Empty when `has-hazard-rules` returns false.
         hazard-lines: list,
-        /// The module specifiers of the imports that run when the file runs, such as `./greet`.
+        /// The imports that run when the file runs, such as `./greet`.
         /// A Language plugin can normalize specifiers and group imported names from the same module.
         /// Type-only imports are left out.
-        runtime-imports: list,
+        runtime-imports: list,
         /// Whether the file starts a program as shown by its source text, such as a Go `package main` file.
         /// False unless the Language plugin sets it.
         program-start: bool,
@@ -131,12 +144,14 @@ interface language {
         scope-artifact: option>,
     }
 
-    /// One runtime import to resolve: the file that imports, and the specifier it names.
+    /// One runtime import to resolve.
     record import-request {
         /// The importing file, relative to the repository root, with forward slashes.
         importer: string,
         /// The module specifier supplied by the Language plugin, which may be normalized.
         specifier: string,
+        /// The runtime loading operation used by the import.
+        kind: import-kind,
     }
 
     /// Where a runtime import leads.
diff --git a/crates/plugin-sdk/wit/metric.wit b/crates/plugin-sdk/wit/metric.wit
index 4aafe224..4f0aacea 100644
--- a/crates/plugin-sdk/wit/metric.wit
+++ b/crates/plugin-sdk/wit/metric.wit
@@ -1,4 +1,4 @@
-package codeint:plugin@0.5.0;
+package codeint:plugin@0.6.0;
 
 /// The interface a Metric plugin exports: metadata for one Metric and a function that measures a Code model.
 interface metric {
diff --git a/docs/adr/0045-import-kinds-in-plugin-contract.md b/docs/adr/0045-import-kinds-in-plugin-contract.md
new file mode 100644
index 00000000..5355b59c
--- /dev/null
+++ b/docs/adr/0045-import-kinds-in-plugin-contract.md
@@ -0,0 +1,32 @@
+---
+status: accepted
+---
+
+# Plugin contract 0.6.0 carries runtime import kinds
+
+## Context
+
+The 0.5.0 Language plugin interface carries each runtime import as a specifier string.
+An ES module import and a CommonJS require can use the same specifier in the same file.
+Giving both requests the same package export conditions can select the wrong target for either request.
+
+## Decision
+
+The 0.6.0 interface carries an import kind with each runtime import and passes that kind back to the Language plugin during resolution.
+The 0.6.0 Metric interface uses the typed file model as input.
+This supersedes the interface version in [ADR 0036](./0036-plugin-contract-0-5-0.md) and keeps its sandbox rules.
+
+The host also accepts 0.5.0 Language and Metric components.
+It represents old Language plugin imports with an unknown kind and sends 0.5.0 Metric plugins their original specifier strings.
+Both versions use the same verification, capabilities, and resource limits.
+
+## Alternatives
+
+Encoding the kind inside the specifier would overload a field that callers use as source text.
+Supporting only the new version would require every external plugin to rebuild before upgrading codeint.
+
+## Consequences
+
+TypeScript and JavaScript resolve each edge with the package condition for its syntax.
+Existing 0.5.0 components continue to load.
+See [Plugin migration](../plugins.md#moving-a-plugin-from-050-to-060) for the steps to adopt the new interface.
diff --git a/docs/guide/hazards.md b/docs/guide/hazards.md
index d443d379..08e72e3f 100644
--- a/docs/guide/hazards.md
+++ b/docs/guide/hazards.md
@@ -19,7 +19,7 @@ Every other Metric in codeint measures Software entropy, the maintainability cos
 - **No Reference range**: Hazards has no published Reference range.
 
 Currently, the built-in `sql` Language plugin defines 32 Hazard line rules (27 statement rules and 5 schema-backed rules), and the built-in `shell` Language plugin defines 10.
-External WebAssembly Language plugins can also export Hazard line rules through `codeint:plugin@0.5.0`; see [docs/plugins.md](../plugins.md).
+External WebAssembly Language plugins can also export Hazard line rules through `codeint:plugin@0.6.0`; see [docs/plugins.md](../plugins.md).
 See the complete 32-rule SQL list in [docs/reference.md#sql](../reference.md#sql) and the 10-rule Shell list in [docs/reference.md#shell](../reference.md#shell).
 
 ## Configuration
diff --git a/docs/guide/philosophy-and-architecture.md b/docs/guide/philosophy-and-architecture.md
index e416ac7e..8a9e997b 100644
--- a/docs/guide/philosophy-and-architecture.md
+++ b/docs/guide/philosophy-and-architecture.md
@@ -82,5 +82,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, Hazard 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` `