diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 508ad28a..12471fdf 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1032,6 +1032,7 @@ name = "lithe-execution" version = "0.1.0" dependencies = [ "ignore", + "lithe-core-rules", "lithe-diagnostics", "lithe-platform", "lithe-plugin-model", @@ -1521,6 +1522,7 @@ dependencies = [ name = "lithe-vcs" version = "0.1.0" dependencies = [ + "lithe-core-rules", "lithe-plugin-model", "lithe-protocol", "serde", diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index f00107ef..61cf0f4f 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -227,15 +227,26 @@ runs every case of `rust/fixtures/editor/group-layout-v1.json` through them. and returns `{hidden: boolean[], watchedDespiteHiding: boolean[]}` with one answer per entry, in request order. `path` is workspace-relative with `/` separators; `isDirectory` is `true` for a folder, `false` for a file and omitted when the host does not know (every component may then be a folder). The two lists are the user's own entries: Core adds the -built-in folders and patterns, and a `!entry` turns a built-in off. Matching ignores case. A folder name hides the folder, +default folders and patterns, and a `!entry` turns a default off. Matching ignores case. A folder name hides the folder, everything below it and a file with that exact name (a linked worktree's `.git` file). `hidden` means the tree, search and Local History leave the path out; `watchedDespiteHiding` marks the hidden project configuration folder (`.lithe`) whose file events must still be delivered, except the built-in noise below it such as `.lithe/run/local.json`. Hosts send all children -of a directory in one call. `workspace.visibilityDefaults` takes `{}` and returns the built-in lists +of a directory in one call. `workspace.visibilityDefaults` takes `{}` and returns the default lists (`hiddenDirectoryNames`, `hiddenFilePatterns`, `builtInPatterns`, `configurationDirectory`, `configurationPattern`) so hosts display them without keeping a copy. Both live in `rust/crates/core-rules` like `keymap.modifierGestureStep` and are tested against `rust/fixtures/workspace/visibility-v1.json`. +The default folders are Core's own (`.git`, `.worktree`, `.worktrees`) plus the folder names the enabled plugins declare; +Core names no language or tool folder itself. The default file patterns are `.DS_Store`, the root `.lithe/**` and +`.lithe/run/local.json`. `workspace.configureVisibility` accepts `{plugins: [{manifest}]}`, the manifests of every enabled +plugin, and replaces the declared names with theirs: each build system's `layout.hiddenDirectoryNames` (its generated +output, such as `target`) and the directory markers of each VCS provider (its metadata, such as `.svn`). It returns +`{hiddenDirectoryNames, rejected: [{index, error}]}`: every declared name, sorted, and the manifests that failed +validation, which contribute nothing. The names are process-wide and apply from the next request, listing or scan: the +tree, search, file events, Local History's default ignored folders, run discovery, build detection and VCS root and +repository discovery. Hosts send the full list at startup and whenever a plugin is enabled, disabled, installed or +removed; `{plugins: []}` clears it. A malformed payload is `invalid_request`. + ## Terminal link targets `terminal.parseLinkTarget` accepts `{texts: string[], baseDirectory?, homeDirectory?, providerSchemes?: string[]}` @@ -542,11 +553,11 @@ or removing a command fails until the table changes in the same commit. | `plugins.marketplace.validateIndex` | Validate a marketplace index and report each plugin's availability for one platform | | `plugins.marketplace.resolveSource` | Resolve a user-entered marketplace source to the index URL to fetch | | `plugins.marketplace.installReview` | List a package's permissions and programs, and those not yet approved | -| `workspace.snapshot` | Enumerate visible workspace nodes and relative file paths; `nestedWorktrees` lists linked worktrees checked out inside their own repository, which are left out of the tree, files, and search index; the built-in hidden names are skipped without being read, and include `node_modules`, Python virtual environments (`.venv`, `venv`), `__pycache__` and `*.pyc` files; `includeTree: false` returns only `files` and a childless `root`; `files` (and the tree, when included) keep the lowercase traversal order that bounded consumers such as Windows Quick Open rely on, not the natural display order of `workspace.listDirectories` | +| `workspace.snapshot` | Enumerate visible workspace nodes and relative file paths; `nestedWorktrees` lists linked worktrees checked out inside their own repository, which are left out of the tree, files, and search index; hidden folders, Core's own and the ones enabled plugins declare through `workspace.configureVisibility`, are skipped without being read; `includeTree: false` returns only `files` and a childless `root`; `files` (and the tree, when included) keep the lowercase traversal order that bounded consumers such as Windows Quick Open rely on, not the natural display order of `workspace.listDirectories` | | `workspace.releaseIndexing` | Retire a policy and clear index/cache data at project close; accepts `root`, optional `ownerId`, and that owner's last observed `revision`, returns `released`; an old close must not retire a new generation | | `workspace.configureIndexing` | Install a process-local, canonical-root indexing policy before workspace consumers run; returns a monotonic revision, effective directory reasons and Git failure state; see `rust/fixtures/workspace/indexing-policy-v1.json` | | `workspace.refreshIndexing` | Refresh external Git decisions for a live `root`, `ownerId`, `revision` lease without changing preferences or release tokens; returns lazy `IndexingStatus` | -| `workspace.filterChanges` | Filter an array of workspace-relative paths, or `{ paths, hiddenFilePatterns }` whose `!` entries turn default exclusions off, against Core's default build/cache exclusions; preserve order, spelling, and the empty root path. Native event loss bypasses filtering. Hosts relativize to the most specific explicit watch root and retain explicitly watched files | +| `workspace.filterChanges` | Filter an array of workspace-relative paths, or `{ paths, hiddenFilePatterns }` whose `!` entries turn default exclusions off, against Core's default hidden folders and patterns, including the folders enabled plugins declare; preserve order, spelling, and the empty root path. Native event loss bypasses filtering. Hosts relativize to the most specific explicit watch root and retain explicitly watched files | | `workspace.listDirectories` | Return one visible level of children for each requested workspace-relative directory (`""` is the root); missing, hidden, symlinked, or nested-worktree paths are omitted, and each listing reports the nested worktrees it left out. Child directories have `children: []` only when a shallow probe proves them visibly empty; otherwise children remain omitted (unloaded), with no recursive tree allocation. Children list directories first, then names in IDEA's natural file-name order (digit runs compare by value, case-insensitive, `-` next to `_`; fixture `rust/fixtures/workspace/file-name-order-v1.json`) | | `workspace.orderEntries` | Order natively enumerated directory siblings | | `workspace.projectTree.rows` | Say which loaded project tree nodes show as rows, keep the selection on a row that shows, and find the row the top of the view was on, without reading the disk (from `lithe-project-tree`) | @@ -605,7 +616,8 @@ or removing a command fails until the table changes in the same commit. | `editor.groupLayout.reduce` | Apply one transition to the editor groups and the tree that divides the editor area among them: a workbench state action, opening a tab, dropping a dragged tab or removing empty groups (from `lithe-editor-layout`) | | `editor.groupLayout.dropTargets` | Say which places of each editor group accept a dragged tab (from `lithe-editor-layout`) | | `workspace.classifyVisibility` | Classify a batch of workspace-relative paths as hidden or visible. The rule lives in `lithe-core-rules` so the Windows frontend can run it synchronously | -| `workspace.visibilityDefaults` | Return the built-in hidden-path lists (from `lithe-core-rules`) | +| `workspace.visibilityDefaults` | Return the default hidden-path lists, Core's own and the folders enabled plugins declare (from `lithe-core-rules`) | +| `workspace.configureVisibility` | Replace the folder names enabled plugins declare as hidden (build systems' `layout.hiddenDirectoryNames`, VCS providers' directory markers) and return them with the rejected manifests | | `workbench.chromeLayout.reduce` | Apply one transition to the rearrangeable workbench chrome: stripe, title bar and status bar button placement, hidden stripe buttons and open tool panels (from `lithe-core-rules`) | | `workbench.notifications.reduceReadState` | Apply one notification arrival or mark a window's history read; return bounded unread identities and the ready-to-render count (from `lithe-core-rules`) | | `terminal.parseLinkTarget` | Resolve terminal link candidates into file or external targets | @@ -922,9 +934,9 @@ becomes a listed repository when Git can open it: a `.git` directory needs the marker's directory) that exists and holds `HEAD`. A stale submodule or worktree pointer whose gitdir was removed is not listed, because status and reference loads for the whole workspace would otherwise fail for it. The default traversal -skips dot-prefixed descendant directories and the built-in workspace hidden -directory names (including `.build`, `node_modules`, `.venv`, `venv`, `__pycache__`, -`target`, `build`, `DerivedData`, `dist` and `coverage`). `.worktree` and `.worktrees` remain +skips dot-prefixed descendant directories and the folder names enabled plugins +declare through `workspace.configureVisibility` (such as a build system's `target`). +`.worktree` and `.worktrees` remain traversable checkout containers; the same exclusions apply inside them. Traversal continues below eligible discovered repositories, including ordinary `vendor` source checkouts. An explicitly opened root and its containing repository @@ -2303,10 +2315,10 @@ scheme's ignored-file color; Windows tolerates the optional status but does not currently render this foreground. `includeGeneratedFileNames` opts into a separate in-memory names-only index: -built-in build/dependency directory exclusions (including `.build` and `target`) -do not suppress names, even when callers pass the same default exclusions. -Git metadata and nested worktrees remain excluded; custom directory names and -file/path globs still apply. It does not enable generated-file content or symbol +the folders enabled plugins declare as generated output (a build system's +`layout.hiddenDirectoryNames`, such as `target`) do not suppress names, even when +callers also pass them. VCS metadata, Core's own folders and nested worktrees remain +excluded; other custom directory names and file/path globs still apply. It does not enable generated-file content or symbol indexing and does not change `workspace.search`, tree, watcher, or replacement visibility. Names share index invalidation and reported file updates; changes inside unwatched generated directories require workspace/index refresh. No index @@ -3346,8 +3358,8 @@ and an optional `storageLimitBytes` (default Patterns use the hidden-path glob syntax; regexes use Rust `regex` syntax, case-insensitive, matched unanchored against the `/`-separated relative path. A matching file is not recorded, existing entries stay listed, and an invalid -or empty regex never matches. Built-in dependency, cache and build output -folders (such as `node_modules`, `.venv`, `target`) also apply as `**/name/` +or empty regex never matches. The default hidden folders, Core's own and the +ones enabled plugins declare (such as a build system's `target`), also apply as `**/name/` patterns, for baselines and edits alike; a `!**/name/` or `!name` pattern turns one off, and saving drops baselines the current rules reject. `history.ignorePreview` accepts the same `ignoreRules`, optional `hiddenFilePatterns`, an optional relative diff --git a/rust/contracts/vcs-provider-v1.md b/rust/contracts/vcs-provider-v1.md index df076b25..aad2a099 100644 --- a/rust/contracts/vcs-provider-v1.md +++ b/rust/contracts/vcs-provider-v1.md @@ -144,8 +144,10 @@ call. Roots come from static markers; detection never starts a process. One breadth-first walk reads the markers directly inside each directory down to eight levels below the workspace, at most 20,000 directories. It never enters a -marker directory (`.git`, `.svn`), a symbolic link, or a dependency or build -directory such as `node_modules`, `target`, or `.worktrees`. When the workspace +marker directory (`.git`, `.svn`), a symbolic link, or a folder the default +visibility rules hide: Core's `.worktree` and `.worktrees` and the folder names +enabled plugins declare through `workspace.configureVisibility`, such as a build +system's `target`. When the workspace itself has no marker, its ancestors are checked, because a Subversion working copy has one `.svn` at its top; the enclosing root's `id` is `..`, `../..`, …. `truncated` is `true` only when the directory budget ran out, so a root may be diff --git a/rust/crates/build/src/manifest.rs b/rust/crates/build/src/manifest.rs index cb19b03e..f41c1aab 100644 --- a/rust/crates/build/src/manifest.rs +++ b/rust/crates/build/src/manifest.rs @@ -177,6 +177,14 @@ pub fn validate_declarations( } impl BuildSystemDeclaration { + /// Folder names every workspace hides at any depth while the plugin is + /// enabled (`layout.hiddenDirectoryNames`), sorted and unique once validated. + pub fn hidden_directory_names(&self) -> &[String] { + self.layout + .as_ref() + .map_or(&[], |layout| &layout.hidden_directory_names) + } + fn validate(&mut self, field: &str, context: &DeclarationContext<'_>) -> Validation<()> { if !is_entry_identifier(&self.id) { return Err(invalid( @@ -213,6 +221,10 @@ impl BuildSystemDeclaration { &format!("{field}.layout.excluded"), false, )?; + check_directory_names( + &mut layout.hidden_directory_names, + &format!("{field}.layout.hiddenDirectoryNames"), + )?; } self.validate_option_emission(field) } diff --git a/rust/crates/build/src/manifest/checks.rs b/rust/crates/build/src/manifest/checks.rs index 6b8b5cef..59f89722 100644 --- a/rust/crates/build/src/manifest/checks.rs +++ b/rust/crates/build/src/manifest/checks.rs @@ -165,6 +165,35 @@ pub(crate) fn check_paths(values: &mut Vec, field: &str, glob: bool) -> Ok(()) } +/// Folder names matched against one path component at any depth. A name is +/// literal: it holds no separator or glob character, is not `.` or `..`, +/// and does not start with `!`, which users write to turn a default off. +pub(crate) fn check_directory_names(values: &mut Vec, field: &str) -> Validation<()> { + if values.len() > MAX_LIST { + return Err(invalid(field, "The list is too long.")); + } + for (index, value) in values.iter().enumerate() { + let literal = !value.is_empty() + && value.len() <= 255 + && value.trim() == value + && value != "." + && value != ".." + && !value.starts_with('!') + && !value.chars().any(|character| { + character.is_control() || matches!(character, '/' | '\\' | '*' | '?' | '[' | ']') + }); + if !literal { + return Err(PluginRejection::at( + "plugin.path.invalid", + format!("{field}[{index}]"), + "Directory names are single path components without glob characters.", + )); + } + } + *values = sorted_unique(std::mem::take(values)); + Ok(()) +} + pub(crate) fn check_regex(value: &str, field: &str, groups: usize) -> Validation { let compiled = (value.len() <= MAX_REGEX) .then(|| Regex::new(value).ok()) diff --git a/rust/crates/build/src/manifest/dependencies.rs b/rust/crates/build/src/manifest/dependencies.rs index 0759d31a..a7f26b0b 100644 --- a/rust/crates/build/src/manifest/dependencies.rs +++ b/rust/crates/build/src/manifest/dependencies.rs @@ -55,13 +55,19 @@ pub(crate) struct SyncDeclaration { pub(crate) watch: Vec, } -/// Output directories excluded from every project, relative to each -/// project directory. +/// Where the build system puts files nobody edits. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub(crate) struct LayoutDeclaration { + /// Output directories excluded from every project, relative to each + /// project directory. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) excluded: Vec, + /// Folder names, such as `target` or `node_modules`, that every + /// workspace hides at any depth while the plugin is enabled: the tree, + /// search, watchers, local history and every workspace walk skip them. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) hidden_directory_names: Vec, } impl BuildSystemDeclaration { diff --git a/rust/crates/core-rules/src/lib.rs b/rust/crates/core-rules/src/lib.rs index 8271e341..66feb1ab 100644 --- a/rust/crates/core-rules/src/lib.rs +++ b/rust/crates/core-rules/src/lib.rs @@ -3,6 +3,8 @@ //! This crate holds rules that are small, deterministic and sit on a synchronous hot path //! (for example a gesture recognizer that runs on every native key event). It performs no //! file-system, process, thread or clock access: time is always supplied by the caller. +//! The only process-wide state is the folder names enabled plugins hide, which +//! [`visibility::set_plugin_hidden_directories`] replaces as a whole. //! //! `lithe-core` links this crate as a normal dependency and exposes each rule through its JSON //! command dispatch, so hosts reach the rules over the usual Core C ABI. Rule failures use diff --git a/rust/crates/core-rules/src/visibility.rs b/rust/crates/core-rules/src/visibility.rs index 3d28056e..757ddb04 100644 --- a/rust/crates/core-rules/src/visibility.rs +++ b/rust/crates/core-rules/src/visibility.rs @@ -1,14 +1,24 @@ //! Hidden-path rules: the one definition of which workspace paths are hidden. //! -//! This module owns three things that used to exist once per host: the built-in default lists, -//! the glob matcher, and the way a directory differs from a file. `lithe-core` uses -//! [`VisibilityRules`] directly for snapshots, search and history scans. macOS and the Windows -//! frontend reach the same code through two commands, so no host keeps a list or a matcher: +//! This module owns four things that used to exist once per host or once per scan: Core's own +//! default lists, the folder names the enabled plugins declare, the glob matcher, and the way a +//! directory differs from a file. `lithe-core` uses [`VisibilityRules`] directly for snapshots, +//! search, watchers and history, and every other workspace walk (run discovery, build +//! detection, VCS roots, Git repository discovery) prunes the same folder names. Hosts reach the +//! same code through three commands, so no host keeps a list or a matcher: //! -//! - `workspace.visibilityDefaults` returns the built-in lists for display. +//! - `workspace.configureVisibility` replaces the plugin-declared folder names. `lithe-core` +//! validates the enabled plugins' manifests, collects their names and calls +//! [`set_plugin_hidden_directories`]. +//! - `workspace.visibilityDefaults` returns the default lists for display. //! - `workspace.classifyVisibility` classifies a whole batch of paths against one rule set. Hosts //! send every child of a directory in one call instead of one call per file. //! +//! Core knows no language, build tool or plugin-provided VCS. Its own defaults are the Git +//! metadata folder, Lithe's worktree containers and the project configuration folder. Dependency, +//! cache and build output folders such as `node_modules` or `target` are hidden only while a +//! plugin that declares them is enabled. +//! //! Two answers exist for every path. `hidden` means the tree, search and history all leave it out. //! `watchedDespiteHiding` marks the project configuration folder: it is hidden from the tree, but //! edits to its JSON files must still reach project services, so its events are not dropped. @@ -16,39 +26,111 @@ use crate::{RuleError, RuleErrorCode}; use serde::{Deserialize, Serialize}; use serde_json::Value; +use std::sync::{PoisonError, RwLock}; /// Command name of the batch classifier in the Core command namespace. pub const CLASSIFY_VISIBILITY: &str = "workspace.classifyVisibility"; /// Command name of the defaults query in the Core command namespace. pub const VISIBILITY_DEFAULTS: &str = "workspace.visibilityDefaults"; -/// Folder names hidden at any depth unless a `!` entry turns them off. Shared by the tree, search, -/// local history, watchers and Git discovery. -pub const BUILT_IN_HIDDEN_DIRECTORIES: &[&str] = &[ - ".git", - ".svn", - ".worktree", - ".worktrees", - ".build", - ".swiftpm", - "node_modules", - // Python virtual environments and bytecode caches are dependency or generated - // output like `node_modules`. They hold tens of thousands of files that no - // snapshot consumer wants. Environments are matched by their conventional - // names only, so a differently named one still has to be hidden by the user. - ".venv", - "venv", - "__pycache__", - "target", - "build", - "DerivedData", - ".gradle", - ".next", - "dist", - "coverage", - "design-qa-artifacts", - ".artifacts", -]; +/// Folder names Core itself hides at any depth unless a `!` entry turns them off: Git metadata +/// (Git support is built into Core) and the containers Lithe creates for linked worktrees. +/// Every tool-specific folder comes from [`plugin_hidden_directories`]. +pub const BUILT_IN_HIDDEN_DIRECTORIES: &[&str] = &[".git", ".worktree", ".worktrees"]; + +/// Folder names the enabled plugins declare, as `workspace.configureVisibility` last set them. +/// Process-wide because the set of enabled plugins is process-wide, and every workspace walk +/// reads it. +static PLUGIN_HIDDEN_DIRECTORIES: RwLock = + RwLock::new(PluginHiddenDirectories { + generated: Vec::new(), + metadata: Vec::new(), + }); + +/// The folder names the enabled plugins declare, by what the folders hold. Both kinds are +/// hidden alike; only Search Everywhere tells them apart. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PluginHiddenDirectories { + /// Dependency, cache and build output folders, such as `node_modules` or `target`: files a + /// tool regenerates. Search Everywhere may still list their file names. + pub generated: Vec, + /// The metadata folders of a VCS a plugin provides, such as `.svn`, which nothing lists. + pub metadata: Vec, +} + +/// Replaces the plugin-declared folder names and returns all of them as stored: trimmed, +/// without empty entries or case-insensitive duplicates, sorted. Callers validate each name +/// first; a name is compared with one path component, ignoring ASCII case, never as a glob. +pub fn set_plugin_hidden_directories(directories: PluginHiddenDirectories) -> Vec { + let stored = PluginHiddenDirectories { + generated: sorted(normalize(directories.generated)), + metadata: sorted(normalize(directories.metadata)), + }; + let all = all_plugin_directories(&stored); + *PLUGIN_HIDDEN_DIRECTORIES + .write() + .unwrap_or_else(PoisonError::into_inner) = stored; + all +} + +/// Every folder name the enabled plugins declare, sorted. +pub fn plugin_hidden_directories() -> Vec { + all_plugin_directories( + &PLUGIN_HIDDEN_DIRECTORIES + .read() + .unwrap_or_else(PoisonError::into_inner), + ) +} + +/// The plugin-declared folder names that hold generated files only: neither a VCS's metadata +/// nor one of Core's own folders, which stay hidden even where generated files are listed. +pub fn plugin_generated_directories() -> Vec { + let directories = PLUGIN_HIDDEN_DIRECTORIES + .read() + .unwrap_or_else(PoisonError::into_inner); + directories + .generated + .iter() + .filter(|name| { + !directories + .metadata + .iter() + .any(|metadata| metadata.eq_ignore_ascii_case(name)) + && !BUILT_IN_HIDDEN_DIRECTORIES + .iter() + .any(|built_in| built_in.eq_ignore_ascii_case(name)) + }) + .cloned() + .collect() +} + +fn all_plugin_directories(directories: &PluginHiddenDirectories) -> Vec { + sorted(normalize( + directories + .generated + .iter() + .chain(&directories.metadata) + .cloned() + .collect(), + )) +} + +/// Sorts folder names case-insensitively, so the stored order does not depend on plugin order. +fn sorted(mut names: Vec) -> Vec { + names.sort_by_key(|name| name.to_ascii_lowercase()); + names +} + +/// Every folder name hidden by default: Core's own, then the plugin-declared ones. +pub fn default_hidden_directories() -> Vec { + normalize( + BUILT_IN_HIDDEN_DIRECTORIES + .iter() + .map(|name| (*name).to_string()) + .chain(plugin_hidden_directories()) + .collect(), + ) +} /// The project configuration folder is hidden like IDEA's `.idea`; its files are edited through /// Settings and the run configuration editor. @@ -58,18 +140,15 @@ pub const CONFIGURATION_PATTERN: &str = ".lithe/**"; /// the tree hides it, because edits to its JSON files reload project services. pub const CONFIGURATION_DIRECTORY: &str = ".lithe"; -/// File names and globs hidden everywhere unless a `!` entry turns them off. -pub const BUILT_IN_HIDDEN_FILE_PATTERNS: &[&str] = &[ - ".DS_Store", - "*.pyc", - CONFIGURATION_PATTERN, - ".lithe/run/local.json", -]; +/// File names and globs hidden everywhere unless a `!` entry turns them off: Finder metadata and +/// the project configuration folder. +pub const BUILT_IN_HIDDEN_FILE_PATTERNS: &[&str] = + &[".DS_Store", CONFIGURATION_PATTERN, ".lithe/run/local.json"]; -/// The built-in rules written as Hidden paths patterns, for display. Folder names become -/// `**/name/`, the pattern that hides them at any depth. +/// The default rules written as Hidden paths patterns, for display. Folder names, Core's own and +/// the plugin-declared ones, become `**/name/`, the pattern that hides them at any depth. pub fn built_in_patterns() -> Vec { - BUILT_IN_HIDDEN_DIRECTORIES + default_hidden_directories() .iter() .map(|name| format!("**/{name}/")) .chain( @@ -80,7 +159,7 @@ pub fn built_in_patterns() -> Vec { .collect() } -/// Effective built-in plus caller-supplied rules for excluding workspace paths. +/// Effective default plus caller-supplied rules for excluding workspace paths. #[derive(Debug, Clone, PartialEq, Eq)] pub struct VisibilityRules { /// Folder names hidden at any depth, compared case-insensitively. @@ -90,17 +169,29 @@ pub struct VisibilityRules { } impl VisibilityRules { - /// Adds the built-in rules except those turned off by a `!` entry. + /// Adds the default rules, Core's own and the plugin-declared folder names, except those + /// turned off by a `!` entry. /// - /// Callers may already send built-in names; a turned-off entry is dropped from their lists + /// Callers may already send default names; a turned-off entry is dropped from their lists /// too, so the caller's copy cannot re-hide it. User entries keep their stored values; only /// the effective list is normalized. pub fn new(hidden_directories: Vec, hidden_files: Vec) -> Self { + Self::with_default_directories( + default_hidden_directories(), + hidden_directories, + hidden_files, + ) + } + + /// [`Self::new`] with an explicit list of default folder names instead of Core's own and the + /// registered plugin names, so a caller can evaluate rules without the process-wide state. + pub fn with_default_directories( + default_directories: Vec, + hidden_directories: Vec, + hidden_files: Vec, + ) -> Self { let disabled = disabled_built_ins(&hidden_files); - let mut directories = BUILT_IN_HIDDEN_DIRECTORIES - .iter() - .map(|value| (*value).to_string()) - .collect::>(); + let mut directories = default_directories; directories.extend(hidden_directories); directories.retain(|name| !is_disabled_directory(name, &disabled)); let mut files = BUILT_IN_HIDDEN_FILE_PATTERNS @@ -145,7 +236,7 @@ impl VisibilityRules { } /// Whether file events at `path` must still be delivered although the rules hide it. Only - /// the project configuration folder qualifies, and only for files outside the built-in noise + /// the project configuration folder qualifies, and only for files outside the default noise /// below it, such as `.lithe/run/local.json`. pub fn is_watched_despite_hiding(&self, path: &str) -> bool { let first = path.split('/').find(|value| !value.is_empty()); @@ -208,7 +299,7 @@ pub fn is_path_hidden( .any(|pattern| path_glob_matches(pattern, last) || path_glob_matches(pattern, path)) } -/// The entries after a leading `!`. Such an entry turns a built-in rule off instead of hiding +/// The entries after a leading `!`. Such an entry turns a default rule off instead of hiding /// anything; it is never matched as a pattern itself. pub fn disabled_built_ins(hidden_file_patterns: &[String]) -> Vec { hidden_file_patterns @@ -218,7 +309,7 @@ pub fn disabled_built_ins(hidden_file_patterns: &[String]) -> Vec { .collect() } -/// A built-in folder is turned off by its displayed form `**/name/` or its bare name. +/// A default folder is turned off by its displayed form `**/name/` or its bare name. pub fn is_disabled_directory(name: &str, disabled: &[String]) -> bool { disabled.iter().any(|entry| { entry.eq_ignore_ascii_case(name) @@ -316,7 +407,7 @@ struct ClassifyEntry { } /// Payload of `workspace.classifyVisibility`. The rule lists are the user's own entries; the -/// built-in rules are added here. +/// default rules are added here. #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct ClassifyRequest { @@ -375,13 +466,10 @@ pub fn classify_visibility_json(payload: Value) -> Result { .map_err(invalid) } -/// Returns the built-in lists so hosts can display them without keeping a copy. +/// Returns the default lists so hosts can display them without keeping a copy. pub fn visibility_defaults_json(_payload: Value) -> Result { serde_json::to_value(DefaultsResponse { - hidden_directory_names: BUILT_IN_HIDDEN_DIRECTORIES - .iter() - .map(|name| (*name).to_string()) - .collect(), + hidden_directory_names: default_hidden_directories(), hidden_file_patterns: BUILT_IN_HIDDEN_FILE_PATTERNS .iter() .map(|name| (*name).to_string()) diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 933880d6..6de466a8 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -546,8 +546,11 @@ pub enum WorkspaceCommand { /// Classifies a batch of workspace-relative paths as hidden or visible (`workspace.classifyVisibility`). /// The rule lives in `lithe-core-rules` so the Windows frontend can run it synchronously. ClassifyVisibility, - /// Returns the built-in hidden-path lists (`workspace.visibilityDefaults`), also from `lithe-core-rules`. + /// Returns the default hidden-path lists (`workspace.visibilityDefaults`), also from `lithe-core-rules`. VisibilityDefaults, + /// Replaces the folder names the enabled plugins hide in every workspace + /// (`workspace.configureVisibility`), collected from their validated manifests. + ConfigureVisibility, } #[derive(Debug, Clone)] @@ -1269,6 +1272,9 @@ impl CoreCommand { "workspace.visibilityDefaults" => { Some(Self::Workspace(WorkspaceCommand::VisibilityDefaults)) } + "workspace.configureVisibility" => { + Some(Self::Workspace(WorkspaceCommand::ConfigureVisibility)) + } "workbench.chromeLayout.reduce" => Some(Self::WorkbenchChromeLayoutReduce), "workbench.notifications.reduceReadState" => { Some(Self::WorkbenchNotificationsReduceReadState) diff --git a/rust/crates/core/src/runtime/dispatcher/workspace.rs b/rust/crates/core/src/runtime/dispatcher/workspace.rs index 53923e9a..2f11fa6d 100644 --- a/rust/crates/core/src/runtime/dispatcher/workspace.rs +++ b/rust/crates/core/src/runtime/dispatcher/workspace.rs @@ -296,5 +296,22 @@ pub(super) fn dispatch( WorkspaceCommand::VisibilityDefaults => { rules_response(id, "workspace.visibilityDefaults", payload) } + WorkspaceCommand::ConfigureVisibility => { + match lithe_plugin_manifest::declared_hidden_directories(payload) { + Ok(declared) => { + let names = lithe_core_rules::visibility::set_plugin_hidden_directories( + lithe_core_rules::visibility::PluginHiddenDirectories { + generated: declared.generated, + metadata: declared.metadata, + }, + ); + CoreResponse::success( + id, + json!({ "hiddenDirectoryNames": names, "rejected": declared.rejected }), + ) + } + Err(error) => CoreResponse::failure(id, error), + } + } } } diff --git a/rust/crates/core/src/tests/build_systems.rs b/rust/crates/core/src/tests/build_systems.rs index a2794ab4..b7e11868 100644 --- a/rust/crates/core/src/tests/build_systems.rs +++ b/rust/crates/core/src/tests/build_systems.rs @@ -698,7 +698,10 @@ fn detection_applies_nesting_priority_and_rejections() { "android/app/build.gradle.kts", "plugins { id(\"application\") }\n", ) - .write("target/debug/Cargo.toml", "[package]\nname = \"ignored\"\n"); + .write( + ".worktrees/feature/Cargo.toml", + "[package]\nname = \"ignored\"\n", + ); let mut preferred = fixture("build-static-file.plugin.json"); preferred["id"] = json!("dev.lithe.fixture.cargo-preferred"); diff --git a/rust/crates/core/src/tests/detectors.rs b/rust/crates/core/src/tests/detectors.rs index 9535df54..090e19e5 100644 --- a/rust/crates/core/src/tests/detectors.rs +++ b/rust/crates/core/src/tests/detectors.rs @@ -6,10 +6,10 @@ use std::path::Path; /// Builds a project that mixes six ecosystems in one tree, including the /// traps that break naive detectors: a lockfile that is not npm's, a -/// `node_modules` full of decoy manifests, and a Go command in a +/// nested worktree full of decoy manifests, and a Go command in a /// subdirectory with no manifest of its own. fn multi_language_project(root: &Path) { - for directory in ["frontend/node_modules/decoy", "api", "cmd/gateway"] { + for directory in ["frontend/.worktrees/decoy", "api", "cmd/gateway"] { fs::create_dir_all(root.join(directory)).unwrap(); } fs::write( @@ -19,7 +19,7 @@ fn multi_language_project(root: &Path) { .unwrap(); fs::write(root.join("frontend/pnpm-lock.yaml"), "lockfileVersion: 9\n").unwrap(); fs::write( - root.join("frontend/node_modules/decoy/package.json"), + root.join("frontend/.worktrees/decoy/package.json"), r#"{"scripts":{"dev":"should-never-appear"}}"#, ) .unwrap(); @@ -105,10 +105,10 @@ fn detectors_find_services_across_unrelated_ecosystems() { fs::remove_dir_all(root).unwrap(); } -/// A dependency tree contains thousands of manifests. Descending into it +/// A worktree container repeats every manifest of the project. Descending into it /// would both bury the real services and make project open unusably slow. #[test] -fn detectors_never_descend_into_dependency_directories() { +fn detectors_never_descend_into_hidden_folders() { let root = temporary_root("detect-prune"); fs::create_dir_all(&root).unwrap(); multi_language_project(&root); @@ -131,7 +131,9 @@ fn detectors_never_descend_into_dependency_directories() { .collect::>(); assert!( - !sources.iter().any(|source| source.contains("node_modules")), + !sources + .iter() + .any(|source| source.contains(".worktrees/decoy")), "{sources:?}" ); assert!( diff --git a/rust/crates/core/src/tests/project.rs b/rust/crates/core/src/tests/project.rs index 7df8392f..4e43904f 100644 --- a/rust/crates/core/src/tests/project.rs +++ b/rust/crates/core/src/tests/project.rs @@ -275,18 +275,25 @@ fn search_everywhere_matches_names_before_limits_and_shares_utf16_fragments() { for i in 0..60 { fs::write(root.join(format!("aName{i}.txt")), "").unwrap(); } - let search = |generated: bool, cap: usize| -> Vec { - let response: Value = serde_json::from_str(&execute_json(&serde_json::json!({ - "command": "workspace.searchEverywhere", "payload": { - "root": root, "query": fixture["query"], "maxResults": 1000, - "maxFileResults": cap, "maxContentResults": 0, "maxSymbolResults": 0, - "includeGeneratedFileNames": generated, "hiddenDirectoryNames": ["excluded", ".build", "target"] - } - }).to_string())).unwrap(); + // Folders a plugin declares as generated, listed again by includeGeneratedFileNames, + // are covered by the `configure_visibility` integration test: the declarations are + // process-wide, so these unit tests run with none. + let search = |cap: usize| -> Vec { + let response: Value = serde_json::from_str(&execute_json( + &serde_json::json!({ + "command": "workspace.searchEverywhere", "payload": { + "root": root, "query": fixture["query"], "maxResults": 1000, + "maxFileResults": cap, "maxContentResults": 0, "maxSymbolResults": 0, + "includeGeneratedFileNames": true, "hiddenDirectoryNames": ["excluded"] + } + }) + .to_string(), + )) + .unwrap(); assert_eq!(response["ok"], true, "{response}"); response["data"]["matches"].as_array().unwrap().clone() }; - let results = search(true, 200); + let results = search(200); for case in fixture["cases"].as_array().unwrap() { let result = results .iter() @@ -304,12 +311,8 @@ fn search_everywhere_matches_names_before_limits_and_shares_utf16_fragments() { .any(|m| m["path"].as_str().unwrap().starts_with(".git/") || m["path"].as_str().unwrap().starts_with("excluded/") || m["path"] == "src/Unrelated.rs")); - let limited = search(true, 1); + let limited = search(1); assert_eq!(limited[0]["path"], ".build/checkouts/Name.swift"); - assert!(!search(false, 200) - .iter() - .any(|m| m["path"].as_str().unwrap().contains(".build/") - || m["path"].as_str().unwrap().contains("target/"))); let response: Value = serde_json::from_str(&execute_json( &serde_json::json!({ "command": "workspace.searchEverywhere", "payload": { @@ -321,24 +324,29 @@ fn search_everywhere_matches_names_before_limits_and_shares_utf16_fragments() { )) .unwrap(); assert_eq!(response["data"]["matches"].as_array().unwrap().len(), 2); - // A cached names-only index must follow file updates, deletion and directory invalidation. + // A cached name index must follow file updates, deletion and directory invalidation. let update = |paths: &[&str]| { - crate::project::files::update_search_index(serde_json::from_value(serde_json::json!({ - "root": root, "paths": paths, "hiddenDirectoryNames": ["excluded", ".build", "target"] - })).unwrap(), lithe_lsp_engine::indexing_changed).unwrap() + crate::project::files::update_search_index( + serde_json::from_value(serde_json::json!({ + "root": root, "paths": paths, "hiddenDirectoryNames": ["excluded"] + })) + .unwrap(), + lithe_lsp_engine::indexing_changed, + ) + .unwrap() }; fs::write(root.join(".build/checkouts/NameGuide.swift"), "").unwrap(); update(&[".build/checkouts/NameGuide.swift"]); - assert!(search(true, 200) + assert!(search(200) .iter() .any(|m| m["path"] == ".build/checkouts/NameGuide.swift")); fs::remove_file(root.join(".build/checkouts/NameGuide.swift")).unwrap(); update(&[".build/checkouts/NameGuide.swift"]); - assert!(!search(true, 200) + assert!(!search(200) .iter() .any(|m| m["path"] == ".build/checkouts/NameGuide.swift")); assert!(update(&[".build/checkouts"]).rebuilt); - assert!(search(true, 200) + assert!(search(200) .iter() .any(|m| m["path"] == ".build/checkouts/Name.swift")); } @@ -498,14 +506,14 @@ fn list_directories_returns_one_visible_level_per_requested_directory() { let root = temporary_root("list-directories"); write_linked_worktree_fixture(&root); write_fixture_file(&root.join("src/main/Util.txt"), "Util"); - write_fixture_file(&root.join("build/output.bin"), ""); + write_fixture_file(&root.join(".worktrees/feature/output.bin"), ""); let data = core_data( "list-directories", "workspace.listDirectories", serde_json::json!({ "root": root, - "paths": ["", "src/", ".claude/worktrees", "missing", "build", "../outside", + "paths": ["", "src/", ".claude/worktrees", "missing", ".worktrees", "../outside", ".claude/worktrees/agent", ".claude/worktrees/agent/src"] }), ); @@ -668,7 +676,7 @@ fn workspace_snapshot_keeps_worktrees_outside_their_main_checkout() { } #[test] -fn workspace_snapshot_hides_build_artifact_directory() { +fn workspace_snapshot_hides_the_folders_the_user_names() { let root = temporary_root("snapshot-artifacts"); write_fixture_file(&root.join("src/App.txt"), "App"); write_fixture_file( @@ -679,7 +687,7 @@ fn workspace_snapshot_hides_build_artifact_directory() { let data = core_data( "snapshot-artifacts", "workspace.snapshot", - serde_json::json!({"root": root}), + serde_json::json!({"root": root, "hiddenDirectoryNames": [".artifacts"]}), ); assert_eq!(data["files"], serde_json::json!(["src/App.txt"])); @@ -687,26 +695,25 @@ fn workspace_snapshot_hides_build_artifact_directory() { } #[test] -fn workspace_snapshot_skips_python_environments_and_bytecode_caches() { - let root = temporary_root("snapshot-python"); +fn workspace_snapshot_skips_hidden_folders_and_files_at_any_depth() { + let root = temporary_root("snapshot-hidden"); write_fixture_file(&root.join("app/main.py"), "print('hi')"); write_fixture_file(&root.join("app/helper.py"), ""); - // Environments are skipped at any depth, not only at the workspace root. - write_fixture_file(&root.join(".venv/Lib/site-packages/pkg/mod.py"), ""); - write_fixture_file(&root.join("venv/bin/activate"), ""); - write_fixture_file(&root.join("service/.venv/Lib/site-packages/dep.py"), ""); - // Bytecode is generated output: both the cache folder and stray `.pyc` files. - write_fixture_file(&root.join("app/__pycache__/main.cpython-311.pyc"), ""); - write_fixture_file(&root.join("app/legacy.pyc"), ""); + // Core's folders are skipped at any depth, not only at the workspace root. + write_fixture_file(&root.join(".worktrees/feature/app/main.py"), ""); + write_fixture_file(&root.join(".worktree/bin/activate"), ""); + write_fixture_file(&root.join("service/.worktrees/fix/dep.py"), ""); + // Core's file patterns hide files by name too. + write_fixture_file(&root.join("app/.DS_Store"), ""); // Names that merely resemble the hidden ones stay visible. - write_fixture_file(&root.join("environment/venv_notes.md"), ""); - write_fixture_file(&root.join("app/pyc_overview.md"), ""); + write_fixture_file(&root.join("environment/worktree_notes.md"), ""); + write_fixture_file(&root.join("app/DS_Store_overview.md"), ""); let expected = serde_json::json!([ + "app/DS_Store_overview.md", "app/helper.py", "app/main.py", - "app/pyc_overview.md", - "environment/venv_notes.md", + "environment/worktree_notes.md", ]); let sorted = |data: &Value| { let mut files: Vec = data["files"] @@ -719,12 +726,12 @@ fn workspace_snapshot_skips_python_environments_and_bytecode_caches() { serde_json::json!(files) }; let full = core_data( - "snapshot-python", + "snapshot-hidden", "workspace.snapshot", serde_json::json!({"root": root}), ); let files_only = core_data( - "snapshot-python-files-only", + "snapshot-hidden-files-only", "workspace.snapshot", serde_json::json!({"root": root, "includeTree": false}), ); @@ -734,12 +741,12 @@ fn workspace_snapshot_skips_python_environments_and_bytecode_caches() { // The project tree lists directories through the same rules, so the hidden // folders must not appear one level at a time either. let listing = core_data( - "list-python", + "list-hidden", "workspace.listDirectories", - serde_json::json!({"root": root, "paths": ["", "app"]}), + serde_json::json!({"root": root, "paths": ["", "app", "service"]}), ); let listed = listing.to_string(); - for hidden in [".venv", "\"venv\"", "__pycache__", "legacy.pyc"] { + for hidden in ["\".worktrees\"", "\".worktree\"", ".DS_Store\""] { assert!( !listed.contains(hidden), "{hidden} must stay hidden: {listed}" @@ -747,33 +754,36 @@ fn workspace_snapshot_skips_python_environments_and_bytecode_caches() { } assert!(listed.contains("main.py"), "{listed}"); - // File watchers use the same boundary, so environment churn raises no refresh. + // File watchers use the same boundary, so churn in hidden folders raises no refresh. assert!(!crate::project::files::is_workspace_event_relevant( - ".venv/Lib/site-packages/pkg/mod.py" + ".worktrees/feature/app/main.py" )); assert!(!crate::project::files::is_workspace_event_relevant( - "app/__pycache__/main.cpython-311.pyc" + "service/.worktrees/fix/dep.py" )); assert!(crate::project::files::is_workspace_event_relevant( "app/main.py" )); - // A built-in folder turned off with `!` is shown again, and its events kept. + // A default folder or pattern turned off with `!` is shown again, and its events kept. let turned_off = crate::project::files::VisibilityRules::new( - vec!["venv".into()], - vec!["!**/venv/".into(), "!*.pyc".into()], + Vec::new(), + vec!["!**/.worktree/".into(), "!.DS_Store".into()], ); - assert!(!turned_off.is_hidden("venv/lib/site.py", false)); - assert!(!turned_off.is_hidden("app/a.pyc", false)); - assert!(turned_off.is_hidden(".venv/lib/site.py", false)); + assert!(!turned_off.is_hidden(".worktree/bin/activate", false)); + assert!(!turned_off.is_hidden("app/.DS_Store", false)); + assert!(turned_off.is_hidden(".worktrees/feature/app/main.py", false)); assert_eq!( crate::project::filter_workspace_changes( serde_json::from_value(serde_json::json!({ - "paths": ["venv/lib/site.py", ".venv/lib/site.py", "app/main.py"], - "hiddenFilePatterns": ["!**/venv/"] + "paths": [".worktree/bin/activate", ".worktrees/fix/dep.py", "app/main.py"], + "hiddenFilePatterns": ["!**/.worktree/"] })) .unwrap() ), - vec!["venv/lib/site.py".to_string(), "app/main.py".to_string()] + vec![ + ".worktree/bin/activate".to_string(), + "app/main.py".to_string() + ] ); fs::remove_dir_all(root).expect("temporary fixture should be removable"); } diff --git a/rust/crates/core/src/tests/run_configuration.rs b/rust/crates/core/src/tests/run_configuration.rs index aceda01d..10b5b2ee 100644 --- a/rust/crates/core/src/tests/run_configuration.rs +++ b/rust/crates/core/src/tests/run_configuration.rs @@ -1185,7 +1185,7 @@ fn working_directory_override_must_name_an_existing_project_directory() { } #[test] -fn shared_run_scan_excludes_caches_and_keeps_hidden_sources() { +fn shared_run_scan_excludes_hidden_folders_and_keeps_dot_named_sources() { let root = temporary_root("shared-run-scan"); struct Cleanup(PathBuf); impl Drop for Cleanup { @@ -1195,14 +1195,14 @@ fn shared_run_scan_excludes_caches_and_keeps_hidden_sources() { } fs::create_dir_all(&root).unwrap(); let _cleanup = Cleanup(root.clone()); - // Core scans the workspace itself: cache directories are left out, a hidden - // source directory stays. + // Core scans the workspace itself: the folders it hides are left out at any + // depth, a dot-named source directory stays. for path in [ ".sources/Makefile", "src/Makefile", - ".pytest_cache/Makefile", - "node_modules/Makefile", - "target/Makefile", + ".git/Makefile", + ".worktrees/feature/Makefile", + "app/.worktree/Makefile", ] { let file = root.join(path); fs::create_dir_all(file.parent().unwrap()).unwrap(); @@ -1226,9 +1226,9 @@ fn shared_run_scan_excludes_caches_and_keeps_hidden_sources() { assert!(inputs.contains_key(".sources/Makefile")); assert!(inputs.contains_key("src/Makefile")); assert!(!inputs.keys().any(|path| { - path.starts_with(".pytest_cache/") - || path.starts_with("node_modules/") - || path.starts_with("target/") + path.starts_with(".git/") + || path.starts_with(".worktrees/") + || path.starts_with("app/.worktree/") })); let mut document = generated["generated"].clone(); // A persisted incomplete baseline cannot certify freshness or infer deletion, diff --git a/rust/crates/core/tests/configure_visibility.rs b/rust/crates/core/tests/configure_visibility.rs new file mode 100644 index 00000000..62c13deb --- /dev/null +++ b/rust/crates/core/tests/configure_visibility.rs @@ -0,0 +1,418 @@ +//! Folder names enabled plugins declare through `workspace.configureVisibility` +//! are hidden by every workspace walk, and clearing them shows the folders again. +//! +//! The declarations are process-wide, so this binary holds the only test that sets +//! them; Core's unit tests run with none. + +use lithe_core::execute_json; +use serde_json::{json, Value}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +fn response(command: &str, payload: Value) -> Value { + serde_json::from_str(&execute_json( + &json!({ + "id": "configure-visibility", + "command": command, + "timeoutMilliseconds": 5000, + "payload": payload, + }) + .to_string(), + )) + .expect("Core should answer with JSON") +} + +fn data(command: &str, payload: Value) -> Value { + let response = response(command, payload); + assert_eq!(response["ok"], true, "{command}: {response}"); + response["data"].clone() +} + +fn configure(plugins: Vec) -> Value { + let plugins: Vec = plugins + .into_iter() + .map(|manifest| json!({ "manifest": manifest })) + .collect(); + data( + "workspace.configureVisibility", + json!({ "plugins": plugins }), + ) +} + +/// Clears the declarations when the test ends, also after a failed assertion. +struct Declarations; + +impl Drop for Declarations { + fn drop(&mut self) { + configure(Vec::new()); + } +} + +struct Workspace(PathBuf); + +impl Workspace { + fn new() -> Self { + let nonce = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock should be valid") + .as_nanos(); + let root = std::env::temp_dir().join(format!( + "lithe-configure-visibility-{}-{nonce}", + std::process::id() + )); + fs::create_dir_all(&root).expect("workspace should be creatable"); + Self(root.canonicalize().expect("workspace should resolve")) + } + + fn write(&self, path: &str, content: &str) -> &Self { + let file = self.0.join(path); + fs::create_dir_all(file.parent().expect("file should have a parent")) + .expect("parent should be creatable"); + fs::write(file, content).expect("file should be writable"); + self + } + + fn git_init(&self, path: &str) { + let directory = self.0.join(path); + fs::create_dir_all(&directory).expect("repository should be creatable"); + let result = data( + "git.command", + json!({ + "root": directory, + "arguments": ["init", "--template=", "-q", "-b", "main"], + }), + ); + assert_eq!(result["exitCode"], 0, "{result}"); + } +} + +impl Drop for Workspace { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn manifest(name: &str) -> Value { + serde_json::from_str(match name { + "build" => include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/build-systems/build-static-file.plugin.json" + )), + "vcs" => include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/vcs/vcs-provider.plugin.json" + )), + _ => unreachable!("unknown fixture {name}"), + }) + .expect("fixture manifest should be JSON") +} + +/// A build system that hides its output folders, a VCS provider whose `.svn` +/// marker is hidden, and a build system with an invalid folder name. +fn declaring_plugins() -> Vec { + let mut build = manifest("build"); + build["id"] = json!("dev.lithe.test.generated-folders"); + build["buildSystems"][0]["layout"]["hiddenDirectoryNames"] = json!(["target", "Generated"]); + let mut vcs = manifest("vcs"); + vcs["id"] = json!("dev.lithe.test.metadata-folders"); + let mut invalid = manifest("build"); + invalid["id"] = json!("dev.lithe.test.invalid-folder-name"); + invalid["buildSystems"][0]["layout"]["hiddenDirectoryNames"] = json!(["out/classes"]); + vec![build, vcs, invalid] +} + +fn strings(values: &Value) -> Vec { + values + .as_array() + .expect("value should be an array") + .iter() + .map(|value| value.as_str().expect("entry should be text").to_string()) + .collect() +} + +fn snapshot_files(root: &Path) -> Vec { + let mut files = strings(&data("workspace.snapshot", json!({ "root": root }))["files"]); + files.sort(); + files +} + +fn file_names(root: &Path, include_generated: bool) -> Vec { + let found = data( + "workspace.searchEverywhere", + json!({ + "root": root, "query": "Report", "maxResults": 100, "maxFileResults": 100, + "maxContentResults": 0, "maxSymbolResults": 0, + "includeGeneratedFileNames": include_generated, + }), + ); + let mut paths: Vec = found["matches"] + .as_array() + .expect("search should list matches") + .iter() + .map(|item| { + item["path"] + .as_str() + .expect("path should be text") + .to_string() + }) + .collect(); + paths.sort(); + paths.dedup(); + paths +} + +fn content_matches(root: &Path) -> Vec { + let found = data( + "workspace.searchEverywhere", + json!({ + "root": root, "query": "report body", "maxResults": 100, "maxFileResults": 0, + "maxContentResults": 100, "maxSymbolResults": 0, "includeGeneratedFileNames": true, + }), + ); + let mut paths: Vec = found["matches"] + .as_array() + .expect("search should list matches") + .iter() + .map(|item| { + item["path"] + .as_str() + .expect("path should be text") + .to_string() + }) + .collect(); + paths.sort(); + paths.dedup(); + paths +} + +fn run_scan_inputs(root: &Path) -> Vec { + let generated = data("runConfig.generate", json!({ "root": root })); + let mut inputs: Vec = generated["generated"]["generator"]["inputs"] + .as_object() + .expect("generation should list its inputs") + .keys() + .filter(|path| path.ends_with("Makefile")) + .cloned() + .collect(); + inputs.sort(); + inputs +} + +fn build_instances(root: &Path) -> Vec { + let detected = data( + "build.detect", + json!({ + "workspaceRoot": root, + "plugins": [{ "manifest": declaring_plugins()[0] }], + }), + ); + assert_eq!(detected["status"], "ok", "{detected}"); + strings( + &detected["detection"]["instances"] + .as_array() + .expect("detection should list instances") + .iter() + .map(|instance| instance["id"].clone()) + .collect::(), + ) +} + +fn vcs_roots(root: &Path) -> Vec { + let detected = data( + "vcs.detectRoots", + json!({ + "workspaceRoot": root, + "plugins": [{ "manifest": declaring_plugins()[1] }], + }), + ); + assert_eq!(detected["status"], "ok", "{detected}"); + let mut roots: Vec = detected["detection"]["roots"] + .as_array() + .expect("detection should list roots") + .iter() + .filter(|root| root["vcs"] == "svn") + .map(|root| root["id"].as_str().expect("id should be text").to_string()) + .collect(); + roots.sort(); + roots +} + +fn repositories(root: &Path) -> Vec { + let mut paths: Vec = data("workspace.repositories", json!({ "root": root })) + ["repositories"] + .as_array() + .expect("discovery should list repositories") + .iter() + .map(|entry| { + entry["path"] + .as_str() + .expect("path should be text") + .to_string() + }) + .collect(); + paths.sort(); + paths +} + +#[test] +fn plugin_declared_folders_are_hidden_by_every_walk_until_cleared() { + let workspace = Workspace::new(); + let root = workspace.0.clone(); + workspace + .write("Cargo.toml", "[package]\nname = \"app\"\n") + .write("Makefile", "all:\n\ttrue\n") + .write("src/Report.txt", "report body\n") + .write("target/Makefile", "all:\n\ttrue\n") + .write("target/debug/Report.txt", "report body\n") + .write( + "target/debug/Cargo.toml", + "[package]\nname = \"generated\"\n", + ) + // Declared names match one path component, ignoring ASCII case. + .write("module/generated/Report.txt", "report body\n") + .write("legacy/.svn/Report.txt", "report body\n") + .write("target/checkout/.svn/wc.db", ""); + workspace.git_init("."); + workspace.git_init("target/repository"); + let checkout = |path: &str| { + lithe_git::simplified_canonical_path(root.join(path).canonicalize().unwrap()) + .unwrap() + .to_string_lossy() + .replace('\\', "/") + }; + + // Without declarations, only Core's own folders are hidden. + let everything = [ + "legacy/.svn/Report.txt", + "module/generated/Report.txt", + "src/Report.txt", + "target/debug/Report.txt", + ]; + assert_eq!(file_names(&root, false), everything); + assert_eq!(run_scan_inputs(&root), ["Makefile", "target/Makefile"]); + assert_eq!(build_instances(&root), ["cargo:.", "cargo:target/debug"]); + assert_eq!(vcs_roots(&root), ["legacy", "target/checkout"]); + assert_eq!( + repositories(&root), + [checkout("."), checkout("target/repository")] + ); + + let _declarations = Declarations; + let configured = configure(declaring_plugins()); + assert_eq!( + configured["hiddenDirectoryNames"], + json!([".svn", "Generated", "target"]) + ); + let rejected = configured["rejected"].as_array().unwrap(); + assert_eq!(rejected.len(), 1, "{configured}"); + assert_eq!(rejected[0]["index"], 2); + assert_eq!(rejected[0]["error"]["code"], "plugin.path.invalid"); + + // Hosts read the folders to display them and classify paths without a copy. + let defaults = data("workspace.visibilityDefaults", json!({})); + let names = strings(&defaults["hiddenDirectoryNames"]); + for name in [ + ".git", + ".worktree", + ".worktrees", + ".svn", + "Generated", + "target", + ] { + assert!(names.iter().any(|entry| entry == name), "{name}: {names:?}"); + } + let classified = data( + "workspace.classifyVisibility", + json!({ "entries": [ + { "path": "target", "isDirectory": true }, + { "path": "module/GENERATED/Report.txt", "isDirectory": false }, + { "path": "src/target.txt", "isDirectory": false }, + ]}), + ); + assert_eq!(classified["hidden"], json!([true, true, false])); + // `!` turns a plugin-declared folder off like one of Core's own. + let turned_off = data( + "workspace.classifyVisibility", + json!({ + "hiddenFilePatterns": ["!target"], + "entries": [{ "path": "target/debug", "isDirectory": true }], + }), + ); + assert_eq!(turned_off["hidden"], json!([false])); + + // The tree and its listing skip the folders without reading them. + assert_eq!( + snapshot_files(&root), + ["Cargo.toml", "Makefile", "src/Report.txt"] + ); + let listing = data( + "workspace.listDirectories", + json!({ "root": root, "paths": ["", "legacy", "module"] }), + ) + .to_string(); + for hidden in ["\"target\"", "\"generated\"", "\".svn\""] { + assert!(!listing.contains(hidden), "{hidden}: {listing}"); + } + + // Search Everywhere lists generated file names on request, never VCS metadata, + // and content search reads none of them. + assert_eq!(file_names(&root, false), ["src/Report.txt"]); + assert_eq!( + file_names(&root, true), + [ + "module/generated/Report.txt", + "src/Report.txt", + "target/debug/Report.txt" + ] + ); + assert_eq!(content_matches(&root), ["src/Report.txt"]); + + // The cached name index follows additions, deletions and folder invalidation + // inside a generated folder. + let update = |paths: &[&str]| { + data( + "workspace.searchIndex.update", + json!({ "root": root, "paths": paths }), + ) + }; + workspace.write("target/debug/ReportGuide.txt", ""); + update(&["target/debug/ReportGuide.txt"]); + assert!(file_names(&root, true).contains(&"target/debug/ReportGuide.txt".to_string())); + fs::remove_file(root.join("target/debug/ReportGuide.txt")).unwrap(); + update(&["target/debug/ReportGuide.txt"]); + assert!(!file_names(&root, true).contains(&"target/debug/ReportGuide.txt".to_string())); + assert_eq!(update(&["target/debug"])["rebuilt"], true); + assert!(file_names(&root, true).contains(&"target/debug/Report.txt".to_string())); + + // File events inside the folders raise no refresh. + assert!(!lithe_core::is_workspace_event_relevant( + "target/debug/Report.txt" + )); + assert!(!lithe_core::is_workspace_event_relevant( + "legacy/.svn/wc.db" + )); + assert!(lithe_core::is_workspace_event_relevant("src/Report.txt")); + + // Run discovery, build detection, VCS roots and Git repositories skip them too. + assert_eq!(run_scan_inputs(&root), ["Makefile"]); + assert_eq!(build_instances(&root), ["cargo:."]); + assert_eq!(vcs_roots(&root), ["legacy"]); + assert_eq!(repositories(&root), [checkout(".")]); + + // An empty list clears the declarations, and every walk sees the folders again. + let cleared = configure(Vec::new()); + assert_eq!( + cleared, + json!({ "hiddenDirectoryNames": [], "rejected": [] }) + ); + assert_eq!(file_names(&root, false), everything); + assert_eq!(vcs_roots(&root), ["legacy", "target/checkout"]); + + // A malformed payload is refused and leaves the current declarations alone. + configure(declaring_plugins()); + let refused = response("workspace.configureVisibility", json!({ "plugin": [] })); + assert_eq!(refused["ok"], false, "{refused}"); + assert_eq!(refused["error"]["code"], "invalid_request", "{refused}"); + assert_eq!(file_names(&root, false), ["src/Report.txt"]); +} diff --git a/rust/crates/execution/Cargo.toml b/rust/crates/execution/Cargo.toml index 518d9540..2463284a 100644 --- a/rust/crates/execution/Cargo.toml +++ b/rust/crates/execution/Cargo.toml @@ -11,6 +11,7 @@ test-support = [] [dependencies] ignore = "=0.4.33" +lithe-core-rules = { path = "../core-rules" } lithe-diagnostics = { path = "../diagnostics" } lithe-platform = { path = "../platform" } lithe-plugin-model = { path = "../plugin-model" } diff --git a/rust/crates/execution/src/detectors/scan.rs b/rust/crates/execution/src/detectors/scan.rs index 15f4eb8e..518fc754 100644 --- a/rust/crates/execution/src/detectors/scan.rs +++ b/rust/crates/execution/src/detectors/scan.rs @@ -78,7 +78,7 @@ impl DirectoryContext { } /// Walks the project, pruning uninteresting subtrees *before* descending rather -/// than filtering afterwards, so a `node_modules` tree is never read at all. +/// than filtering afterwards, so a hidden tree is never read at all. pub fn scan(root: &Path) -> Result, CoreError> { scan_ignoring(root, &IgnoredPaths::default()) } diff --git a/rust/crates/execution/src/lib.rs b/rust/crates/execution/src/lib.rs index a53e6e84..a65e3eda 100644 --- a/rust/crates/execution/src/lib.rs +++ b/rust/crates/execution/src/lib.rs @@ -23,7 +23,7 @@ pub use detectors::{scan, scan_ignoring, DirectoryContext}; pub use title_action::{decide_title_action, TitleActionRequest}; pub mod workspace_scan; -pub use workspace_scan::{is_run_scan_excluded_directory, IgnoredPaths}; +pub use workspace_scan::IgnoredPaths; mod environment; pub use environment::{ diff --git a/rust/crates/execution/src/workspace_scan.rs b/rust/crates/execution/src/workspace_scan.rs index 3978f1ba..b35a6952 100644 --- a/rust/crates/execution/src/workspace_scan.rs +++ b/rust/crates/execution/src/workspace_scan.rs @@ -3,6 +3,12 @@ //! Automatic discovery is best effort below the required workspace root. Declared //! build-system modules remain owned by their provider and bypass these defaults. //! +//! Every scan, fingerprints included, skips the directories the default +//! visibility rules hide: Core's own folders (`.git`, the worktree containers and +//! the root `.lithe`) and the folder names the enabled plugins declare, such as +//! `target` while a Cargo plugin is enabled. The rules are read once per scan, so +//! a plugin enabled during a scan applies from the next one. +//! //! Heuristic discovery also skips the directories Git ignores: agent worktrees, //! generated trees and local checkouts repeat or imitate the project's own //! manifests, and listing them as run or build roots shows every module twice. @@ -20,6 +26,7 @@ use ignore::gitignore::{Gitignore, GitignoreBuilder}; use ignore::Match; +use lithe_core_rules::visibility::VisibilityRules; use lithe_platform::paths::slash_separated_path; use lithe_platform::Platform; use lithe_protocol::CoreError; @@ -37,51 +44,6 @@ const MAX_HEURISTIC_DIRECTORIES: usize = 4000; /// contributes no rules, which only lets the scan see more directories. const MAX_IGNORE_SOURCE_BYTES: u64 = 1 << 20; -const EXCLUDED_DIRECTORIES: &[&str] = &[ - ".git", - ".worktree", - ".worktrees", - ".lithe", - ".idea", - ".vscode", - ".gradle", - ".venv", - "venv", - ".tox", - ".mypy_cache", - ".pytest_cache", - "__pycache__", - ".next", - ".nuxt", - ".svelte-kit", - ".terraform", - ".cargo", - ".stack-work", - ".bundle", - ".dart_tool", - ".build", - ".swiftpm", - "node_modules", - "bower_components", - "vendor", - "target", - "build", - "dist", - "out", - "obj", - "coverage", - "DerivedData", - "Pods", -]; - -/// Default pruning for automatic run discovery, fingerprints and host file lists. -/// Hidden source directories are allowed unless explicitly named here. -pub fn is_run_scan_excluded_directory(name: &str) -> bool { - EXCLUDED_DIRECTORIES - .iter() - .any(|excluded| excluded.eq_ignore_ascii_case(name)) -} - /// One directory's files, without following directory symlinks. pub struct ScannedDirectory { /// Absolute path of the directory. @@ -373,6 +335,7 @@ fn visit_with_readers( mut visit: impl FnMut(ScannedDirectory) -> ControlFlow<()>, ) -> Result, CoreError> { let heuristic = max_depth.is_some(); + let hidden = VisibilityRules::new(Vec::new(), Vec::new()); let mut unreadable_paths = BTreeSet::new(); let mut directory_count = 0; let mut pending: Vec<(PathBuf, usize, Option>)> = @@ -415,8 +378,8 @@ fn visit_with_readers( repository = Some(directory); } if directory { - if !is_run_scan_excluded_directory(name) - && max_depth.is_none_or(|limit| depth < limit) + if max_depth.is_none_or(|limit| depth < limit) + && !hidden.is_hidden(&relative(root, &child), true) { subdirectories.push(child); } @@ -506,7 +469,7 @@ mod tests { Ok(vec![ (root.join("blocked"), true, false), (root.join(".sources"), true, false), - (root.join(".pytest_cache"), true, false), + (root.join(".git"), true, false), ]) } else if path.ends_with(".sources") { Ok(vec![(path.join("main.txt"), false, false)]) diff --git a/rust/crates/git/src/repository.rs b/rust/crates/git/src/repository.rs index 21bb4a87..2a8c9c64 100644 --- a/rust/crates/git/src/repository.rs +++ b/rust/crates/git/src/repository.rs @@ -22,6 +22,8 @@ pub fn workspace_repositories( let mut queue = VecDeque::from([(workspace_root.clone(), 0usize)]); let mut visited_directories = HashSet::new(); + // Read once per scan: a plugin enabled during the scan applies from the next one. + let hidden_directories = lithe_core_rules::visibility::default_hidden_directories(); while let Some((directory, depth)) = queue.pop_front() { lithe_protocol::cancellation::check()?; @@ -55,7 +57,7 @@ pub fn workspace_repositories( } continue; } - if !repository_scan_directory_is_visible(&name) { + if !repository_scan_directory_is_visible(&name, &hidden_directories) { continue; } let file_type = entry.file_type().map_err(repository_scan_error)?; @@ -154,7 +156,7 @@ fn workspace_repository_id(repository: &Path, workspace_root: &Path) -> Option bool { +fn repository_scan_directory_is_visible(name: &str, hidden_directories: &[String]) -> bool { // These intentional checkout containers are hidden in the file tree but // remain discoverable in Git. Apply exclusions to their children as usual. if name.eq_ignore_ascii_case(".worktree") || name.eq_ignore_ascii_case(".worktrees") { @@ -163,9 +165,9 @@ fn repository_scan_directory_is_visible(name: &str) -> bool { // Filter descendants, never the explicitly opened root or its containing // repository. Git ignore rules govern tracked files, not repository ownership. !name.starts_with('.') - && !lithe_core_rules::visibility::BUILT_IN_HIDDEN_DIRECTORIES + && !hidden_directories .iter() - .any(|hidden| name.eq_ignore_ascii_case(hidden)) + .any(|hidden| hidden.eq_ignore_ascii_case(name)) } /// Rejects Windows names that cannot round-trip through ordinary path identifiers. diff --git a/rust/crates/plugin-manifest/src/commands.rs b/rust/crates/plugin-manifest/src/commands.rs index 225bd2b8..62bd7297 100644 --- a/rust/crates/plugin-manifest/src/commands.rs +++ b/rust/crates/plugin-manifest/src/commands.rs @@ -211,3 +211,66 @@ pub fn decode_grammar_command(payload: Value) -> Result { }, ))) } + +/// Payload of `workspace.configureVisibility`: the manifests of every enabled +/// plugin, in any order. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct VisibilityPayload { + plugins: Vec, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct VisibilityPlugin { + manifest: Value, +} + +/// The folder names the enabled plugins hide in every workspace, unordered and +/// possibly repeated. +pub struct DeclaredHiddenDirectories { + /// Each build system's `layout.hiddenDirectoryNames`: dependency, cache + /// and build output folders. + pub generated: Vec, + /// Each VCS provider's directory markers, such as `.svn`. + pub metadata: Vec, + /// `{index, error}` for each manifest that failed validation, by its + /// position in the payload; such a manifest contributes no names. + pub rejected: Vec, +} + +/// Decodes a `workspace.configureVisibility` payload and collects the folder +/// names of every manifest that validates. As in `build.detect`, an invalid +/// manifest is reported instead of failing the call. +pub fn declared_hidden_directories(payload: Value) -> Result { + let payload: VisibilityPayload = decode_payload(payload, "workspace.configureVisibility")?; + let mut generated = Vec::new(); + let mut metadata = Vec::new(); + let mut rejected = Vec::new(); + for (index, plugin) in payload.plugins.into_iter().enumerate() { + match validate_manifest_value(plugin.manifest) { + Ok(manifest) => { + generated.extend( + manifest + .build_systems + .iter() + .flat_map(|build_system| build_system.hidden_directory_names()) + .cloned(), + ); + metadata.extend( + manifest + .vcs_providers + .iter() + .flat_map(|provider| provider.metadata_directory_names()) + .map(str::to_string), + ); + } + Err(error) => rejected.push(json!({ "index": index, "error": error })), + } + } + Ok(DeclaredHiddenDirectories { + generated, + metadata, + rejected, + }) +} diff --git a/rust/crates/project/src/files.rs b/rust/crates/project/src/files.rs index ddddbb04..0ced6c86 100644 --- a/rust/crates/project/src/files.rs +++ b/rust/crates/project/src/files.rs @@ -20,11 +20,11 @@ use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; -/// Default workspace exclusions, also used by Git discovery for generated directories. -/// The list lives in `lithe-core-rules`, the only definition every host shares. -pub(crate) use lithe_core_rules::visibility::BUILT_IN_HIDDEN_DIRECTORIES; +// The default workspace exclusions live in `lithe-core-rules`, the only definition every host +// shares: Core's own folders and the folder names the enabled plugins declare. use lithe_core_rules::visibility::{ - self as shared_visibility, disabled_built_ins, glob_matches, is_disabled_directory, + self as shared_visibility, default_hidden_directories, disabled_built_ins, glob_matches, + is_disabled_directory, plugin_generated_directories, }; mod events; diff --git a/rust/crates/project/src/files/events.rs b/rust/crates/project/src/files/events.rs index 289e2a84..ccf515b6 100644 --- a/rust/crates/project/src/files/events.rs +++ b/rust/crates/project/src/files/events.rs @@ -6,30 +6,34 @@ use super::*; /// Callers first relativize to the most specific explicitly watched root; native /// event-loss flags always bypass this filter and request recovery. pub fn is_workspace_event_relevant(relative: &str) -> bool { - is_workspace_event_relevant_with(relative, &[]) + is_workspace_event_relevant_with(relative, &default_hidden_directories(), &[]) } -/// Like [`is_workspace_event_relevant`], but a built-in folder the user turned -/// off with a `!` hidden-path entry is visible, so its events are kept. -fn is_workspace_event_relevant_with(relative: &str, hidden_file_patterns: &[String]) -> bool { - let disabled = disabled_built_ins(hidden_file_patterns); +/// Like [`is_workspace_event_relevant`] against one snapshot of the default +/// hidden folders, where a folder the user turned off with a `!` hidden-path +/// entry (`disabled`, see [`disabled_built_ins`]) is visible, so its events are kept. +fn is_workspace_event_relevant_with( + relative: &str, + hidden_directories: &[String], + disabled: &[String], +) -> bool { !relative .split(|character| is_separator(character, Platform::HOST)) .any(|component| { - BUILT_IN_HIDDEN_DIRECTORIES.iter().any(|name| { - component.eq_ignore_ascii_case(name) && !is_disabled_directory(name, &disabled) + hidden_directories.iter().any(|name| { + component.eq_ignore_ascii_case(name) && !is_disabled_directory(name, disabled) }) }) } /// Changed paths for `workspace.filterChanges`: a bare path list, or the -/// paths with the hidden-path entries whose `!` lines turn built-in folders off. +/// paths with the hidden-path entries whose `!` lines turn default folders off. #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum WorkspaceChangeFilterRequest { - /// Changed workspace-relative paths, filtered with the built-in rules only. + /// Changed workspace-relative paths, filtered with the default rules only. Paths(Vec), - /// Changed paths plus the hidden-path entries that adjust the built-in folders. + /// Changed paths plus the hidden-path entries that adjust the default folders. #[serde(rename_all = "camelCase")] WithRules { /// Changed workspace-relative paths. @@ -40,7 +44,7 @@ pub enum WorkspaceChangeFilterRequest { }, } -/// Keeps the changed paths outside the effective built-in hidden folders. +/// Keeps the changed paths outside the effective default hidden folders. pub fn filter_workspace_changes(request: WorkspaceChangeFilterRequest) -> Vec { let (paths, patterns) = match request { WorkspaceChangeFilterRequest::Paths(paths) => (paths, Vec::new()), @@ -49,8 +53,10 @@ pub fn filter_workspace_changes(request: WorkspaceChangeFilterRequest) -> Vec (paths, hidden_file_patterns), }; + let hidden_directories = default_hidden_directories(); + let disabled = disabled_built_ins(&patterns); paths .into_iter() - .filter(|path| is_workspace_event_relevant_with(path, &patterns)) + .filter(|path| is_workspace_event_relevant_with(path, &hidden_directories, &disabled)) .collect() } diff --git a/rust/crates/project/src/files/requests.rs b/rust/crates/project/src/files/requests.rs index 7b3419c0..742b7af5 100644 --- a/rust/crates/project/src/files/requests.rs +++ b/rust/crates/project/src/files/requests.rs @@ -11,10 +11,10 @@ pub struct WorkspaceSnapshotRequest { /// Explicit roots of this workspace; nested roots own their inventories independently. #[serde(default)] pub workspace_roots: Vec, - /// Extra directory names hidden from the tree, on top of the built-in ones. + /// Extra directory names hidden from the tree, on top of the default ones. #[serde(default)] pub hidden_directory_names: Vec, - /// Hidden-path globs; `!` lines turn built-in hidden folders back on. + /// Hidden-path globs; `!` lines turn default hidden folders back on. #[serde(default)] pub hidden_file_patterns: Vec, /// When false, the response keeps only the file list and returns `root` @@ -37,10 +37,10 @@ pub struct DirectoryListingRequest { /// Workspace-relative directories; an empty string is the root itself. #[serde(default)] pub paths: Vec, - /// Extra directory names hidden from the tree, on top of the built-in ones. + /// Extra directory names hidden from the tree, on top of the default ones. #[serde(default)] pub hidden_directory_names: Vec, - /// Hidden-path globs; `!` lines turn built-in hidden folders back on. + /// Hidden-path globs; `!` lines turn default hidden folders back on. #[serde(default)] pub hidden_file_patterns: Vec, } @@ -83,10 +83,10 @@ pub struct SearchRequest { /// Search Everywhere may discover generated file names without indexing their contents. #[serde(default)] pub include_generated_file_names: bool, - /// Extra directory names hidden from the tree, on top of the built-in ones. + /// Extra directory names hidden from the tree, on top of the default ones. #[serde(default)] pub hidden_directory_names: Vec, - /// Hidden-path globs; `!` lines turn built-in hidden folders back on. + /// Hidden-path globs; `!` lines turn default hidden folders back on. #[serde(default)] pub hidden_file_patterns: Vec, /// Comma-separated file masks such as `*.md, *.txt`; empty means no filter. @@ -119,10 +119,10 @@ pub struct SearchIndexRequest { /// Explicit workspace roots used when warming this index variant. #[serde(default)] pub workspace_roots: Vec, - /// Extra directory names hidden from the tree, on top of the built-in ones. + /// Extra directory names hidden from the tree, on top of the default ones. #[serde(default)] pub hidden_directory_names: Vec, - /// Hidden-path globs; `!` lines turn built-in hidden folders back on. + /// Hidden-path globs; `!` lines turn default hidden folders back on. #[serde(default)] pub hidden_file_patterns: Vec, } @@ -139,10 +139,10 @@ pub struct SearchIndexUpdateRequest { /// Workspace-relative paths that changed on disk. #[serde(default)] pub paths: Vec, - /// Extra directory names hidden from the tree, on top of the built-in ones. + /// Extra directory names hidden from the tree, on top of the default ones. #[serde(default)] pub hidden_directory_names: Vec, - /// Hidden-path globs; `!` lines turn built-in hidden folders back on. + /// Hidden-path globs; `!` lines turn default hidden folders back on. #[serde(default)] pub hidden_file_patterns: Vec, } @@ -196,10 +196,10 @@ pub struct ReplacementPreviewRequest { /// Unsaved editor text by workspace-relative path, used instead of the file on disk. #[serde(default)] pub text_overrides: HashMap, - /// Extra directory names hidden from the tree, on top of the built-in ones. + /// Extra directory names hidden from the tree, on top of the default ones. #[serde(default)] pub hidden_directory_names: Vec, - /// Hidden-path globs; `!` lines turn built-in hidden folders back on. + /// Hidden-path globs; `!` lines turn default hidden folders back on. #[serde(default)] pub hidden_file_patterns: Vec, } diff --git a/rust/crates/project/src/files/search_everywhere.rs b/rust/crates/project/src/files/search_everywhere.rs index b7187f92..169822c4 100644 --- a/rust/crates/project/src/files/search_everywhere.rs +++ b/rust/crates/project/src/files/search_everywhere.rs @@ -69,15 +69,22 @@ pub(crate) fn search_everywhere_with_page( let mut symbols = Vec::new(); let mut last_flush = None; if file_limit > 0 { + // Generated output is a file-name source, not a content/symbol index: with + // includeGeneratedFileNames the folders plugins declare as generated are listed + // again, while VCS metadata and Core's own folders stay hidden. + let generated = if request.include_generated_file_names { + plugin_generated_directories() + } else { + Vec::new() + }; let name_rules = VisibilityRules { - // Generated output is a file-name source, not a content/symbol index. hidden_directories: rules .hidden_directories .iter() .filter(|name| { - !request.include_generated_file_names - || !BUILT_IN_HIDDEN_DIRECTORIES.contains(&name.as_str()) - || [".git", ".svn", ".worktree", ".worktrees"].contains(&name.as_str()) + !generated + .iter() + .any(|generated| generated.eq_ignore_ascii_case(name)) }) .cloned() .collect(), diff --git a/rust/crates/project/src/history.rs b/rust/crates/project/src/history.rs index c4fbb3f2..9831aae6 100644 --- a/rust/crates/project/src/history.rs +++ b/rust/crates/project/src/history.rs @@ -25,46 +25,6 @@ const MAX_CONFIGURED_STORAGE_BYTES: u64 = 100 * 1024 * 1024 * 1024; /// Small files still occupy whole filesystem blocks; counting blocks keeps the /// budget close to what Finder and disk cleaners report. const STORAGE_BLOCK_BYTES: u64 = 4096; -/// Dependency, cache, and build output folders local history ignores by default. -/// -/// Like IDEA's excluded roots, these are regenerated by tools rather than -/// edited, yet a single virtual environment holds tens of thousands of files. -/// Settings show each as the wildcard rule `**/name/`, which the user can delete. -/// The list repeats the built-in hidden folders so pruning also reclaims -/// baselines that releases before those rules recorded, and adds tool caches -/// and agent worktrees that stay visible in the project tree. -const BUILT_IN_IGNORED_DIRECTORY_NAMES: &[&str] = &[ - ".artifacts", - ".build", - ".cache", - ".claude", - ".git", - ".gradle", - ".idea", - ".mypy_cache", - ".next", - ".nuxt", - ".pytest_cache", - ".ruff_cache", - ".swiftpm", - ".svn", - ".tox", - ".uv-cache", - ".venv", - ".worktree", - ".worktrees", - "DerivedData", - "Pods", - "__pycache__", - "build", - "coverage", - "design-qa-artifacts", - "dist", - "node_modules", - "out", - "target", - "venv", -]; #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] @@ -84,10 +44,10 @@ pub struct HistoryRecordRequest { /// Whether recording also drops expired snapshots and enforces the storage cap; defaults to true. #[serde(default = "default_prune_expired")] pub prune_expired: bool, - /// Extra directory names hidden from the tree, on top of the built-in ones. + /// Extra directory names hidden from the tree, on top of the default ones. #[serde(default)] pub hidden_directory_names: Vec, - /// Hidden-path globs; `!` lines turn built-in hidden folders back on. + /// Hidden-path globs; `!` lines turn default hidden folders back on. #[serde(default)] pub hidden_file_patterns: Vec, /// Rules for files whose changes are not recorded. @@ -104,12 +64,12 @@ pub struct HistoryRecordRequest { /// tree and their existing history stays listed. Globs use the hidden-path /// syntax; regexes are case-insensitive and match anywhere in the /// workspace-relative path unless anchored. An invalid regex never matches. -/// The built-in folders apply as `**/name/` globs unless a `!**/name/` (or +/// The default ignored folders apply as `**/name/` globs unless a `!**/name/` (or /// `!name`) glob turns one off. #[derive(Debug, Default, Deserialize)] #[serde(rename_all = "camelCase")] pub struct HistoryIgnoreRules { - /// Globs in hidden-path syntax; `!` lines turn built-in folders back on. + /// Globs in hidden-path syntax; `!` lines turn default folders back on. #[serde(default)] pub path_patterns: Vec, /// Case-insensitive regexes matched against the workspace-relative path. @@ -118,29 +78,34 @@ pub struct HistoryIgnoreRules { } impl HistoryIgnoreRules { - /// The built-in folders no `!` glob turned off. - fn built_in_ignored_directories(&self) -> Vec<&'static str> { + /// The folders local history ignores by default, except those a `!` glob turned off. + /// + /// They are the default hidden folders: Core's own and the folder names the enabled plugins + /// declare, such as a virtual environment that holds tens of thousands of regenerated files. + /// Like IDEA's excluded roots they are regenerated by tools rather than edited. Repeating + /// the hidden folders here also lets pruning reclaim baselines recorded before those rules + /// existed. Settings show each as the wildcard rule `**/name/`, which the user can delete. + fn default_ignored_directories(&self) -> Vec { let disabled = self .path_patterns .iter() .filter_map(|pattern| pattern.trim().strip_prefix('!')) .map(str::trim) .collect::>(); - BUILT_IN_IGNORED_DIRECTORY_NAMES - .iter() - .copied() + lithe_core_rules::visibility::default_hidden_directories() + .into_iter() .filter(|name| { !disabled.iter().any(|entry| { entry.eq_ignore_ascii_case(name) - || entry.eq_ignore_ascii_case(&built_in_ignore_pattern(name)) + || entry.eq_ignore_ascii_case(&default_ignore_pattern(name)) }) }) .collect() } } -/// The wildcard rule settings show for a built-in ignored folder. -fn built_in_ignore_pattern(name: &str) -> String { +/// The wildcard rule settings show for a default ignored folder. +fn default_ignore_pattern(name: &str) -> String { format!("**/{name}/") } @@ -154,7 +119,7 @@ pub struct HistoryIgnorePreviewRequest { /// Rules being edited in settings. #[serde(default)] pub ignore_rules: HistoryIgnoreRules, - /// Hidden-path entries, so the preview honours built-ins the user turned off. + /// Hidden-path entries, so the preview honours defaults the user turned off. #[serde(default)] pub hidden_file_patterns: Vec, /// Project root; when given, the preview also asks Git whether it ignores `path`. @@ -178,7 +143,7 @@ pub struct HistoryIgnoreRegexError { pub enum HistoryIgnoreMatch { /// Hidden from the project tree, so never recorded. Hidden, - /// The wildcard rule as written, built-in or the user's own. + /// The wildcard rule as written, a default or the user's own. Pattern { /// The wildcard rule. pattern: String, @@ -196,7 +161,9 @@ pub enum HistoryIgnoreMatch { pub struct HistoryIgnorePreviewResponse { /// Regexes that failed to compile. pub regex_errors: Vec, - /// The built-in wildcard rules, for settings to show and edit against. + /// The default wildcard rules, for settings to show and edit against. + /// + /// The wire name `builtInIgnorePatterns` predates plugin-declared folders and stays for hosts. pub built_in_ignore_patterns: Vec, /// Rule that keeps the sample path out of history; absent when it would be recorded. pub matched: Option, @@ -237,10 +204,10 @@ pub struct HistoryEntriesRequest { /// Workspace-relative file to list; absent lists every visible file. #[serde(default)] pub path: Option, - /// Extra directory names hidden from the tree, on top of the built-in ones. + /// Extra directory names hidden from the tree, on top of the default ones. #[serde(default)] pub hidden_directory_names: Vec, - /// Hidden-path globs; `!` lines turn built-in hidden folders back on. + /// Hidden-path globs; `!` lines turn default hidden folders back on. #[serde(default)] pub hidden_file_patterns: Vec, } @@ -691,9 +658,9 @@ pub fn ignore_preview( }; Ok(HistoryIgnorePreviewResponse { regex_errors, - built_in_ignore_patterns: BUILT_IN_IGNORED_DIRECTORY_NAMES + built_in_ignore_patterns: lithe_core_rules::visibility::default_hidden_directories() .iter() - .map(|name| built_in_ignore_pattern(name)) + .map(|name| default_ignore_pattern(name)) .collect(), matched, git_ignored, @@ -752,23 +719,23 @@ fn preview_match( ignored_rule(rules, relative_path) } -/// The first rule that matches: built-in folders, the user's globs, then regexes. +/// The first rule that matches: default folders, the user's globs, then regexes. fn ignored_rule(rules: &HistoryIgnoreRules, relative_path: &str) -> Option { // Folder names are compared directly; baseline seeding asks for thousands of files. let mut folders = relative_path.split('/').collect::>(); folders.pop(); - let built_in = rules.built_in_ignored_directories(); + let defaults = rules.default_ignored_directories(); if let Some(name) = folders.iter().find_map(|folder| { - built_in + defaults .iter() .find(|name| folder.eq_ignore_ascii_case(name)) }) { return Some(HistoryIgnoreMatch::Pattern { - pattern: built_in_ignore_pattern(name), + pattern: default_ignore_pattern(name), }); } // Match only this history glob. Re-adding default hidden rules here would - // override the caller's disabled built-ins and misreport unrelated globs. + // override the caller's disabled defaults and misreport unrelated globs. let found = rules .path_patterns .iter() @@ -1336,14 +1303,12 @@ mod tests { let workspace = root.join("workspace"); let storage = root.join("storage"); write_file(&workspace, "src/main.py", "print('a')\n"); - write_file(&workspace, "tools/.uv-cache/wheel/site.py", "import os\n"); - write_file(&workspace, ".claude/worktrees/a/src/main.py", "x\n"); + write_file(&workspace, "tools/.worktrees/wheel/site.py", "import os\n"); write_file(&workspace, "worktrees/feature/.git", "gitdir: elsewhere\n"); write_file(&workspace, "worktrees/feature/src/main.py", "print('b')\n"); for path in [ - "tools/.uv-cache/wheel/site.py", - ".claude/worktrees/a/src/main.py", + "tools/.worktrees/wheel/site.py", "worktrees/feature/src/main.py", ] { let response = record(record_request( @@ -1366,20 +1331,23 @@ mod tests { .unwrap(); assert!(response.is_some()); - // Edits there are ignored too, until the built-in rule is deleted. - let save = |patterns: &[&str]| { + // Edits there are ignored too, until the default rule is turned off in Hidden paths and + // in local history. + let save = |hidden: &[&str], patterns: &[&str]| { let mut request = record_request( &workspace, &storage, - "tools/.uv-cache/wheel/site.py", + "tools/.worktrees/wheel/site.py", "saved", Some("import sys\n"), ); + request.hidden_file_patterns = hidden.iter().map(|entry| entry.to_string()).collect(); request.ignore_rules = ignore_rules(patterns, &[]); record(request).unwrap() }; - assert!(save(&[]).is_none()); - assert!(save(&["!**/.uv-cache/"]).is_some()); + assert!(save(&[], &[]).is_none()); + assert!(save(&["!**/.worktrees/"], &[]).is_none()); + assert!(save(&["!**/.worktrees/"], &["!**/.worktrees/"]).is_some()); fs::remove_dir_all(root).unwrap(); } @@ -1390,8 +1358,8 @@ mod tests { let storage = root.join("storage"); fs::create_dir_all(&workspace).unwrap(); let now = unix_seconds(); - write_stored_entry(&storage, ".venv/lib/site.py", "projectBaseline", now, 10); - write_stored_entry(&storage, ".venv/lib/edited.py", "saved", now, 10); + write_stored_entry(&storage, ".worktrees/a/site.py", "projectBaseline", now, 10); + write_stored_entry(&storage, ".worktrees/a/edited.py", "saved", now, 10); write_stored_entry(&storage, "src/main.py", "projectBaseline", now, 10); record(record_request( @@ -1405,7 +1373,7 @@ mod tests { assert_eq!( stored_paths(&storage.canonicalize().unwrap()), - [".venv/lib/edited.py", "src/main.py", "src/other.py"] + [".worktrees/a/edited.py", "src/main.py", "src/other.py"] ); fs::remove_dir_all(root).unwrap(); } @@ -1674,7 +1642,7 @@ mod tests { assert_eq!(result.regex_errors[0].index, 0); assert!(result .built_in_ignore_patterns - .contains(&"**/Pods/".to_string())); + .contains(&"**/.worktrees/".to_string())); assert_eq!( result.matched, Some(HistoryIgnoreMatch::Pattern { @@ -1685,12 +1653,6 @@ mod tests { preview("a/b.TMP").matched, Some(HistoryIgnoreMatch::Regex { index: 1 }) ); - assert_eq!( - preview("ios/Pods/Lib/a.h").matched, - Some(HistoryIgnoreMatch::Pattern { - pattern: "**/Pods/".into() - }) - ); assert_eq!( preview(".git/config").matched, Some(HistoryIgnoreMatch::Hidden) @@ -1738,31 +1700,29 @@ mod tests { } #[test] - fn built_in_ignored_folders_can_be_turned_off() { - let rules = ignore_rules(&[" !**/Pods/ ", "!.uv-cache", "**/generated/"], &[]); - assert_eq!(preview_match(&rules, &[], "ios/Pods/Lib/a.h"), None); - assert_eq!(preview_match(&rules, &[], "tools/.uv-cache/a.py"), None); + fn default_ignored_folders_can_be_turned_off() { + // History ignores the default hidden folders a second time, so turning one off takes + // a `!` entry in Hidden paths and another in local history, by displayed form or name. + let shown = ["!**/.worktrees/".to_string(), "!.worktree".to_string()]; + let rules = ignore_rules(&[" !**/.worktrees/ ", "!.worktree", "**/generated/"], &[]); + assert_eq!(preview_match(&rules, &shown, "a/.worktrees/x/a.txt"), None); + assert_eq!(preview_match(&rules, &shown, ".worktree/a.txt"), None); assert_eq!( - preview_match(&rules, &[], "src/generated/a.txt"), + preview_match(&rules, &shown, "src/generated/a.txt"), Some(HistoryIgnoreMatch::Pattern { pattern: "**/generated/".into() }) ); + // A hidden folder shown again is still ignored by history; one only history turned + // off is still hidden. assert_eq!( - preview_match(&ignore_rules(&[], &[]), &[], "tools/.uv-cache/a.py"), - Some(HistoryIgnoreMatch::Pattern { - pattern: "**/.uv-cache/".into() - }) - ); - // A turned-off hidden folder is visible again; `build` is still ignored. - assert_eq!( - preview_match(&rules, &["!**/build/".into()], "build/out.txt"), + preview_match(&ignore_rules(&[], &[]), &shown, "a/.worktrees/x/a.txt"), Some(HistoryIgnoreMatch::Pattern { - pattern: "**/build/".into() + pattern: "**/.worktrees/".into() }) ); assert_eq!( - preview_match(&rules, &[], "build/out.txt"), + preview_match(&rules, &[], "a/.worktrees/x/a.txt"), Some(HistoryIgnoreMatch::Hidden) ); } @@ -1781,8 +1741,8 @@ mod tests { let storage = root.join("storage"); fs::create_dir_all(&workspace).unwrap(); for (path, disabled) in [ - ("build/src/main.txt", "**/build/"), - ("src/cached.pyc", "*.pyc"), + (".worktrees/src/main.txt", "**/.worktrees/"), + ("src/.DS_Store", ".DS_Store"), ] { let hidden = vec![format!("!{disabled}")]; let rules = ignore_rules(&[&format!("!{disabled}"), "*.log", "**/generated/"], &[]); @@ -1792,13 +1752,13 @@ mod tests { request.ignore_rules = rules; assert!(record(request).unwrap().is_some()); } - let rules = ignore_rules(&["!**/build/", "*.log", "**/generated/"], &[]); + let rules = ignore_rules(&["!**/.worktrees/", "*.log", "**/generated/"], &[]); for (path, pattern) in [ - ("build/run.log", "*.log"), - ("build/generated/main.txt", "**/generated/"), + (".worktrees/run.log", "*.log"), + (".worktrees/generated/main.txt", "**/generated/"), ] { assert_eq!( - preview_match(&rules, &["!**/build/".into()], path), + preview_match(&rules, &["!**/.worktrees/".into()], path), Some(HistoryIgnoreMatch::Pattern { pattern: pattern.into() }) diff --git a/rust/crates/project/src/search_index.rs b/rust/crates/project/src/search_index.rs index 743a04f0..d4fdaffe 100644 --- a/rust/crates/project/src/search_index.rs +++ b/rust/crates/project/src/search_index.rs @@ -622,7 +622,7 @@ mod tests { } #[test] - fn source_caps_build_only_required_cold_indexes_and_skip_generated_text_enumeration() { + fn source_caps_build_only_required_cold_indexes_and_never_enumerate_hidden_folders() { let root = crate::test_support::temporary_root("search-source-caps"); fs::create_dir_all(root.join("src")).unwrap(); let root = root.canonicalize().unwrap(); @@ -636,12 +636,15 @@ mod tests { } let _cleanup = Cleanup(root.clone()); fs::write(root.join("src/Name.txt"), "Name\n").unwrap(); - // This guards enumeration decisions, not filesystem throughput. Both generated - // roots only need enough entries to exceed the result cap on every platform. - let generated_files_per_directory = 16; - for directory in [".build", "node_modules"] { + // This guards enumeration decisions, not filesystem throughput. Core's own folders + // stay hidden even where generated file names are listed, and only need enough + // entries to exceed the result cap on every platform. Plugin-declared generated + // folders are covered by `lithe-core`'s configure_visibility test, which owns the + // process-wide registry. + let hidden_files_per_directory = 16; + for directory in [".worktree", ".worktrees"] { fs::create_dir(root.join(directory)).unwrap(); - for number in 0..generated_files_per_directory { + for number in 0..hidden_files_per_directory { fs::write(root.join(directory).join(format!("Name{number}.bin")), "").unwrap(); } } @@ -691,8 +694,7 @@ mod tests { .sum(); assert_eq!( resident_files, - usize::from(files > 0) * (2 * generated_files_per_directory + 1) - + usize::from(content > 0) + usize::from(files > 0) + usize::from(content > 0) ); eprintln!("Cold source caps files={files} content={content} symbols={symbols}: {:?}, indexes={}, resident files={resident_files}, results={}", started.elapsed(), built.len(), response.matches.len()); @@ -701,12 +703,10 @@ mod tests { if expected_indexes.is_empty() { assert!(visits.is_empty()); } - if files == 0 { - assert!(!visits - .iter() - .any(|path| path.starts_with(root.join(".build")) - || path.starts_with(root.join("node_modules")))); - } + assert!(!visits + .iter() + .any(|path| path.starts_with(root.join(".worktree")) + || path.starts_with(root.join(".worktrees")))); }); } } diff --git a/rust/crates/vcs/Cargo.toml b/rust/crates/vcs/Cargo.toml index 8b067c9f..41f93d2f 100644 --- a/rust/crates/vcs/Cargo.toml +++ b/rust/crates/vcs/Cargo.toml @@ -6,6 +6,7 @@ license = "Apache-2.0" description = "The unified VCS model for Lithe: provider declarations, root detection, request planning and reply validation" [dependencies] +lithe-core-rules = { path = "../core-rules" } lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } serde = { version = "1.0", features = ["derive"] } diff --git a/rust/crates/vcs/src/manifest.rs b/rust/crates/vcs/src/manifest.rs index 4fffda7f..b3172322 100644 --- a/rust/crates/vcs/src/manifest.rs +++ b/rust/crates/vcs/src/manifest.rs @@ -260,6 +260,16 @@ impl VcsProviderDeclaration { "mayUseNetwork": self.may_use_network, }) } + + /// Names of the directory markers, such as `.svn`: the VCS's own + /// metadata, which every workspace hides while the plugin is enabled. + pub fn metadata_directory_names(&self) -> impl Iterator { + self.detection + .markers + .iter() + .filter(|marker| marker.kind == MarkerKind::Directory) + .map(|marker| marker.name.as_str()) + } } /// Activation event the host raises before starting a VCS provider, once a diff --git a/rust/crates/vcs/src/roots.rs b/rust/crates/vcs/src/roots.rs index 51a7e64d..d5445fc3 100644 --- a/rust/crates/vcs/src/roots.rs +++ b/rust/crates/vcs/src/roots.rs @@ -3,7 +3,9 @@ //! Roots are found from static markers only, so opening a workspace never //! starts a provider. One bounded walk serves every provider: it records the //! markers directly inside each directory, never descends into a VCS's own -//! metadata directory or through a symbolic link, and stops at a depth and +//! metadata directory, a directory the default visibility rules hide (Core's +//! own folders and the folder names the enabled plugins declare, such as +//! `target`) or through a symbolic link, and stops at a depth and //! directory budget. When the workspace root itself carries no marker, its //! ancestors are checked too, because a Subversion working copy has a single //! `.svn` at its top and a workspace may be opened below it. @@ -14,6 +16,7 @@ use super::manifest::{MarkerKind, VcsMarker}; use super::model::is_root_relative; +use lithe_core_rules::visibility::VisibilityRules; use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::fs::{self, FileType}; use std::path::{Path, PathBuf}; @@ -23,37 +26,6 @@ const MAX_DEPTH: usize = 8; /// Most directories one detection reads before reporting a partial result. const MAX_DIRECTORIES: usize = 20_000; -/// Directories that hold generated or downloaded files and never a working -/// copy worth tracking, and whose size would dominate the walk. Lithe's own -/// worktrees are pruned so they are not listed as nested repositories. -const PRUNED: &[&str] = &[ - ".build", - ".cargo", - ".dart_tool", - ".gradle", - ".idea", - ".lithe", - ".mypy_cache", - ".next", - ".nuxt", - ".pytest_cache", - ".stack-work", - ".svelte-kit", - ".swiftpm", - ".terraform", - ".tox", - ".venv", - ".vscode", - ".worktree", - ".worktrees", - "DerivedData", - "Pods", - "__pycache__", - "bower_components", - "node_modules", - "target", -]; - /// The markers of one VCS, as detection sees them. pub(crate) struct MarkerSet<'a> { pub(crate) vcs: &'a str, @@ -206,6 +178,7 @@ pub(crate) fn detect(workspace: &Path, sets: &[MarkerSet<'_>], mappings: &[Mappi .filter(|marker| marker.kind == MarkerKind::Directory) .map(|marker| marker.name.as_str()) .collect(); + let hidden = VisibilityRules::new(Vec::new(), Vec::new()); let mut found: BTreeMap)> = BTreeMap::new(); let mut truncated = false; let mut visited = 0usize; @@ -239,7 +212,6 @@ pub(crate) fn detect(workspace: &Path, sets: &[MarkerSet<'_>], mappings: &[Mappi if !file_type.is_dir() || level == MAX_DEPTH || metadata_directories.contains(name.as_str()) - || PRUNED.contains(&name.as_str()) { continue; } @@ -248,6 +220,9 @@ pub(crate) fn detect(workspace: &Path, sets: &[MarkerSet<'_>], mappings: &[Mappi } else { format!("{relative}/{name}") }; + if hidden.is_hidden(&child, true) { + continue; + } queue.push_back((path, child, level + 1)); } if !here.is_empty() { diff --git a/rust/fixtures/vcs/model-v1.json b/rust/fixtures/vcs/model-v1.json index b07d993c..b01b2f0d 100644 --- a/rust/fixtures/vcs/model-v1.json +++ b/rust/fixtures/vcs/model-v1.json @@ -248,7 +248,7 @@ "expectedAmbiguous": [] }, { - "name": "metadata and dependency directories are not searched", + "name": "metadata directories and the folders Core hides are not searched", "markers": [ { "directory": "", @@ -261,12 +261,12 @@ "type": "directory" }, { - "directory": "node_modules/left-pad", + "directory": ".worktrees/left-pad", "name": ".git", "type": "directory" }, { - "directory": "target/checkout", + "directory": "app/.worktree/checkout", "name": ".svn", "type": "directory" } @@ -279,7 +279,7 @@ ], "expectedOwnership": [ { - "path": "node_modules/left-pad/index.js", + "path": ".worktrees/left-pad/index.js", "root": "" } ], diff --git a/rust/fixtures/workspace/change-filter-v1.json b/rust/fixtures/workspace/change-filter-v1.json index 0db0a6c5..b60bdd6c 100644 --- a/rust/fixtures/workspace/change-filter-v1.json +++ b/rust/fixtures/workspace/change-filter-v1.json @@ -2,21 +2,21 @@ "paths": [ "", "src/Main.java", - "target/classes/Main.class", - "TARGET/classes/Main.class", - "module/build/generated.java", - ".gradle/cache.bin", - "src/targeted/Main.java", + ".worktrees/feature/src/Main.java", + ".WORKTREES/feature/src/Main.java", + "module/.worktree/generated.java", + ".git/index", + "src/worktrees/Main.java", ".sources/Main.java", ".lithe/run/generated.json", "pom.xml", - "module/target/X.class", + "module/.git/HEAD", "module/src/main/resources/application.yml" ], "expected": [ "", "src/Main.java", - "src/targeted/Main.java", + "src/worktrees/Main.java", ".sources/Main.java", ".lithe/run/generated.json", "pom.xml", diff --git a/rust/fixtures/workspace/repository-visibility-v1.json b/rust/fixtures/workspace/repository-visibility-v1.json index 21a52600..b5761873 100644 --- a/rust/fixtures/workspace/repository-visibility-v1.json +++ b/rust/fixtures/workspace/repository-visibility-v1.json @@ -4,10 +4,6 @@ ".build/checkouts/SwiftTerm", "macos/.build/checkouts/SwiftTerm", ".cache/package", - "node_modules/package", - "target/package", - "build/package", - "DerivedData/package", "visible", "vendor/source" ], diff --git a/rust/fixtures/workspace/visibility-v1.json b/rust/fixtures/workspace/visibility-v1.json index a1266095..af29c4f0 100644 --- a/rust/fixtures/workspace/visibility-v1.json +++ b/rust/fixtures/workspace/visibility-v1.json @@ -1,55 +1,21 @@ { - "description": "Hidden-path rules shared by Rust Core, macOS and Windows. isDirectory is true for a folder, false for a file and null when the host does not know. hidden means the tree, search and history leave the path out; watchedDespiteHiding marks hidden paths whose file events must still be delivered. Rule lists are the user's own entries; built-ins are added by Core.", + "description": "Hidden-path rules shared by Rust Core, macOS and Windows. isDirectory is true for a folder, false for a file and null when the host does not know. hidden means the tree, search and history leave the path out; watchedDespiteHiding marks hidden paths whose file events must still be delivered. Rule lists are the user's own entries; Core adds its own folders and patterns and, while plugins declare any through workspace.configureVisibility, their folder names. No plugin is configured here.", "defaults": { "hiddenDirectoryNames": [ ".git", - ".svn", ".worktree", - ".worktrees", - ".build", - ".swiftpm", - "node_modules", - ".venv", - "venv", - "__pycache__", - "target", - "build", - "DerivedData", - ".gradle", - ".next", - "dist", - "coverage", - "design-qa-artifacts", - ".artifacts" + ".worktrees" ], "hiddenFilePatterns": [ ".DS_Store", - "*.pyc", ".lithe/**", ".lithe/run/local.json" ], "builtInPatterns": [ "**/.git/", - "**/.svn/", "**/.worktree/", "**/.worktrees/", - "**/.build/", - "**/.swiftpm/", - "**/node_modules/", - "**/.venv/", - "**/venv/", - "**/__pycache__/", - "**/target/", - "**/build/", - "**/DerivedData/", - "**/.gradle/", - "**/.next/", - "**/dist/", - "**/coverage/", - "**/design-qa-artifacts/", - "**/.artifacts/", ".DS_Store", - "*.pyc", ".lithe/**", ".lithe/run/local.json" ], @@ -58,7 +24,7 @@ }, "cases": [ { - "name": "built-in folders are hidden at any depth, as folders and as ancestors", + "name": "Core's folders are hidden at any depth, as folders and as ancestors", "hiddenDirectoryNames": [], "hiddenFilePatterns": [], "entries": [ @@ -68,27 +34,27 @@ "hidden": true }, { - "path": "node_modules", + "path": ".worktree", "isDirectory": true, "hidden": true }, { - "path": "target", + "path": ".worktrees", "isDirectory": true, "hidden": true }, { - "path": "a/b/node_modules", + "path": "a/b/.git", "isDirectory": true, "hidden": true }, { - "path": "node_modules/left-pad/index.js", + "path": ".worktrees/feature/src/App.java", "isDirectory": false, "hidden": true }, { - "path": "packages/app/target/classes/A.class", + "path": "packages/app/.git/HEAD", "isDirectory": false, "hidden": true }, @@ -110,9 +76,45 @@ ] }, { - "name": "a file named like a built-in folder is hidden too, such as a linked worktree's .git", + "name": "a tool's folders stay listed until a plugin declares them", "hiddenDirectoryNames": [], "hiddenFilePatterns": [], + "entries": [ + { + "path": "node_modules", + "isDirectory": true, + "hidden": false + }, + { + "path": "target", + "isDirectory": true, + "hidden": false + }, + { + "path": "build/out.txt", + "isDirectory": false, + "hidden": false + }, + { + "path": ".svn", + "isDirectory": true, + "hidden": false + }, + { + "path": "mod/__init__.pyc", + "isDirectory": false, + "hidden": false + } + ] + }, + { + "name": "a file named like a hidden folder is hidden too, such as a linked worktree's .git", + "hiddenDirectoryNames": [ + "build", + "target", + "dist" + ], + "hiddenFilePatterns": [], "entries": [ { "path": "build", @@ -157,7 +159,7 @@ ] }, { - "name": "built-in file patterns", + "name": "Core's file patterns", "hiddenDirectoryNames": [], "hiddenFilePatterns": [], "entries": [ @@ -171,16 +173,6 @@ "isDirectory": false, "hidden": true }, - { - "path": "mod/__init__.pyc", - "isDirectory": false, - "hidden": true - }, - { - "path": "a/b/c.pyc", - "isDirectory": false, - "hidden": true - }, { "path": "main.py", "isDirectory": false, @@ -195,18 +187,20 @@ }, { "name": "matching ignores case on every platform", - "hiddenDirectoryNames": [], + "hiddenDirectoryNames": [ + "generated" + ], "hiddenFilePatterns": [ "*.LOG" ], "entries": [ { - "path": "Node_Modules/x.js", + "path": ".WORKTREES/x.js", "isDirectory": false, "hidden": true }, { - "path": "SRC/TARGET", + "path": "SRC/GENERATED", "isDirectory": true, "hidden": true }, @@ -233,7 +227,7 @@ ] }, { - "name": "user folder names and globs add to the built-ins", + "name": "user folder names and globs add to the defaults", "hiddenDirectoryNames": [ "generated", "Out" @@ -350,41 +344,36 @@ ] }, { - "name": "a bang entry turns a built-in rule off, by name or by displayed form", + "name": "a bang entry turns a default rule off, by name or by displayed form", "hiddenDirectoryNames": [ "build" ], "hiddenFilePatterns": [ - "!node_modules", - "!**/target/", - "!*.pyc" + "!.worktrees", + "!**/.worktree/", + "!.DS_Store" ], "entries": [ { - "path": "node_modules/x.js", + "path": ".worktrees/x.js", "isDirectory": false, "hidden": false }, { - "path": "target", + "path": ".worktree", "isDirectory": true, "hidden": false }, { - "path": "a/target/x", + "path": "a/.worktree/x", "isDirectory": false, "hidden": false }, { - "path": "mod/a.pyc", + "path": "src/.DS_Store", "isDirectory": false, "hidden": false }, - { - "path": "dist", - "isDirectory": true, - "hidden": true - }, { "path": "build", "isDirectory": true, @@ -396,7 +385,7 @@ "hidden": true }, { - "path": ".DS_Store", + "path": ".lithe/run/local.json", "isDirectory": false, "hidden": true } @@ -411,12 +400,12 @@ ], "entries": [ { - "path": "build", + "path": ".worktrees", "isDirectory": null, "hidden": true }, { - "path": "src/build", + "path": "src/.git", "isDirectory": null, "hidden": true }, @@ -554,14 +543,14 @@ "hidden": true }, { - "path": "app/node_modules", + "path": "app/.worktrees", "isDirectory": true, "hidden": true }, { "path": "app/target", "isDirectory": true, - "hidden": true + "hidden": false }, { "path": "app/src", diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index ac7a00d0..67ef7168 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -1692,7 +1692,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 known caches and build outputs, 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 `!`. `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`). | @@ -1704,7 +1704,7 @@ declaration are relative, use `/`, and stay inside their base directory | `diagnostics` | `lineMatcher` patterns with capture-group numbers, or `litheDiagnostics` lines. | | `dependencies` | A command (with `scopes`) whose output Core decodes, as a flat list through a `map` or as a tree from `litheDependencies`; or `provider` (with `scopes`, `workspace` and `project` only). | | `sync` | Files whose change makes the model stale, relative to the root and to each project. | -| `layout` | `excluded` directories relative to each project, added to every project as `excluded` content roots. | +| `layout` | `excluded` directories relative to each project, added to every project as `excluded` content roots. `hiddenDirectoryNames` (at most 32) are folder names, such as dependency, cache and build output folders, that every workspace hides at any depth while the plugin is enabled: the project tree, search, file events, Local History, run discovery, build detection and VCS and Git repository discovery skip them. Each name is one path component compared ignoring ASCII case, never a glob: it is not `.` or `..`, has no surrounding whitespace, `/`, `\`, `*`, `?`, `[`, `]` or control character, and does not start with `!` (`plugin.path.invalid` otherwise). Search Everywhere still lists their file names when the host asks for generated file names. Users turn a name off with a `!name` hidden-file pattern, as for Core's own folders. | An option may declare `scope: "instance"`. Omitted scope (or `"workspace"`) keeps workspace/build-system storage. Instance @@ -2473,7 +2473,10 @@ version of `vcsProviders`. Detection never starts a process: `vcs.detectRoots` finds roots from the markers, and the host starts a provider only after a root of its VCS is -found. The install review lists the provider as a `…VcsProvider` program with +found. Directory markers, such as `.svn`, are the VCS's metadata: while the +plugin is enabled every workspace hides them like the folders a build system +lists in `layout.hiddenDirectoryNames`, except that Search Everywhere never +lists their file names. The install review lists the provider as a `…VcsProvider` program with its VCS client (`vcsTool`) and `mayUseNetwork`. Requests go through `lsp.vcsRequest` by operation name and replies are normalized by `vcs.decodeReply`. The fields, operations, reply shapes, and error codes are diff --git a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json index 15489c33..fbac5f8d 100644 --- a/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json +++ b/shared/plugins/contract/v1/fixtures/manifest/invalid-manifests.json @@ -476,6 +476,27 @@ "edits": [{ "op": "set", "path": "/buildSystems/0/model/file", "value": "../Cargo.toml" }], "expectedCode": "plugin.path.invalid" }, + { + "name": "hidden directory name with a path separator", + "base": "build-static-file.plugin.json", + "edits": [{ "op": "set", "path": "/buildSystems/0/layout/hiddenDirectoryNames", "value": ["target", "out/classes"] }], + "expectedCode": "plugin.path.invalid", + "expectedField": "buildSystems[0].layout.hiddenDirectoryNames[1]" + }, + { + "name": "hidden directory name with a glob character", + "base": "build-static-file.plugin.json", + "edits": [{ "op": "set", "path": "/buildSystems/0/layout/hiddenDirectoryNames", "value": ["*.egg-info"] }], + "expectedCode": "plugin.path.invalid", + "expectedField": "buildSystems[0].layout.hiddenDirectoryNames[0]" + }, + { + "name": "hidden directory name that turns a default off", + "base": "build-static-file.plugin.json", + "edits": [{ "op": "set", "path": "/buildSystems/0/layout/hiddenDirectoryNames", "value": ["!target"] }], + "expectedCode": "plugin.path.invalid", + "expectedField": "buildSystems[0].layout.hiddenDirectoryNames[0]" + }, { "name": "selector without a pointer", "base": "build-static-file.plugin.json", diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 124894c9..49dda628 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -3477,6 +3477,16 @@ "pattern": "^[^/\\\\]" }, "maxItems": 32 + }, + "hiddenDirectoryNames": { + "description": "Folder names every workspace hides at any depth while the plugin is enabled, compared with one path component ignoring ASCII case.", + "type": "array", + "items": { + "type": "string", + "maxLength": 255, + "pattern": "^(?!\\.{1,2}$)(?![!\\s])(?!.*\\s$)[^/\\\\*?\\[\\]\\u0000-\\u001f\\u007f]+$" + }, + "maxItems": 32 } } } diff --git a/shared/plugins/reference/domains/build-systems.md b/shared/plugins/reference/domains/build-systems.md index 461743c4..9439ea35 100644 --- a/shared/plugins/reference/domains/build-systems.md +++ b/shared/plugins/reference/domains/build-systems.md @@ -35,7 +35,7 @@ | `provider` | 没有命令能打印模型时,由[构建提供者](build-providers.md)回答模型和依赖请求 | | `tasks`、`run`、`test` | 任务目录、从模型目标或任务生成的运行入口、测试的范围、过滤器和结果文件 | | `diagnostics`、`dependencies` | 诊断的行匹配或 `litheDiagnostics`;依赖列表或依赖树的来源 | -| `sync`、`layout` | 哪些文件变化会让模型过期;每个项目要作为 `excluded` 内容根加入的目录 | +| `sync`、`layout` | 哪些文件变化会让模型过期;每个项目要作为 `excluded` 内容根加入的目录;`layout.hiddenDirectoryNames` 是插件启用期间所有工作区在任意层级隐藏的目录名(如依赖、缓存和构建输出目录),项目树、搜索、文件事件、本地历史、运行发现、构建探测和仓库发现都会跳过 | ### 模型来源 @@ -132,7 +132,7 @@ IDs of build systems, tasks, and run entries start with a lowercase letter and u | `provider` | The [build provider](build-providers.md) that answers model and dependency requests when no command prints them | | `tasks`, `run`, `test` | The task catalog, run entries generated from model targets or tasks, and the scopes, filters, and result files of tests | | `diagnostics`, `dependencies` | Line matchers or `litheDiagnostics` for diagnostics; the source of the dependency list or tree | -| `sync`, `layout` | Which file changes make the model stale; directories added to every project as `excluded` content roots | +| `sync`, `layout` | Which file changes make the model stale; directories added to every project as `excluded` content roots; `layout.hiddenDirectoryNames`, folder names such as dependency, cache and build output folders that every workspace hides at any depth while the plugin is enabled: the project tree, search, file events, Local History, run discovery, build detection and repository discovery skip them | ### Model sources diff --git a/shared/plugins/reference/domains/vcs.md b/shared/plugins/reference/domains/vcs.md index 1ecb34f1..f2529326 100644 --- a/shared/plugins/reference/domains/vcs.md +++ b/shared/plugins/reference/domains/vcs.md @@ -13,7 +13,7 @@ | 协议 | `litheVcs` 0:宿主在 `initialize` 里提供 `capabilities.experimental.litheVcs: {"versions": [0]}`,提供者回答 `{"version": 0, "vcs", "capabilities"}`,见[进程协议版本](../capabilities-and-versions.md#进程协议版本) | | API 编号 | [API-31](../api-catalog.md#现在能用的-api):VCS 提供者。读取内置 Git 的公共接口是另一项(API-42,计划中) | | 权限 | `process.vcs`、`languageServer.launch` | -| 激活事件 | `onVcsRoot:`;根目录检测只看标记文件,不启动进程,找到该 VCS 的根目录后才启动提供者 | +| 激活事件 | `onVcsRoot:`;根目录检测只看标记文件,不启动进程,找到该 VCS 的根目录后才启动提供者。目录标记(如 `.svn`)是 VCS 元数据,插件启用期间所有工作区都会隐藏,Search Everywhere 也不列出其中的文件名 | | Lithe 桌面端 | 未声明 `vcsProviders`,安装时拒绝需要它的包 | | 官方 SDK | [Node SDK](../../sdk/node/README.md#a-vcs-provider) 0.5.0 实现 `litheVcs` 0;Java、Rust SDK 不实现 | @@ -67,7 +67,7 @@ A plugin can implement a provider for a version control system other than Git (S | Protocols | `litheVcs` 0: the host offers `capabilities.experimental.litheVcs: {"versions": [0]}` in `initialize`, and the provider answers `{"version": 0, "vcs", "capabilities"}`; see [process protocol versions](../capabilities-and-versions.md#process-protocol-versions) | | API IDs | [API-31](../api-catalog.md#apis-usable-now): VCS providers. Public reads of the built-in Git are a separate item (API-42, planned) | | Permissions | `process.vcs`, `languageServer.launch` | -| Activation events | `onVcsRoot:`; root detection reads marker files only and starts no process, and a provider starts only after a root of its VCS is found | +| Activation events | `onVcsRoot:`; root detection reads marker files only and starts no process, and a provider starts only after a root of its VCS is found. Directory markers, such as `.svn`, are VCS metadata: every workspace hides them while the plugin is enabled, and Search Everywhere never lists their file names | | Lithe desktop | Does not declare `vcsProviders`; packages that require it are refused before installation | | Official SDKs | The [Node SDK](../../sdk/node/README.md#a-vcs-provider) 0.5.0 implements `litheVcs` 0; the Java and Rust SDKs do not | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index cb1ba7fc..922ef533 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -137,6 +137,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#72](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/72) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-29、API-31 | `buildSystems` 0、`vcsProviders` 0 内的补充 | 构建系统新增可选字段 `layout.hiddenDirectoryNames`([1lck/Lithe-IDEA#1856](https://github.com/1lck/Lithe-IDEA/issues/1856)):插件启用期间所有工作区在任意层级隐藏的目录名,最多 32 个。每个名字是一段路径,忽略 ASCII 大小写比较,不是 glob;是 `.` 或 `..`、有首尾空白、含 `/`、`\`、`*`、`?`、`[`、`]` 或控制字符、以 `!` 开头时,以 `plugin.path.invalid`(字段 `buildSystems[].layout.hiddenDirectoryNames[]`)拒绝。VCS 提供者的目录标记(如 `.svn`)是 VCS 元数据,插件启用期间同样隐藏。Core 不再内置 `.svn`、`.build`、`node_modules`、`target`、`build`、`.gradle`、`.venv` 等工具目录,默认只隐藏自己的 `.git`、`.worktree`、`.worktrees`;宿主用命令 `workspace.configureVisibility` 把已启用插件的清单交给 Core,项目树、搜索、文件事件、本地历史、运行发现、构建探测和 VCS、Git 仓库发现都读这份名单。Search Everywhere 在 `includeGeneratedFileNames` 时仍列出构建系统声明目录里的文件名,不列 VCS 元数据。旧宿主不认识这个字段,会拒绝带它的清单,所以插件要等包含本改动的桌面端发布后再声明。`workspace.configureVisibility` 是宿主调用 Core 的命令,不是插件方法;没有新增宿主方法、通知或能力版本。 | | [#69](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/69) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23 | `buildSystems` 0 内的修正 | Core 不再把 `go`、`node` 当作宿主管理的运行时([1lck/Lithe-IDEA#1856](https://github.com/1lck/Lithe-IDEA/issues/1856) 第 3 项):`runtimeDependencies` 里没有 `executables` 的运行时一律按同 ID 的工具定义解析,`go`、`node` 也不例外。`build.invocationPlan` 对它们返回 `{ "kind": "toolchain", "toolchainID": , "root": }` 和 `version: null`,不再返回 `{ "kind": "runtime" }` 候选和 Core 自带的版本参数(`["version"]`、`["--version"]`);`build.checkToolVersion` 对它们以 `plugin.build.unavailable` 拒绝,版本由工具定义检查。运行时计划删掉 `hostManaged` 字段。`go`、`node` 写了自己的 `executables` 时按普通运行时校验,不再报“由宿主发现”。已发布的清单不用改:Go 插件本来就提供 `go` 工具定义。没有新增方法、字段或能力版本。 | | [#68](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/68) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-25 | `languageServers` 0 内的补充 | 语言服务器新增可选字段 `indexingExclusions`([1lck/Lithe-IDEA#1856](https://github.com/1lck/Lithe-IDEA/issues/1856)):声明工作区配置里列出排除目录的数组 `section`、一项的写法 `entry`(恰好一个 `${path}`)、根目录写法 `rootEntry?`、配置没有该数组时的 `default?`(最多 32 项)和 `pathSyntax?`(`literal` 默认或 `glob`,`glob` 时名字含通配符的目录不写入)。LSP 引擎只按这份声明把排除目录追加进服务器读到的配置,不再按 `rust`、`go` 识别 rust-analyzer 和 gopls;没有声明的服务器配置不变。启动计划的 `sessionPolicy` 带上这份声明,宿主原样交给 `lsp.startServer`。违反时以 `plugin.manifest.invalid`(字段 `languageServers[].indexingExclusions.`)拒绝。旧宿主不认识这个字段,会拒绝带它的清单,所以 Go 插件要等包含本改动的桌面端发布后再声明。没有新增宿主方法、通知或能力版本。 | | [#61](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/61) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | — | `languageServers` 0 内的补充 | LSP 引擎在一次会话里保留语言服务器的悬浮提示答案([1lck/Lithe-IDEA#1995](https://github.com/1lck/Lithe-IDEA/issues/1995)):同一文档版本的同一位置,或答案 `range` 在同一行内覆盖的位置,直接用保留的答案完成请求,不再发 `textDocument/hover`。每个会话最多 32 个,先丢最久没用的;空答案、错误、文本超过 64 KiB 的答案和清空之后才到达的答案照常交付但不保留。文档打开、修改、保存、关闭,工作区文件变化,设置或索引排除项变化,运行命令,后端的 `languageServer/request`、`languageServer/notify` 和宿主通知,服务器发来的任何请求和 `$/progress` 结束,以及会话停止时全部清空。`requestCompleted` 的结果形状不变,没有新增方法、字段或能力版本。 |