diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 48d10a92..cde65f01 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -538,8 +538,8 @@ or removing a command fails until the table changes in the same commit. | `build.decodeConfiguration` | Validate native source identities, raw/effective values and XML bindings | | `build.prepareRunPlan` | Plan Provider-owned application/service/task preparation from a model target | | `build.decodeRunPreparation` | Validate portable launch data before the native Run host starts a process | -| `build.testDiscoveryPlan` | Plan opt-in Provider test discovery for an instance | -| `build.decodeTestDiscovery` | Validate, deduplicate and order Provider test selectors | +| `build.testDiscoveryPlan` | Plan opt-in command or Provider test discovery for an instance | +| `build.decodeTestDiscovery` | Validate, deduplicate and order discovered test selectors | | `build.runEntrypointsPlan` | Plan a Provider request for the run entrypoints of one source file (`buildProviders` 1) | | `build.decodeRunEntrypoints` | Validate and deduplicate the run entrypoints a Provider named | | `build.dependencyPlan` | Expand the command that prints a project's dependency tree, or the request a build provider answers | @@ -5281,8 +5281,8 @@ and the directories are absolute host paths used only as substitution text. | `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The instance is the deepest one whose root holds the working directory, or the only one; `plugin.build.invalidSelection` when several exist and none holds it or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call | | `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?}`, with `task` and `workingDirectory` as `runConfig.beforeLaunch` returned the step | `plan` as `build.taskPlan` returns it plus `beforeLaunchTask: {pluginID, buildSystemID, type}`: the global arguments, then the task's `arguments` with the saved field values and the instance's options, at the step's working directory with the options' environment, as a `task` execution. The instance is chosen as for `build.runConfigurationPlan`; `plugin.build.invalidSelection` when several exist and none holds the working directory or the task belongs to another plugin or build system, `plugin.build.unavailable` when the task is no longer declared, `plugin.build.invalidBeforeLaunchTask` with `field: values.` when a saved value no longer fits. A working directory outside the workspace fails the call | | `build.testPlan` | plan fields plus `project?`, `target?`, `suite?`, `case?`, `userArguments?`, `projects?` (the model's project directories) | command plan or `provider: {method: "lithe/build/test", params}`, plus `results`: `null`, `{ decoder, reports }` with workspace-relative globs (for the selected project, or for the root and every listed project when none is selected), or command-only `{ decoder: "hostIntegration" }`. Command filters that templates cannot place, such as a case without its suite when the tool only addresses `Suite#case`, are `plugin.build.invalidSelection`; Provider filters remain separate typed values and must be declared supported | -| `build.testDiscoveryPlan` | common plan fields plus `refresh?`, `tool?`; no project/output file | `plan.provider` for `lithe/build/discoverTests`, only with `test.discovery: true`, using the same effective options and effect metadata | -| `build.decodeTestDiscovery` | common plan fields plus canonical `result` | `discovery.tests` with validated `{id, suite, case, project?, target?}` selectors; bounded at 10,000 items/32 MiB, deterministic and exactly runnable; malformed replies reject in full | +| `build.testDiscoveryPlan` | Common plan fields, plus a fresh absolute `outputFile` for `test.discoveryCommand`, or optional `refresh` and `tool` for `test.discovery: true`. No project selection. | Command plan with argv, environment, instance working directory, `output: "outputFile"`, `decoder: "litheTestDiscovery"` and effect metadata, or `plan.provider` for `lithe/build/discoverTests` with the effective options. | +| `build.decodeTestDiscovery` | Original common plan fields plus the same `outputFile` for a completed command or canonical inline `result` for a Provider. | `discovery.tests` with validated `{id, suite, case, project?, target?}` selectors. Bounded at 10,000 items and 32 MiB, deterministic and exactly runnable. Malformed results reject in full with `plugin.build.invalidOutput`. | | `build.runEntrypointsPlan` | common plan fields plus `file` (workspace-relative, inside the instance), `refresh?`, `tool?`; no project/output file | `plan.provider` for `lithe/build/runEntrypoints` with `file`, only when a run declares `entrypoints: true`; decoder `litheRunEntrypoints` | | `build.decodeRunEntrypoints` | common plan fields plus canonical `result` | `entrypoints.entrypoints`: `[{run, name, entrypoint, project:{name, path}}]` in the provider's order without exact duplicates; at most 64; each names an entrypoint run, a 1–256 byte name, a 1–4,096 byte entrypoint and a project inside the instance; malformed replies reject in full with `plugin.build.invalidOutput` | | `build.prepareRunPlan` | common plan fields, `run`, required `project`, `target` (required for a target run, refused for an entrypoint run), `userArguments?`, `optionOverrides?`, `launchOptions?`, `workspaceRoot?` (required for an explicit launch cwd); no output file | `plan.provider` for `lithe/build/prepareRun`, selected declaration/tags/paths/options validated; typed launch options must match the run's declared execution kind, a service or task run requires them, and an entrypoint run requires `launchOptions.entrypoint` and sends no `target` | @@ -6935,6 +6935,7 @@ a code has one meaning across every contribution with that lifecycle: | `debugAdapter/start` | `debugAdapters[]` | process start | | `lithe/build/model` | `buildSystems[].model` command source | command run | | `lithe/build/dependencies` | `buildSystems[].dependencies` command source | command run | +| `lithe/build/discoverTests` | `buildSystems[].test.discoveryCommand` | command run | | `commandInstaller/install` | `commandInstallers[]` installation the user confirmed; `decode` when a provided command is missing after a successful exit | command run | | `stage` | Process start | Command run | diff --git a/rust/crates/build/src/commands.rs b/rust/crates/build/src/commands.rs index 5e284680..89af3faa 100644 --- a/rust/crates/build/src/commands.rs +++ b/rust/crates/build/src/commands.rs @@ -302,7 +302,7 @@ pub fn build_test_plan_command(payload: Value) -> Result( payload: Value, ) -> Result { diff --git a/rust/crates/build/src/decode.rs b/rust/crates/build/src/decode.rs index 5081de5d..2668c0d0 100644 --- a/rust/crates/build/src/decode.rs +++ b/rust/crates/build/src/decode.rs @@ -9,6 +9,7 @@ use lithe_plugin_model::{PluginRejection, Validation}; use lithe_workspace::{self as workspace, fs}; use serde_json::Value; +use std::io::Read; use std::path::{Component, Path, PathBuf}; use std::time::UNIX_EPOCH; @@ -62,6 +63,18 @@ fn first_line(text: &str) -> &str { /// Reads a UTF-8 file up to the output bound. pub(crate) fn read_bounded(path: &Path) -> Validation { + String::from_utf8(read_file_bytes(path)?) + .map_err(|_| invalid_output("The build tool output is not UTF-8.")) +} + +/// Bytes of a file up to the output bound, or `None` when it is absent, not +/// a regular file, or too large. +pub(crate) fn read_bytes_bounded(path: &Path) -> Option> { + // Sync fingerprints treat an unreadable input as absent. + read_file_bytes(path).ok() +} + +fn read_file_bytes(path: &Path) -> Validation> { let metadata = fs::metadata(path) .map_err(|_| invalid_output("The build tool did not write its output file."))?; if !metadata.is_file() || metadata.len() > MAX_OUTPUT_BYTES as u64 { @@ -69,17 +82,22 @@ pub(crate) fn read_bounded(path: &Path) -> Validation { "The build tool output file is missing or too large.", )); } - fs::read_to_string(path).map_err(|_| invalid_output("The build tool output is not UTF-8.")) + let file = fs::File::open(path) + .map_err(|_| invalid_output("The build tool output file could not be opened."))?; + read_output(file, metadata.len() as usize) } -/// Bytes of a file up to the output bound, or `None` when it is absent, not -/// a regular file, or too large. -pub(crate) fn read_bytes_bounded(path: &Path) -> Option> { - let metadata = fs::metadata(path).ok()?; - if !metadata.is_file() || metadata.len() > MAX_OUTPUT_BYTES as u64 { - return None; +fn read_output(reader: impl Read, observed_size: usize) -> Validation> { + let mut bytes = Vec::with_capacity(observed_size + 1); + // The opened file may have grown since the metadata check. + reader + .take(MAX_OUTPUT_BYTES as u64 + 1) + .read_to_end(&mut bytes) + .map_err(|_| invalid_output("The build tool output file could not be read."))?; + if bytes.len() > MAX_OUTPUT_BYTES { + return Err(invalid_output("The build tool output is too large.")); } - fs::read(path).ok() + Ok(bytes) } /// Bounds a host-provided output text before it is parsed line by line. @@ -428,6 +446,29 @@ fn is_current(path: &Path, not_before_millis: Option) -> bool { mod tests { use super::*; + #[test] + fn output_read_enforces_the_limit_even_if_the_file_grows() { + let limit = MAX_OUTPUT_BYTES as u64; + let at_limit = std::io::repeat(b'x').take(limit); + assert_eq!( + read_output(at_limit, MAX_OUTPUT_BYTES).unwrap().len(), + MAX_OUTPUT_BYTES + ); + + // Metadata reported an in-budget size, but the stream contains more. + let mut over_limit = std::io::repeat(b'x').take(limit + 2); + let rejected = match read_output(&mut over_limit, MAX_OUTPUT_BYTES) { + Ok(bytes) => panic!("accepted an oversized output of {} bytes", bytes.len()), + Err(error) => error, + }; + assert_eq!(rejected.code, "plugin.build.invalidOutput"); + assert_eq!( + over_limit.limit(), + 1, + "read past the extra byte needed to detect overflow" + ); + } + #[test] fn wildcards_match_within_a_segment() { assert!(wildcard("TEST-*.xml", "TEST-demo.OrderTest.xml")); diff --git a/rust/crates/build/src/manifest/checks.rs b/rust/crates/build/src/manifest/checks.rs index 3a089ff1..f28961f4 100644 --- a/rust/crates/build/src/manifest/checks.rs +++ b/rust/crates/build/src/manifest/checks.rs @@ -122,6 +122,9 @@ fn program(build_system: &BuildSystemDeclaration) -> Value { review["source"] = json!("provider"); } if test.discovery { review["discovery"] = json!(true); } + if let Some(command) = &test.discovery_command { + review["discoveryCommand"] = json!(command); + } review }), "model": model, diff --git a/rust/crates/build/src/manifest/options.rs b/rust/crates/build/src/manifest/options.rs index 3d3a533a..06ada0c0 100644 --- a/rust/crates/build/src/manifest/options.rs +++ b/rust/crates/build/src/manifest/options.rs @@ -232,6 +232,12 @@ impl BuildSystemDeclaration { } if let Some(test) = &self.test { lists.push((format!("{field}.test.arguments"), &test.arguments)); + if let Some(command) = &test.discovery_command { + lists.push(( + format!("{field}.test.discoveryCommand.arguments"), + &command.arguments, + )); + } } if let Some(ModelSource::Command { arguments, .. }) = &self.model { lists.push((format!("{field}.model.arguments"), arguments)); diff --git a/rust/crates/build/src/manifest/testing.rs b/rust/crates/build/src/manifest/testing.rs index e7157c87..6f7edef7 100644 --- a/rust/crates/build/src/manifest/testing.rs +++ b/rust/crates/build/src/manifest/testing.rs @@ -33,11 +33,29 @@ pub(crate) struct TestDeclaration { /// The provider can enumerate exact selectors for the native test tree. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub(crate) discovery: bool, + /// A separate discovery command that writes a canonical selector document. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) discovery_command: Option, pub(crate) arguments: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) results: Option, } +impl TestDeclaration { + pub(crate) fn discovers_tests(&self) -> bool { + self.discovery || self.discovery_command.is_some() + } +} + +/// Command input plus the effect facts the host needs before launch. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct TestDiscoveryCommand { + pub(crate) arguments: Vec, + pub(crate) executes_project_code: bool, + pub(crate) may_use_network: bool, +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub(crate) enum TestFilter { @@ -62,6 +80,13 @@ pub(crate) enum TestResultsSource { } impl BuildSystemDeclaration { + /// Whether the declaration needs buildSystems 1 for command-based discovery. + pub fn has_test_discovery_command(&self) -> bool { + self.test + .as_ref() + .is_some_and(|test| test.discovery_command.is_some()) + } + pub(crate) fn validate_test( &mut self, field: &str, @@ -95,16 +120,39 @@ impl BuildSystemDeclaration { test.selector_kinds.sort(); test.filters.sort(); test.filters.dedup(); - if test.discovery - && (test.source != TaskSource::Provider - || !test.filters.contains(&TestFilter::Suite) + if test.discovers_tests() + && (!test.filters.contains(&TestFilter::Suite) || !test.filters.contains(&TestFilter::Case)) { return Err(invalid( &field, - "Test discovery requires a provider and suite/case filters.", + "Test discovery requires suite and case filters.", )); } + if test.discovery + && (test.source != TaskSource::Provider || test.discovery_command.is_some()) + { + return Err(invalid( + &field, + "Provider test discovery requires provider tests and no discoveryCommand.", + )); + } + if let Some(command) = &test.discovery_command { + let field = format!("{field}.discoveryCommand"); + let arguments = format!("{field}.arguments"); + check_argument_count(&command.arguments, &arguments)?; + template::validate_arguments( + &command.arguments, + &Allowed { + root: true, + host_directories: true, + options: Some(options), + ..Allowed::none() + }, + &arguments, + )?; + check_output_channel(OutputChannel::OutputFile, &command.arguments, &field)?; + } if test.source == TaskSource::Provider { if !test.arguments.is_empty() { return Err(invalid(&field, "Provider tests require empty arguments.")); diff --git a/rust/crates/build/src/outputs.rs b/rust/crates/build/src/outputs.rs index ae1f3cbe..5e5bf8f7 100644 --- a/rust/crates/build/src/outputs.rs +++ b/rust/crates/build/src/outputs.rs @@ -66,7 +66,7 @@ fn message_text(value: &str) -> Option { } /// The text a finished command left: its stdout, or the file it wrote. -fn command_output( +pub(crate) fn command_output( channel: OutputChannel, output: Option<&str>, output_file: Option<&str>, diff --git a/rust/crates/build/src/plans.rs b/rust/crates/build/src/plans.rs index f39ce2d0..8626cea2 100644 --- a/rust/crates/build/src/plans.rs +++ b/rust/crates/build/src/plans.rs @@ -11,8 +11,8 @@ use super::decode::{self, join_relative}; use super::manifest::{ BuildExecution, BuildSystemDeclaration, DependenciesSource, ExecutableCandidate, ModelSource, - OutputChannel, ProviderDeclaration, RunDeclaration, Scope, TaskSource, TestFilter, - TestResultsSource, WorkingDirectory, + OutputChannel, ProviderDeclaration, RunDeclaration, Scope, TaskSource, TestDeclaration, + TestFilter, TestResultsSource, WorkingDirectory, }; use super::model::{entry_id, BuildModel, ModelProject}; use super::options::{self, OptionContribution}; @@ -106,6 +106,14 @@ pub(crate) struct TaskPlanRequest { pub(crate) struct TestPlanRequest { #[serde(flatten)] pub(crate) base: PlanBase, + #[serde(flatten)] + pub(crate) run: TestRunRequest, +} + +/// Selection, arguments and report roots of one test run. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct TestRunRequest { #[serde(default)] pub(crate) project: Option, #[serde(default)] @@ -134,7 +142,7 @@ pub(crate) struct OutputPlanRequest { pub(crate) base: PlanBase, #[serde(default)] pub(crate) project: Option, - /// Fresh absolute host-owned path, for `"output": "outputFile"`. + /// Fresh absolute host-owned path, for `"output": "outputFile"` commands. #[serde(default)] pub(crate) output_file: Option, /// Provider sources only: the user asked to reload, or the host reloads @@ -216,6 +224,14 @@ pub(crate) struct Selection { } impl Selection { + /// Typed test selectors retain the workspace-relative path across round trips. + pub(crate) fn test_selector(&self) -> Value { + json!({ + "name": self.name, "path": self.path, + "tags": self.tags, "properties": self.properties, + }) + } + fn selected(&self) -> Selected<'_> { Selected { name: &self.name, @@ -629,19 +645,39 @@ pub(crate) fn test_discovery_plan( build_system: &BuildSystemDeclaration, request: &OutputPlanRequest, ) -> Validation { - if !build_system + let test = build_system .test .as_ref() - .is_some_and(|test| test.discovery) - { - return Err(unavailable(build_system, "test discovery")); - } - if request.project.is_some() || request.output_file.is_some() { + .filter(|test| test.discovers_tests()) + .ok_or_else(|| unavailable(build_system, "test discovery"))?; + if request.project.is_some() { return Err(invalid_selection( "Test discovery addresses the whole instance.", )); } let context = PlanContext::new(build_system, &request.base)?; + if let Some(command) = &test.discovery_command { + let output = OutputChannel::OutputFile; + let output_file = output_file(request.output_file.as_deref(), output)?; + let mut values = context.values(&[]); + values.output_file = output_file.as_deref(); + return context.plan( + &command.arguments, + &values, + BuildExecution::Task, + output_extra( + output, + json!("litheTestDiscovery"), + command.executes_project_code, + command.may_use_network, + ), + ); + } + if request.output_file.is_some() { + return Err(invalid_selection( + "A provider returns test discovery directly.", + )); + } Ok(context.provider_plan( declared_provider(build_system)?, "lithe/build/discoverTests", @@ -650,13 +686,13 @@ pub(crate) fn test_discovery_plan( )) } -/// `build.testPlan`: the command and where its results will be. /// Whether a selected target carries one of the declared tags; no tags /// accept every target. fn target_matches(target: Option<&Selection>, tags: &[String]) -> bool { target.is_none_or(|target| tags.is_empty() || target.tags.iter().any(|tag| tags.contains(tag))) } +/// `build.testPlan`: the command and where its results will be. pub(crate) fn test_plan( build_system: &BuildSystemDeclaration, request: &TestPlanRequest, @@ -666,6 +702,22 @@ pub(crate) fn test_plan( .as_ref() .ok_or_else(|| unavailable(build_system, "tests"))?; let context = PlanContext::new(build_system, &request.base)?; + test_plan_with_selection(&context, test, &request.run).map(|(plan, _)| plan) +} + +/// Normalized test selections shared by command and provider plans. +pub(crate) struct TestSelection { + pub(crate) project: Option, + pub(crate) target: Option, +} + +/// Validates and expands the plan before returning its normalized selection. +pub(crate) fn test_plan_with_selection( + context: &PlanContext<'_>, + test: &TestDeclaration, + request: &TestRunRequest, +) -> Validation<(Value, TestSelection)> { + let build_system = context.build_system; if test.source == TaskSource::Provider { check_argument_limits(&request.user_arguments)?; } else { @@ -814,13 +866,7 @@ pub(crate) fn test_plan( } for (name, selected) in [("project", &project), ("target", &target)] { if let Some(selected) = selected { - params.insert( - name.to_string(), - json!({ - "name": selected.name, "path": selected.path, - "tags": selected.tags, "properties": selected.properties - }), - ); + params.insert(name.to_string(), selected.test_selector()); } } let mut plan = context.provider_plan( @@ -832,9 +878,10 @@ pub(crate) fn test_plan( plan.as_object_mut() .expect("provider plan is an object") .extend(extra); - return Ok(plan); + return Ok((plan, TestSelection { project, target })); } - context.plan(&test.arguments, &values, BuildExecution::Task, extra) + let plan = context.plan(&test.arguments, &values, BuildExecution::Task, extra)?; + Ok((plan, TestSelection { project, target })) } fn output_extra( diff --git a/rust/crates/build/src/test_discovery.rs b/rust/crates/build/src/test_discovery.rs index 0c67337a..a3d5b1d0 100644 --- a/rust/crates/build/src/test_discovery.rs +++ b/rust/crates/build/src/test_discovery.rs @@ -1,28 +1,32 @@ -//! Normalizes provider-owned test selectors without inferring test semantics. +//! Normalizes discovered test selectors without inferring test semantics. //! Every item must round-trip through the ordinary typed test plan, so discovery //! cannot expose an item the declaration is unable to run exactly. use super::decode::{invalid_output, MAX_OUTPUT_BYTES}; -use super::manifest::BuildSystemDeclaration; -use super::plans::{self, PlanBase, SelectedEntity, TestPlanRequest}; +use super::manifest::{BuildSystemDeclaration, OutputChannel}; +use super::outputs; +use super::plans::{self, PlanBase, SelectedEntity, TestRunRequest}; use lithe_plugin_model::Validation; use serde::Deserialize; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use std::collections::BTreeMap; -/// Version of the `litheTestDiscovery` document a provider returns. +/// Version of the `litheTestDiscovery` document. const DISCOVERY_VERSION: u64 = 0; const MAX_TESTS: usize = 10_000; -/// The plan's configuration and a provider's canonical discovery result. +/// The plan's configuration and the discovery source's canonical result. #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct DecodeTestDiscoveryRequest { #[serde(flatten)] pub(crate) base: PlanBase, - pub(crate) result: Value, + /// Provider discovery's inline JSON-RPC result. + pub(crate) result: Option, + /// The fresh host-owned output path passed to the command plan. + pub(crate) output_file: Option, } /// Selectors have no host-generated command or cached upstream project model. @@ -40,20 +44,44 @@ pub(crate) fn decode( build_system: &BuildSystemDeclaration, request: &DecodeTestDiscoveryRequest, ) -> Validation { - if !build_system + let test = build_system .test .as_ref() - .is_some_and(|test| test.discovery) - { - return Err(plans::unavailable(build_system, "test discovery")); - } + .filter(|test| test.discovers_tests()) + .ok_or_else(|| plans::unavailable(build_system, "test discovery"))?; // Validate host context even for a valid empty discovery result. - plans::PlanContext::new(build_system, &request.base)?; - let result = &request.result; - if serde_json::to_vec(result).map_or(usize::MAX, |bytes| bytes.len()) > MAX_OUTPUT_BYTES - || result["format"] != "litheTestDiscovery" - || result["version"] != DISCOVERY_VERSION - { + let context = plans::PlanContext::new(build_system, &request.base)?; + let command_result; + let result = if test.discovery_command.is_some() { + if request.result.is_some() { + return Err(plans::invalid_selection( + "Command test discovery reads only outputFile.", + )); + } + let text = outputs::command_output( + OutputChannel::OutputFile, + None, + request.output_file.as_deref(), + )?; + command_result = serde_json::from_str::(&text) + .map_err(|_| invalid_output("Invalid test discovery document."))?; + &command_result + } else { + if request.output_file.is_some() { + return Err(plans::invalid_selection( + "A provider returns test discovery directly.", + )); + } + let result = request + .result + .as_ref() + .ok_or_else(|| invalid_output("Invalid test discovery document."))?; + if serde_json::to_vec(result).map_or(usize::MAX, |bytes| bytes.len()) > MAX_OUTPUT_BYTES { + return Err(invalid_output("Invalid test discovery document.")); + } + result + }; + if result["format"] != "litheTestDiscovery" || result["version"] != DISCOVERY_VERSION { return Err(invalid_output("Invalid test discovery document.")); } let tests = result["tests"] @@ -61,29 +89,27 @@ pub(crate) fn decode( .filter(|tests| tests.len() <= MAX_TESTS) .ok_or_else(|| invalid_output("Test discovery requires at most 10000 selectors."))?; let mut normalized = BTreeMap::new(); - for test in tests { - let selector: Selector = serde_json::from_value(test.clone()) + for item in tests { + let selector: Selector = serde_json::from_value(item.clone()) .map_err(|_| invalid_output("Invalid test selector."))?; - let plan = plans::test_plan( - build_system, - &TestPlanRequest { - selector_kind: None, - selectors: Vec::new(), - base: request.base.clone(), - project: selector.project, - target: selector.target, - suite: Some(selector.suite), - case: Some(selector.case), - user_arguments: vec![], - projects: vec![], - }, - ) - .map_err(|_| invalid_output("A discovered selector cannot be run by this declaration."))?; - let params = &plan["provider"]["params"]; - let mut selected = json!({"suite":params["suite"],"case":params["case"]}); - for field in ["project", "target"] { - if let Some(value) = params.get(field) { - selected[field] = value.clone(); + let request = TestRunRequest { + selector_kind: None, + selectors: Vec::new(), + project: selector.project, + target: selector.target, + suite: Some(selector.suite), + case: Some(selector.case), + user_arguments: vec![], + projects: vec![], + }; + let (_, selection) = + plans::test_plan_with_selection(&context, test, &request).map_err(|_| { + invalid_output("A discovered selector cannot be run by this declaration.") + })?; + let mut selected = json!({"suite":request.suite,"case":request.case}); + for (field, entity) in [("project", selection.project), ("target", selection.target)] { + if let Some(entity) = entity { + selected[field] = entity.test_selector(); } } let key = serde_json::to_string(&selected).expect("selector is JSON"); diff --git a/rust/crates/build/src/tree.rs b/rust/crates/build/src/tree.rs index 52bd18ca..4c2b0cab 100644 --- a/rust/crates/build/src/tree.rs +++ b/rust/crates/build/src/tree.rs @@ -580,7 +580,7 @@ impl<'a> Index<'a> { .build_system .test .as_ref() - .is_some_and(|test| test.discovery); + .is_some_and(|test| test.discovers_tests()); if instance && discovers_tests && budget.take() { let key = format!("{container}{KEY_SEPARATOR}tests"); nodes.push(TreeNode::new(NodeKind::Tests, key)); diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 970d63fe..00c235ec 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -478,9 +478,9 @@ pub enum BuildCommand { DecodeDebugPreparation, /// Validates prepared launch data (`build.decodeRunPreparation`). DecodeRunPreparation, - /// Plans provider-owned test discovery (`build.testDiscoveryPlan`). + /// Plans command or provider test discovery (`build.testDiscoveryPlan`). TestDiscoveryPlan, - /// Validates provider-owned test selectors (`build.decodeTestDiscovery`). + /// Validates discovered test selectors (`build.decodeTestDiscovery`). DecodeTestDiscovery, /// Asks a provider for the entrypoints of a file (`build.runEntrypointsPlan`). RunEntrypointsPlan, diff --git a/rust/crates/core/src/tests/build_systems.rs b/rust/crates/core/src/tests/build_systems.rs index 5596a762..ead95ab0 100644 --- a/rust/crates/core/src/tests/build_systems.rs +++ b/rust/crates/core/src/tests/build_systems.rs @@ -2320,6 +2320,190 @@ fn provider_test_discovery_is_bounded_deterministic_and_runnable() { assert_eq!(validate(missing_filter)["status"], "rejected"); } +const COMMAND_TEST_DISCOVERY_MANIFEST: &str = + contract_file!("fixtures/build-systems/build-command-test-discovery.plugin.json"); +const COMMAND_TEST_DISCOVERY_OUTPUT: &str = + contract_file!("fixtures/build-systems/build-command-test-discovery.json"); + +#[test] +fn command_test_discovery_requires_host_support_and_reviews_the_command() { + let manifest: Value = serde_json::from_str(COMMAND_TEST_DISCOVERY_MANIFEST).unwrap(); + for (versions, status) in [(json!([0]), "rejected"), (json!([0, 1]), "ok")] { + let validated = validate_command(json!({ + "manifest": manifest, "hostCapabilities": {"buildSystems": versions}, + })) + .unwrap(); + assert_eq!(validated["status"], status, "{validated}"); + } + + let review = install_review_command(json!({"manifest":manifest})).unwrap(); + let program = &review["review"]["programs"][0]; + assert_eq!(program["kind"], "buildSystem"); + assert_eq!( + program["test"]["discoveryCommand"], + manifest["buildSystems"][0]["test"]["discoveryCommand"], + ); + + let mut old = manifest.clone(); + old["requires"]["buildSystems"] = json!(0); + let refused = validate(old); + assert_eq!(refused["error"]["field"], "requires.buildSystems"); + + for (field, value) in [ + ("/test/discovery", json!(true)), + ("/test/filters", json!(["suite"])), + ("/test/discoveryCommand/arguments", json!(["discover"])), + ( + "/test/discoveryCommand/arguments", + json!(["${test.suite}", "${outputFile}"]), + ), + ( + "/test/discoveryCommand/arguments", + json!(["${optionArguments}", "${outputFile}"]), + ), + ] { + let mut broken = manifest["buildSystems"][0].clone(); + if field == "/test/discovery" { + broken["test"]["discovery"] = value; + } else { + *broken.pointer_mut(field).unwrap() = value; + } + let mut invalid = manifest.clone(); + invalid["buildSystems"][0] = broken; + let rejected = validate(invalid); + assert_eq!(rejected["status"], "rejected", "{field}: {rejected}"); + } +} + +#[test] +fn command_test_discovery_plans_a_file_and_round_trips_exact_selectors() { + let manifest: Value = serde_json::from_str(COMMAND_TEST_DISCOVERY_MANIFEST).unwrap(); + let workspace = TemporaryWorkspace::new("command-test-discovery"); + let output_file = workspace.0.join("output with spaces.json"); + let request = json!({ + "root": ".", + "options": {"offline": true}, + "pluginDirectory": workspace.root(), + "workspaceStateDirectory": workspace.root(), + "outputFile": output_file, + }); + let payload = + |request: &Value| json!({"manifest":manifest, "buildSystemID":"sample", "request":request}); + + let plan = build_test_discovery_plan_command::(payload(&request)).unwrap(); + assert_eq!(plan["status"], "ok", "{plan}"); + assert_eq!(plan["plan"]["output"], "outputFile"); + assert_eq!(plan["plan"]["decoder"], "litheTestDiscovery"); + assert_eq!(plan["plan"]["workingDirectory"], "."); + assert_eq!(plan["plan"]["executesProjectCode"], true); + assert_eq!(plan["plan"]["mayUseNetwork"], false); + assert!(plan["plan"].get("provider").is_none()); + assert_eq!( + plan["plan"]["arguments"], + json!([ + "--plain", + "--offline", + "discover", + format!("{}/discover.v1", workspace.root()), + format!("--state={}", workspace.root()), + output_file, + ]), + ); + for (field, value) in [ + ("outputFile", json!(null)), + ("outputFile", json!("relative-output.json")), + ("project", json!({"name":"app","path":"app"})), + ] { + let mut unsafe_request = request.clone(); + unsafe_request[field] = value; + let rejected = + build_test_discovery_plan_command::(payload(&unsafe_request)).unwrap(); + assert_eq!(rejected["error"]["code"], "plugin.build.invalidSelection"); + } + + fs::write(&output_file, COMMAND_TEST_DISCOVERY_OUTPUT).unwrap(); + let discovered = build_decode_test_discovery_command::(payload(&request)).unwrap(); + assert_eq!(discovered["status"], "ok", "{discovered}"); + let tests = discovered["discovery"]["tests"].as_array().unwrap(); + assert_eq!(tests.len(), 2); + assert_ne!(tests[0]["id"], tests[1]["id"]); + let app = tests + .iter() + .find(|item| item["project"]["path"] == "app") + .unwrap(); + assert_eq!(app["target"]["path"], "app"); + for test in tests { + let mut run = test.clone(); + run["root"] = json!("."); + let plan = build_test_plan_command::(payload(&run)).unwrap(); + assert_eq!(plan["status"], "ok", "{plan}"); + let argv = plan["plan"]["arguments"].as_array().unwrap(); + assert!(argv.contains(&json!("--suite=ExampleSuite")), "{argv:?}"); + assert!( + argv.contains(&json!("--case=checks spaces # [exact]")), + "{argv:?}" + ); + } + + let mut reordered: Value = serde_json::from_str(COMMAND_TEST_DISCOVERY_OUTPUT).unwrap(); + let tests = reordered["tests"].as_array_mut().unwrap(); + tests.reverse(); + tests.push(tests[0].clone()); + fs::write(&output_file, reordered.to_string()).unwrap(); + assert_eq!( + build_decode_test_discovery_command::(payload(&request)).unwrap(), + discovered, + ); + + let tree = + crate::build::build_model_tree_command::(payload(&json!({"model":{}}))).unwrap(); + assert_eq!(tree["status"], "ok", "{tree}"); + let nodes = tree["tree"]["nodes"].as_array().unwrap(); + assert!(nodes.iter().any(|node| node["kind"] == "tests"), "{tree}"); +} + +#[test] +fn command_test_discovery_refuses_malformed_files_and_unrunnable_selectors() { + let mut manifest: Value = serde_json::from_str(COMMAND_TEST_DISCOVERY_MANIFEST).unwrap(); + let workspace = TemporaryWorkspace::new("command-test-discovery-invalid"); + let output_file = workspace.0.join("output.json"); + let decode = |manifest: &Value| { + build_decode_test_discovery_command::(json!({ + "manifest": manifest, "buildSystemID": "sample", + "request": {"root": ".", "outputFile": output_file}, + })) + .unwrap() + }; + let cases = [ + b"\xff".as_slice(), + br#"{"format":"litheTestDiscovery","version":0,"tests":[{"suite":"ok","case":"ok","project":{"name":"escape","path":"../escape"}}]}"#.as_slice(), + br#"{"format":"litheTestDiscovery","version":1,"tests":[]}"#.as_slice(), + ]; + let missing = decode(&manifest); + assert_eq!(missing["error"]["code"], "plugin.build.invalidOutput"); + for bytes in cases { + fs::write(&output_file, bytes).unwrap(); + let rejected = decode(&manifest); + assert_eq!( + rejected["error"]["code"], "plugin.build.invalidOutput", + "{rejected}" + ); + } + + // The declaration may permit suite reruns while lacking an exact case + // command. A discovery result must not silently widen to the suite. + manifest["buildSystems"][0]["test"]["arguments"] + .as_array_mut() + .unwrap() + .pop(); + fs::write(&output_file, COMMAND_TEST_DISCOVERY_OUTPUT).unwrap(); + let rejected = decode(&manifest); + assert_eq!( + rejected["error"]["code"], "plugin.build.invalidOutput", + "{rejected}" + ); +} + /// buildProviders 1: a provider names the entrypoints of a file, each of which an /// entrypoint run starts in its project without a target. Malformed answers are /// refused whole, and a manifest needs buildProviders 1 to declare such a run. diff --git a/rust/crates/diagnostics/src/plugin_operations.rs b/rust/crates/diagnostics/src/plugin_operations.rs index 972aafb6..3acd2b8e 100644 --- a/rust/crates/diagnostics/src/plugin_operations.rs +++ b/rust/crates/diagnostics/src/plugin_operations.rs @@ -105,6 +105,12 @@ pub static BUILD_MODEL: Contribution = Contribution { lifecycle: Lifecycle::CommandRun, }; +/// `buildSystems[].test.discoveryCommand`: one test discovery command. +pub static BUILD_TEST_DISCOVERY: Contribution = Contribution { + operation: "lithe/build/discoverTests", + lifecycle: Lifecycle::CommandRun, +}; + /// `buildSystems[].dependencies` with a command source: one dependency tree load. pub static BUILD_DEPENDENCIES: Contribution = Contribution { operation: "lithe/build/dependencies", @@ -125,6 +131,7 @@ pub static CONTRIBUTIONS: &[&Contribution] = &[ &LANGUAGE_SERVER_START, &DEBUG_ADAPTER_START, &BUILD_MODEL, + &BUILD_TEST_DISCOVERY, &BUILD_DEPENDENCIES, &COMMAND_INSTALLER_INSTALL, ]; @@ -438,6 +445,7 @@ mod tests { ("languageServer/start", Lifecycle::ProcessStart), ("debugAdapter/start", Lifecycle::ProcessStart), ("lithe/build/model", Lifecycle::CommandRun), + ("lithe/build/discoverTests", Lifecycle::CommandRun), ("lithe/build/dependencies", Lifecycle::CommandRun), ("commandInstaller/install", Lifecycle::CommandRun), ]; diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index fcd3bddd..097043ba 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -127,6 +127,20 @@ impl DeclarativePluginManifest { "Entrypoint runs need buildProviders 1.", )); } + if self + .build_systems + .iter() + .any(|system| system.has_test_discovery_command()) + && self + .requires + .get(capabilities::BUILD_SYSTEMS) + .is_none_or(|version| *version < 1) + { + return Err(invalid( + "requires.buildSystems", + "Command test discovery needs buildSystems 1.", + )); + } if self.tool_definitions.iter().any(|definition| { definition.get("category").is_some() || definition.get("audience").is_some() }) && self diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index 42f9e1b8..3ce7d39f 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -64,6 +64,7 @@ pub const SOURCE_SETTINGS: &str = "sourceSettings"; /// settings regions, and commands. pub const UI: &str = "ui"; /// Declarative build detection, models, and command plans. +/// Version 1 adds command-based test discovery. pub const BUILD_SYSTEMS: &str = "buildSystems"; /// `buildSystems[].provider`, whether it owns or shares a language server process. /// Version 1 adds runs with `entrypoints: true`, which start an entrypoint the @@ -128,7 +129,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (BEFORE_LAUNCH_TASKS, &[0]), (BUILD_MODEL_INPUTS, &[0]), (BUILD_PROVIDERS, &[0, 1]), - (BUILD_SYSTEMS, &[0]), + (BUILD_SYSTEMS, &[0, 1]), (COMMAND_INSTALLERS, &[0]), (DEBUG_ADAPTERS, &[0]), (EXECUTION_PROVIDERS, &[0]), diff --git a/rust/logging/README.md b/rust/logging/README.md index 63189d5f..01fdf221 100644 --- a/rust/logging/README.md +++ b/rust/logging/README.md @@ -92,7 +92,7 @@ - Core 的 stderr 读取器(`rust/crates/lsp-engine/src/logging.rs`)限制每行 4 KiB、每秒 200 行,之后再走 `text` 的 1 KiB 脱敏规范化。与 v1 相比唯一的兼容变化是从任意 trim 的读取块改为逐行文本:保留行内空格,移除 LF 和末尾 CR,并应用已声明的长度上限和限流。 - 上游明确给出的严重度通过独立的目录事件保留:`window/logMessage` 和 `window/showMessage` 的 type 1/2/3/4 分别为 ERROR/WARN/INFO/DEBUG,未知类型为 DEBUG。未分类的 stderr 是 DEBUG 排障证据,流名称不表示警告;实际的进程或协议失败由 `*.session.failed` 记录 ERROR,正常关闭仍是生命周期状态。 - 插件自身使用独立协商的 `litheLogging` 0 和 `lithe/log`,由 Core 把四种受控事实映射到插件目录事件,不能再用 stderr 或任意自由消息代替。协议字段、op、限额和 fixture 以 [插件契约](../../shared/plugins/contract/v1/README.md#structured-plugin-diagnostics) 为准。 -- 声明式贡献没有插件进程,不能发 `lithe/log`。实际执行它的一方通过 `diagnostics.recordPluginOperation` 代记每次尝试的一条终态,事件和通道与 SDK 插件相同:`plugins.operation.finished` 或 `plugins.operation.failed`,写入 `plugins/{plugin}/host`。平台层只上报观察到的阶段和耗时,级别和 `host.*` 失败类别只由 Core 按阶段决定;取消、停止和过期结果不记录。宿主当前代记下表五种贡献,唯一来源是 `rust/crates/diagnostics/src/plugin_operations.rs` 的 `CONTRIBUTIONS`;输入、阶段到类别的对应和 -32064 见 [Rust Core API](../contracts/rust-core-api.md#engine-logging-v2-handoff-pr3)。 +- 声明式贡献没有插件进程,不能发 `lithe/log`。实际执行它的一方通过 `diagnostics.recordPluginOperation` 代记每次尝试的一条终态,事件和通道与 SDK 插件相同:`plugins.operation.finished` 或 `plugins.operation.failed`,写入 `plugins/{plugin}/host`。平台层只上报观察到的阶段和耗时,级别和 `host.*` 失败类别只由 Core 按阶段决定;取消、停止和过期结果不记录。宿主代记下表列出的贡献,唯一来源是 `rust/crates/diagnostics/src/plugin_operations.rs` 的 `CONTRIBUTIONS`;输入、阶段到类别的对应和 -32064 见 [Rust Core API](../contracts/rust-core-api.md#engine-logging-v2-handoff-pr3)。 | operation | 声明来源 | 记录方 | 可能的失败阶段 | | --- | --- | --- | --- | @@ -100,6 +100,7 @@ | `debugAdapter/start` | `debugAdapters[]` | 桌面宿主;op 为调试会话 ID,用户停止和 Core 拒绝建会话不记录 | resolve、launch、exit、initialize、timeout | | `lithe/build/model` | `buildSystems[]` 的命令式模型 | 桌面宿主,op 为加载模型的操作;计划由插件后端提供时由 SDK 记录 | plan、resolve、launch、timeout、exit、decode | | `lithe/build/dependencies` | `buildSystems[]` 的命令式依赖树 | 桌面宿主,op 为加载依赖的操作;计划由插件后端提供时由 SDK 记录 | plan、resolve、launch、timeout、exit、decode | + | `lithe/build/discoverTests` | `buildSystems[].test.discoveryCommand` | 桌面宿主,op 为发现测试的操作;provider 的请求由 SDK 记录 | plan、resolve、launch、timeout、exit、decode | | `commandInstaller/install` | `commandInstallers[]` | 桌面宿主,每次用户确认的安装记一条,op 为这次安装;用户取消不记录;安装正常退出但命令不在目录里记 decode | plan、resolve、launch、timeout、exit、decode | 新增一种声明式贡献时,在同一次改动里给 `CONTRIBUTIONS` 加一行,在执行方开始和结束一次 attempt,并更新本表;不新增事件、通道或错误码。Core 拒绝或无法入队一条代记结果时,桌面宿主记 `app.background.operation_failed`(`operation` 为 `plugin_operation_record`),不重试。 diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 6d072f1d..c980fb27 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -563,8 +563,9 @@ executes the declared work records the same `plugins.operation.finished` and declarative plugin writes no logging code. Each start of a `languageServers[]` or `debugAdapters[]` entry is one `languageServer/start` or `debugAdapter/start` operation, from launch resolution until `initialize` succeeds. Each run of a -`buildSystems[]` model or dependencies command source is one `lithe/build/model` or -`lithe/build/dependencies` operation, using the SDK request names. Each +`buildSystems[]` command source for a model, dependencies, or test discovery +is one `lithe/build/model`, `lithe/build/dependencies`, or +`lithe/build/discoverTests` operation, using the SDK request names. Each installation of a [command installer](#command-installers) the user confirmed is one `commandInstaller/install` operation, from planning the chosen target until every provided command is in its directory. A failure carries one `code`: @@ -1924,7 +1925,7 @@ they are not those plugins. `build-provider` and `build-provider-language-server forms of a build provider, and `fixtures/build-systems/build-plans.json` is the golden list of plans and decoded outputs every host gets from them. -A build system needs `buildSystems: 0` in `requires`, +A build system needs `buildSystems: 0` in `requires` (`1` with [command test discovery](#test-discovery)), the `process.build` permission, and the activation event `onBuildSystem:`. IDs of build systems, tasks, and run entries start with a lowercase letter and use lowercase letters, @@ -1944,7 +1945,7 @@ declaration are relative, use `/`, and stay inside their base directory | `run` | Run entries from model targets (`fromTargets.tags`, with `arguments`) or model tasks (`fromTasks`, reusing the template task's arguments). | | `runConfigurationTypes` | Kinds of run configuration the user creates in the Run/Debug Configurations dialog, from declared fields and a command line; see [Run configuration types](#run-configuration-types). | | `beforeLaunchTasks` | Kinds of step a configuration's Before Launch list runs first, declared like run configuration types; see [Before-launch tasks](#before-launch-tasks). | -| `test` | How tests run: `scopes`, `targetTags`, the `filters` (`suite`, `case`) it can select, and `results` (`junitXml` or `litheTestResults` report globs relative to the project). A workspace run reads the globs under the root and every model project. A requested filter must reach the command line through a template whose conditions hold; a `case` guarded by `suiteSelected` therefore needs its suite. | +| `test` | How tests run: `scopes`, `targetTags`, the `filters` (`suite`, `case`) it can select, and `results` (`junitXml` or `litheTestResults` report globs relative to the project). [Test discovery](#test-discovery) is opt-in. A workspace run reads the globs under the root and every model project. A requested filter must reach the command line through a template whose conditions hold; a `case` guarded by `suiteSelected` therefore needs its suite. | | `diagnostics` | `lineMatcher` patterns with capture-group numbers, or `litheDiagnostics` lines. | | `dependencies` | A command (with `scopes`) whose output Core decodes, as a flat list through a `map` or as a tree from `litheDependencies`; or `provider` (with `scopes`, `workspace` and `project` only). | | `sync` | Files whose change makes the model stale, relative to the root and to each project. | @@ -2187,15 +2188,32 @@ Canonical examples: `fixtures/build-providers/build-provider-tests.plugin.json` #### Test discovery -Provider tests may additionally declare `discovery: true`. This requires both -`suite` and `case` filters: every discovered selector must be exactly runnable. -`build.testDiscoveryPlan` accepts the common plan fields and optional `refresh` -and `tool`, returning a request for the whole instance: -`lithe/build/discoverTests` with its effective options. Project/output-file -selection is refused. This method uses -the existing bounded request/cancellation lifecycle, without execution progress. - -The provider returns `{ "format": "litheTestDiscovery", "version": 0, +A build system can discover exact test selectors for the native test tree. Both +sources require the `suite` and `case` filters and discover the whole instance. + +- **Command.** A plugin that declares `requires.buildSystems: 1` may set + `test.discoveryCommand: { arguments, executesProjectCode, mayUseNetwork }`. + The command uses the existing `process.build` permission, build tool selection, + global arguments, effective options and build-instance working directory. + Use `${outputFile}` in the discovery arguments to tell the tool where to write + the document. The same template family as a command model also allows + `${pluginDir}`, `${workspaceStateDir}`, root and option arguments. The host + supplies a fresh absolute file path in its writable workspace state and + deletes it when the attempt ends. The command must exit successfully before + the host decodes its file. The two effect flags are required and become part + of install review and the plan. Discovery runs on request, with a deadline + and process-tree cancellation. The test run itself uses the separately + declared `test.source` and existing argument or provider contract. +- **Provider.** Provider tests may declare `test.discovery: true`, using the + existing `buildProviders` protocol. `build.testDiscoveryPlan` returns + `lithe/build/discoverTests` with the effective options and optional + `refresh` and `tool` hints. The provider sends the document as an inline + result under the existing bounded request and cancellation lifecycle, + without execution progress. + +Enable one source. Project selection is refused for both. `outputFile` is +required for command plans and refused for provider plans. The command writes +and the provider returns `{ "format": "litheTestDiscovery", "version": 0, "tests": [{ "suite", "case", "project"?, "target"? }] }`. Project and target are the usual typed selections with workspace-relative paths. There may be at most 10,000 items and 32 MiB UTF-8 JSON. Unknown document/item fields are @@ -2203,7 +2221,8 @@ ignored; malformed selectors, invalid paths/scopes, unsupported versions and oversized lists reject the entire result with `plugin.build.invalidOutput`. An empty array is a successful discovery with no tests. -The host passes the reply and original plan configuration to +The host passes the original plan configuration and either the same +`outputFile` (command) or inline `result` (provider) to `build.decodeTestDiscovery`. Core validates every selector through the same test-plan rules, deterministically orders the list, collapses exact duplicates, and derives an opaque `id` including project/target identity. Equal suite/case @@ -2211,13 +2230,20 @@ names in sibling modules therefore remain distinct. The returned `discovery` contains `tests: [{ id, suite, case, project?, target? }]`. No source parsing, framework detection, or second project graph occurs in the host/Core. -Native discovery starts only on a user action, reuses the workspace Provider, -and is independent of plugin pages. Source edits, configuration changes, -package changes and workspace teardown revoke the cached list and in-flight -discovery. A native action must revalidate the selected ID against the current -list before submitting its exact selectors to `lithe/build/test`; stale -toolbar selections cannot run. The backend must reject a selector whose facts -have become stale externally. Canonical example: `fixtures/build-providers/build-test-discovery.json`. +Native discovery starts only on a user action and is independent of plugin +pages. A provider request reuses the workspace Provider. Source edits, +configuration changes, package changes and workspace teardown revoke cached +selectors and in-flight discovery. Before running a selected item, the host +revalidates its ID against the current list and plans the exact selectors with +`build.testPlan`. The selected command or provider must reject a selector +whose facts have become stale externally. The host records a terminal +`lithe/build/discoverTests` operation for each command attempt, following the +existing [declarative logging rules](#structured-plugin-diagnostics). + +Canonical examples are +[`build-command-test-discovery.plugin.json`](fixtures/build-systems/build-command-test-discovery.plugin.json), +[command output](fixtures/build-systems/build-command-test-discovery.json) +and [the provider result](fixtures/build-providers/build-test-discovery.json). ### Provider run preparation @@ -2673,7 +2699,7 @@ Test. A type is data only: the fields of its editor and the command line their values make. Core draws the editor, checks and saves the values, and expands the command line, so a type needs no backend and the host has no code for any type. A build system that declares types needs -`runConfigurationTypes: 0` in `requires` beside `buildSystems: 0`. Fixture: +`runConfigurationTypes: 0` in `requires` alongside the required `buildSystems` capability. Fixture: `fixtures/run-configuration-types/`, translated by its `l10n/zh-Hans.json`. ```json @@ -2776,7 +2802,7 @@ configuration has, as IntelliJ IDEA's Go plugin adds Run Go Command to its Configuration; picking one opens a form of the task's fields, and the step keeps their values. Before the configuration starts, each step runs and must exit with 0. A build system that declares tasks needs `beforeLaunchTasks: 0` -in `requires` beside `buildSystems: 0`. Fixture: +in `requires` alongside the required `buildSystems` capability. Fixture: `fixtures/before-launch-tasks/`, translated by its `l10n/zh-Hans.json`. ```json diff --git a/shared/plugins/contract/v1/fixtures/build-systems/build-command-test-discovery.json b/shared/plugins/contract/v1/fixtures/build-systems/build-command-test-discovery.json new file mode 100644 index 00000000..32e97a61 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/build-systems/build-command-test-discovery.json @@ -0,0 +1,17 @@ +{ + "format": "litheTestDiscovery", + "version": 0, + "tests": [ + { + "suite": "ExampleSuite", + "case": "checks spaces # [exact]", + "project": { "name": "app", "path": "app" }, + "target": { "name": "main", "tags": ["runnable"] } + }, + { + "suite": "ExampleSuite", + "case": "checks spaces # [exact]", + "project": { "name": "lib", "path": "lib" } + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/build-systems/build-command-test-discovery.plugin.json b/shared/plugins/contract/v1/fixtures/build-systems/build-command-test-discovery.plugin.json new file mode 100644 index 00000000..0f555521 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/build-systems/build-command-test-discovery.plugin.json @@ -0,0 +1,42 @@ +{ + "schemaVersion": 0, + "id": "dev.lithe.fixture.build-command-test-discovery", + "displayName": "Command Test Discovery Fixture", + "version": "0.1.0", + "pluginAPIVersion": 0, + "requires": { "buildSystems": 1 }, + "vendor": { "id": "org.example", "displayName": "Example", "signatureRequirement": "publisherPackage" }, + "permissions": ["process.build"], + "activationEvents": ["onBuildSystem:sample"], + "buildSystems": [ + { + "id": "sample", + "displayName": "Sample Build", + "detection": { "markers": ["sample.toml"] }, + "invocation": { + "executables": [{ "kind": "command", "command": "sample" }], + "globalArguments": ["--plain", "${optionArguments}"] + }, + "options": [ + { "id": "offline", "displayName": "Offline", "kind": "boolean", "arguments": ["--offline"] } + ], + "test": { + "scopes": ["workspace", "project", "target"], + "targetTags": ["runnable"], + "filters": ["suite", "case"], + "discoveryCommand": { + "arguments": ["discover", "${pluginDir}/discover.v1", "--state=${workspaceStateDir}", "${outputFile}"], + "executesProjectCode": true, + "mayUseNetwork": false + }, + "arguments": [ + "test", + { "value": "--project=${project.path}", "when": "projectSelected" }, + { "value": "--target=${target.name}", "when": "targetSelected" }, + { "value": "--suite=${test.suite}", "when": "suiteSelected" }, + { "value": "--case=${test.case}", "when": ["suiteSelected", "caseSelected"] } + ] + } + } + ] +} diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index fbac5f8d..267b8dfe 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -698,7 +698,7 @@ "edits": [{ "op": "set", "path": "/requires/buildSystems", "value": 5 }], "expectedCode": "plugin.api.unsupported" }, - {"name": "capability version 1 is not defined", "base": "build-static-file.plugin.json", "edits": [{"op": "set", "path": "/requires/buildSystems", "value": 1}], "expectedCode": "plugin.api.unsupported", "expectedField": "requires.buildSystems"}, + {"name": "capability version 2 is not defined", "base": "build-static-file.plugin.json", "edits": [{"op": "set", "path": "/requires/buildSystems", "value": 2}], "expectedCode": "plugin.api.unsupported", "expectedField": "requires.buildSystems"}, { "name": "used capability missing from requires", "base": "build-provider-language-server.plugin.json", diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 17fa5a64..1b1596ce 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -11,6 +11,7 @@ {"if": {"required": ["toolDefinitions"]}, "then": {"properties": {"requires": {"required": ["toolDefinitions"]}}}}, {"if": {"required": ["buildSystems"], "properties": {"buildSystems": {"contains": {"required": ["runConfigurationTypes"]}}}}, "then": {"properties": {"requires": {"required": ["runConfigurationTypes"]}}}}, {"if": {"required": ["buildSystems"], "properties": {"buildSystems": {"contains": {"required": ["beforeLaunchTasks"]}}}}, "then": {"properties": {"requires": {"required": ["beforeLaunchTasks"]}}}}, + {"if": {"required": ["buildSystems"], "properties": {"buildSystems": {"contains": {"required": ["test"], "properties": {"test": {"required": ["discoveryCommand"]}}}}}}, "then": {"properties": {"requires": {"required": ["buildSystems"], "properties": {"buildSystems": {"const": 1}}}}}}, {"if": {"required": ["commandInstallers"]}, "then": {"required": ["permissions"], "properties": {"requires": {"required": ["commandInstallers"]}, "permissions": {"contains": {"const": "commands.install"}}}}}, {"if": {"required": ["managedRuntimes"]}, "then": {"required": ["backend", "permissions"], "properties": {"requires": {"required": ["managedRuntimes", "backend"]}, "permissions": {"allOf": [{"contains": {"const": "runtimes.install"}}, {"contains": {"const": "backend.launch"}}]}}}}, {"if": {"required": ["toolchainProviders"]}, "then": {"required": ["backend"], "properties": {"requires": {"required": ["toolchainProviders", "backend"]}, "permissions": {"allOf": [{"contains": {"const": "toolchains.provide"}}, {"contains": {"const": "backend.launch"}}]}}}}, @@ -26,7 +27,7 @@ "version": { "type": "string", "pattern": "^[0-9]+\\.[0-9]+\\.[0-9]+$" }, "pluginAPIVersion": { "description": "Plugin API version of the manifest format. Always 0 in this contract; a host refuses any other value with plugin.api.unsupported.", "const": 0 }, "requires": { - "description": "Required: every capability the manifest uses, each with the version of that capability's contract it was written against. Every capability defines only version 0 today. Listing a capability the manifest does not use, or leaving out one it uses, is refused.", + "description": "Required: every capability the manifest uses, each with the version of that capability's contract it was written against. Listing a capability the manifest does not use, or leaving out one it uses, is refused.", "type": "object", "minProperties": 1, "additionalProperties": false, @@ -35,7 +36,7 @@ "beforeLaunchTasks": { "description": "Required exactly when any buildSystems[].beforeLaunchTasks is non-empty: kinds of step a run configuration's Before Launch list runs first, offered in its Add New Task menu, drawn from declared fields and run through a declared command line. Needs buildSystems.", "enum": [0] }, "buildModelInputs": {"description": "Optional public model sharing between already enabled workspace plugins; no installation, private function, or process authority. Required exactly when modelSharing or modelInputs is used. Consumers require buildProviders. A producer cannot also consume inputs.", "enum": [0]}, "buildProviders": { "description": "Required exactly when any buildSystems[].provider is present, including own-process and shared language-server providers. Declares host support for Provider orchestration (task execution, test execution and discovery, run preparation, native debug preparation, optional read-only model inputs, non-sensitive native configuration sources, inline test reports, opaque semantic test selectors, typed run options and service/task preparation, registry-selected adapters and host-owned connection targets for service debugging), independent of declarative buildSystems. Version 1 adds entrypoint runs (lithe/build/runEntrypoints).", "enum": [0, 1] }, - "buildSystems": { "description": "Declarative build detection, models, and command plans, including the executable setting adapter, instance-scoped options, and declarative preparation roles; does not imply buildProviders support.", "enum": [0] }, + "buildSystems": { "description": "Declarative build detection, models, and command plans. Version 1 adds command-based test discovery. Neither version implies buildProviders support.", "enum": [0, 1] }, "commandInstallers": { "description": "Required exactly when commandInstallers is non-empty: installations of bare commands that systemCommand launches name, run by the host only after the user confirms them.", "enum": [0] }, "debugAdapters": { "description": "Required exactly when debugAdapters is non-empty. Covers bounded target argument and environment bindings and debugAdapters[].features and defaults. The DAP session itself is negotiated by the adapter in initialize.", "enum": [0] }, "executionProviders": { "enum": [0] }, @@ -3475,6 +3476,16 @@ "test": { "type": "object", "additionalProperties": false, + "allOf": [ + { + "if": {"required": ["discoveryCommand"]}, + "then": { + "not": {"required": ["discovery"], "properties": {"discovery": {"const": true}}}, + "required": ["filters"], + "properties": {"filters": {"allOf": [{"contains": {"const": "suite"}}, {"contains": {"const": "case"}}]}} + } + } + ], "required": [ "scopes", "arguments" @@ -3489,6 +3500,17 @@ "type": "boolean", "description": "Opt in to lithe/build/discoverTests; requires provider test source and suite/case filters." }, + "discoveryCommand": { + "type": "object", + "description": "A separate command writing litheTestDiscovery v0 to the fresh ${outputFile}. Requires buildSystems 1 and suite/case filters.", + "additionalProperties": false, + "required": ["arguments", "executesProjectCode", "mayUseNetwork"], + "properties": { + "arguments": {"$ref": "#/$defs/buildArgumentList"}, + "executesProjectCode": {"type": "boolean"}, + "mayUseNetwork": {"type": "boolean"} + } + }, "source": { "description": "Omitted expands argv; provider sends lithe/build/test, requires empty arguments, and plugin-owned report decoding.", "enum": ["provider"] diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 693f2cb7..b6095d92 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -49,6 +49,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `sourceSettings` `1` | 在 `0` 之上加:模块列表布局 `sidebar`(来源可用 `parent` 嵌套)、字段 `section`(标签页或小标题)、有序类型化条目列表 `entryList`(添加菜单、文件/目录选择器、可选项、按条目的属性列) | ✅ | ✅ | [Entry lists](../contract/v1/README.md#source-backed-settings-editors) | | `ui` `0` | [`ui`](../contract/v1/README.md#host-owned-workbench-ui):文本、[包内网页](../contract/v1/README.md#web-content)和[插件视图](../contract/v1/README.md#plugin-views)的工具窗口、设置区域里的插件视图、命令,以及[不打开工具窗口的后端命令](../contract/v1/README.md#backend-only-commands);视图函数的结果由 Core 命令 `plugins.ui.applyResult` 校验,形状见 [`plugin-ui.schema.json`](../contract/v1/plugin-ui.schema.json) | ✅ | ✅¹ | [界面](domains/ui.md) | | `buildSystems` `0` | 不带 `provider` 的 [`buildSystems[]`](../contract/v1/README.md#build-systems):检测、选项、项目模型、任务、运行入口、测试、诊断、依赖、同步和[声明式项目准备](../contract/v1/README.md#declarative-project-preparation) | ✅ | ✅¹ | [声明式构建系统](domains/build-systems.md) | +| `buildSystems` `1` | 新增 [命令式测试发现](../contract/v1/README.md#test-discovery),复用声明的构建工具和测试选择器 | ✅ | 待宿主声明 | [声明式构建系统](domains/build-systems.md) | | `buildProviders` `0` | `buildSystems[].provider`:[构建提供者](../contract/v1/README.md#build-providers),可以是自有进程或共享语言服务器;说 `litheBuild`,包含任务执行、测试执行与发现、运行准备、原生调试准备、原生配置、内联测试报告、语义测试选择器、类型化运行选项和注册表连接调试 | ✅ | ✅¹ | [构建提供者](domains/build-providers.md) | | `buildProviders` `1` | 在 `0` 之上加:运行声明 `entrypoints: true`(入口运行,不需要目标),提供者用 `lithe/build/runEntrypoints` 回答一个源文件里可运行的入口,宿主把它保存为运行配置并按入口启动 | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `buildModelInputs` `0` | `buildSystems[].modelSharing` 与 `modelInputs`:[已启用工作区插件之间共享的只读模型输入](../contract/v1/README.md#optional-read-only-model-inputs)(可选) | ✅ | 未声明 | [构建提供者](domains/build-providers.md) | @@ -163,6 +164,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `sourceSettings` `1` | Adds to `0`: the `sidebar` module-list layout with sources nested by `parent`, field `section`s shown as tabs or subheadings, and ordered typed `entryList`s with an add menu, file and folder pickers, offered choices and per-entry attribute columns | ✅ | ✅ | [Entry lists](../contract/v1/README.md#source-backed-settings-editors) | | `ui` `0` | [`ui`](../contract/v1/README.md#host-owned-workbench-ui): text, [web](../contract/v1/README.md#web-content), and [plugin view](../contract/v1/README.md#plugin-views) tool windows, plugin views in settings regions, commands, and [backend-only commands](../contract/v1/README.md#backend-only-commands) without a tool window; the Core command `plugins.ui.applyResult` checks view function results, shaped as in [`plugin-ui.schema.json`](../contract/v1/plugin-ui.schema.json) | ✅ | ✅¹ | [UI](domains/ui.md) | | `buildSystems` `0` | [`buildSystems[]`](../contract/v1/README.md#build-systems) without `provider`: detection, options, project model, tasks, run entries, tests, diagnostics, dependencies, sync, and [declarative preparation](../contract/v1/README.md#declarative-project-preparation) | ✅ | ✅¹ | [Declarative build systems](domains/build-systems.md) | +| `buildSystems` `1` | Adds [command test discovery](../contract/v1/README.md#test-discovery) using the declared build tool and the existing test selectors | ✅ | Pending host declaration | [Declarative build systems](domains/build-systems.md) | | `buildProviders` `0` | `buildSystems[].provider`: [build providers](../contract/v1/README.md#build-providers), in their own process or a shared language server; they speak `litheBuild`, which covers task execution, test execution and discovery, run preparation, native debug preparation, native configuration, inline test reports, semantic test selectors, typed run options, and registry connection debugging | ✅ | ✅¹ | [Build providers](domains/build-providers.md) | | `buildProviders` `1` | Adds to `0`: run declarations with `entrypoints: true` (entrypoint runs, without a target); the provider answers `lithe/build/runEntrypoints` with the runnable entrypoints of one source file, which the host saves as run configurations and starts | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `buildModelInputs` `0` | `buildSystems[].modelSharing` and `modelInputs`: [optional read-only model inputs](../contract/v1/README.md#optional-read-only-model-inputs) shared between enabled workspace plugins | ✅ | Not declared | [Build providers](domains/build-providers.md) | diff --git a/shared/plugins/reference/domains/build-systems.md b/shared/plugins/reference/domains/build-systems.md index b835ecaf..025a0aa7 100644 --- a/shared/plugins/reference/domains/build-systems.md +++ b/shared/plugins/reference/domains/build-systems.md @@ -86,6 +86,7 @@ | [`build-systems/build-static-file.plugin.json`](../../contract/v1/fixtures/build-systems/build-static-file.plugin.json) | `static` 模型(Cargo) | | [`build-systems/build-command-stdout.plugin.json`](../../contract/v1/fixtures/build-systems/build-command-stdout.plugin.json) | 命令标准输出模型(Go) | | [`build-systems/build-command-output-file.plugin.json`](../../contract/v1/fixtures/build-systems/build-command-output-file.plugin.json) | 命令输出文件模型(Gradle) | +| [`build-systems/build-command-test-discovery.plugin.json`](../../contract/v1/fixtures/build-systems/build-command-test-discovery.plugin.json) | 命令式测试发现清单,使用 `buildSystems` 1 | | [`build-systems/build-instance-options.plugin.json`](../../contract/v1/fixtures/build-systems/build-instance-options.plugin.json) | 按实例保存的选项 | | [`build-systems/build-tool-path.plugin.json`](../../contract/v1/fixtures/build-systems/build-tool-path.plugin.json) | 用 `file` 设置选择构建工具 | | [`build-systems/build-toolchains.plugin.json`](../../contract/v1/fixtures/build-systems/build-toolchains.plugin.json) | 可执行文件候选和运行时依赖用 `toolchain` 来源 | @@ -187,6 +188,7 @@ The examples use Cargo, Go, and Gradle as realistic inputs; they are not those p | [`build-systems/build-static-file.plugin.json`](../../contract/v1/fixtures/build-systems/build-static-file.plugin.json) | `static` model (Cargo) | | [`build-systems/build-command-stdout.plugin.json`](../../contract/v1/fixtures/build-systems/build-command-stdout.plugin.json) | Command stdout model (Go) | | [`build-systems/build-command-output-file.plugin.json`](../../contract/v1/fixtures/build-systems/build-command-output-file.plugin.json) | Command output-file model (Gradle) | +| [`build-systems/build-command-test-discovery.plugin.json`](../../contract/v1/fixtures/build-systems/build-command-test-discovery.plugin.json) | Command test discovery manifest, using `buildSystems` 1 | | [`build-systems/build-instance-options.plugin.json`](../../contract/v1/fixtures/build-systems/build-instance-options.plugin.json) | Per-instance options | | [`build-systems/build-tool-path.plugin.json`](../../contract/v1/fixtures/build-systems/build-tool-path.plugin.json) | A `file` setting selects the build tool | | [`build-systems/build-toolchains.plugin.json`](../../contract/v1/fixtures/build-systems/build-toolchains.plugin.json) | Executable candidates and a runtime dependency with `toolchain` sources | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index c6548410..16d87ab4 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -目前没有。 +- [#112](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/112),[@Mucheen](https://github.com/Mucheen),**`buildSystems` 1**(API-29):清单新增 `buildSystems[].test.discoveryCommand`,已有测试运行可以独立采用命令或 provider。命令使用现有构建工具,把 `litheTestDiscovery` v0 写到宿主提供的 `${outputFile}`。Core 的 `build.testDiscoveryPlan`、`build.decodeTestDiscovery` 和测试树兼容两种发现来源,检查每条选择器可原样运行,命令尝试沿用 `lithe/build/discoverTests` 的结构化终态。没有新增宿主方法、通知或 SDK 版本。见 [1lck/Lithe-IDEA#2122](https://github.com/1lck/Lithe-IDEA/issues/2122)。 ## 按协议查首次出现 @@ -45,6 +45,7 @@ | `buildProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `buildProviders` | 1 | 2026-11-18 | [#89](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/89) | | `buildSystems` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| `buildSystems` | 1 | 待合入 | [#112](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/112) | | `commandInstallers` | 0 | 2026-11-15 | [#53](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/53) | | `debugAdapters` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `executionProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) |