diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 219f679f..c7749b61 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -5680,13 +5680,13 @@ user to trust the workspace before an action the user started. | Command | Request | Result | | --- | --- | --- | -| `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: a value a declared option does not accept, and a value saved for an option ID the build system no longer declares (in `options`, the root's `instanceOptions` or `instanceDefaults`), which contributes nothing to `options`, the model or the fingerprint. 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.detect` | `{ workspaceRoot, plugins: [{ manifest }], options?: { : { : value } }, instanceOptions?: { : { : { : value } } }, instanceDefaults?: { : { : value } }, emptySelections?: { : { : [optionID] } }, ignoredPaths?: [pattern] }` | `detection`: `{ instances, rejected: [{ index, error }], shadowed: [{ pluginID, buildSystemID, by }], pluginIgnoredPaths: [{ pluginID, buildSystemID, displayName, patterns }] }`; 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: a value a declared option does not accept, and a value saved for an option ID the build system no longer declares (in `options`, the root's `instanceOptions` or `instanceDefaults`), which contributes nothing to `options`, the model or the fingerprint. 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 `[]` supplies no workspace rules. The shared scan policy and plugin-specific defaults still apply. `pluginIgnoredPaths` holds, in build-system ID order, one entry for every winning declaration with `detection.ignoredPaths`, even if it has no instance, and is `[]` when none has any; a shadowed declaration's rules neither apply nor appear. Each list filters only that system's candidates: a candidate is dropped when it or a directory between it and the workspace root is ignored, so under `outermost` nesting a marker below an ignored root does not become an instance; at each of those directories the workspace rules decide first, so a workspace `!pattern` brings the directory back. Manifest validation compiles these lists, so a plugin with a list Core cannot compile is reported in `rejected` under its index with `plugin.manifest.invalid` at `buildSystems[].detection.ignoredPaths[]` and none of its build systems is detected. See [the plugin ignore fixture](../fixtures/build/detect-plugin-ignored-paths-v1.json). Hosts display these lists separately from editable workspace patterns. Hosts pass `storage.ignoredPaths.patterns` from `build.resolveStoredOptions`. An unusable workspace `ignoredPaths` list rejects with `plugin.build.invalidIgnoredPath` (see `build.editIgnoredPaths`). | | `build.localizeOptions` | `{ language?, plugins: [{ manifest, localizations? }] }`, without the standard manifest/build-system wrapper | `{ manifests, localizations }`: one manifest per plugin in request order, with the `buildOptions` part of the first accepted translation file applied to `buildSystems[].options[]` (`displayName`, `description`, choice `title`), else as sent; one report per plugin that declares a build option when `language` is set, `{ pluginID, language, candidates, maximumBytes, readRequired, applied, rejected }` as in `plugins.settings`. Hosts send it without `localizations`, read the named candidates from the installed package, send it again with them, and detect with the returned manifests. A file that does not fit is refused whole as `plugin.build.invalidLocalization` | | `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.resolveStoredInstanceOptions` | `{ document, local, root }` in the standard manifest/build-system envelope. The preference documents use the same shapes as `build.resolveStoredOptions`. | `options`: accepted stored values keyed by option ID, using the same merge, scope and root rules as `build.detect`. Use an empty string for the workspace root. Unavailable build systems and invalid roots are rejected. No filesystem I/O. | | `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. An `optionID` the declaration no longer has (a plugin update dropped it; `build.detect` names it in `droppedOptions`) accepts only `value: null`, which removes its local workspace value, instance default and this root's value, so a host can clear what no longer applies; anything else rejects with `plugin.build.invalidOption`. 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.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; `[]` explicitly clears the workspace rules. Plugin-specific detection defaults still apply. 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](../../shared/plugins/contract/v1/README.md#optional-read-only-model-inputs) | diff --git a/rust/crates/build/src/detect.rs b/rust/crates/build/src/detect.rs index 68340cd8..ff4dfefd 100644 --- a/rust/crates/build/src/detect.rs +++ b/rust/crates/build/src/detect.rs @@ -14,7 +14,7 @@ use super::manifest::{BuildSystemDeclaration, ModelSource, Nesting, OptionKind, use super::options; use super::outputs::{model_value, read_model, source_marker}; use super::BuildManifest; -use lithe_plugin_model::{PluginRejection, Validation}; +use lithe_plugin_model::{invalid, PluginRejection, Validation}; use lithe_protocol::CoreError; use serde::Deserialize; use serde_json::{json, Value}; @@ -57,6 +57,10 @@ pub(crate) struct DetectPlugin { /// The declaration that answers for one build-system ID. struct Owner<'a> { + /// The plugin's position in the request, as `rejected` reports it. + index: usize, + /// The declaration's position in the manifest's `buildSystems`. + position: usize, plugin_id: &'a str, declaration: &'a BuildSystemDeclaration, } @@ -79,6 +83,9 @@ fn is_below(path: &str, ancestor: &str) -> bool { fn roots( declaration: &BuildSystemDeclaration, directories: &[lithe_execution::DirectoryContext], + workspace_root: &Path, + workspace_rules: &lithe_execution::IgnoredPaths, + plugin_rules: Option<&lithe_execution::IgnoredPaths>, ) -> Vec<(String, Vec)> { let mut candidates: Vec<(String, Vec)> = directories .iter() @@ -90,7 +97,27 @@ fn roots( .filter(|marker| directory.has(marker)) .map(|marker| directory.join_relative(marker)) .collect(); - (!markers.is_empty()).then(|| (directory.relative.clone(), markers)) + if markers.is_empty() { + return None; + } + // A pruned ancestor also excludes its descendants. The shared walk has + // already applied workspace and Git rules, so only the plugin can add exclusions. + if let Some(plugin_rules) = plugin_rules { + let path = workspace_root.join(&directory.relative); + if path + .ancestors() + .take_while(|p| *p != workspace_root) + .any(|p| { + workspace_rules + .decides(p) + .or_else(|| plugin_rules.decides(p)) + == Some(true) + }) + { + return None; + } + } + Some((directory.relative.clone(), markers)) }) .collect(); candidates.sort_by(|left, right| left.0.cmp(&right.0)); @@ -198,16 +225,18 @@ pub(crate) fn detect(request: DetectRequest) -> Validation manifests.push(manifest), + Ok(manifest) => manifests.push((index, manifest)), Err(error) => rejected.push(json!({ "index": index, "error": error })), } } let mut owners: BTreeMap<&str, Owner<'_>> = BTreeMap::new(); let mut shadowed = Vec::new(); - for manifest in &manifests { - for declaration in manifest.build_systems() { + for (index, manifest) in &manifests { + for (position, declaration) in manifest.build_systems().iter().enumerate() { let candidate = Owner { + index: *index, + position, plugin_id: manifest.id(), declaration, }; @@ -243,7 +272,12 @@ pub(crate) fn detect(request: DetectRequest) -> Validation(request: DetectRequest) -> Validation { + plugin_ignored_paths.push(json!({ + "pluginID": owner.plugin_id, + "buildSystemID": owner.declaration.id, + "displayName": owner.declaration.display_name, + "patterns": patterns, + })); + Some(rules) + } + Err(error) => { + let field = format!( + "buildSystems[{}].detection.{}", + owner.position, + error.field().unwrap_or("ignoredPaths") + ); + rejected.push(json!({ + "index": owner.index, + "error": invalid(field, error.message), + })); + continue; + } + } + }; let stored = request.options.get(&owner.declaration.id).unwrap_or(&empty); - for (root, markers) in roots(owner.declaration, &directories) { + for (root, markers) in roots( + owner.declaration, + &directories, + &workspace.path, + &ignored, + plugin_rules.as_ref(), + ) { if seen.insert((owner.declaration.id.clone(), root.clone())) { let local = request .instance_options @@ -309,6 +382,7 @@ pub(crate) fn detect(request: DetectRequest) -> Validation, + /// Workspace-relative directory rules applied only to this declaration's candidates. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) ignored_paths: Vec, #[serde(default)] pub(crate) nesting: Nesting, /// Decides between plugins declaring the same build-system ID. @@ -49,6 +52,17 @@ impl BuildSystemDeclaration { )); } detection.markers = sorted_unique(std::mem::take(&mut detection.markers)); + if !detection.ignored_paths.is_empty() { + super::super::ignored_paths::check(&detection.ignored_paths).map_err(|error| { + invalid( + format!( + "{field}.detection.{}", + error.field.as_deref().unwrap_or("ignoredPaths") + ), + error.message, + ) + })?; + } if detection.priority > MAX_PRIORITY { return Err(invalid( format!("{field}.detection.priority"), diff --git a/rust/crates/core/src/tests/build_systems.rs b/rust/crates/core/src/tests/build_systems.rs index bdfdeeed..e863bdf9 100644 --- a/rust/crates/core/src/tests/build_systems.rs +++ b/rust/crates/core/src/tests/build_systems.rs @@ -868,6 +868,149 @@ fn detection_skips_the_ignored_paths_and_by_default_every_dot_directory() { assert_eq!(rejected["error"]["field"], "ignoredPaths[1]"); } +/// A plugin's rules filter only its own build system's candidates. An ignored +/// directory also hides the markers below it, so `outermost` nesting does not +/// promote them, and a plugin `!` keeps one directory its broader rule names. +/// The workspace restores a directory a plugin ignores without editing the +/// declaration. The fixture is the shared golden for these results. +#[test] +fn detection_follows_the_plugin_ignored_paths_fixture() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../fixtures/build/detect-plugin-ignored-paths-v1.json" + )) + .unwrap(); + let workspace = TemporaryWorkspace::new("build-plugin-ignore"); + for file in fixture["files"].as_array().unwrap() { + workspace.write(file.as_str().unwrap(), ""); + } + let detect = |manifest: &Value, paths: &Value| { + let outcome = build_detect_command::(json!({ + "workspaceRoot": workspace.root(), + "plugins": [{"manifest": manifest}], + "ignoredPaths": paths, + })) + .expect("payload is well formed"); + assert_eq!(outcome["status"], "ok", "{outcome}"); + outcome["detection"].clone() + }; + for case in fixture["cases"].as_array().unwrap() { + let detection = detect(&fixture["manifest"], &case["ignoredPaths"]); + assert_eq!( + json!(instance_ids(&detection)), + case["expectedInstances"], + "{}", + case["name"] + ); + assert_eq!( + detection["pluginIgnoredPaths"], fixture["expectedPluginIgnoredPaths"], + "{}", + case["name"] + ); + assert_eq!(detection["rejected"], json!([]), "{}", case["name"]); + } + + let mut manifest = fixture["manifest"].clone(); + manifest["buildSystems"][0]["detection"]["ignoredPaths"] = json!(["ok", "# comment"]); + let rejected = detect(&manifest, &Value::Null); + assert_eq!( + rejected["rejected"][0]["error"]["code"], + "plugin.manifest.invalid" + ); + assert_eq!( + rejected["rejected"][0]["error"]["field"], + "buildSystems[0].detection.ignoredPaths[1]" + ); + assert_eq!(rejected["instances"], json!([])); + assert_eq!(rejected["pluginIgnoredPaths"], json!([])); +} + +/// Only the declaration that answers for a build-system ID filters with its +/// rules; the rules of the one it shadows neither apply nor appear. +#[test] +fn detection_applies_only_the_winning_declaration_rules() { + let workspace = TemporaryWorkspace::new("build-plugin-ignore-shadowed"); + workspace + .write("snapshots/a/Cargo.toml", "") + .write("vendor/b/Cargo.toml", ""); + let shadowed = fixture("build-static-file.plugin.json"); + let mut preferred = shadowed.clone(); + preferred["id"] = json!("dev.lithe.fixture.cargo-preferred"); + preferred["buildSystems"][0]["detection"]["priority"] = json!(80); + preferred["buildSystems"][0]["detection"]["ignoredPaths"] = json!(["vendor/"]); + + let detection = detect( + &workspace, + vec![shadowed.clone(), preferred.clone()], + json!({}), + ); + assert_eq!(instance_ids(&detection), ["cargo:snapshots/a"]); + assert_eq!( + detection["pluginIgnoredPaths"], + json!([{ + "pluginID": "dev.lithe.fixture.cargo-preferred", "buildSystemID": "cargo", + "displayName": "Cargo", "patterns": ["vendor/"] + }]) + ); + + preferred["buildSystems"][0]["detection"] + .as_object_mut() + .unwrap() + .remove("ignoredPaths"); + let detection = detect(&workspace, vec![shadowed, preferred], json!({})); + assert_eq!( + instance_ids(&detection), + ["cargo:snapshots/a", "cargo:vendor/b"] + ); + assert_eq!(detection["pluginIgnoredPaths"], json!([])); +} + +/// Plugin rules are relative to the workspace root, so the root's own name +/// never matches them: a workspace opened at a `snapshots` folder is detected. +#[test] +fn detection_never_matches_plugin_rules_against_the_workspace_root() { + let workspace = TemporaryWorkspace::new("build-plugin-ignore-root"); + workspace + .write("snapshots/Cargo.toml", "") + .write("snapshots/crates/a/Cargo.toml", "") + .write("snapshots/snapshots/b/Cargo.toml", ""); + let outcome = build_detect_command::(json!({ + "workspaceRoot": workspace.0.join("snapshots").to_string_lossy(), + "plugins": [{"manifest": fixture("build-static-file.plugin.json")}], + })) + .expect("payload is well formed"); + assert_eq!(outcome["status"], "ok", "{outcome}"); + assert_eq!( + instance_ids(&outcome["detection"]), + ["cargo:.", "cargo:crates/a"] + ); +} + +/// The manifest preflight counts the encoded bytes of a rule, including negation. +#[test] +fn detection_ignore_rule_preflight_validates_syntax_and_utf8_size() { + let mut manifest = fixture("build-static-file.plugin.json"); + let limit = "é".repeat(512); + for (rule, valid) in [ + ("# comment", false), + ("!", false), + ("! spaced", false), + ("!snapshots/", true), + (&limit, true), + (&format!("!{limit}"), false), + ] { + manifest["buildSystems"][0]["detection"]["ignoredPaths"] = json!([rule]); + let result = validate_command(json!({"manifest": manifest})).unwrap(); + if valid { + assert_eq!(result["status"], "ok", "{result}"); + } else { + assert_eq!( + result["error"]["field"], "buildSystems[0].detection.ignoredPaths[0]", + "{result}" + ); + } + } +} + #[test] fn detection_returns_empty_for_non_directory_and_missing_workspace_roots() { let workspace = TemporaryWorkspace::new("build-detect-non-directory"); @@ -888,7 +1031,10 @@ fn detection_returns_empty_for_non_directory_and_missing_workspace_roots() { assert_eq!(outcome["status"], "ok", "{}: {outcome}", root.display()); assert_eq!( outcome["detection"], - json!({"instances": [], "rejected": [], "shadowed": []}), + json!({"instances": [], "rejected": [], "shadowed": [], "pluginIgnoredPaths": [{ + "pluginID": "dev.lithe.fixture.build-static-file", "buildSystemID": "cargo", + "displayName": "Cargo", "patterns": ["snapshots/"] + }]}), "{}", root.display(), ); diff --git a/rust/crates/execution/src/workspace_scan.rs b/rust/crates/execution/src/workspace_scan.rs index e53b944e..f32d8a7c 100644 --- a/rust/crates/execution/src/workspace_scan.rs +++ b/rust/crates/execution/src/workspace_scan.rs @@ -106,7 +106,7 @@ impl IgnoredPaths { /// Whether the patterns decide about `directory`: `Some(true)` skips it, /// `Some(false)` keeps it whatever Git says, `None` leaves it to Git. - fn decides(&self, directory: &Path) -> Option { + pub fn decides(&self, directory: &Path) -> Option { match self.matcher.as_ref()?.matched(directory, true) { Match::Ignore(_) => Some(true), Match::Whitelist(_) => Some(false), diff --git a/rust/fixtures/build/detect-plugin-ignored-paths-v1.json b/rust/fixtures/build/detect-plugin-ignored-paths-v1.json new file mode 100644 index 00000000..4d5b569e --- /dev/null +++ b/rust/fixtures/build/detect-plugin-ignored-paths-v1.json @@ -0,0 +1,96 @@ +{ + "version": 1, + "files": [ + "Cargo.toml", + "snapshots/nested/Cargo.toml", + "snapshots/nested/go.mod", + "examples/basic/Cargo.toml", + "examples/broken/Cargo.toml", + "legacy/settings.gradle", + "legacy/app/build.gradle", + "current/settings.gradle", + "current/app/build.gradle" + ], + "manifest": { + "schemaVersion": 0, + "id": "dev.lithe.fixture.detect-plugin-ignored-paths", + "displayName": "Detection Ignore Fixture", + "version": "0.1.0", + "pluginAPIVersion": 0, + "requires": { "buildSystems": 0 }, + "vendor": { "id": "org.example", "displayName": "Example", "signatureRequirement": "publisherPackage" }, + "permissions": ["process.build"], + "activationEvents": ["onBuildSystem:cargo", "onBuildSystem:go", "onBuildSystem:gradle"], + "languages": [], + "buildSystems": [ + { + "id": "cargo", + "displayName": "Cargo", + "detection": { + "markers": ["Cargo.toml"], + "ignoredPaths": ["snapshots/", "examples/*/", "!examples/basic/"] + }, + "invocation": { "executables": [{ "kind": "command", "command": "cargo" }] } + }, + { + "id": "go", + "displayName": "Go", + "detection": { "markers": ["go.mod"] }, + "invocation": { "executables": [{ "kind": "command", "command": "go" }] } + }, + { + "id": "gradle", + "displayName": "Gradle", + "detection": { + "markers": ["build.gradle", "settings.gradle"], + "nesting": "outermost", + "ignoredPaths": ["legacy/"] + }, + "invocation": { "executables": [{ "kind": "command", "command": "gradle" }] } + } + ] + }, + "expectedPluginIgnoredPaths": [ + { + "pluginID": "dev.lithe.fixture.detect-plugin-ignored-paths", + "buildSystemID": "cargo", + "displayName": "Cargo", + "patterns": ["snapshots/", "examples/*/", "!examples/basic/"] + }, + { + "pluginID": "dev.lithe.fixture.detect-plugin-ignored-paths", + "buildSystemID": "gradle", + "displayName": "Gradle", + "patterns": ["legacy/"] + } + ], + "cases": [ + { + "name": "pluginRulesOnly", + "ignoredPaths": null, + "expectedInstances": ["cargo:.", "cargo:examples/basic", "go:snapshots/nested", "gradle:current"] + }, + { + "name": "workspaceRestoresSnapshots", + "ignoredPaths": [".*", "!snapshots/"], + "expectedInstances": [ + "cargo:.", + "cargo:examples/basic", + "cargo:snapshots/nested", + "go:snapshots/nested", + "gradle:current" + ] + }, + { + "name": "workspaceRestoresLegacy", + "ignoredPaths": [".*", "!legacy/"], + "expectedInstances": [ + "cargo:.", + "cargo:examples/basic", + "go:snapshots/nested", + "gradle:current", + "gradle:legacy" + ] + } + ] +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 09791132..df4c36a3 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -2189,7 +2189,7 @@ declaration are relative, use `/`, and stay inside their base directory | Field | Meaning | | --- | --- | -| `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. | +| `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 `!`. Optional `detection.ignoredPaths` lists up to 256 ordered `.gitignore` directory patterns of up to 1024 UTF-8 bytes each for this system only. It uses the same syntax as Build ignored paths and matches paths relative to the workspace root, which is whatever folder the user opens: a pattern with no `/` before its end, such as `snapshots/`, matches at any depth, while one with a `/` before its end, such as `/snapshots/` or `examples/*/`, matches only from the workspace root (write `**/examples/*/` for any depth), so prefer the unanchored form for plugin defaults. The editor schema checks the entry shape; its `maxLength` counts characters, not UTF-8 bytes. Core compiles each glob and measures its UTF-8 bytes when it validates the manifest and rejects the whole manifest with `plugin.manifest.invalid` at `buildSystems[].detection.ignoredPaths[]`, so load the plugin in a host before publishing. A candidate is dropped when it or a directory between it and the workspace root is ignored; excluded ancestors exclude their descendants, so under `outermost` nesting a marker below an ignored root does not become an instance. At each of those directories a matching workspace rule decides first: the user brings back a directory a plugin ignores by adding `!/` to the workspace's ignored paths, keeping `.*` there to go on skipping dot directories. The workspace root itself remains eligible. `build.detect` returns the lists in effect as `detection.pluginIgnoredPaths`, which hosts show apart from the editable workspace patterns; when another plugin's declaration of the same ID wins, this list neither applies nor appears. These defaults do not affect visibility, indexing, search or other systems. This is an addition within `buildSystems` 0. Older hosts reject manifests that use the field, so release a plugin that uses it only for a host that includes it. `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`, with optional `optionDefaults` for choices the tool activates when unset), or are free (`allowCustom`). A `text`, `file` or `directory` option may also get the value the tool uses while it is unset from the model's `optionDefaults` (Maven's user settings file, its local repository); `build.resolveOptions` returns it as `implicitValue` for display only, and it contributes no argument. `description` (1-512 characters) says what the option does, for the host's info icon; `displayName`, `description` and choice titles are translated through the `buildOptions` part of a [translation file](#translations); a `multiSelect` option may set `excludePrefix` (or report `optionExcludePrefixes` in `litheBuildModel`) so unchecking a default choice passes ``. | diff --git a/shared/plugins/contract/v1/fixtures/build-systems/build-static-file.plugin.json b/shared/plugins/contract/v1/fixtures/build-systems/build-static-file.plugin.json index 6521b0e7..f1e35afb 100644 --- a/shared/plugins/contract/v1/fixtures/build-systems/build-static-file.plugin.json +++ b/shared/plugins/contract/v1/fixtures/build-systems/build-static-file.plugin.json @@ -22,7 +22,8 @@ "id": "cargo", "displayName": "Cargo", "detection": { - "markers": ["Cargo.toml"] + "markers": ["Cargo.toml"], + "ignoredPaths": ["snapshots/"] }, "invocation": { "executables": [ diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 64920563..328c4d22 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -3319,6 +3319,23 @@ "minItems": 1, "maxItems": 32 }, + "ignoredPaths": { + "description": "Workspace-relative .gitignore directory patterns for this build system only. A pattern with no / before its end matches at any depth; one with a / before its end matches only from the workspace root. Workspace rules decide first, so a workspace !pattern restores a directory. Core rejects the whole manifest at buildSystems[i].detection.ignoredPaths[j] when a glob does not compile or exceeds 1024 UTF-8 bytes; JSON Schema maxLength counts characters.", + "type": "array", + "maxItems": 256, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "not": { + "anyOf": [ + { "pattern": "^#|^!$" }, + { "pattern": "[\\u0000-\\u001f\\u007f-\\u009f]" }, + { "pattern": "^!?(?!\\ufeff)\\s|(?!\\ufeff)\\s$" } + ] + } + } + }, "nesting": { "enum": [ "separate", diff --git a/shared/plugins/reference/domains/build-systems.md b/shared/plugins/reference/domains/build-systems.md index 6e8f7b28..a6f2c17a 100644 --- a/shared/plugins/reference/domains/build-systems.md +++ b/shared/plugins/reference/domains/build-systems.md @@ -27,7 +27,7 @@ | 字段 | 决定什么 | | --- | --- | -| `detection` | 用 `markers` 里的文件名识别候选根目录。Core 最多向下找 6 层,跳过已知的缓存和构建输出目录,以及被 Git 忽略的目录(规则来自工作区内途经的 `.gitignore`,以及根目录在工作区内的仓库的 `info/exclude`;不读工作区根以上的目录、`core.excludesFile` 和索引,所以被忽略目录下即使有已跟踪的清单文件也不算候选)。检测还会跳过工作区的忽略路径:这是用户在构建选项里编辑的 `.gitignore` 规则,存放在团队或本机的构建选项中,默认是所有名字以 `.` 开头的目录(如 `.claude/worktrees`),用户可以再添加,也可以用 `!` 放回某个目录;`nesting` 决定深层候选并入外层实例(`outermost`,如 Gradle、Maven)还是各自独立(`separate`,默认,如 Cargo);`priority` 决定多个插件声明同一个 ID 时谁优先 | +| `detection` | 用 `markers` 里的文件名识别候选根目录。Core 最多向下找 6 层,跳过已知的缓存和构建输出目录,以及被 Git 忽略的目录(规则来自工作区内途经的 `.gitignore`,以及根目录在工作区内的仓库的 `info/exclude`;不读工作区根以上的目录、`core.excludesFile` 和索引,所以被忽略目录下即使有已跟踪的清单文件也不算候选)。检测还会跳过工作区的忽略路径:这是用户在构建选项里编辑的 `.gitignore` 规则,存放在团队或本机的构建选项中,默认是所有名字以 `.` 开头的目录(如 `.claude/worktrees`),用户可以再添加,也可以用 `!` 放回某个目录。插件可以用可选的 `detection.ignoredPaths` 只为这一个构建系统声明默认忽略的目录:最多 256 条 `.gitignore` 目录规则、每条不超过 1024 个 UTF-8 字节,相对工作区根匹配;末尾以外不含 `/` 的规则(如 `snapshots/`)在任意层级生效,含 `/` 的规则(如 `/snapshots/`、`examples/*/`)只从工作区根算起,所以插件默认值宜用前一种写法。候选目录本身或它到工作区根之间的任一目录被忽略,它就不算实例;被忽略的外层根下的标记文件在 `outermost` 下也不会变成实例。每一层先看工作区规则,用户在工作区忽略路径里加 `!snapshots/` 就能放回(还想跳过点目录就保留 `.*`)。它和 `layout.hiddenDirectoryNames` 不同,只影响这个构建系统的检测,不影响项目树、搜索、索引和其他构建系统。`build.detect` 用 `detection.pluginIgnoredPaths` 返回当前生效的列表,供宿主和可编辑的工作区规则分开展示;同 ID 的声明输给另一个插件时,它的规则既不生效也不出现。规则无法编译或超长时,Core 拒绝整个清单(`plugin.manifest.invalid`,字段 `buildSystems[i].detection.ignoredPaths[j]`)。这是 `buildSystems` 0 内的补充,旧宿主会拒绝使用该字段的清单;`nesting` 决定深层候选并入外层实例(`outermost`,如 Gradle、Maven)还是各自独立(`separate`,默认,如 Cargo);`priority` 决定多个插件声明同一个 ID 时谁优先 | | `invocation` | 可执行文件候选(`executables`,按偏好排序)、`globalArguments`、版本探测和 `minimumVersion` | | `runtimeDependencies` | 构建工具依赖的运行时。每个运行时要么命名同 ID 的[工具定义](toolchains.md)(不写 `executables`,由工具定义查找可执行文件并检查 `minimumVersion`),要么自己声明 `executables` 和版本探测。Core 不认识任何具体运行时,`node`、`go` 也一样:用它们的插件要提供或依赖同名工具定义 | | `options` | 用户选择的构建维度:`boolean`、`singleSelect`、`multiSelect`、`text`、`file`、`directory`;每个选项在有值时贡献 `arguments` 和 `environment` | @@ -129,7 +129,7 @@ IDs of build systems, tasks, and run entries start with a lowercase letter and u | Field | What it decides | | --- | --- | -| `detection` | Candidate roots are directories holding one of the `markers` file names. Core searches at most 6 levels down and skips known caches and build outputs, plus directories Git ignores (rules from the `.gitignore` files inside the workspace and the `info/exclude` of each repository rooted there; directories above the workspace root, `core.excludesFile` and the index are not read, so a tracked manifest below an ignored directory is no candidate). Detection also skips the workspace's ignored paths, `.gitignore` patterns the user edits 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 add more or bring one back with `!`; `nesting` folds deeper candidates into the outer instance (`outermost`, such as Gradle and Maven) or keeps each one (`separate`, the default, such as Cargo); `priority` decides between plugins declaring the same ID | +| `detection` | Candidate roots are directories holding one of the `markers` file names. Core searches at most 6 levels down and skips known caches and build outputs, plus directories Git ignores (rules from the `.gitignore` files inside the workspace and the `info/exclude` of each repository rooted there; directories above the workspace root, `core.excludesFile` and the index are not read, so a tracked manifest below an ignored directory is no candidate). Detection also skips the workspace's ignored paths, `.gitignore` patterns the user edits 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 add more or bring one back with `!`. The optional `detection.ignoredPaths` lets a plugin ignore directories for this one build system: up to 256 `.gitignore` directory patterns of up to 1024 UTF-8 bytes each, matched relative to the workspace root; a pattern with no `/` before its end (such as `snapshots/`) matches at any depth, one with a `/` before its end (such as `/snapshots/` or `examples/*/`) only from the workspace root, so plugin defaults should prefer the first form. A candidate is no instance when it or a directory between it and the workspace root is ignored, and under `outermost` a marker below an ignored root does not become one either. At each directory the workspace rules decide first, so the user brings one back by adding `!snapshots/` to the workspace's ignored paths (keeping `.*` to go on skipping dot directories). Unlike `layout.hiddenDirectoryNames`, it affects only this build system's detection, not the project tree, search, indexing or other build systems. `build.detect` returns the lists in effect as `detection.pluginIgnoredPaths`, which hosts show apart from the editable workspace patterns; when another plugin's declaration of the same ID wins, its rules neither apply nor appear. A pattern that does not compile or is too long rejects the whole manifest (`plugin.manifest.invalid` at `buildSystems[i].detection.ignoredPaths[j]`). This is an addition within `buildSystems` 0, and older hosts reject manifests that use the field; `nesting` folds deeper candidates into the outer instance (`outermost`, such as Gradle and Maven) or keeps each one (`separate`, the default, such as Cargo); `priority` decides between plugins declaring the same ID | | `invocation` | Executable candidates (`executables`, in preference order), `globalArguments`, the version probe, and `minimumVersion` | | `runtimeDependencies` | Runtimes the build tool needs. Each runtime either names the [tool definition](toolchains.md) with the same ID (no `executables`; the definition finds the executable and checks `minimumVersion`) or declares its own `executables` and version probe. Core knows no runtime by name, `node` and `go` included: a plugin that uses them provides or requires the tool definition with that ID | | `options` | Build dimensions the user chooses: `boolean`, `singleSelect`, `multiSelect`, `text`, `file`, `directory`; each contributes `arguments` and `environment` when it has a value | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 109c1aa7..d14a20af 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,11 @@ ## 待合入 -还没合入的 PR 先在这里登记,日期写“待合入”;合入后移进下面的时间线,并回填“按协议查首次出现”和“宿主方法(按 API 编号)”里的日期。目前没有待合入的记录。 +还没合入的 PR 先在这里登记,日期写“待合入”;合入后移进下面的时间线,并回填“按协议查首次出现”和“宿主方法(按 API 编号)”里的日期。 + +| PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | +| --- | --- | --- | --- | --- | +| [#218](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/218)(待合入) | [@WhiteZeek](https://github.com/WhiteZeek) | API-29 | `buildSystems` 0 内的补充 | 清单 `buildSystems[].detection` 新增可选 `ignoredPaths`:最多 256 条有序的 `.gitignore` 目录规则,每条不超过 1024 个 UTF-8 字节,相对工作区根匹配,只过滤这个构建系统的候选目录。候选目录或它到工作区根之间的任一目录被忽略就不算实例,`outermost` 下被忽略的外层根下的标记文件也不会变成实例;每一层先看工作区规则,工作区的 `!` 规则可以放回;工作区根本身不参与匹配。规则无法编译或超长时整个清单以 `plugin.manifest.invalid` 拒绝,字段为 `buildSystems[i].detection.ignoredPaths[j]`。Core 命令 `build.detect` 的回答总是带 `detection.pluginIgnoredPaths`(`{pluginID, buildSystemID, displayName, patterns}`,按构建系统 ID 排序,只列胜出的声明,没有时为 `[]`),供宿主和可编辑的工作区规则分开展示。固定样例见 [`detect-plugin-ignored-paths-v1.json`](../../../rust/fixtures/build/detect-plugin-ignored-paths-v1.json)。不影响项目树、搜索和索引;没有新增宿主方法、通知、错误码或 SDK 版本。旧宿主会拒绝使用该字段的清单,插件要等包含这个改动的桌面端发布后再用。 | ## 按协议查首次出现