From cd1a11b3054d2f1def32333bf546e7758ed1b586 Mon Sep 17 00:00:00 2001 From: wgw Date: Wed, 18 Nov 2026 09:50:41 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat(build):=20=E6=9E=84=E5=BB=BA=E6=A0=91?= =?UTF-8?q?=E6=8E=92=E5=B8=83=E4=B8=8E=E7=BC=96=E7=A0=81=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E5=A4=9A=E9=80=89=E9=80=89=E9=A1=B9=E7=9A=84=E9=BB=98=E8=AE=A4?= =?UTF-8?q?=E6=BF=80=E6=B4=BB=E9=A1=B9=E5=92=8C=E5=8F=96=E6=B6=88=E5=89=8D?= =?UTF-8?q?=E7=BC=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rust/contracts/rust-core-api.md | 13 +- rust/crates/build/src/commands.rs | 39 ++- rust/crates/build/src/detect.rs | 20 +- rust/crates/build/src/manifest/checks.rs | 8 +- rust/crates/build/src/manifest/model.rs | 14 + rust/crates/build/src/manifest/options.rs | 72 +++- rust/crates/build/src/model.rs | 87 ++++- rust/crates/build/src/options.rs | 307 ++++++++++++++++-- rust/crates/build/src/stored_options.rs | 60 +++- rust/crates/build/src/tree.rs | 109 ++++++- rust/crates/core/src/tests/build_systems.rs | 156 +++++++++ rust/fixtures/build/model-tree-v1.json | 222 +++++++++++++ shared/plugins/contract/v1/README.md | 7 +- .../contract/v1/plugin-manifest.schema.json | 31 ++ .../reference/domains/build-systems.md | 4 +- .../plugins/reference/protocol-changelog.md | 6 + 16 files changed, 1081 insertions(+), 74 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 3c3aabc8..79181b68 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -4749,7 +4749,7 @@ and the directories are absolute host paths used only as substitution text. | `build.invocationPlan` | `{ root, platform: "macos" \| "linux" \| "windows" }` | `invocation`: `{ buildSystemID, root, executables, environmentInputs, runtimeDependencies, version, minimumVersion }` with project-file paths joined to `root`; every runtime dependency with a known probe, host-managed ones included, carries `version: { arguments }` | | `build.checkToolVersion` | `{ runtime?, output }` | `version`: `{ satisfied, version? }`; `runtime` checks that runtime dependency instead of the tool | | `build.resolveModelInputs` | `{revision, sources: [{manifest, instances: [{buildSystemID, root, state, model?, options?}]}]}` from installed enabled current-workspace sources | `modelInputs`: version 1 public snapshot with exact optional producer slots, state, normalized projects/targets/content roots, configuration fingerprint and explicitly shared options; no tasks/run/settings/private functions; see the [plugin contract](https://github.com/1lck/Lithe-IDEA/blob/preview/shared/plugins/contract/v1/README.md#optional-read-only-model-inputs) | -| `build.resolveOptions` | `{ options, modelValues? }` | `options`: `{ options: [{ id, displayName, kind, scope?, value, source, choices, allowCustom }], dropped, fingerprint }` | +| `build.resolveOptions` | `{ options?, selectedChoices?, modelValues?, modelDefaults?, modelExcludePrefixes? }` | `options`: `{ options: [{ id, displayName, kind, scope?, value, selectedChoices?, source, choices: [{ value, title?, fromModel?, custom?, defaultActive? }], allowCustom }], dropped, fingerprint }` | | `build.configurationPlan` | plan fields and optional host-selected `tool` | `plan.provider` for `lithe/build/configuration`; no mutation, project or output-file parameters | | `build.decodeConfiguration` | `{ result }` | `configuration`: bounded `litheBuildConfiguration` v1 native sources/fields; see the plugin contract | | `build.configurationEditPlan` | `{ root, options?, workspaceStateDirectory, outputFile, snapshot, edits: { sourceID, revision, values }, tool? }` | Provider request `lithe/build/editConfiguration`; existing private staging only, no document bytes | @@ -4763,12 +4763,12 @@ and the directories are absolute host paths used only as substitution text. | `build.decodeRunPreparation` | `workspaceRoot`, instance `root`, raw `result`, same optional `launchOptions` | `launch` with portable `{executable:{kind,value},arguments,workingDirectory,environment}`; bounded strings and workspace directory containment, `plugin.build.invalidOutput` on invalid result | | `build.prepareDebugPlan` | same selected fields as `build.prepareRunPlan`; run declares same-plugin `debug.adapter` | `plan.provider` for `lithe/build/prepareDebug`; no cross-package reference, and launch options are refused: they apply only to running a target | | `build.decodeDebugPreparation` | `workspaceRoot`, instance `root`, selected `run`, raw `result` | `preparation` with declaration-owned `adapter`, normalized `root`, `program`, `arguments`, `workingDirectory`, `environment`; program is an existing regular file contained in the instance after canonicalization | -| `build.decodeModel` | `{ workspaceRoot, root, output?, outputFile?, result?, options? }`; `result` is the provider's JSON answer | `model`: `{ projects, targets, tasks, contentRoots, optionValues, run }`; `run` entries carry `buildSystem: { id, root, projectID, targetID?, optionFingerprint }` | +| `build.decodeModel` | `{ workspaceRoot, root, output?, outputFile?, result?, options? }`; `result` is the provider's JSON answer | `model`: `{ projects, targets, tasks, contentRoots, optionValues, optionDefaults?, optionExcludePrefixes?, run }`; `run` entries carry `buildSystem: { id, root, projectID, targetID?, optionFingerprint }` | | `build.decodeTestResults` | `{ workspaceRoot, root, project?, projects?, output, notBeforeMillis?, suite? }`; without `project` the reports of the root and every listed model project are read | `results`: `{ tests: [{ suite, case, status, message?, durationMillis?, path?, line?, invocations }], summary: { total, passed, failed, errors, skipped }, success }`; repeated invocations of one case merge into the most severe status | | `build.decodeDiagnostics` | `{ workspaceRoot, root, output }` | `diagnostics`: `[{ path, line, column?, severity, message }]`, deduplicated, inside the workspace only | | `build.decodeDependencies` | `{ workspaceRoot, root, project?, output?, outputFile?, result? }` | `dependencies`: `{ project, dependencies: [{ name, group?, version?, scope?, properties?, children }], truncated }` | | `build.syncFingerprint` | `{ workspaceRoot, root, projects, options? }` | `sync`: `{ fingerprint, watch }` | -| `build.modelTree` | `{ model: { projects, targets, tasks }, query?, groupHeadings?: { : heading } }`; `model` is a `build.decodeModel` result, other model fields are ignored | `tree`: `{ project?, nodes, truncated? }`; see below | +| `build.modelTree` | `{ model: { projects, targets, tasks, optionValues?, optionDefaults?, optionExcludePrefixes? }, options?, query?, groupHeadings?: { : heading } }`; `model` is a `build.decodeModel` result, other model fields are ignored | `tree`: `{ project?, nodes, truncated? }`; see below | Invocation candidates also include `{ kind: "toolchain", toolchainID, root }`. Hosts resolve them through the same canonical project/subproject @@ -4833,10 +4833,13 @@ themselves. It reads no file and starts no process. matches, keeps everything; the matching `project` then carries `matched: true`. - A node is `{ kind, key, label?, detail?, tooltip?, group?, projectID?, - targetID?, taskID?, matched?, children? }`, `kind` one of `project`, + targetID?, taskID?, optionID?, optionValue?, checked?, defaultActive?, + matched?, children? }`, `kind` one of `option`, `optionChoice`, `project`, `folder`, `task`, `targets`, `target`, `dependencies`, `tests`. `key` is opaque, unique in the instance and stable across reloads and filters, so - hosts remember open nodes by it. `projectID` and `targetID` are what a task + hosts remember open nodes by it. Each `presentation: "tree"` option with at + least one choice adds an `option` node at the top of `nodes` (whose `detail` + summarizes the checked choices) with `optionChoice` children. `projectID` and `targetID` are what a task runs on (absent: the whole instance); `taskID` is a declared task's ID or a model task's ID. `targets`, `dependencies` and `tests` nodes have no label. - The model may hold at most 2,000 projects and 10,000 targets and 10,000 diff --git a/rust/crates/build/src/commands.rs b/rust/crates/build/src/commands.rs index a145f46f..17a0f3c4 100644 --- a/rust/crates/build/src/commands.rs +++ b/rust/crates/build/src/commands.rs @@ -43,10 +43,20 @@ struct ResolveOptionsRequest { /// Stored option values by option ID. #[serde(default)] options: BTreeMap, + /// Positive choices checked in an option editor, encoded into `options` + /// before resolution. + #[serde(default)] + selected_choices: BTreeMap>, /// The loaded model's `optionValues`; absent before a model exists, so /// values only the model can confirm are kept rather than dropped. #[serde(default)] model_values: Option>>, + /// The loaded model's `optionDefaults`. + #[serde(default)] + model_defaults: Option>>, + /// The loaded model's `optionExcludePrefixes`. + #[serde(default)] + model_exclude_prefixes: Option>, } fn with_build_system( @@ -130,16 +140,25 @@ pub fn build_resolve_options_command(payload: Value) -> Result "build.resolveOptions", "options", |build_system, request: &ResolveOptionsRequest| { - let resolved = options::resolve( - build_system, - &request.options, - request.model_values.as_ref(), - ); - Ok(options::describe( - build_system, - &resolved, - request.model_values.as_ref(), - )) + let facts = options::ModelOptionFacts { + values: request.model_values.as_ref(), + defaults: request.model_defaults.as_ref(), + exclude_prefixes: request.model_exclude_prefixes.as_ref(), + }; + let mut stored = request.options.clone(); + for (id, selected) in &request.selected_choices { + let option = build_system.option(id).ok_or_else(|| { + PluginRejection::new("plugin.build.invalidOption", "Unknown declared option") + })?; + let encoded = options::encode_selected_choices(option, selected, false, &facts)?; + if encoded.is_null() { + stored.remove(id); + } else { + stored.insert(id.clone(), encoded); + } + } + let resolved = options::resolve_with_facts(build_system, &stored, facts); + Ok(options::describe_with_facts(build_system, &resolved, facts)) }, ) } diff --git a/rust/crates/build/src/detect.rs b/rust/crates/build/src/detect.rs index d0227859..a823bb82 100644 --- a/rust/crates/build/src/detect.rs +++ b/rust/crates/build/src/detect.rs @@ -119,14 +119,18 @@ fn instance( "modelSource": model_source_name(declaration.model.as_ref()), }); let mut model_values = None; + let mut model_defaults = None; + let mut model_exclude_prefixes = None; if matches!(declaration.model, Some(ModelSource::Static { .. })) { let source = source_marker(declaration, workspace, root); match read_model(declaration, workspace, root, None, None, None).and_then(|model| { let value = model_value(declaration, &model, root, stored, source.as_deref())?; - Ok((model.option_values, value)) + Ok((model, value)) }) { - Ok((values, value)) => { - model_values = Some(values); + Ok((model, value)) => { + model_values = Some(model.option_values); + model_defaults = Some(model.option_defaults); + model_exclude_prefixes = Some(model.option_exclude_prefixes); instance["model"] = value; } Err(error) => { @@ -134,7 +138,15 @@ fn instance( } } } - let resolved = options::resolve(declaration, stored, model_values.as_ref()); + let resolved = options::resolve_with_facts( + declaration, + stored, + options::ModelOptionFacts { + values: model_values.as_ref(), + defaults: model_defaults.as_ref(), + exclude_prefixes: model_exclude_prefixes.as_ref(), + }, + ); // Hosts must not recreate scope/default/root merging when handing this // exact instance to a provider. Explicit empty selections remain chosen. instance["options"] = json!(resolved.chosen_values); diff --git a/rust/crates/build/src/manifest/checks.rs b/rust/crates/build/src/manifest/checks.rs index 59f89722..58d423a9 100644 --- a/rust/crates/build/src/manifest/checks.rs +++ b/rust/crates/build/src/manifest/checks.rs @@ -29,7 +29,7 @@ fn program(build_system: &BuildSystemDeclaration) -> Value { .options .iter() .map(|option| { - json!({ + let mut review = json!({ "id": option.id, "kind": option.kind, "default": option.default, @@ -39,7 +39,11 @@ fn program(build_system: &BuildSystemDeclaration) -> Value { "separator": option.separator(), "arguments": option.arguments, "environment": option.environment, - }) + }); + if let Some(prefix) = &option.exclude_prefix { + review["excludePrefix"] = json!(prefix); + } + review }) .collect(); let tasks: Vec = build_system diff --git a/rust/crates/build/src/manifest/model.rs b/rust/crates/build/src/manifest/model.rs index e2b71e37..471efe79 100644 --- a/rust/crates/build/src/manifest/model.rs +++ b/rust/crates/build/src/manifest/model.rs @@ -84,6 +84,8 @@ pub(crate) struct ModelMap { pub(crate) projects: Vec, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(crate) option_values: BTreeMap, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub(crate) option_defaults: BTreeMap, } /// Fields every rule shares: which elements it reads and when it applies. @@ -323,6 +325,18 @@ impl ModelMap { check_predicates(&rule.filter, &field)?; rule.value.validate(&format!("{field}.value"))?; } + for (id, rule) in &self.option_defaults { + let field = format!("{field}.optionDefaults.{id}"); + if !model_options.contains(id) { + return Err(invalid( + field, + "optionDefaults may only fill options declared with choicesFromModel.", + )); + } + select::validate(&rule.each, &format!("{field}.each"), false)?; + check_predicates(&rule.filter, &field)?; + rule.value.validate(&format!("{field}.value"))?; + } Ok(()) } } diff --git a/rust/crates/build/src/manifest/options.rs b/rust/crates/build/src/manifest/options.rs index cd253961..4371ac5f 100644 --- a/rust/crates/build/src/manifest/options.rs +++ b/rust/crates/build/src/manifest/options.rs @@ -25,6 +25,9 @@ pub(crate) struct OptionDeclaration { /// Joins multi-select values in `${value}`; `,` by default. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) separator: Option, + /// Prefix on a stored multi-select item that turns a default choice off. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) exclude_prefix: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) arguments: Vec, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] @@ -77,14 +80,31 @@ impl OptionDeclaration { ) } - /// Whether a single value is acceptable, given the model's values for a - /// `choicesFromModel` option (`None` while no model is loaded, in which - /// case model choices cannot be checked and are accepted). - pub(crate) fn accepts_value(&self, value: &str, model_values: Option<&[String]>) -> bool { + /// Whether `prefix` is a valid exclusion prefix for this option. + pub(crate) fn is_valid_exclude_prefix(&self, prefix: &str) -> bool { + let separator = self.separator(); + self.kind == OptionKind::MultiSelect + && !prefix.is_empty() + && prefix.len() <= 4 + && !prefix.chars().any(char::is_control) + && !prefix.contains(separator) + && !separator.contains(prefix) + } + + /// Whether a positive (non-excluded) choice value is acceptable. + pub(crate) fn accepts_positive_value( + &self, + value: &str, + model_values: Option<&[String]>, + exclude_prefix: Option<&str>, + ) -> bool { if !is_option_value(value) { return false; } - if self.kind == OptionKind::MultiSelect && value.contains(self.separator()) { + if self.kind == OptionKind::MultiSelect + && (value.contains(self.separator()) + || exclude_prefix.is_some_and(|prefix| value.starts_with(prefix))) + { return false; } if !self.is_select() || self.allow_custom { @@ -96,6 +116,32 @@ impl OptionDeclaration { self.choices_from_model && model_values.is_none_or(|values| values.iter().any(|known| known == value)) } + + /// Whether a stored value (positive or excluded) is acceptable under an + /// effective exclusion prefix. + pub(crate) fn accepts_value_with_prefix( + &self, + value: &str, + model_values: Option<&[String]>, + exclude_prefix: Option<&str>, + ) -> bool { + let effective = self.exclude_prefix.as_deref().or(exclude_prefix); + if self.kind == OptionKind::MultiSelect { + if let Some(prefix) = effective { + if let Some(rest) = value.strip_prefix(prefix) { + return self.accepts_positive_value(rest, model_values, Some(prefix)); + } + } + } + self.accepts_positive_value(value, model_values, effective) + } + + /// Whether a single value is acceptable, given the model's values for a + /// `choicesFromModel` option (`None` while no model is loaded, in which + /// case model choices cannot be checked and are accepted). + pub(crate) fn accepts_value(&self, value: &str, model_values: Option<&[String]>) -> bool { + self.accepts_value_with_prefix(value, model_values, None) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] @@ -233,6 +279,14 @@ impl OptionDeclaration { )); } } + if let Some(prefix) = &self.exclude_prefix { + if !self.is_valid_exclude_prefix(prefix) { + return Err(invalid( + format!("{field}.excludePrefix"), + "Only multiSelect options take an excludePrefix of 1-4 printable characters free of the separator.", + )); + } + } if self.choices.len() > MAX_CHOICES { return Err(invalid(format!("{field}.choices"), "Too many choices.")); } @@ -240,11 +294,15 @@ impl OptionDeclaration { for (index, choice) in self.choices.iter().enumerate() { let bad_value = !is_option_value(&choice.value) || (self.kind == OptionKind::MultiSelect - && choice.value.contains(self.separator())); + && (choice.value.contains(self.separator()) + || self + .exclude_prefix + .as_deref() + .is_some_and(|prefix| choice.value.starts_with(prefix)))); if bad_value || !values.insert(choice.value.clone()) { return Err(invalid( format!("{field}.choices[{index}].value"), - "Choice values are unique, printable, and free of the separator.", + "Choice values are unique, printable, and free of the separator and excludePrefix.", )); } if let Some(title) = &choice.title { diff --git a/rust/crates/build/src/model.rs b/rust/crates/build/src/model.rs index 9e809981..246cfc83 100644 --- a/rust/crates/build/src/model.rs +++ b/rust/crates/build/src/model.rs @@ -38,6 +38,12 @@ pub(crate) struct BuildModel { pub(crate) content_roots: Vec, /// Values the model offers for `choicesFromModel` options. pub(crate) option_values: BTreeMap>, + /// Subset of `option_values` the build tool activates when the option is unset. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub(crate) option_defaults: BTreeMap>, + /// Per-option prefix a `litheBuildModel` script supplies to turn a default choice off. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub(crate) option_exclude_prefixes: BTreeMap, /// True when a bound dropped entries. #[serde(skip_serializing_if = "std::ops::Not::not")] pub(crate) truncated: bool, @@ -138,6 +144,8 @@ pub(crate) struct ModelBuilder<'a> { /// Explicit parent directory per project, resolved in `finish`. parents: Vec>, option_values: BTreeMap>, + option_defaults: BTreeMap>, + option_exclude_prefixes: BTreeMap, } impl<'a> ModelBuilder<'a> { @@ -153,6 +161,8 @@ impl<'a> ModelBuilder<'a> { model: BuildModel::default(), parents: Vec::new(), option_values: BTreeMap::new(), + option_defaults: BTreeMap::new(), + option_exclude_prefixes: BTreeMap::new(), } } @@ -333,6 +343,32 @@ impl<'a> ModelBuilder<'a> { } } + fn add_option_default(&mut self, option: &str, value: &str) { + let accepted = self + .build_system + .option(option) + .is_some_and(|declaration| declaration.choices_from_model) + && super::manifest::is_option_value(value); + if accepted { + let values = self.option_defaults.entry(option.to_string()).or_default(); + if values.len() < MAX_ITEMS { + values.insert(value.to_string()); + } + } + } + + fn set_option_exclude_prefix(&mut self, option: &str, prefix: &str) { + let accepted = self.build_system.option(option).is_some_and(|declaration| { + declaration.choices_from_model + && declaration.exclude_prefix.is_none() + && declaration.is_valid_exclude_prefix(prefix) + }); + if accepted { + self.option_exclude_prefixes + .insert(option.to_string(), prefix.to_string()); + } + } + /// Resolves parents, applies the declared layout, and orders entries. pub(crate) fn finish(mut self) -> BuildModel { let paths: Vec = self.model.projects.iter().map(|p| p.path.clone()).collect(); @@ -413,10 +449,38 @@ impl<'a> ModelBuilder<'a> { }); model.content_roots.sort(); model.content_roots.dedup(); + model.option_exclude_prefixes = self.option_exclude_prefixes; model.option_values = self .option_values .into_iter() - .map(|(id, values)| (id, values.into_iter().collect())) + .filter_map(|(id, values)| { + let declaration = self.build_system.option(&id)?; + let prefix = declaration + .exclude_prefix + .as_deref() + .or_else(|| model.option_exclude_prefixes.get(&id).map(String::as_str)); + let kept: Vec = values + .into_iter() + .filter(|value| { + declaration.kind != super::manifest::OptionKind::MultiSelect + || (!value.contains(declaration.separator()) + && !prefix.is_some_and(|prefix| value.starts_with(prefix))) + }) + .collect(); + Some((id, kept)) + }) + .collect(); + model.option_defaults = self + .option_defaults + .into_iter() + .filter_map(|(id, defaults)| { + let known = model.option_values.get(&id)?; + let kept: Vec = defaults + .into_iter() + .filter(|value| known.binary_search(value).is_ok()) + .collect(); + (!kept.is_empty()).then_some((id, kept)) + }) .collect(); model } @@ -447,6 +511,15 @@ pub(crate) fn map_document(builder: &mut ModelBuilder<'_>, map: &ModelMap, docum } } } + for (option, rule) in &map.option_defaults { + for node in select::nodes(&rule.each, document, &root) { + if select::all_hold(&rule.filter, document, &node) { + if let Some(value) = rule.value.text(document, &node) { + builder.add_option_default(option, &value); + } + } + } + } } /// Applies a rule list: each element a rule selects is offered to `apply`, @@ -660,6 +733,10 @@ struct CanonicalModel { content_roots: Vec, #[serde(default)] option_values: BTreeMap>, + #[serde(default)] + option_defaults: BTreeMap>, + #[serde(default)] + option_exclude_prefixes: BTreeMap, } #[derive(Debug, Deserialize)] @@ -834,5 +911,13 @@ pub(crate) fn map_canonical(builder: &mut ModelBuilder<'_>, document: Value) -> builder.add_option_value(option, value); } } + for (option, values) in &model.option_defaults { + for value in values { + builder.add_option_default(option, value); + } + } + for (option, prefix) in &model.option_exclude_prefixes { + builder.set_option_exclude_prefix(option, prefix); + } Ok(()) } diff --git a/rust/crates/build/src/options.rs b/rust/crates/build/src/options.rs index d88ea5e7..573d91ed 100644 --- a/rust/crates/build/src/options.rs +++ b/rust/crates/build/src/options.rs @@ -5,13 +5,33 @@ use super::manifest::{BuildSystemDeclaration, OptionDeclaration, OptionKind}; use super::template::{self, Values}; -use lithe_plugin_model::Validation; +use lithe_plugin_model::{PluginRejection, Validation}; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; const FINGERPRINT_DOMAIN: &str = "lithe.build.options/1"; +/// Model-supplied facts for `choicesFromModel` options: available values, +/// values active when the option is unset, and per-option exclusion prefixes. +#[derive(Debug, Clone, Copy, Default)] +pub(crate) struct ModelOptionFacts<'a> { + pub(crate) values: Option<&'a BTreeMap>>, + pub(crate) defaults: Option<&'a BTreeMap>>, + pub(crate) exclude_prefixes: Option<&'a BTreeMap>, +} + +/// One choice of a select option as resolved for display and editing. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ResolvedChoice { + pub(crate) value: String, + pub(crate) title: Option, + pub(crate) from_model: bool, + pub(crate) custom: bool, + pub(crate) default_active: bool, + pub(crate) checked: bool, +} + /// Effective option values of one request, by option ID. Options with no /// effective value contribute nothing and are absent. #[derive(Debug, Clone, Default)] @@ -28,12 +48,41 @@ pub(crate) struct ResolvedOptions { pub(crate) dropped: Vec, } +/// Effective exclusion prefix of `option`, preferring the declaration's own. +pub(crate) fn effective_exclude_prefix<'a>( + option: &'a OptionDeclaration, + facts: &ModelOptionFacts<'a>, +) -> Option<&'a str> { + option.exclude_prefix.as_deref().or_else(|| { + facts + .exclude_prefixes + .and_then(|prefixes| prefixes.get(&option.id).map(String::as_str)) + .filter(|prefix| option.is_valid_exclude_prefix(prefix)) + }) +} + /// Checks stored values against the declaration. `model_values` are the /// model's `optionValues`, or `None` when no model is loaded yet. pub(crate) fn resolve( build_system: &BuildSystemDeclaration, stored: &BTreeMap, model_values: Option<&BTreeMap>>, +) -> ResolvedOptions { + resolve_with_facts( + build_system, + stored, + ModelOptionFacts { + values: model_values, + ..ModelOptionFacts::default() + }, + ) +} + +/// Checks stored values against the declaration and full model option facts. +pub(crate) fn resolve_with_facts( + build_system: &BuildSystemDeclaration, + stored: &BTreeMap, + facts: ModelOptionFacts<'_>, ) -> ResolvedOptions { let mut resolved = ResolvedOptions::default(); for id in stored.keys() { @@ -42,11 +91,13 @@ pub(crate) fn resolve( } } for option in &build_system.options { - let known = - model_values.map(|values| values.get(&option.id).map(Vec::as_slice).unwrap_or(&[])); + let known = facts + .values + .map(|values| values.get(&option.id).map(Vec::as_slice).unwrap_or(&[])); + let exclude_prefix = effective_exclude_prefix(option, &facts); let user = stored .get(&option.id) - .map(|value| accepted(option, value, known)); + .map(|value| accepted(option, value, known, exclude_prefix)); let value = match user { Some(Some((value, discarded))) => { resolved.chosen.push(option.id.clone()); @@ -85,18 +136,19 @@ fn accepted( option: &OptionDeclaration, value: &Value, known: Option<&[String]>, + exclude_prefix: Option<&str>, ) -> Option<(Value, bool)> { match (option.kind, value) { (OptionKind::Boolean, Value::Bool(_)) => Some((value.clone(), false)), (OptionKind::SingleSelect, Value::String(text)) => option - .accepts_value(text, known) + .accepts_value_with_prefix(text, known, exclude_prefix) .then(|| (value.clone(), false)), (OptionKind::MultiSelect, Value::Array(items)) => { let mut values = Vec::new(); let mut discarded = false; for item in items { let text = item.as_str()?; - if option.accepts_value(text, known) { + if option.accepts_value_with_prefix(text, known, exclude_prefix) { values.push(text.to_string()); } else { discarded = true; @@ -105,6 +157,19 @@ fn accepted( if discarded && values.is_empty() { return None; } + if let Some(prefix) = exclude_prefix { + let positives: BTreeSet = values + .iter() + .filter(|item| !item.starts_with(prefix)) + .cloned() + .collect(); + let before = values.len(); + values.retain(|item| { + item.strip_prefix(prefix) + .is_none_or(|rest| !positives.contains(rest)) + }); + discarded |= values.len() != before; + } values.sort(); values.dedup(); Some((json!(values), discarded)) @@ -201,37 +266,207 @@ pub(crate) fn fingerprint( format!("{:x}", hasher.finalize()) } -/// The `build.resolveOptions` view: every option with its effective value, -/// where the value came from, and the choices the UI should offer. -pub(crate) fn describe( +/// Positive choice values that are active when `option` has no user override: +/// the declaration's `default`, else the model's `optionDefaults`. +pub(crate) fn default_choice_set( + option: &OptionDeclaration, + facts: &ModelOptionFacts<'_>, +) -> BTreeSet { + let mut defaults = BTreeSet::new(); + match (&option.kind, &option.default) { + (OptionKind::SingleSelect, Some(Value::String(value))) if !value.is_empty() => { + defaults.insert(value.clone()); + return defaults; + } + (OptionKind::MultiSelect, Some(Value::Array(items))) => { + for item in items.iter().filter_map(Value::as_str) { + defaults.insert(item.to_string()); + } + return defaults; + } + _ => {} + } + if option.choices_from_model { + let exclude_prefix = effective_exclude_prefix(option, facts); + let known = facts + .values + .and_then(|values| values.get(&option.id).map(Vec::as_slice)); + if let Some(values) = facts.defaults.and_then(|map| map.get(&option.id)) { + for value in values { + if option.accepts_positive_value(value, known, exclude_prefix) + && known.is_none_or(|list| list.iter().any(|item| item == value)) + { + defaults.insert(value.clone()); + } + } + } + } + defaults +} + +/// Ordered choices of `option`, with whether each is active by default and +/// currently checked. +pub(crate) fn choice_state( + option: &OptionDeclaration, + resolved: &ResolvedOptions, + facts: &ModelOptionFacts<'_>, +) -> Vec { + let exclude_prefix = effective_exclude_prefix(option, facts); + let defaults = default_choice_set(option, facts); + let chosen = resolved.chosen.contains(&option.id); + let stored_positives: BTreeSet<&str> = resolved + .chosen_values + .get(&option.id) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .filter(|value| !exclude_prefix.is_some_and(|prefix| value.starts_with(prefix))) + .collect(); + let is_checked = |value: &str| { + if option.kind != OptionKind::MultiSelect { + return false; + } + if chosen { + stored_positives.contains(value) + } else { + defaults.contains(value) + } + }; + + let mut seen = BTreeSet::new(); + let mut choices = Vec::new(); + for declared in &option.choices { + if seen.insert(declared.value.clone()) { + choices.push(ResolvedChoice { + checked: is_checked(&declared.value), + default_active: defaults.contains(&declared.value), + value: declared.value.clone(), + title: declared.title.clone(), + from_model: false, + custom: false, + }); + } + } + if option.choices_from_model { + for value in facts + .values + .and_then(|values| values.get(&option.id)) + .into_iter() + .flatten() + { + if exclude_prefix.is_some_and(|prefix| value.starts_with(prefix)) { + continue; + } + if seen.insert(value.clone()) { + choices.push(ResolvedChoice { + checked: is_checked(value), + default_active: defaults.contains(value), + value: value.clone(), + title: None, + from_model: true, + custom: false, + }); + } + } + } + if option.kind == OptionKind::MultiSelect && option.allow_custom { + for value in &stored_positives { + if seen.insert((*value).to_string()) { + choices.push(ResolvedChoice { + value: (*value).to_string(), + title: None, + from_model: false, + custom: true, + default_active: false, + checked: true, + }); + } + } + } + choices +} + +/// Turns the positive choices the user checked for a `multiSelect` option into +/// the stored JSON value (`Value::Null` when no team override exists and the +/// checked set equals the default active set). +pub(crate) fn encode_selected_choices( + option: &OptionDeclaration, + selected: &[String], + has_team_override: bool, + facts: &ModelOptionFacts<'_>, +) -> Validation { + if option.kind != OptionKind::MultiSelect { + return Err(PluginRejection::new( + "plugin.build.invalidOption", + "selectedChoices applies to multiSelect options only", + )); + } + let exclude_prefix = effective_exclude_prefix(option, facts); + let known = facts + .values + .map(|values| values.get(&option.id).map(Vec::as_slice).unwrap_or(&[])); + let mut checked = Vec::with_capacity(selected.len()); + for value in selected { + if !option.accepts_positive_value(value, known, exclude_prefix) { + return Err(PluginRejection::new( + "plugin.build.invalidOption", + "The option value is not accepted by its declaration", + )); + } + checked.push(value.clone()); + } + checked.sort(); + checked.dedup(); + let defaults: Vec = default_choice_set(option, facts).into_iter().collect(); + if !has_team_override && checked == defaults { + return Ok(Value::Null); + } + let mut items = checked.clone(); + if let Some(prefix) = exclude_prefix { + for default in &defaults { + if checked.binary_search(default).is_err() { + items.push(format!("{prefix}{default}")); + } + } + } + items.sort(); + items.dedup(); + Ok(json!(items)) +} + +/// The `build.resolveOptions` view with model defaults and exclusion prefixes. +pub(crate) fn describe_with_facts( build_system: &BuildSystemDeclaration, resolved: &ResolvedOptions, - model_values: Option<&BTreeMap>>, + facts: ModelOptionFacts<'_>, ) -> Value { let options: Vec = build_system .options .iter() .map(|option| { - let mut choices: Vec = option - .choices + let resolved_choices = choice_state(option, resolved, &facts); + let choices: Vec = resolved_choices .iter() - .map(|choice| json!({ "value": choice.value, "title": choice.title })) + .map(|choice| { + let mut entry = if choice.from_model { + json!({ "value": choice.value, "fromModel": true }) + } else if choice.custom { + json!({ "value": choice.value, "custom": true }) + } else { + json!({ "value": choice.value, "title": choice.title }) + }; + if choice.default_active { + entry["defaultActive"] = json!(true); + } + entry + }) .collect(); - if option.choices_from_model { - let declared: Vec<&String> = - option.choices.iter().map(|choice| &choice.value).collect(); - for value in model_values - .and_then(|values| values.get(&option.id)) - .into_iter() - .flatten() - .filter(|value| !declared.contains(value)) - { - choices.push(json!({ "value": value, "fromModel": true })); - } - } + let defaults = default_choice_set(option, &facts); + let exclude_prefix = effective_exclude_prefix(option, &facts); let source = if resolved.chosen.contains(&option.id) { "user" - } else if option.default.is_some() { + } else if option.default.is_some() || !defaults.is_empty() { "default" } else { "unset" @@ -256,7 +491,7 @@ pub(crate) fn describe( _ => Value::Null, }) }; - let mut value = json!({ + let mut entry = json!({ "id": option.id, "displayName": option.display_name, "kind": option.kind, @@ -265,10 +500,22 @@ pub(crate) fn describe( "choices": choices, "allowCustom": option.allow_custom, }); + if option.kind == OptionKind::MultiSelect + && (!defaults.is_empty() + || exclude_prefix.is_some() + || resolved_choices.iter().any(|choice| choice.custom)) + { + let selected: Vec<&str> = resolved_choices + .iter() + .filter(|choice| choice.checked) + .map(|choice| choice.value.as_str()) + .collect(); + entry["selectedChoices"] = json!(selected); + } if option.scope == super::manifest::OptionScope::Instance { - value["scope"] = json!("instance"); + entry["scope"] = json!("instance"); } - value + entry }) .collect(); json!({ diff --git a/rust/crates/build/src/stored_options.rs b/rust/crates/build/src/stored_options.rs index 282c2664..18850e8e 100644 --- a/rust/crates/build/src/stored_options.rs +++ b/rust/crates/build/src/stored_options.rs @@ -37,9 +37,20 @@ pub(super) struct EditRequest { root: String, #[serde(rename = "optionID")] option_id: String, - value: Value, + #[serde(default, deserialize_with = "optional_value")] + value: Option, + #[serde(default)] + selected_choices: Option>, #[serde(default)] model_values: Option>>, + #[serde(default)] + model_defaults: Option>>, + #[serde(default)] + model_exclude_prefixes: Option>, +} + +fn optional_value<'de, D: Deserializer<'de>>(input: D) -> Result, D::Error> { + Value::deserialize(input).map(Some) } #[derive(Deserialize)] @@ -206,14 +217,39 @@ pub(super) fn edit(system: &BuildSystemDeclaration, request: &EditRequest) -> Va .ok_or_else(|| { PluginRejection::new("plugin.build.invalidOption", "Unknown declared option") })?; + let facts = options::ModelOptionFacts { + values: request.model_values.as_ref(), + defaults: request.model_defaults.as_ref(), + exclude_prefixes: request.model_exclude_prefixes.as_ref(), + }; let before = merge(&team, &local); let current = effective(system, &before, &local, &request.root); - let mut next = request.value.clone(); + let mut next = match (&request.value, &request.selected_choices) { + (Some(value), None) => value.clone(), + (None, Some(selected)) => { + let team_system = &team["systems"][&system.id]; + let has_team_override = if option.scope == OptionScope::Instance { + team_system["instances"][&request.root] + .get(&option.id) + .is_some() + || team_system["instanceDefaults"].get(&option.id).is_some() + } else { + team_system["options"].get(&option.id).is_some() + }; + options::encode_selected_choices(option, selected, has_team_override, &facts)? + } + _ => { + return Err(PluginRejection::new( + "plugin.build.invalidOption", + "Pass either value or selectedChoices", + )); + } + }; if !next.is_null() { - let resolved = options::resolve( + let resolved = options::resolve_with_facts( system, &BTreeMap::from([(option.id.clone(), next)]), - request.model_values.as_ref(), + facts, ); next = resolved .chosen_values @@ -257,7 +293,7 @@ pub(super) fn edit(system: &BuildSystemDeclaration, request: &EditRequest) -> Va } } else { if option.scope == OptionScope::Workspace && option.kind == OptionKind::MultiSelect { - let visible = options::resolve(system, ¤t, request.model_values.as_ref()) + let visible = options::resolve_with_facts(system, ¤t, facts) .chosen_values .get(&option.id) .and_then(Value::as_array) @@ -271,7 +307,15 @@ pub(super) fn edit(system: &BuildSystemDeclaration, request: &EditRequest) -> Va .into_iter() .filter(|value| !visible.contains(value)) .collect::>(); + let exclude_prefix = options::effective_exclude_prefix(option, &facts); for value in next.as_array().expect("checked multi-select") { + if let (Some(prefix), Some(text)) = (exclude_prefix, value.as_str()) { + let opposite = match text.strip_prefix(prefix) { + Some(rest) => rest.to_string(), + None => format!("{prefix}{text}"), + }; + merged.retain(|entry| entry.as_str() != Some(opposite.as_str())); + } if !merged.contains(value) { merged.push(value.clone()); } @@ -325,10 +369,8 @@ pub(super) fn edit(system: &BuildSystemDeclaration, request: &EditRequest) -> Va let local = validate_local(serde_json::to_value(local).map_err(|_| invalid())?)?; let document = merge(&team, &local); let stored = effective(system, &document, &local, &request.root); - let resolved = options::resolve(system, &stored, request.model_values.as_ref()); - Ok( - json!({"local":local,"options":options::describe(system,&resolved,request.model_values.as_ref())}), - ) + let resolved = options::resolve_with_facts(system, &stored, facts); + Ok(json!({"local":local,"options":options::describe_with_facts(system,&resolved,facts)})) } /// `build.editIgnoredPaths`: replaces or removes the local ignored-path list. diff --git a/rust/crates/build/src/tree.rs b/rust/crates/build/src/tree.rs index ccd1f3ef..740332ae 100644 --- a/rust/crates/build/src/tree.rs +++ b/rust/crates/build/src/tree.rs @@ -15,9 +15,11 @@ //! themselves. Nothing here reads a file or starts a process. use super::manifest::{ - BuildSystemDeclaration, DependenciesSource, Scope, TaskDeclaration, TaskGroup, + BuildSystemDeclaration, DependenciesSource, OptionPresentation, Scope, TaskDeclaration, + TaskGroup, }; use super::model::{MAX_ITEMS, MAX_PROJECTS}; +use super::options::{self, ModelOptionFacts}; use lithe_plugin_model::Validation; use serde::de::Error as _; use serde::{Deserialize, Deserializer, Serialize}; @@ -39,6 +41,9 @@ const KEY_SEPARATOR: char = '\u{1f}'; #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(crate) struct ModelTreeRequest { model: TreeModel, + /// Stored option values of the instance, for `presentation: "tree"` options. + #[serde(default)] + options: BTreeMap, /// Case-insensitive filter; empty or blank keeps every node. #[serde(default, deserialize_with = "query")] query: String, @@ -59,6 +64,12 @@ struct TreeModel { targets: Vec, #[serde(default, deserialize_with = "items")] tasks: Vec, + #[serde(default)] + option_values: BTreeMap>, + #[serde(default)] + option_defaults: BTreeMap>, + #[serde(default)] + option_exclude_prefixes: BTreeMap, } #[derive(Debug, Deserialize)] @@ -121,6 +132,10 @@ struct ModelTree { #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] enum NodeKind { + /// A `multiSelect` option with `presentation: "tree"`, such as build profiles. + Option, + /// One toggleable choice under an `Option` node. + OptionChoice, Project, /// A category heading of the plugin, or a task group. Folder, @@ -157,6 +172,18 @@ struct TreeNode { /// A declared task's ID or a model task's ID. #[serde(rename = "taskID", skip_serializing_if = "String::is_empty")] task_id: String, + /// The declared option an `option` or `optionChoice` node belongs to. + #[serde(rename = "optionID", skip_serializing_if = "String::is_empty")] + option_id: String, + /// The choice value an `optionChoice` node toggles. + #[serde(rename = "optionValue", skip_serializing_if = "String::is_empty")] + option_value: String, + /// True on an `optionChoice` node that is currently active. + #[serde(skip_serializing_if = "std::ops::Not::not")] + checked: bool, + /// True on an `optionChoice` node that is active when the option is unset. + #[serde(skip_serializing_if = "std::ops::Not::not")] + default_active: bool, /// True on a node the query matches itself, so the host opens the nodes /// on the way to it and shows the match as the user left it. #[serde(skip_serializing_if = "std::ops::Not::not")] @@ -177,12 +204,23 @@ impl TreeNode { project_id: String::new(), target_id: String::new(), task_id: String::new(), + option_id: String::new(), + option_value: String::new(), + checked: false, + default_active: false, matched: false, children: Vec::new(), } } fn matches(&self, query: &str) -> bool { + // An option node's detail summarizes its checked children; matching it + // there would keep the folder closed instead of opening onto the child. + if self.kind == NodeKind::Option { + return [&self.label, &self.tooltip] + .iter() + .any(|text| text.to_lowercase().contains(query)); + } [&self.label, &self.detail, &self.tooltip] .iter() .any(|text| text.to_lowercase().contains(query)) @@ -199,13 +237,15 @@ pub(crate) fn model_tree( left: MAX_NODES, truncated: false, }; - let (mut project, nodes) = match index.roots.as_slice() { + let mut nodes = tree_option_nodes(build_system, request, &mut budget); + let (mut project, contents) = match index.roots.as_slice() { &[root] => ( index.project_node(root, &mut budget), index.contents(Some(root), true, &mut budget), ), _ => (None, index.contents(None, true, &mut budget)), }; + nodes.extend(contents); let query = request.query.trim().to_lowercase(); if let Some(node) = project.as_mut() { node.matched = !query.is_empty() && node.matches(&query); @@ -223,6 +263,71 @@ pub(crate) fn model_tree( Ok(serde_json::to_value(tree).expect("a model tree serializes")) } +/// Checklist nodes at the top of the tree for `presentation: "tree"` options +/// that currently offer at least one choice. +fn tree_option_nodes( + build_system: &BuildSystemDeclaration, + request: &ModelTreeRequest, + budget: &mut Budget, +) -> Vec { + if !build_system + .options + .iter() + .any(|option| option.presentation == Some(OptionPresentation::Tree)) + { + return Vec::new(); + } + let facts = ModelOptionFacts { + values: Some(&request.model.option_values), + defaults: Some(&request.model.option_defaults), + exclude_prefixes: Some(&request.model.option_exclude_prefixes), + }; + let resolved = options::resolve_with_facts(build_system, &request.options, facts); + let mut nodes = Vec::new(); + for option in build_system + .options + .iter() + .filter(|option| option.presentation == Some(OptionPresentation::Tree)) + { + let choices = options::choice_state(option, &resolved, &facts); + if choices.is_empty() { + continue; + } + if !budget.take() { + break; + } + let key = format!("o{KEY_SEPARATOR}{}", option.id); + let mut parent = TreeNode::new(NodeKind::Option, key.clone()); + parent.label = option.display_name.clone(); + parent.option_id = option.id.clone(); + let active: Vec<&str> = choices + .iter() + .filter(|choice| choice.checked) + .map(|choice| choice.title.as_deref().unwrap_or(choice.value.as_str())) + .collect(); + if !active.is_empty() { + parent.detail = active.join(", "); + } + for choice in choices { + if !budget.take() { + break; + } + let mut item = TreeNode::new( + NodeKind::OptionChoice, + format!("{key}{KEY_SEPARATOR}{}", choice.value), + ); + item.label = choice.title.unwrap_or_else(|| choice.value.clone()); + item.option_id = option.id.clone(); + item.option_value = choice.value; + item.checked = choice.checked; + item.default_active = choice.default_active; + parent.children.push(item); + } + nodes.push(parent); + } + nodes +} + /// Keeps the nodes that match `query`, marked and each with its whole /// subtree, and the nodes on the way to them. Dependencies are loaded by the /// host, so their node stays only inside a match; tests are filtered by the diff --git a/rust/crates/core/src/tests/build_systems.rs b/rust/crates/core/src/tests/build_systems.rs index e79e2afb..4523e802 100644 --- a/rust/crates/core/src/tests/build_systems.rs +++ b/rust/crates/core/src/tests/build_systems.rs @@ -2907,3 +2907,159 @@ fn provider_run_options_refuse_explicit_cwd_symlinks_outside_workspace() { "request":{"workspaceRoot":workspace.root(),"root":"app","launchOptions":fixture["launchOptions"],"result":fixture["result"]}})).unwrap(); assert_eq!(result["error"]["code"], "plugin.build.invalidOutput"); } + +/// Model-supplied default choices and exclusion prefixes let a build tool's +/// profiles or features show default-active entries, deactivate them on CLI +/// even before the model reloads, and clear the local override once the user +/// returns to the defaults. +#[test] +fn model_option_defaults_and_exclusions_round_trip_through_storage_and_plans() { + use crate::build::{build_edit_stored_option_command, build_model_plan_command}; + let workspace = TemporaryWorkspace::new("model-option-defaults"); + let manifest: Value = serde_json::from_str(include_str!( + "fixtures/published_build_plugins/maven/plugin.json" + )) + .unwrap(); + let canonical = json!({ + "format": "litheBuildModel", + "version": 0, + "projects": [{"path": ".", "name": "demo"}], + "optionValues": {"profiles": ["dev", "prod", "release"]}, + "optionDefaults": {"profiles": ["dev"]}, + "optionExcludePrefixes": {"profiles": "-"} + }); + workspace.write("model.json", &canonical.to_string()); + let decoded = build_decode_model_command::(json!({ + "manifest": manifest, + "buildSystemID": "maven", + "request": { + "workspaceRoot": workspace.root(), + "root": ".", + "outputFile": workspace.0.join("model.json").to_string_lossy(), + } + })) + .unwrap(); + assert_eq!(decoded["status"], "ok", "{decoded}"); + let model = &decoded["model"]; + assert_eq!( + model["optionValues"]["profiles"], + json!(["dev", "prod", "release"]) + ); + assert_eq!(model["optionDefaults"]["profiles"], json!(["dev"])); + assert_eq!(model["optionExcludePrefixes"]["profiles"], json!("-")); + + let option_by_id = |options: &Value, id: &str| { + options["options"] + .as_array() + .unwrap() + .iter() + .find(|opt| opt["id"] == id) + .unwrap() + .clone() + }; + + let resolved = build_resolve_options_command::(json!({ + "manifest": manifest, + "buildSystemID": "maven", + "request": { + "options": {}, + "modelValues": model["optionValues"], + "modelDefaults": model["optionDefaults"], + "modelExcludePrefixes": model["optionExcludePrefixes"] + } + })) + .unwrap(); + let profiles = option_by_id(&resolved["options"], "profiles"); + assert_eq!(profiles["source"], "default", "{profiles}"); + assert_eq!(profiles["value"], json!([])); + assert_eq!(profiles["selectedChoices"], json!(["dev"])); + assert_eq!(profiles["choices"][0]["defaultActive"], json!(true)); + + let empty_team = json!({"version": 1, "systems": {}}); + let empty_local = json!({"version": 1, "document": {"version": 1, "systems": {}}}); + + // Unchecking the default-active `dev` profile stores `["-dev"]`, so even a + // cold `build.modelPlan` before the model loads passes `-P -dev`. + let unchecked = build_edit_stored_option_command::(json!({ + "manifest": manifest, + "buildSystemID": "maven", + "request": { + "document": empty_team, + "local": empty_local, + "root": ".", + "optionID": "profiles", + "selectedChoices": [], + "modelValues": model["optionValues"], + "modelDefaults": model["optionDefaults"], + "modelExcludePrefixes": model["optionExcludePrefixes"] + } + })) + .unwrap(); + assert_eq!(unchecked["status"], "ok", "{unchecked}"); + let after_uncheck = option_by_id(&unchecked["edit"]["options"], "profiles"); + assert_eq!(after_uncheck["value"], json!(["-dev"])); + assert_eq!(after_uncheck["selectedChoices"], json!([])); + + let plan = build_model_plan_command::(json!({ + "manifest": manifest, + "buildSystemID": "maven", + "request": { + "root": ".", + "options": {"profiles": ["-dev"]}, + "pluginDirectory": workspace.root(), + "outputFile": workspace.0.join("next.json").to_string_lossy() + } + })) + .unwrap(); + let args: Vec<&str> = plan["plan"]["arguments"] + .as_array() + .unwrap() + .iter() + .filter_map(Value::as_str) + .collect(); + assert!( + args.windows(2).any(|pair| pair == ["-P", "-dev"]), + "expected -P -dev in {args:?}" + ); + + // Switching to `prod` while keeping `dev` unchecked passes `-P -dev,prod`. + let switched = build_edit_stored_option_command::(json!({ + "manifest": manifest, + "buildSystemID": "maven", + "request": { + "document": empty_team, + "local": unchecked["edit"]["local"], + "root": ".", + "optionID": "profiles", + "selectedChoices": ["prod"], + "modelValues": model["optionValues"], + "modelDefaults": model["optionDefaults"], + "modelExcludePrefixes": model["optionExcludePrefixes"] + } + })) + .unwrap(); + let after_switch = option_by_id(&switched["edit"]["options"], "profiles"); + assert_eq!(after_switch["value"], json!(["-dev", "prod"])); + assert_eq!(after_switch["selectedChoices"], json!(["prod"])); + + // Returning to `["dev"]` removes the local override altogether. + let restored = build_edit_stored_option_command::(json!({ + "manifest": manifest, + "buildSystemID": "maven", + "request": { + "document": empty_team, + "local": switched["edit"]["local"], + "root": ".", + "optionID": "profiles", + "selectedChoices": ["dev"], + "modelValues": model["optionValues"], + "modelDefaults": model["optionDefaults"], + "modelExcludePrefixes": model["optionExcludePrefixes"] + } + })) + .unwrap(); + assert_eq!(restored["edit"]["local"]["document"]["systems"], json!({})); + assert_eq!(restored["edit"]["local"]["emptySelections"], json!({})); + let after_restore = option_by_id(&restored["edit"]["options"], "profiles"); + assert_eq!(after_restore["source"], "default"); +} diff --git a/rust/fixtures/build/model-tree-v1.json b/rust/fixtures/build/model-tree-v1.json index 801e7f3a..ce3d713e 100644 --- a/rust/fixtures/build/model-tree-v1.json +++ b/rust/fixtures/build/model-tree-v1.json @@ -43,8 +43,26 @@ "kind": "command", "command": "nested" } + ], + "globalArguments": [ + "${optionArguments:profiles}" ] }, + "options": [ + { + "id": "profiles", + "displayName": "Profiles", + "kind": "multiSelect", + "choicesFromModel": true, + "allowCustom": true, + "presentation": "tree", + "excludePrefix": "-", + "arguments": [ + "-P", + "${value}" + ] + } + ], "model": { "source": "command", "arguments": [ @@ -1915,6 +1933,210 @@ } ] } + }, + { + "name": "Tree options list model choices, defaults and excluded defaults at the top", + "buildSystemID": "nested", + "request": { + "model": { + "projects": [ + { + "id": "nested:app", + "path": ".", + "name": "app", + "properties": {} + } + ], + "targets": [], + "tasks": [], + "optionValues": { + "profiles": [ + "dev", + "prod", + "release" + ] + }, + "optionDefaults": { + "profiles": [ + "dev" + ] + } + }, + "options": { + "profiles": [ + "-dev", + "prod" + ] + } + }, + "expected": { + "project": { + "kind": "project", + "key": "p\u001fnested:app", + "label": "app", + "projectID": "nested:app" + }, + "nodes": [ + { + "kind": "option", + "key": "o\u001fprofiles", + "label": "Profiles", + "detail": "prod", + "optionID": "profiles", + "children": [ + { + "kind": "optionChoice", + "key": "o\u001fprofiles\u001fdev", + "label": "dev", + "optionID": "profiles", + "optionValue": "dev", + "defaultActive": true + }, + { + "kind": "optionChoice", + "key": "o\u001fprofiles\u001fprod", + "label": "prod", + "optionID": "profiles", + "optionValue": "prod", + "checked": true + }, + { + "kind": "optionChoice", + "key": "o\u001fprofiles\u001frelease", + "label": "release", + "optionID": "profiles", + "optionValue": "release" + } + ] + }, + { + "kind": "folder", + "key": "p\u001fnested:app\u001fc\u001fLifecycle", + "label": "Lifecycle", + "children": [ + { + "kind": "task", + "key": "p\u001fnested:app\u001fc\u001fLifecycle\u001ft\u001fclean", + "label": "clean", + "tooltip": "Deletes the build outputs.", + "projectID": "nested:app", + "taskID": "clean" + }, + { + "kind": "task", + "key": "p\u001fnested:app\u001fc\u001fLifecycle\u001ft\u001fpackage", + "label": "package", + "projectID": "nested:app", + "taskID": "package" + } + ] + }, + { + "kind": "folder", + "key": "p\u001fnested:app\u001fg\u001fverification", + "group": "verification", + "children": [ + { + "kind": "task", + "key": "p\u001fnested:app\u001fg\u001fverification\u001ft\u001fcheck", + "label": "Check", + "projectID": "nested:app", + "taskID": "check" + } + ] + }, + { + "kind": "folder", + "key": "p\u001fnested:app\u001fg\u001fother", + "group": "other", + "children": [ + { + "kind": "task", + "key": "p\u001fnested:app\u001fg\u001fother\u001ft\u001fgoal", + "label": "Run Goal…", + "taskID": "goal" + } + ] + }, + { + "kind": "folder", + "key": "p\u001fnested:app\u001fg\u001fdocumentation", + "group": "documentation", + "children": [ + { + "kind": "task", + "key": "p\u001fnested:app\u001fg\u001fdocumentation\u001ft\u001freport", + "label": "Report", + "taskID": "report" + } + ] + }, + { + "kind": "dependencies", + "key": "p\u001fnested:app\u001fdependencies", + "projectID": "nested:app" + } + ] + } + }, + { + "name": "Filtering a tree option choice opens the option folder onto the match", + "buildSystemID": "nested", + "request": { + "model": { + "projects": [ + { + "id": "nested:app", + "path": ".", + "name": "app", + "properties": {} + } + ], + "targets": [], + "tasks": [], + "optionValues": { + "profiles": [ + "dev", + "prod" + ] + }, + "optionDefaults": { + "profiles": [ + "dev" + ] + } + }, + "query": "dev" + }, + "expected": { + "project": { + "kind": "project", + "key": "p\u001fnested:app", + "label": "app", + "projectID": "nested:app" + }, + "nodes": [ + { + "kind": "option", + "key": "o\u001fprofiles", + "label": "Profiles", + "detail": "dev", + "optionID": "profiles", + "children": [ + { + "kind": "optionChoice", + "key": "o\u001fprofiles\u001fdev", + "label": "dev", + "optionID": "profiles", + "optionValue": "dev", + "checked": true, + "defaultActive": true, + "matched": true + } + ] + } + ] + } } ], "rejected": [ diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 3aa46044..7a056d90 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -1726,7 +1726,7 @@ declaration are relative, use `/`, and stay inside their base directory | `detection` | `markers` are file names; a directory holding one is a candidate root. Core searches at most 6 levels below the workspace root and skips the folders hidden by default (Core's own and the names enabled plugins declare, see `layout`), plus directories Git ignores: the rules come from the `.gitignore` files inside the workspace and the `info/exclude` of each repository whose root lies in it, not from directories above the workspace root, `core.excludesFile` or the index, so a tracked manifest below an ignored directory is not a candidate. Detection also skips the workspace's ignored paths, a Build option the user edits (`.gitignore` patterns stored in the team or machine-local Build options): by default every directory whose name starts with a dot, such as `.claude/worktrees`, and the user can list more or bring one back with `!`. `nesting: "outermost"` folds deeper candidates into the outer instance (Gradle builds, Maven reactors); `"separate"` (default) keeps each (Cargo packages). `priority` (0–100, default 50) decides between plugins declaring the same ID; ties go to the smaller plugin ID. | | `invocation` | `executables` in preference order: `projectFile` (a wrapper inside the root, with `requires` files; always runs project code), `environment` (a path below a variable listed in `environmentInputs`), `command` (a bare name found on `PATH`), `runtime` (a declared runtime dependency itself). `platforms` limits a candidate. `globalArguments` precede every command. `version` probes the executable with literal `arguments` and a `pattern` whose first group is the version; `minimumVersion` needs a probe. | | `runtimeDependencies` | Core knows no runtime by name; `node` and `go` follow the same rules as any other ID. A runtime without `executables` names the [tool definition](toolchains/README.md) with the same ID, so its `id` must be a valid tool-definition ID and it declares only `minimumVersion`: `build.invocationPlan` returns it with `version: null` and the single candidate `{ "kind": "toolchain", "toolchainID": , "root": }`, whose resolution checks `minimumVersion`, and `build.checkToolVersion` for it is `plugin.build.unavailable` because Core reads no version. Any other runtime describes its own `executables` and `version` probe, so the runtime list is open; a runtime whose only candidate is a `toolchain` candidate may omit the probe, since the definition checks the version. | -| `options` | Build dimensions the user chooses: `boolean`, `singleSelect`, `multiSelect`, `text`, `file`, `directory`. Each contributes `arguments` and `environment` (with `${value}`) when it has a value. Choices are declared, come from the model (`choicesFromModel`), or are free (`allowCustom`). | +| `options` | Build dimensions the user chooses: `boolean`, `singleSelect`, `multiSelect`, `text`, `file`, `directory`. Each contributes `arguments` and `environment` (with `${value}`) when it has a value. Choices are declared, come from the model (`choicesFromModel`, with optional `optionDefaults` for choices the tool activates when unset), or are free (`allowCustom`); a `multiSelect` option may set `excludePrefix` (or report `optionExcludePrefixes` in `litheBuildModel`) so unchecking a default choice passes ``. | | `provider` | The process that answers model and dependency requests when no command prints them; see [Build providers](#build-providers). | | `model` | `static` (a `toml` file read during detection, no process), `command` (a command whose output Core decodes; it states `executesProjectCode` and `mayUseNetwork`), or `provider`. | | `tasks` | The task catalog. `scopes` say what a task runs on (`workspace`, `project`, `target`); `targetTags` restrict targets; `requiresUserArguments` makes the host ask for arguments. A `fromModel` task is the template for tasks the model lists. | @@ -1779,6 +1779,9 @@ Core lays out the window's tree from the model, the same way for every build tool (`build.modelTree` in the [Rust Core API](../../../../rust/contracts/rust-core-api.md#build-systems)): +- Each `options[]` entry with `presentation: "tree"` that currently offers at + least one choice appears at the top of `nodes` as an `option` checklist node + with `optionChoice` children (`checked`, `defaultActive`). - Projects nest by `parentID`. A project with no parent in the model, or one whose parent chain loops back to itself, becomes a root. - Each project lists, in this order, its tasks in their folders, a @@ -1862,7 +1865,7 @@ Canonical formats let a plugin's own script print the shape Core expects: | Format | Shape | | --- | --- | -| `litheBuildModel` | `{ "format": "litheBuildModel", "version": 0, "projects", "targets", "tasks", "contentRoots", "optionValues" }` with the model's field names; `tasks[].category` is an array of headings | +| `litheBuildModel` | `{ "format": "litheBuildModel", "version": 0, "projects", "targets", "tasks", "contentRoots", "optionValues", "optionDefaults"?, "optionExcludePrefixes"? }` with the model's field names; `tasks[].category` is an array of headings | | `litheTestResults` | `{ "format": "litheTestResults", "version": 0, "tests": [{ "suite", "case", "status", "message"?, "durationMillis"?, "path"?, "line"? }] }` | | `litheDependencies` | `{ "format": "litheDependencies", "version": 0, "dependencies": [{ "name", "group"?, "version"?, "scope"?, "properties"?, "children" }] }` | | `litheDiagnostics` | output lines `{ "lithe": "diagnostic", "path", "line", "column"?, "severity"?, "message" }` | diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index a05ad4d3..0c9fcb5b 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -2644,6 +2644,31 @@ } } } + }, + "optionDefaults": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "required": [ + "each", + "value" + ], + "properties": { + "each": { + "type": "string" + }, + "where": { + "type": "array", + "items": { + "$ref": "#/$defs/buildPredicate" + } + }, + "value": { + "$ref": "#/$defs/buildFieldSpec" + } + } + } } } }, @@ -2890,6 +2915,12 @@ "type": "string", "minLength": 1 }, + "excludePrefix": { + "description": "multiSelect only: 1-4 printable characters free of separator that turn a default choice off when prefixed to its value (such as '-' in '-P -dev').", + "type": "string", + "minLength": 1, + "maxLength": 4 + }, "arguments": { "type": "array", "items": { diff --git a/shared/plugins/reference/domains/build-systems.md b/shared/plugins/reference/domains/build-systems.md index 88b4a530..17ef5d19 100644 --- a/shared/plugins/reference/domains/build-systems.md +++ b/shared/plugins/reference/domains/build-systems.md @@ -55,7 +55,7 @@ - **选项范围。** 选项可以声明 `scope: "instance"`,按检测到的每个根目录分别保存:改动或重置 `a` 不会影响 `b`。省略范围(或 `"workspace"`)使用工作区和构建系统存储。显式的 `false`、`""`、`[]` 仍然是用户保存的值。实例值不能覆盖工作区选项,工作区值也不能悄悄覆盖实例选项。示例:`build-instance-options`。 - **可执行文件解析。** `invocation.executables` 按偏好顺序列出来源:`projectFile`(项目里的包装脚本,总是运行项目代码)、`environment`、`command`(`PATH` 上的命令名)、`runtime`、`setting`(引用声明为 `file` 的全局设置)和 `toolchain`(工具定义 ID)。可以用 `id`、`priority`、`insertBefore`、`insertAfter` 调整同一个候选集内的顺序。用户配置的路径失败是终止性的,不会回退到后面的候选或提供者自己的查找。示例:`build-tool-path`(`setting`)、`build-toolchains`(`toolchain`)。规则见[可执行文件解析](../../contract/v1/README.md#executable-resolution)。 -- **展示。** 每个启用的构建系统有自己的工具窗口,由宿主按模型绘制;`options[].presentation` 把布尔选项放到工具栏(`toolbar`,需要 `icon`)或把多选选项放成树顶部的清单(`tree`),`tasks[].category` 给任务归类。这些字段不改变任何计划。树由 Core 统一排布:项目按 `parentID` 嵌套,每个项目下依次是它的任务文件夹、依赖、目标和子项目;只作用于整个工作区的任务、依赖和测试在根项目旁边只出现一次;只有一个根项目时,它的内容直接作为构建系统的内容,任务仍在根项目上运行。 +- **展示。** 每个启用的构建系统有自己的工具窗口,由宿主按模型绘制;`options[].presentation` 把布尔选项放到工具栏(`toolbar`,需要 `icon`)或把多选选项放成树顶部的清单(`tree`),`tasks[].category` 给任务归类。模型可以通过 `optionDefaults` 给出未设置时默认激活的多选候选,并通过 `options[].excludePrefix` 或 `litheBuildModel` 的 `optionExcludePrefixes` 声明取消默认激活项的前缀(如 `"-"`),Core 负责把勾选集合编码成存储值并在树顶生成 `option` 与 `optionChoice` 节点。树由 Core 统一排布:项目按 `parentID` 嵌套,每个项目下依次是它的任务文件夹、依赖、目标和子项目;只作用于整个工作区的任务、依赖和测试在根项目旁边只出现一次;只有一个根项目时,它的内容直接作为构建系统的内容,任务仍在根项目上运行。 - **项目准备任务。** 项目任务可以声明 `preparation: { purpose, sourceRoles }`,按用途(如 `run`)和内容根角色绑定运行前要执行的任务;宿主从当前模型选出最深的所属项目和内容根,要求恰好一个匹配的声明,不猜任务名,也不回退到约定的任务 ID。示例:`build-providers/build-provider-preparation`。 - **只读模型输入。** 生产者用 `modelSharing: { options: [...] }` 公开规范化的项目、目标和内容根(以及明确列出的普通选项的有效值),消费者用 `modelInputs: [{ pluginID, buildSystemID }]` 读取,最多 8 个槽位。缺失、被禁用或不公开的生产者只会让该槽位 `unavailable`,从不被自动安装或激活;一个生产者不能同时是消费者。示例:`build-model-producer`、`build-model-consumer`。 @@ -152,7 +152,7 @@ A build system's `hostIntegration` and a language server's `hostIntegration` are - **Option scope.** An option may declare `scope: "instance"`, stored separately per detected root: changing or resetting `a` cannot change `b`. Omitting the scope (or `"workspace"`) uses the workspace and build-system storage. Explicit `false`, `""`, and `[]` remain stored user values. Instance values cannot override workspace options, and workspace values cannot silently override an instance option. Example: `build-instance-options`. - **Executable resolution.** `invocation.executables` lists sources in preference order: `projectFile` (a wrapper inside the project; always runs project code), `environment`, `command` (a bare name on `PATH`), `runtime`, `setting` (references a declared global `file` setting), and `toolchain` (a tool-definition ID). `id`, `priority`, `insertBefore`, and `insertAfter` reorder candidates within one candidate set. A configured path that fails is terminal and never falls back to later candidates or to the provider's own lookup. Examples: `build-tool-path` (`setting`) and `build-toolchains` (`toolchain`). The rules are in [Executable resolution](../../contract/v1/README.md#executable-resolution). -- **Presentation.** Every enabled build system gets a tool window of its own, drawn by the host from the model; `options[].presentation` puts a boolean option on the toolbar (`toolbar`, needs an `icon`) or a multiSelect option as a checklist at the top of the tree (`tree`), and `tasks[].category` files a task under headings. None of these fields changes a plan. Core lays out the tree the same way for every tool: projects nest by `parentID`, and each project lists its task folders, its dependencies, its targets and then its child projects; tasks, dependencies and tests that act on the whole workspace appear once, beside the root projects. With a single root project, its contents become the build system's own, and its tasks still run on the root project. +- **Presentation.** Every enabled build system gets a tool window of its own, drawn by the host from the model; `options[].presentation` puts a boolean option on the toolbar (`toolbar`, needs an `icon`) or a multiSelect option as a checklist at the top of the tree (`tree`), and `tasks[].category` files a task under headings. A model may also report choices active when the option is unset (`optionDefaults`) and a prefix that turns a default choice off (`options[].excludePrefix` or `optionExcludePrefixes` in `litheBuildModel`, such as `"-"`), so Core encodes the checked set and places `option` and `optionChoice` nodes at the top of the tree. Core lays out the tree the same way for every tool: projects nest by `parentID`, and each project lists its task folders, its dependencies, its targets and then its child projects; tasks, dependencies and tests that act on the whole workspace appear once, beside the root projects. With a single root project, its contents become the build system's own, and its tasks still run on the root project. - **Project preparation tasks.** A project task may declare `preparation: { purpose, sourceRoles }`, binding the task to run first by purpose (such as `run`) and content-root role. The host selects the deepest owning project and content root from the current model, requires exactly one matching declaration, never guesses a task name, and never falls back to a conventional task ID. Example: `build-providers/build-provider-preparation`. - **Read-only model inputs.** A producer publishes normalized projects, targets, and content roots (and the effective values of explicitly listed ordinary options) with `modelSharing: { options: [...] }`; a consumer reads them with `modelInputs: [{ pluginID, buildSystemID }]`, up to 8 slots. A missing, disabled, or non-public producer only makes that slot `unavailable` and is never installed or activated automatically; a producer cannot also be a consumer. Examples: `build-model-producer` and `build-model-consumer`. diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 12497129..1ba91c4d 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -134,6 +134,12 @@ ## 时间线(新的在上) +### 2026-11-18 + +| PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | +| --- | --- | --- | --- | --- | +| 待提 PR | [@Mucheen](https://github.com/Mucheen) | API-29 | `buildSystems` 0 内的补充 | 模型提供的多选构建选项支持默认激活项、取消前缀与树上勾选节点([1lck/Lithe-IDEA#2092](https://github.com/1lck/Lithe-IDEA/issues/2092)):`buildSystems[].options[]` 的 `multiSelect` 可选声明 `excludePrefix`(1–4 个可打印字符,不含 `separator`),`model.map` 新增可选 `optionDefaults`,`litheBuildModel` 新增可选 `optionDefaults` 与 `optionExcludePrefixes`(只写此二者、不改 `plugin.json` 的插件在旧宿主上也会安全忽略未知模型字段)。Core 在 `build.resolveOptions` 与 `build.editStoredOption` 中新增可选 `selectedChoices`、`modelDefaults`、`modelExcludePrefixes`,把用户勾选的集合编码为存储值(取消默认激活项时自动写入 ``,无团队覆盖且与默认激活集一致时清回 `null`),并在候选上标出 `defaultActive`、返回 `selectedChoices`;`build.modelTree` 在构建系统树顶部为 `presentation: "tree"` 的多选选项生成 `option` 与 `optionChoice` 节点(带 `checked`、`defaultActive` 和当前生效摘要)。清单格式向后兼容,没有新增宿主方法、通知或能力版本。 | + ### 2026-11-17 | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | From e441598bb3b120d5fe6caadfd7bc65cd386acf73 Mon Sep 17 00:00:00 2001 From: Mucheen <1528136628@qq.com> Date: Wed, 18 Nov 2026 09:51:45 +0800 Subject: [PATCH 2/3] =?UTF-8?q?docs(plugins):=20=E5=9B=9E=E5=A1=AB?= =?UTF-8?q?=E5=8D=8F=E8=AE=AE=E6=9B=B4=E6=96=B0=E8=AE=B0=E5=BD=95=E4=B8=AD?= =?UTF-8?q?=E7=9A=84=20Core=20PR=20#86=20=E7=BC=96=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/plugins/reference/protocol-changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 1ba91c4d..13c51229 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -138,7 +138,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | -| 待提 PR | [@Mucheen](https://github.com/Mucheen) | API-29 | `buildSystems` 0 内的补充 | 模型提供的多选构建选项支持默认激活项、取消前缀与树上勾选节点([1lck/Lithe-IDEA#2092](https://github.com/1lck/Lithe-IDEA/issues/2092)):`buildSystems[].options[]` 的 `multiSelect` 可选声明 `excludePrefix`(1–4 个可打印字符,不含 `separator`),`model.map` 新增可选 `optionDefaults`,`litheBuildModel` 新增可选 `optionDefaults` 与 `optionExcludePrefixes`(只写此二者、不改 `plugin.json` 的插件在旧宿主上也会安全忽略未知模型字段)。Core 在 `build.resolveOptions` 与 `build.editStoredOption` 中新增可选 `selectedChoices`、`modelDefaults`、`modelExcludePrefixes`,把用户勾选的集合编码为存储值(取消默认激活项时自动写入 ``,无团队覆盖且与默认激活集一致时清回 `null`),并在候选上标出 `defaultActive`、返回 `selectedChoices`;`build.modelTree` 在构建系统树顶部为 `presentation: "tree"` 的多选选项生成 `option` 与 `optionChoice` 节点(带 `checked`、`defaultActive` 和当前生效摘要)。清单格式向后兼容,没有新增宿主方法、通知或能力版本。 | +| [#86](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/86) | [@Mucheen](https://github.com/Mucheen) | API-29 | `buildSystems` 0 内的补充 | 模型提供的多选构建选项支持默认激活项、取消前缀与树上勾选节点([1lck/Lithe-IDEA#2092](https://github.com/1lck/Lithe-IDEA/issues/2092)):`buildSystems[].options[]` 的 `multiSelect` 可选声明 `excludePrefix`(1–4 个可打印字符,不含 `separator`),`model.map` 新增可选 `optionDefaults`,`litheBuildModel` 新增可选 `optionDefaults` 与 `optionExcludePrefixes`(只写此二者、不改 `plugin.json` 的插件在旧宿主上也会安全忽略未知模型字段)。Core 在 `build.resolveOptions` 与 `build.editStoredOption` 中新增可选 `selectedChoices`、`modelDefaults`、`modelExcludePrefixes`,把用户勾选的集合编码为存储值(取消默认激活项时自动写入 ``,无团队覆盖且与默认激活集一致时清回 `null`),并在候选上标出 `defaultActive`、返回 `selectedChoices`;`build.modelTree` 在构建系统树顶部为 `presentation: "tree"` 的多选选项生成 `option` 与 `optionChoice` 节点(带 `checked`、`defaultActive` 和当前生效摘要)。清单格式向后兼容,没有新增宿主方法、通知或能力版本。 | ### 2026-11-17 From 380b6d9abcb66e8fff106a5bed948100b52a295f Mon Sep 17 00:00:00 2001 From: wgw Date: Wed, 18 Nov 2026 11:26:45 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix(build):=20=E4=BF=9D=E7=95=99=E9=80=89?= =?UTF-8?q?=E9=A1=B9=E7=BB=A7=E6=89=BF=E5=B9=B6=E5=9B=9E=E6=98=BE=E5=AE=9E?= =?UTF-8?q?=E9=99=85=E6=BF=80=E6=B4=BB=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 保留兄弟构建根的本机值和空选择标记,恢复默认前检查实例继承。 - 在生成 Run 条目时使用模型取消前缀,并在配置启动时应用逐项覆盖。 - 为实际激活集合绑定模型调用的选项指纹,供构建树和编辑器复用。 - 用合成清单覆盖回归,补齐选项编辑契约、共享样例和协议记录。 Refs 1lck/Lithe-IDEA#2092 --- rust/contracts/rust-core-api.md | 23 ++- rust/crates/build/src/commands.rs | 23 ++- rust/crates/build/src/model.rs | 21 ++ rust/crates/build/src/model_inputs.rs | 17 +- rust/crates/build/src/options.rs | 44 ++++- rust/crates/build/src/outputs.rs | 7 + rust/crates/build/src/plans.rs | 16 +- rust/crates/build/src/run_preparation.rs | 7 +- rust/crates/build/src/stored_options.rs | 68 ++++--- rust/crates/build/src/tree.rs | 10 +- rust/crates/core/src/tests/build_systems.rs | 183 ++++++++++++++++-- rust/fixtures/build/option-edit-v1.json | 72 +++++++ shared/plugins/contract/v1/README.md | 10 +- .../plugins/reference/protocol-changelog.md | 2 +- 14 files changed, 434 insertions(+), 69 deletions(-) create mode 100644 rust/fixtures/build/option-edit-v1.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 8ac34187..db9500ed 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -4986,12 +4986,12 @@ and the directories are absolute host paths used only as substitution text. | `build.detect` | `{ workspaceRoot, plugins: [{ manifest }], options?: { : { : value } }, instanceOptions?: { : { : { : value } } }, instanceDefaults?: { : { : value } }, emptySelections?: { : { : [optionID] } }, ignoredPaths?: [pattern] }` | `detection`: `{ instances, rejected: [{ index, error }], shadowed: [{ pluginID, buildSystemID, by }] }`; each instance is `{ id, pluginID, buildSystemID, displayName, root, markers, modelSource, optionFingerprint, options, droppedOptions }` plus `model` or `modelError` for `static` and `hostIntegration` sources; a `provider` source has neither. `options` contains accepted stored values after Core scope/root merging, including explicit empty selections; `droppedOptions` names rejected stored values without rewriting the source document. The scan does not enter a directory `ignoredPaths` names; omitted (or `null`), it is Core's default `[".*"]`, every directory whose name starts with a dot, and `[]` ignores nothing beyond the shared scan policy. Hosts pass `storage.ignoredPaths.patterns` from `build.resolveStoredOptions`. An unusable list rejects with `plugin.build.invalidIgnoredPath` (see `build.editIgnoredPaths`). | | `build.projectOptions` | `{ document }`, host-read persisted v1 Build options, without a manifest | `document`: validated storage with version 1, systems and optional `ignoredPaths`; options, instance defaults, root values, explicit empty selections and saved custom choices are retained. Missing system fields normalize to empty maps; malformed, unsupported or oversized documents reject with `plugin.build.invalidOptionsDocument`. This pure operation never reads or writes a file and does not replace declared option resolution. | | `build.resolveStoredOptions` | `{ document, local: { version: 1, document, emptySelections?: { : { : [optionID] } } } }`, without a manifest | `storage: { document, local, emptySelections, ignoredPaths: { patterns, source } }`: checked team/local merge; local values override matching keys, unrelated systems/roots/choices stay intact. `ignoredPaths` is the list `build.detect` uses: a local list replaces the team's whole (`source: "local"`), then the team's (`"team"`), then Core's default `[".*"]` (`"default"`). No filesystem I/O. Local documents are machine/workspace preferences, not team files or plugin-native configuration. Their storage syntax is [build-local-options-v1.schema.json](build-local-options-v1.schema.json), with additional cross-field membership and byte limits checked by Core. | -| `build.editStoredOption` | `{ document, local, root, optionID, value, modelValues? }` in the standard manifest/build-system envelope | `edit: { local, options }`: changes one declared local preference. `null` removes the local override and restores team/declaration inheritance. Invalid or partially accepted edits reject before persistence. Workspace multi-selections preserve sibling-only values; explicit per-root empty markers apply only to workspace multi-select declarations. Platforms compare both native source revisions, atomically write only the local document and read back. | +| `build.editStoredOption` | `{ document, local, root, optionID, value?, selectedChoices?, modelValues?, modelDefaults?, modelExcludePrefixes?, modelSelection? }` in the standard manifest/build-system envelope | `edit: { local, options }`: changes one declared local preference. Pass exactly one of raw `value` or positive `selectedChoices` for a multi-select. Explicit `value: null` removes the local override. When the checked set equals the defaults, Core clears the local override only if the edited root would inherit those defaults and sibling-only selections and empty markers would survive. See [the option edit fixture](../fixtures/build/option-edit-v1.json). Invalid or partially accepted edits reject before persistence. Workspace multi-selections preserve sibling-only values; explicit per-root empty markers apply only to workspace multi-select declarations. Platforms compare both native source revisions, atomically write only the local document and read back. | | `build.editIgnoredPaths` | `{ document, local, patterns: [pattern] \| null }`, without a manifest; `patterns` is required | `edit: { local, ignoredPaths: { patterns, source } }`: the local document with its `ignoredPaths` replaced, or removed for `null` so the team list or the default applies again; `[]` is kept as an explicit choice to ignore nothing. A pattern uses `.gitignore` syntax relative to the workspace root and names directories only: as in one ignore file the last matching pattern decides, `!pattern` keeps a directory even if Git ignores it (the shared scan policy's caches and build outputs stay pruned), a pattern with a `/` before its end is anchored at the root and any other matches a directory name at any depth. At most 256 patterns of at most 1024 bytes; an empty or whitespace-padded entry, a comment, a lone `!`, a control character or an unparsable glob rejects with `plugin.build.invalidIgnoredPath` at `ignoredPaths[]`, the first entry not accepted (`ignoredPaths` when they cannot be compiled together). The team document is only read; an unusable list stored in either document makes it `plugin.build.invalidOptionsDocument`. Platforms publish the local document as for `build.editStoredOption`. | | `build.invocationPlan` | `{ root, platform: "macos" \| "linux" \| "windows" }` | `invocation`: `{ buildSystemID, root, executables, environmentInputs, runtimeDependencies, version, minimumVersion }` with project-file paths joined to `root`; every runtime dependency with a known probe, host-managed ones included, carries `version: { arguments }` | | `build.checkToolVersion` | `{ runtime?, output }` | `version`: `{ satisfied, version? }`; `runtime` checks that runtime dependency instead of the tool | | `build.resolveModelInputs` | `{revision, sources: [{manifest, instances: [{buildSystemID, root, state, model?, options?}]}]}` from installed enabled current-workspace sources | `modelInputs`: version 1 public snapshot with exact optional producer slots, state, normalized projects/targets/content roots, configuration fingerprint and explicitly shared options; no tasks/run/settings/private functions; see the [plugin contract](https://github.com/1lck/Lithe-IDEA/blob/preview/shared/plugins/contract/v1/README.md#optional-read-only-model-inputs) | -| `build.resolveOptions` | `{ options?, selectedChoices?, modelValues?, modelDefaults?, modelExcludePrefixes? }` | `options`: `{ options: [{ id, displayName, kind, scope?, value, selectedChoices?, source, choices: [{ value, title?, fromModel?, custom?, defaultActive? }], allowCustom }], dropped, fingerprint }` | +| `build.resolveOptions` | `{ options?, inheritedOptions?, selectedChoices?, modelValues?, modelDefaults?, modelExcludePrefixes?, modelSelection? }` | `options`: `{ options: [{ id, displayName, kind, scope?, value, selectedChoices?, source, choices: [{ value, title?, fromModel?, custom?, defaultActive? }], allowCustom }], dropped, fingerprint }` | | `build.configurationPlan` | plan fields and optional host-selected `tool` | `plan.provider` for `lithe/build/configuration`; no mutation, project or output-file parameters | | `build.decodeConfiguration` | `{ result }` | `configuration`: bounded `litheBuildConfiguration` v1 native sources/fields; see the plugin contract | | `build.configurationEditPlan` | `{ root, options?, workspaceStateDirectory, outputFile, snapshot, edits: { sourceID, revision, values }, tool? }` | Provider request `lithe/build/editConfiguration`; existing private staging only, no document bytes | @@ -5003,16 +5003,29 @@ and the directories are absolute host paths used only as substitution text. | `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.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?`, `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` | +| `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` | | `build.decodeRunPreparation` | `workspaceRoot`, instance `root`, raw `result`, same optional `launchOptions` | `launch` with portable `{executable:{kind,value},arguments,workingDirectory,environment}`; bounded strings and workspace directory containment, `plugin.build.invalidOutput` on invalid result | | `build.prepareDebugPlan` | same selected fields as `build.prepareRunPlan`; run declares same-plugin `debug.adapter` | `plan.provider` for `lithe/build/prepareDebug`; no cross-package reference, and launch options are refused: they apply only to running a target | | `build.decodeDebugPreparation` | `workspaceRoot`, instance `root`, selected `run`, raw `result` | `preparation` with declaration-owned `adapter`, normalized `root`, `program`, `arguments`, `workingDirectory`, `environment`; program is an existing regular file contained in the instance after canonicalization | -| `build.decodeModel` | `{ workspaceRoot, root, output?, outputFile?, result?, options? }`; `result` is the provider's JSON answer | `model`: `{ projects, targets, tasks, contentRoots, optionValues, optionDefaults?, optionExcludePrefixes?, run }`; `run` entries carry `buildSystem: { id, root, projectID, targetID?, optionFingerprint }` | +| `build.decodeModel` | `{ workspaceRoot, root, output?, outputFile?, result?, options? }`; `result` is the provider's JSON answer | `model`: `{ projects, targets, tasks, contentRoots, optionValues, optionDefaults?, optionExcludePrefixes?, optionSelection?, run }`; `run` entries carry `buildSystem: { id, root, projectID, targetID?, optionFingerprint }` | | `build.decodeTestResults` | `{ workspaceRoot, root, project?, projects?, output, notBeforeMillis?, suite? }`; without `project` the reports of the root and every listed model project are read | `results`: `{ tests: [{ suite, case, status, message?, durationMillis?, path?, line?, invocations }], summary: { total, passed, failed, errors, skipped }, success }`; repeated invocations of one case merge into the most severe status | | `build.decodeDiagnostics` | `{ workspaceRoot, root, output }` | `diagnostics`: `[{ path, line, column?, severity, message }]`, deduplicated, inside the workspace only | | `build.decodeDependencies` | `{ workspaceRoot, root, project?, output?, outputFile?, result? }` | `dependencies`: `{ project, dependencies: [{ name, group?, version?, scope?, properties?, children }], truncated }` | | `build.syncFingerprint` | `{ workspaceRoot, root, projects, options? }` | `sync`: `{ fingerprint, watch }` | -| `build.modelTree` | `{ model: { projects, targets, tasks, optionValues?, optionDefaults?, optionExcludePrefixes? }, options?, query?, groupHeadings?: { : heading } }`; `model` is a `build.decodeModel` result, other model fields are ignored | `tree`: `{ project?, nodes, truncated? }`; see below | +| `build.modelTree` | `{ model: { projects, targets, tasks, optionValues?, optionDefaults?, optionExcludePrefixes?, optionSelection? }, options?, query?, groupHeadings?: { : heading } }`; `model` is a `build.decodeModel` result, other model fields are ignored | `tree`: `{ project?, nodes, truncated? }`; see below | + +When the plugin reports actual active choices, `build.decodeModel` returns +`optionSelection: { fingerprint, activeChoices: { : [...] } }`. +Hosts pass this snapshot as `modelSelection` when resolving or editing options +and in the tree's `model`. Core uses observed choices only when the fingerprint +matches the effective invocation options. An explicit empty array represents +no active choices. Without a matching snapshot the checked state is derived +from the stored options and declared or model defaults. The defaults and +normalized invocation value remain distinct from the tool's observed choices. +To edit per-run build options, pass instance options as `inheritedOptions` and +explicit run choices as `options`. Each run choice replaces its inherited key. +`build.prepareRunPlan` applies the same precedence using instance `options` +and `optionOverrides` returned by `runConfig.providerLaunchInputs`. Invocation candidates also include `{ kind: "toolchain", toolchainID, root }`. Hosts resolve them through the same canonical project/subproject diff --git a/rust/crates/build/src/commands.rs b/rust/crates/build/src/commands.rs index 851862dd..40ace8b3 100644 --- a/rust/crates/build/src/commands.rs +++ b/rust/crates/build/src/commands.rs @@ -43,6 +43,9 @@ struct ResolveOptionsRequest { /// Stored option values by option ID. #[serde(default)] options: BTreeMap, + /// Lower-priority instance options when editing per-run overrides. + #[serde(default)] + inherited_options: BTreeMap, /// Positive choices checked in an option editor, encoded into `options` /// before resolution. #[serde(default)] @@ -57,6 +60,9 @@ struct ResolveOptionsRequest { /// The loaded model's `optionExcludePrefixes`. #[serde(default)] model_exclude_prefixes: Option>, + /// The loaded model's observed choices, valid for its option fingerprint. + #[serde(default)] + model_selection: Option, } fn with_build_system( @@ -145,12 +151,18 @@ pub fn build_resolve_options_command(payload: Value) -> Result defaults: request.model_defaults.as_ref(), exclude_prefixes: request.model_exclude_prefixes.as_ref(), }; - let mut stored = request.options.clone(); + let mut stored = request.inherited_options.clone(); + stored.extend(request.options.clone()); for (id, selected) in &request.selected_choices { let option = build_system.option(id).ok_or_else(|| { PluginRejection::new("plugin.build.invalidOption", "Unknown declared option") })?; - let encoded = options::encode_selected_choices(option, selected, false, &facts)?; + let encoded = options::encode_selected_choices( + option, + selected, + request.inherited_options.contains_key(id), + &facts, + )?; if encoded.is_null() { stored.remove(id); } else { @@ -158,7 +170,12 @@ pub fn build_resolve_options_command(payload: Value) -> Result } } let resolved = options::resolve_with_facts(build_system, &stored, facts); - Ok(options::describe_with_facts(build_system, &resolved, facts)) + Ok(options::describe_with_facts( + build_system, + &resolved, + facts, + request.model_selection.as_ref(), + )) }, ) } diff --git a/rust/crates/build/src/model.rs b/rust/crates/build/src/model.rs index 246cfc83..4cf57021 100644 --- a/rust/crates/build/src/model.rs +++ b/rust/crates/build/src/model.rs @@ -44,6 +44,9 @@ pub(crate) struct BuildModel { /// Per-option prefix a `litheBuildModel` script supplies to turn a default choice off. #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub(crate) option_exclude_prefixes: BTreeMap, + /// Actual choices reported by the tool. Model output attaches the invocation fingerprint. + #[serde(skip)] + pub(crate) option_active_choices: BTreeMap>, /// True when a bound dropped entries. #[serde(skip_serializing_if = "std::ops::Not::not")] pub(crate) truncated: bool, @@ -482,6 +485,15 @@ impl<'a> ModelBuilder<'a> { (!kept.is_empty()).then_some((id, kept)) }) .collect(); + model.option_active_choices.retain(|id, active| { + let Some(known) = model.option_values.get(id) else { + return false; + }; + active.retain(|choice| known.binary_search(choice).is_ok()); + active.sort(); + active.dedup(); + true + }); model } } @@ -737,6 +749,8 @@ struct CanonicalModel { option_defaults: BTreeMap>, #[serde(default)] option_exclude_prefixes: BTreeMap, + #[serde(default)] + option_active_choices: BTreeMap>, } #[derive(Debug, Deserialize)] @@ -916,6 +930,13 @@ pub(crate) fn map_canonical(builder: &mut ModelBuilder<'_>, document: Value) -> builder.add_option_default(option, value); } } + for (id, choices) in model.option_active_choices { + if builder.build_system.option(&id).is_some_and(|option| { + option.choices_from_model && option.kind == super::manifest::OptionKind::MultiSelect + }) { + builder.model.option_active_choices.insert(id, choices); + } + } for (option, prefix) in &model.option_exclude_prefixes { builder.set_option_exclude_prefix(option, prefix); } diff --git a/rust/crates/build/src/model_inputs.rs b/rust/crates/build/src/model_inputs.rs index f0b911bb..3848df37 100644 --- a/rust/crates/build/src/model_inputs.rs +++ b/rust/crates/build/src/model_inputs.rs @@ -182,8 +182,21 @@ pub(crate) fn resolve( .unwrap_or_else(|| json!({})), ) .map_err(|_| invalid())?; - let resolved = - options::resolve(producer, &instance.options, Some(&values)); + let exclude_prefixes = model + .get("optionExcludePrefixes") + .cloned() + .map(serde_json::from_value) + .transpose() + .map_err(|_| invalid())?; + let resolved = options::resolve_with_facts( + producer, + &instance.options, + options::ModelOptionFacts { + values: Some(&values), + exclude_prefixes: exclude_prefixes.as_ref(), + ..options::ModelOptionFacts::default() + }, + ); shared["configurationFingerprint"] = json!(options::fingerprint(producer, &resolved)); let shared_values: BTreeMap<_, _> = producer diff --git a/rust/crates/build/src/options.rs b/rust/crates/build/src/options.rs index 573d91ed..b5ebb268 100644 --- a/rust/crates/build/src/options.rs +++ b/rust/crates/build/src/options.rs @@ -6,6 +6,7 @@ use super::manifest::{BuildSystemDeclaration, OptionDeclaration, OptionKind}; use super::template::{self, Values}; use lithe_plugin_model::{PluginRejection, Validation}; +use serde::Deserialize; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; @@ -21,6 +22,25 @@ pub(crate) struct ModelOptionFacts<'a> { pub(crate) exclude_prefixes: Option<&'a BTreeMap>, } +/// Choices the tool observed when it produced a model, scoped to its invocation. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub(crate) struct ModelOptionSelection { + pub(crate) fingerprint: String, + pub(crate) active_choices: BTreeMap>, +} + +impl ModelOptionSelection { + /// A model can answer only for the option values used to load it. + pub(crate) fn matching_choices( + &self, + build_system: &BuildSystemDeclaration, + resolved: &ResolvedOptions, + ) -> Option<&BTreeMap>> { + (self.fingerprint == fingerprint(build_system, resolved)).then_some(&self.active_choices) + } +} + /// One choice of a select option as resolved for display and editing. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct ResolvedChoice { @@ -310,6 +330,7 @@ pub(crate) fn choice_state( option: &OptionDeclaration, resolved: &ResolvedOptions, facts: &ModelOptionFacts<'_>, + active: Option<&[String]>, ) -> Vec { let exclude_prefix = effective_exclude_prefix(option, facts); let defaults = default_choice_set(option, facts); @@ -323,11 +344,14 @@ pub(crate) fn choice_state( .filter_map(Value::as_str) .filter(|value| !exclude_prefix.is_some_and(|prefix| value.starts_with(prefix))) .collect(); + let active = active.map(|choices| choices.iter().map(String::as_str).collect::>()); let is_checked = |value: &str| { if option.kind != OptionKind::MultiSelect { return false; } - if chosen { + if let Some(active) = &active { + active.contains(value) + } else if chosen { stored_positives.contains(value) } else { defaults.contains(value) @@ -379,7 +403,7 @@ pub(crate) fn choice_state( from_model: false, custom: true, default_active: false, - checked: true, + checked: is_checked(value), }); } } @@ -388,12 +412,12 @@ pub(crate) fn choice_state( } /// Turns the positive choices the user checked for a `multiSelect` option into -/// the stored JSON value (`Value::Null` when no team override exists and the -/// checked set equals the default active set). +/// the stored JSON value. Callers can require an explicit override to preserve +/// inheritance and sibling selections even when the checked set is the default. pub(crate) fn encode_selected_choices( option: &OptionDeclaration, selected: &[String], - has_team_override: bool, + keep_override: bool, facts: &ModelOptionFacts<'_>, ) -> Validation { if option.kind != OptionKind::MultiSelect { @@ -419,7 +443,7 @@ pub(crate) fn encode_selected_choices( checked.sort(); checked.dedup(); let defaults: Vec = default_choice_set(option, facts).into_iter().collect(); - if !has_team_override && checked == defaults { + if !keep_override && checked == defaults { return Ok(Value::Null); } let mut items = checked.clone(); @@ -440,12 +464,15 @@ pub(crate) fn describe_with_facts( build_system: &BuildSystemDeclaration, resolved: &ResolvedOptions, facts: ModelOptionFacts<'_>, + selection: Option<&ModelOptionSelection>, ) -> Value { + let active = selection.and_then(|selection| selection.matching_choices(build_system, resolved)); let options: Vec = build_system .options .iter() .map(|option| { - let resolved_choices = choice_state(option, resolved, &facts); + let active = active.and_then(|choices| choices.get(&option.id).map(Vec::as_slice)); + let resolved_choices = choice_state(option, resolved, &facts, active); let choices: Vec = resolved_choices .iter() .map(|choice| { @@ -501,7 +528,8 @@ pub(crate) fn describe_with_facts( "allowCustom": option.allow_custom, }); if option.kind == OptionKind::MultiSelect - && (!defaults.is_empty() + && (active.is_some() + || !defaults.is_empty() || exclude_prefix.is_some() || resolved_choices.iter().any(|choice| choice.custom)) { diff --git a/rust/crates/build/src/outputs.rs b/rust/crates/build/src/outputs.rs index 8fbb5c6d..ae1f3cbe 100644 --- a/rust/crates/build/src/outputs.rs +++ b/rust/crates/build/src/outputs.rs @@ -188,6 +188,13 @@ pub(crate) fn model_value( let mut value = serde_json::to_value(model).map_err(|error| decode::invalid_output(error.to_string()))?; value["run"] = json!(run); + if !model.option_active_choices.is_empty() { + let resolved = options::resolve(build_system, options, None); + value["optionSelection"] = json!({ + "fingerprint": options::fingerprint(build_system, &resolved), + "activeChoices": model.option_active_choices, + }); + } Ok(value) } diff --git a/rust/crates/build/src/plans.rs b/rust/crates/build/src/plans.rs index 86042eed..a9e84b27 100644 --- a/rust/crates/build/src/plans.rs +++ b/rust/crates/build/src/plans.rs @@ -308,15 +308,15 @@ impl<'a> PlanContext<'a> { )) } } - Self::with_model_options(build_system, base, None) + Self::with_model_options(build_system, base, options::ModelOptionFacts::default()) } fn with_model_options( build_system: &'a BuildSystemDeclaration, base: &PlanBase, - model_values: Option<&BTreeMap>>, + facts: options::ModelOptionFacts<'_>, ) -> Validation { - let resolved = options::resolve(build_system, &base.options, model_values); + let resolved = options::resolve_with_facts(build_system, &base.options, facts); let contribution = options::contribution(build_system, &resolved)?; let fingerprint = options::fingerprint(build_system, &resolved); Ok(Self { @@ -1039,7 +1039,15 @@ pub(crate) fn run_entries( plugin_directory: None, workspace_state_directory: None, }; - let context = PlanContext::with_model_options(build_system, &base, Some(&model.option_values))?; + let context = PlanContext::with_model_options( + build_system, + &base, + options::ModelOptionFacts { + values: Some(&model.option_values), + defaults: Some(&model.option_defaults), + exclude_prefixes: Some(&model.option_exclude_prefixes), + }, + )?; let projects: BTreeMap<&str, &ModelProject> = model .projects .iter() diff --git a/rust/crates/build/src/run_preparation.rs b/rust/crates/build/src/run_preparation.rs index 8aec3067..a56f1e3a 100644 --- a/rust/crates/build/src/run_preparation.rs +++ b/rust/crates/build/src/run_preparation.rs @@ -162,6 +162,9 @@ pub(crate) struct PrepareRunRequest { /// The target of a target run; an entrypoint run has none. #[serde(default)] pub(crate) target: Option, + /// Per-run preferences take precedence over the instance's build options. + #[serde(default)] + pub(crate) option_overrides: BTreeMap, #[serde(default)] pub(crate) user_arguments: Vec, #[serde(default)] @@ -214,7 +217,9 @@ pub(crate) fn plan( "Provider run preparation does not use an output file.", )); } - let context = plans::PlanContext::new(build_system, &request.base.base)?; + let mut base = request.base.base.clone(); + base.options.extend(request.option_overrides.clone()); + let context = plans::PlanContext::new(build_system, &base)?; let project = request .base .project diff --git a/rust/crates/build/src/stored_options.rs b/rust/crates/build/src/stored_options.rs index 18850e8e..6d3a3a83 100644 --- a/rust/crates/build/src/stored_options.rs +++ b/rust/crates/build/src/stored_options.rs @@ -47,6 +47,8 @@ pub(super) struct EditRequest { model_defaults: Option>>, #[serde(default)] model_exclude_prefixes: Option>, + #[serde(default)] + model_selection: Option, } fn optional_value<'de, D: Deserializer<'de>>(input: D) -> Result, D::Error> { @@ -223,20 +225,49 @@ pub(super) fn edit(system: &BuildSystemDeclaration, request: &EditRequest) -> Va exclude_prefixes: request.model_exclude_prefixes.as_ref(), }; let before = merge(&team, &local); - let current = effective(system, &before, &local, &request.root); + let workspace_multi = + option.scope == OptionScope::Workspace && option.kind == OptionKind::MultiSelect; + let mut sibling_values = Vec::new(); + let mut sibling_clear = false; + if workspace_multi { + let current = effective(system, &before, &local, &request.root); + let visible = options::resolve_with_facts(system, ¤t, facts); + let visible = visible + .chosen_values + .get(&option.id) + .and_then(Value::as_array); + if let Some(raw) = before["systems"][&system.id]["options"][&option.id].as_array() { + sibling_values.extend( + raw.iter() + .filter(|value| visible.is_none_or(|values| !values.contains(value))) + .cloned(), + ); + } + sibling_clear = local.empty_selections.get(&system.id).is_some_and(|roots| { + roots + .iter() + .any(|(root, ids)| root != &request.root && ids.contains(&option.id)) + }); + } let mut next = match (&request.value, &request.selected_choices) { (Some(value), None) => value.clone(), (None, Some(selected)) => { let team_system = &team["systems"][&system.id]; - let has_team_override = if option.scope == OptionScope::Instance { + // Reset only if the current root inherits the model's defaults + // and removing the workspace value cannot erase sibling state. + let keep_override = if option.scope == OptionScope::Instance { team_system["instances"][&request.root] .get(&option.id) .is_some() - || team_system["instanceDefaults"].get(&option.id).is_some() + || before["systems"][&system.id]["instanceDefaults"] + .get(&option.id) + .is_some() } else { team_system["options"].get(&option.id).is_some() + || !sibling_values.is_empty() + || sibling_clear }; - options::encode_selected_choices(option, selected, has_team_override, &facts)? + options::encode_selected_choices(option, selected, keep_override, &facts)? } _ => { return Err(PluginRejection::new( @@ -292,21 +323,7 @@ pub(super) fn edit(system: &BuildSystemDeclaration, request: &EditRequest) -> Va } } } else { - if option.scope == OptionScope::Workspace && option.kind == OptionKind::MultiSelect { - let visible = options::resolve_with_facts(system, ¤t, facts) - .chosen_values - .get(&option.id) - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(); - let raw = before["systems"][&system.id]["options"][&option.id] - .as_array() - .cloned() - .unwrap_or_default(); - let mut merged = raw - .into_iter() - .filter(|value| !visible.contains(value)) - .collect::>(); + if workspace_multi { let exclude_prefix = options::effective_exclude_prefix(option, &facts); for value in next.as_array().expect("checked multi-select") { if let (Some(prefix), Some(text)) = (exclude_prefix, value.as_str()) { @@ -314,10 +331,10 @@ pub(super) fn edit(system: &BuildSystemDeclaration, request: &EditRequest) -> Va Some(rest) => rest.to_string(), None => format!("{prefix}{text}"), }; - merged.retain(|entry| entry.as_str() != Some(opposite.as_str())); + sibling_values.retain(|entry| entry.as_str() != Some(opposite.as_str())); } - if !merged.contains(value) { - merged.push(value.clone()); + if !sibling_values.contains(value) { + sibling_values.push(value.clone()); } } let ids = local @@ -331,7 +348,7 @@ pub(super) fn edit(system: &BuildSystemDeclaration, request: &EditRequest) -> Va } else { ids.remove(&option.id); } - next = json!(merged); + next = json!(sibling_values); } values.insert(option.id.clone(), next); } @@ -370,7 +387,10 @@ pub(super) fn edit(system: &BuildSystemDeclaration, request: &EditRequest) -> Va let document = merge(&team, &local); let stored = effective(system, &document, &local, &request.root); let resolved = options::resolve_with_facts(system, &stored, facts); - Ok(json!({"local":local,"options":options::describe_with_facts(system,&resolved,facts)})) + Ok(json!({ + "local": local, + "options": options::describe_with_facts(system, &resolved, facts, request.model_selection.as_ref()) + })) } /// `build.editIgnoredPaths`: replaces or removes the local ignored-path list. diff --git a/rust/crates/build/src/tree.rs b/rust/crates/build/src/tree.rs index 740332ae..52bd18ca 100644 --- a/rust/crates/build/src/tree.rs +++ b/rust/crates/build/src/tree.rs @@ -70,6 +70,8 @@ struct TreeModel { option_defaults: BTreeMap>, #[serde(default)] option_exclude_prefixes: BTreeMap, + #[serde(default)] + option_selection: Option, } #[derive(Debug, Deserialize)] @@ -283,13 +285,19 @@ fn tree_option_nodes( exclude_prefixes: Some(&request.model.option_exclude_prefixes), }; let resolved = options::resolve_with_facts(build_system, &request.options, facts); + let active = request + .model + .option_selection + .as_ref() + .and_then(|selection| selection.matching_choices(build_system, &resolved)); let mut nodes = Vec::new(); for option in build_system .options .iter() .filter(|option| option.presentation == Some(OptionPresentation::Tree)) { - let choices = options::choice_state(option, &resolved, &facts); + let active = active.and_then(|choices| choices.get(&option.id).map(Vec::as_slice)); + let choices = options::choice_state(option, &resolved, &facts, active); if choices.is_empty() { continue; } diff --git a/rust/crates/core/src/tests/build_systems.rs b/rust/crates/core/src/tests/build_systems.rs index c0fec527..5596a762 100644 --- a/rust/crates/core/src/tests/build_systems.rs +++ b/rust/crates/core/src/tests/build_systems.rs @@ -2469,6 +2469,16 @@ fn provider_run_preparation_selects_targets_and_validates_launch_data() { json!(["application"]) ); assert!(prepared["plan"].get("arguments").is_none()); + let mut request = fixture["request"].clone(); + request["options"] = json!({"offline": true}); + request["optionOverrides"] = json!({"offline": false}); + let override_plan = plan(request); + assert_eq!( + override_plan["plan"]["provider"]["params"]["options"]["offline"], + Value::Null, + "{override_plan}" + ); + for (field, value) in [ ( "target", @@ -3033,26 +3043,24 @@ fn provider_run_options_refuse_explicit_cwd_symlinks_outside_workspace() { fn model_option_defaults_and_exclusions_round_trip_through_storage_and_plans() { use crate::build::{build_edit_stored_option_command, build_model_plan_command}; let workspace = TemporaryWorkspace::new("model-option-defaults"); - let manifest: Value = serde_json::from_str(include_str!( - "fixtures/published_build_plugins/maven/plugin.json" - )) - .unwrap(); + let fixture = option_edit_fixture(); + let manifest = &fixture["manifest"]; let canonical = json!({ "format": "litheBuildModel", "version": 0, "projects": [{"path": ".", "name": "demo"}], + "targets": [{"path": ".", "name": "demo", "tags": ["launchable"]}], "optionValues": {"profiles": ["dev", "prod", "release"]}, "optionDefaults": {"profiles": ["dev"]}, "optionExcludePrefixes": {"profiles": "-"} }); - workspace.write("model.json", &canonical.to_string()); let decoded = build_decode_model_command::(json!({ "manifest": manifest, - "buildSystemID": "maven", + "buildSystemID": "fixture", "request": { "workspaceRoot": workspace.root(), "root": ".", - "outputFile": workspace.0.join("model.json").to_string_lossy(), + "output": canonical.to_string(), } })) .unwrap(); @@ -3077,7 +3085,7 @@ fn model_option_defaults_and_exclusions_round_trip_through_storage_and_plans() { let resolved = build_resolve_options_command::(json!({ "manifest": manifest, - "buildSystemID": "maven", + "buildSystemID": "fixture", "request": { "options": {}, "modelValues": model["optionValues"], @@ -3096,10 +3104,10 @@ fn model_option_defaults_and_exclusions_round_trip_through_storage_and_plans() { let empty_local = json!({"version": 1, "document": {"version": 1, "systems": {}}}); // Unchecking the default-active `dev` profile stores `["-dev"]`, so even a - // cold `build.modelPlan` before the model loads passes `-P -dev`. + // cold `build.modelPlan` before the model loads passes `--profiles -dev`. let unchecked = build_edit_stored_option_command::(json!({ "manifest": manifest, - "buildSystemID": "maven", + "buildSystemID": "fixture", "request": { "document": empty_team, "local": empty_local, @@ -3119,12 +3127,10 @@ fn model_option_defaults_and_exclusions_round_trip_through_storage_and_plans() { let plan = build_model_plan_command::(json!({ "manifest": manifest, - "buildSystemID": "maven", + "buildSystemID": "fixture", "request": { "root": ".", - "options": {"profiles": ["-dev"]}, - "pluginDirectory": workspace.root(), - "outputFile": workspace.0.join("next.json").to_string_lossy() + "options": {"profiles": ["-dev"]} } })) .unwrap(); @@ -3135,14 +3141,30 @@ fn model_option_defaults_and_exclusions_round_trip_through_storage_and_plans() { .filter_map(Value::as_str) .collect(); assert!( - args.windows(2).any(|pair| pair == ["-P", "-dev"]), - "expected -P -dev in {args:?}" + args.windows(2).any(|pair| pair == ["--profiles", "-dev"]), + "expected --profiles -dev in {args:?}" + ); + + let decoded = build_decode_model_command::(json!({ + "manifest": manifest, + "buildSystemID": "fixture", + "request": { + "workspaceRoot": workspace.root(), + "root": ".", + "output": canonical.to_string(), + "options": {"profiles": ["-dev"]} + } + })) + .unwrap(); + assert_eq!( + decoded["model"]["run"][0]["args"], + json!(["--profiles", "-dev", "launch"]) ); - // Switching to `prod` while keeping `dev` unchecked passes `-P -dev,prod`. + // Switching to `prod` while keeping `dev` unchecked passes `--profiles -dev,prod`. let switched = build_edit_stored_option_command::(json!({ "manifest": manifest, - "buildSystemID": "maven", + "buildSystemID": "fixture", "request": { "document": empty_team, "local": unchecked["edit"]["local"], @@ -3162,7 +3184,7 @@ fn model_option_defaults_and_exclusions_round_trip_through_storage_and_plans() { // Returning to `["dev"]` removes the local override altogether. let restored = build_edit_stored_option_command::(json!({ "manifest": manifest, - "buildSystemID": "maven", + "buildSystemID": "fixture", "request": { "document": empty_team, "local": switched["edit"]["local"], @@ -3180,3 +3202,126 @@ fn model_option_defaults_and_exclusions_round_trip_through_storage_and_plans() { let after_restore = option_by_id(&restored["edit"]["options"], "profiles"); assert_eq!(after_restore["source"], "default"); } + +fn option_edit_fixture() -> Value { + serde_json::from_str(include_str!( + "../../../../fixtures/build/option-edit-v1.json" + )) + .unwrap() +} + +#[test] +fn selecting_model_defaults_preserves_sibling_and_inherited_options() { + use crate::build::build_edit_stored_option_command; + let fixture = option_edit_fixture(); + let case = &fixture["restoreDefault"]; + let outcome = build_edit_stored_option_command::(json!({ + "manifest": fixture["manifest"], + "buildSystemID": "fixture", + "request": case["request"], + })) + .unwrap(); + let edit = &outcome["edit"]; + assert_eq!( + edit["local"]["document"]["systems"]["fixture"]["options"]["profiles"], + case["expectedStoredChoices"], + "{outcome}" + ); + assert_eq!( + edit["local"]["emptySelections"], + case["expectedEmptySelections"] + ); + assert_eq!( + edit["options"]["options"][0]["selectedChoices"], + case["expectedSelectedChoices"] + ); + + let mut manifest = fixture["manifest"].clone(); + manifest["buildSystems"][0]["options"][0]["scope"] = json!("instance"); + let mut request = case["request"].clone(); + request["local"] = json!({"version": 1, "document": {"version": 1, "systems": { + "fixture": {"instanceDefaults": {"profiles": ["prod"]}} + }}}); + let outcome = build_edit_stored_option_command::(json!({ + "manifest": manifest, + "buildSystemID": "fixture", + "request": request, + })) + .unwrap(); + let edit = &outcome["edit"]; + assert_eq!( + edit["local"]["document"]["systems"]["fixture"]["instances"]["a"]["profiles"], + json!(["dev"]), + "{outcome}" + ); + assert_eq!( + edit["options"]["options"][0]["selectedChoices"], + json!(["dev"]) + ); +} + +#[test] +fn observed_model_choices_apply_only_to_the_matching_build_options() { + use crate::build::build_model_tree_command; + let fixture = option_edit_fixture(); + let manifest = &fixture["manifest"]; + let workspace = TemporaryWorkspace::new("observed-build-option-choices"); + let stored = json!({"profiles": ["prod"]}); + let result = build_decode_model_command::(json!({ + "manifest": manifest, + "buildSystemID": "fixture", + "request": { + "workspaceRoot": workspace.root(), "root": ".", "options": stored, + "output": json!({ + "format": "litheBuildModel", "version": 0, + "optionValues": {"profiles": ["dev", "prod"]}, + "optionDefaults": {"profiles": ["dev"]}, + "optionExcludePrefixes": {"profiles": "-"}, + "optionActiveChoices": {"profiles": ["prod", "dev", "-dev", "unknown"]} + }).to_string() + } + })) + .unwrap(); + let model = &result["model"]; + assert_eq!( + model["optionSelection"]["activeChoices"]["profiles"], + json!(["dev", "prod"]), + "{result}" + ); + let mut request = json!({ + "options": stored, "modelValues": model["optionValues"], + "modelDefaults": model["optionDefaults"], + "modelExcludePrefixes": model["optionExcludePrefixes"], + "modelSelection": model["optionSelection"] + }); + let resolve = |request: &Value| { + let result = build_resolve_options_command::(json!({ + "manifest": manifest, "buildSystemID": "fixture", "request": request + })) + .unwrap(); + result["options"]["options"][0]["selectedChoices"].clone() + }; + assert_eq!(resolve(&request), json!(["dev", "prod"])); + let mut editor_request = request.clone(); + editor_request["inheritedOptions"] = stored.clone(); + editor_request["options"] = json!({}); + assert_eq!(resolve(&editor_request), json!(["dev", "prod"])); + editor_request["selectedChoices"] = json!({"profiles": ["dev"]}); + assert_eq!(resolve(&editor_request), json!(["dev"])); + + request["options"]["profiles"] = json!(["-dev", "prod"]); + assert_eq!(resolve(&request), json!(["prod"])); + let tree = build_model_tree_command::(json!({ + "manifest": manifest, "buildSystemID": "fixture", + "request": {"model": model, "options": stored} + })) + .unwrap(); + assert_eq!( + tree["tree"]["nodes"][0]["children"][0]["checked"], true, + "{tree}" + ); + assert_eq!( + tree["tree"]["nodes"][0]["children"][1]["checked"], true, + "{tree}" + ); +} diff --git a/rust/fixtures/build/option-edit-v1.json b/rust/fixtures/build/option-edit-v1.json new file mode 100644 index 00000000..f11af444 --- /dev/null +++ b/rust/fixtures/build/option-edit-v1.json @@ -0,0 +1,72 @@ +{ + "version": 1, + "manifest": { + "schemaVersion": 0, + "id": "dev.lithe.test.build-option-edit", + "displayName": "Build Option Fixture", + "version": "0.1.0", + "pluginAPIVersion": 0, + "requires": { "buildSystems": 0 }, + "vendor": { "id": "org.example", "displayName": "Example", "signatureRequirement": "publisherPackage" }, + "permissions": ["process.build"], + "activationEvents": ["onBuildSystem:fixture"], + "languages": [], + "buildSystems": [ + { + "id": "fixture", + "displayName": "Build Fixture", + "detection": { "markers": ["fixture.toml"] }, + "invocation": { + "executables": [{ "kind": "command", "command": "fixture-tool" }], + "globalArguments": ["${optionArguments:profiles}"] + }, + "options": [ + { + "id": "profiles", + "displayName": "Profiles", + "kind": "multiSelect", + "choicesFromModel": true, + "presentation": "tree", + "arguments": ["--profiles", "${value}"] + } + ], + "model": { + "source": "command", + "arguments": ["model"], + "decoder": "litheBuildModel", + "executesProjectCode": false, + "mayUseNetwork": false + }, + "run": [ + { + "id": "launch", + "fromTargets": { "tags": ["launchable"] }, + "arguments": ["launch"] + } + ] + } + ] + }, + "restoreDefault": { + "request": { + "document": { "version": 1, "systems": {} }, + "local": { + "version": 1, + "document": { + "version": 1, + "systems": { "fixture": { "options": { "profiles": ["qa", "-dev"] } } } + }, + "emptySelections": { "fixture": { "c": ["profiles"] } } + }, + "root": "a", + "optionID": "profiles", + "selectedChoices": ["dev"], + "modelValues": { "profiles": ["dev", "prod"] }, + "modelDefaults": { "profiles": ["dev"] }, + "modelExcludePrefixes": { "profiles": "-" } + }, + "expectedStoredChoices": ["qa", "dev"], + "expectedSelectedChoices": ["dev"], + "expectedEmptySelections": { "fixture": { "c": ["profiles"] } } + } +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 4c2a0b84..789049ba 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -1866,11 +1866,19 @@ Canonical formats let a plugin's own script print the shape Core expects: | Format | Shape | | --- | --- | -| `litheBuildModel` | `{ "format": "litheBuildModel", "version": 0, "projects", "targets", "tasks", "contentRoots", "optionValues", "optionDefaults"?, "optionExcludePrefixes"? }` with the model's field names; `tasks[].category` is an array of headings | +| `litheBuildModel` | `{ "format": "litheBuildModel", "version": 0, "projects", "targets", "tasks", "contentRoots", "optionValues", "optionDefaults"?, "optionExcludePrefixes"?, "optionActiveChoices"? }` with the model's field names; `tasks[].category` is an array of headings | | `litheTestResults` | `{ "format": "litheTestResults", "version": 0, "tests": [{ "suite", "case", "status", "message"?, "durationMillis"?, "path"?, "line"? }] }` | | `litheDependencies` | `{ "format": "litheDependencies", "version": 0, "dependencies": [{ "name", "group"?, "version"?, "scope"?, "properties"?, "children" }] }` | | `litheDiagnostics` | output lines `{ "lithe": "diagnostic", "path", "line", "column"?, "severity"?, "message" }` | +A canonical model can report `optionActiveChoices: { : [...] }` for +model-backed multi-select options. List the values the tool actually activated +for this invocation, including values activated outside the IDE's saved +options. Use an empty array if the tool reports that none are active. Omit the +entry when the tool cannot observe the active set. Report baseline defaults in +`optionDefaults`; Core restricts both sets to the available `optionValues` and +ties the observed set to the option fingerprint of the model load. + Unknown fields in canonical documents are ignored, so a script may add fields without a new version. Output that does not fit its decoder is `plugin.build.invalidOutput`. diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 06becfd3..42e8de22 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -141,7 +141,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | | [#89](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/89) | [@1lck](https://github.com/1lck) | — | **`buildProviders` 1**、**`litheBuild` 1** | 按源文件找运行入口([1lck/Lithe-IDEA#2104](https://github.com/1lck/Lithe-IDEA/issues/2104)):运行声明可写 `entrypoints: true`(只能是提供者的 `application`,不写 `fromTargets`、`fromTasks`、`arguments`、`extension`、`debug`),它不对应任何目标,宿主不按目标列出它。新提供者方法 `lithe/build/runEntrypoints`(参数多一个工作区相对路径 `file`)返回 `litheRunEntrypoints` 0 文档,列出这个文件里可运行的入口 `{run, name, entrypoint, project}`,最多 64 个;Core 新增 `build.runEntrypointsPlan` 和 `build.decodeRunEntrypoints` 校验。`lithe/build/prepareRun` 对入口运行不带 `target`,必须带 `launchOptions.entrypoint`。宿主提供 `litheBuild` 版本 `[0, 1]`,三个 SDK 回答宿主提供的最新版本,Java/Node SDK 新增 `onRunEntrypoints`/`build.runEntrypoints`。用入口运行的插件声明 `buildProviders: 1`,只支持 0 的宿主不会安装;其他插件不受影响。新增 fixture `build-provider-run-entrypoints.plugin.json`、`build-run-entrypoints.json`。没有新增宿主方法或通知。 | -| [#86](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/86) | [@Mucheen](https://github.com/Mucheen) | API-29 | `buildSystems` 0 内的补充 | 模型提供的多选构建选项支持默认激活项、取消前缀与树上勾选节点([1lck/Lithe-IDEA#2092](https://github.com/1lck/Lithe-IDEA/issues/2092)):`buildSystems[].options[]` 的 `multiSelect` 可选声明 `excludePrefix`(1–4 个可打印字符,不含 `separator`),`model.map` 新增可选 `optionDefaults`,`litheBuildModel` 新增可选 `optionDefaults` 与 `optionExcludePrefixes`(只写此二者、不改 `plugin.json` 的插件在旧宿主上也会安全忽略未知模型字段)。Core 在 `build.resolveOptions` 与 `build.editStoredOption` 中新增可选 `selectedChoices`、`modelDefaults`、`modelExcludePrefixes`,把用户勾选的集合编码为存储值(取消默认激活项时自动写入 ``,无团队覆盖且与默认激活集一致时清回 `null`),并在候选上标出 `defaultActive`、返回 `selectedChoices`;`build.modelTree` 在构建系统树顶部为 `presentation: "tree"` 的多选选项生成 `option` 与 `optionChoice` 节点(带 `checked`、`defaultActive` 和当前生效摘要)。清单格式向后兼容,没有新增宿主方法、通知或能力版本。 | +| [#86](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/86) | [@Mucheen](https://github.com/Mucheen) | API-29 | `buildSystems` 0 内的补充 | 构建树与选项编辑支持模型提供的默认激活项、实际激活集合和取消前缀([1lck/Lithe-IDEA#2092](https://github.com/1lck/Lithe-IDEA/issues/2092))。规范模型可报告 `optionDefaults`、`optionExcludePrefixes` 和 `optionActiveChoices`。Core 按选项指纹匹配实际激活集合,保留兄弟构建根和继承值,并在生成运行条目时解析取消前缀。清单中的 `excludePrefix` 和 `model.map.optionDefaults` 需要支持这些字段的 Core。旧 Core 可忽略规范模型新增字段。宿主方法、通知和能力版本沿用现有契约。 | | [#85](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/85) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | 插件清单 `schemaVersion` 0 内的补充 | 清单新增可选字段 `repository`([1lck/Lithe-IDEA#2100](https://github.com/1lck/Lithe-IDEA/issues/2100)):值是插件源码仓库的 GitHub 地址 `https://github.com/<作者>/<仓库>`,格式不对时以 `plugin.manifest.invalid`(字段 `repository`)拒绝。项目里由插件提供的 Run 配置改存 `.lithe/run/plugin/<插件 ID>.toml`(共享)和 `<插件 ID>.local.toml`(本机),文件头 `[plugin]` 记录插件 ID、名称、作者、仓库、版本、版本要求(默认 `>=保存时的版本`)、`pluginAPIVersion` 和用到的能力,作者和仓库取自 `repository`,用来区分同名插件;插件没有安装、仓库不一致或版本不满足要求时,这些配置在 Run 列表里显示为不可用并说明原因,不会让整个列表读取失败。Core 自带的脚本和程序运行(shell、PowerShell、Windows 批处理、可执行文件)不依赖任何插件。没写 `repository` 的插件照常安装,Run 文件里不记作者和仓库、也不比对仓库;清单格式和能力版本不变,没有新增宿主方法或通知。 | ### 2026-11-17