diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 6c24241c..8e61ba32 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -568,7 +568,7 @@ or removing a command fails until the table changes in the same commit. | `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 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.listDirectories` | Return one visible level of children for each requested workspace-relative directory (`""` is the root); missing, hidden, external/cyclic symlink, or nested-worktree paths are omitted; workspace-internal aliases are browsable and each listing reports `linked: true` when reached through an alias, 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`) | | `workspace.rowSelection.reduce` | Apply one plain, Cmd/Ctrl or Shift click, or the end of a batch, to the multi-selection of rows of workspace paths and return what a batch acts on (from `lithe-row-selection`) | @@ -2332,7 +2332,41 @@ Without `projectPage`, its original capped literal-search response is unchanged. Project pages use path/line continuation inside matching, including across pages within one file; options and immutable `textOverrides` bind the cursor. There is no 200-result total ceiling. Each page observes current files; edits before a -cursor require a fresh query. +cursor require a fresh query. Like Search Everywhere text queries, project pages +reuse ready content postings or search the names-only inventory directly; they +never synchronously build a full content index before returning the first page. + +`workspace.search` with `countOnly: true` scans the same query, scope, decoding, +visibility and unsaved snapshots independently of the loaded page. It returns +`{ files, lines, occurrences, fileOccurrences }`: files with at least one content +match, matching lines, and every non-overlapping occurrence (including zero-width +regex matches). `countPaths` selects at most 200 loaded paths for per-file totals; +the map contains only selected matching paths, while the three totals cover the +entire query. No previews are retained or returned. The host publishes its first +page before starting this cancellable scan, labels counting/failure distinctly, +and discards totals when the query, snapshots or watched files change. + +`workspace.search` with `languageSources` discovers relevant language providers +without opening documents. Each source has opaque `languageId`, optional +`fileExtensions` (with or without a dot) and `fileNames` (including project +markers). Core matches case-insensitively against the workspace name inventory +and returns sorted unique `{ languages }`. Sources are limited to 1024, each ID +to 256 bytes, each source to 1024 selectors and each selector to 1024 bytes. +The host reads enabled manifests, starts only relevant servers when symbol +search is requested, and queries their standard `workspace/symbol` capability +as readiness arrives. Core does not duplicate a language parser or semantic index. + +Search, Search Everywhere and replacement accept query-local +`includeGenerated` and `followSymlinks`. Generated output declarations can be +included without overriding explicitly hidden names/globs or manual indexing +exclusions. Internal links retain lexical result paths; canonical targets must +stay inside the workspace and respect target exclusions and delegated roots. +Canonical ancestor checks stop cycles. External roots must be opened as workspace +roots rather than traversed implicitly. Link-aware indexes are rebuilt on native +file events and invalidated on saves, so a physical target change cannot leave +an alias stale. Replacement previews deduplicate canonical files to avoid writing +one file twice. Directory listings expose internal aliases and `linked`; hosts +refresh expanded linked listings when recursive physical-target events arrive. Search and replacement accept `scopeExpression`: comma-separated relative paths, include globs and `!`-prefixed exclude globs. `scopePaths` remains supported. diff --git a/rust/crates/core/src/tests/project.rs b/rust/crates/core/src/tests/project.rs index 416940f4..67a6a73a 100644 --- a/rust/crates/core/src/tests/project.rs +++ b/rust/crates/core/src/tests/project.rs @@ -2381,13 +2381,15 @@ fn file_encoding_options_are_optional_and_validated() { serde_json::json!({"root": root, "path": "a.txt", "encoding": "ebcdic"}), ); assert_eq!(unknown["error"]["code"], "invalid_request"); - // Invalid bytes fail automatic detection but are repaired on an explicit reopen. - fs::write(root.join("bad.txt"), [0x41, 0xFF, 0xFE, 0x42, 0x81]).unwrap(); + // Legacy bytes use the lossless Windows-1252 fallback; explicit UTF-8 repairs them. + fs::write(root.join("bad.txt"), b"caf\xE9").unwrap(); let auto = call( "file.read", serde_json::json!({"root": root, "path": "bad.txt"}), ); - assert_eq!(auto["error"]["code"], "parse_failed"); + assert_eq!(auto["data"]["encoding"], "windows-1252", "{auto}"); + assert_eq!(auto["data"]["text"], "cafĂ©", "{auto}"); + assert_eq!(auto["data"]["lossy"], false, "{auto}"); let lossy = call( "file.read", serde_json::json!({"root": root, "path": "bad.txt", "encoding": "utf-8"}), @@ -2616,7 +2618,7 @@ fn search_reads_every_encoding_and_size_the_editor_opens() { assert_eq!(search("binaryToken417", false), Vec::new()); assert_eq!(search("binary[T]oken417", true), Vec::new()); - // Replacement writes UTF-8 back, so it must not offer the files that are not UTF-8. + // Replacement preserves the source encoding, so every searchable encoding is offered. let replacement = run_project_command( "workspace.replacePreview", serde_json::json!({"root": root, "query": "Token417", "replacement": "Mark", @@ -2629,10 +2631,17 @@ fn search_reads_every_encoding_and_size_the_editor_opens() { .iter() .map(|file| file["path"].as_str().expect("path should be text")) .collect::>(); - assert!(replaced.contains(&"plain.txt"), "{replacement}"); - for path in ["gbk.txt", "utf16-le.txt", "utf16-be.txt", "data.bin"] { - assert!(!replaced.contains(&path), "{path}: {replacement}"); + for path in [ + "plain.txt", + "gbk.txt", + "utf16-le.txt", + "utf16-be.txt", + "large.log", + ] { + assert!(replaced.contains(&path), "{path}: {replacement}"); } + assert!(!replaced.contains(&"data.bin"), "{replacement}"); + assert!(!replaced.contains(&"huge.log"), "{replacement}"); } #[test] diff --git a/rust/crates/project/src/contracts.rs b/rust/crates/project/src/contracts.rs index a51c8fb1..fa0ed26e 100644 --- a/rust/crates/project/src/contracts.rs +++ b/rust/crates/project/src/contracts.rs @@ -47,6 +47,8 @@ pub struct DirectoryListingResponse { #[serde(rename_all = "camelCase")] /// One directory's children, each without its own children. pub struct DirectoryListing { + /// This listing is reached through a workspace-internal alias and needs refresh on target events. + pub linked: bool, /// Normalized workspace-relative path; empty for the root. pub path: String, /// Directories first, then case-insensitive names, as in snapshots. diff --git a/rust/crates/project/src/files/matcher.rs b/rust/crates/project/src/files/matcher.rs index 2621f0bf..25aafcc4 100644 --- a/rust/crates/project/src/files/matcher.rs +++ b/rust/crates/project/src/files/matcher.rs @@ -123,6 +123,40 @@ pub(crate) struct Matcher { } impl Matcher { + /// Counts occurrences without constructing replacement text. + pub(crate) fn occurrence_count(&self, text: &str) -> usize { + if let Some(regex) = &self.regex { + regex.find_iter(text).count() + } else { + let haystack = if self.case_sensitive { + std::borrow::Cow::Borrowed(text) + } else { + std::borrow::Cow::Owned(text.to_lowercase()) + }; + let needle = if self.case_sensitive { + std::borrow::Cow::Borrowed(self.plain_query.as_str()) + } else { + std::borrow::Cow::Owned(self.plain_query.to_lowercase()) + }; + if needle.is_empty() { + return 0; + } + haystack + .match_indices(needle.as_ref()) + .filter(|(start, matched)| { + !self.whole_words + || (!haystack[..*start] + .chars() + .next_back() + .is_some_and(is_word_character) + && !haystack[*start + matched.len()..] + .chars() + .next() + .is_some_and(is_word_character)) + }) + .count() + } + } /// Projects original byte ranges into the editor's UTF-16 coordinate space. pub(crate) fn content_ranges(&self, text: &str) -> Vec { let ranges = if let Some(regex) = &self.regex { diff --git a/rust/crates/project/src/files/paths.rs b/rust/crates/project/src/files/paths.rs index cf204ebc..619c7be6 100644 --- a/rust/crates/project/src/files/paths.rs +++ b/rust/crates/project/src/files/paths.rs @@ -43,6 +43,25 @@ pub(crate) fn safe_relative_path(root: &Path, value: &str) -> Result( + root: &Path, + overrides: impl IntoIterator, + follow_links: bool, +) -> HashMap { + let mut result = HashMap::new(); + if follow_links { + let mut paths: Vec<_> = overrides.into_iter().collect(); + paths.sort_by_key(|(path, _)| *path); + for (path, text) in paths { + if let Ok(canonical) = safe_relative_path(root, path) { + result.entry(canonical).or_insert(text.as_str()); + } + } + } + result +} + pub(crate) fn writable_relative_path(root: &Path, value: &str) -> Result { let path = root.join(relative_request_path(value)?.as_ref()); if let Some(parent) = path.parent() { diff --git a/rust/crates/project/src/files/replace.rs b/rust/crates/project/src/files/replace.rs index 145a9760..68064965 100644 --- a/rust/crates/project/src/files/replace.rs +++ b/rust/crates/project/src/files/replace.rs @@ -67,8 +67,13 @@ pub fn replace_preview( request.hidden_file_patterns.clone(), ) .with_workspace_roots(&root, &request.workspace_roots) - .with_search_options(request.max_file_bytes, request.include_ignored)?; - let shared_index = search_index::get_or_build(&root, &rules)?; + .with_search_options(request.max_file_bytes, request.include_ignored)? + .with_search_visibility( + request.include_generated, + request.follow_symlinks, + &request.hidden_directory_names, + ); + let shared_index = search_index::get_for_text(&root, &rules)?; let index = shared_index .read() .map_err(|_| CoreError::new(ErrorCode::Unknown, "Search index lock was poisoned"))?; @@ -78,7 +83,12 @@ pub fn replace_preview( request.whole_words, request.regular_expression, )?; - let candidate_ids = index.candidate_ids(&query, request.regular_expression); + let aliases = canonical_text_overrides(&root, &request.text_overrides, request.follow_symlinks); + let candidate_ids = if aliases.is_empty() { + index.candidate_ids(&query, request.regular_expression) + } else { + index.all_file_ids() + }; let candidate_set = candidate_ids.iter().copied().collect::>(); let mut paths = if request.paths.is_empty() { candidate_ids @@ -108,6 +118,7 @@ pub fn replace_preview( drop(index); let masks = parse_file_mask(&request.file_mask); let mut files = Vec::new(); + let mut canonical_files = HashSet::new(); for path in paths { lithe_protocol::cancellation::check()?; let relative = safe_relative_path_string(&path)?; @@ -120,6 +131,9 @@ pub fn replace_preview( let Ok(file) = safe_relative_path(&root, &relative) else { continue; }; + if !canonical_files.insert(file.clone()) { + continue; + } if rules.is_delegated(&file) || indexing_policy .as_ref() @@ -130,8 +144,13 @@ pub fn replace_preview( { continue; } - let (text, source_identity) = if let Some(text) = request.text_overrides.get(&relative) { - (text.clone(), None) + let snapshot = request + .text_overrides + .get(&relative) + .map(String::as_str) + .or_else(|| aliases.get(&file).copied()); + let (text, source_identity) = if let Some(text) = snapshot { + (text.to_owned(), None) } else { let Some(bytes) = read_searchable_bytes(&file, rules.max_file_bytes) else { continue; diff --git a/rust/crates/project/src/files/requests.rs b/rust/crates/project/src/files/requests.rs index 2a3eb419..cb37a74a 100644 --- a/rust/crates/project/src/files/requests.rs +++ b/rust/crates/project/src/files/requests.rs @@ -49,6 +49,12 @@ pub struct DirectoryListingRequest { #[serde(rename_all = "camelCase")] /// Bounded file, content, and symbol search options. pub struct SearchRequest { + /// Includes plugin-declared generated folders for this query, retaining manual exclusions. + #[serde(default)] + pub include_generated: bool, + /// Follows only links whose canonical targets stay inside the workspace. + #[serde(default)] + pub follow_symlinks: bool, /// Comma-separated project paths and include/exclude globs; parsed only by Core. #[serde(default)] pub scope_expression: String, @@ -190,6 +196,12 @@ pub struct SearchIndexStatusResponse { #[serde(rename_all = "camelCase")] /// Search and replacement options used to produce a non-mutating preview. pub struct ReplacementPreviewRequest { + /// Uses the same request-local generated-folder visibility as search. + #[serde(default)] + pub include_generated: bool, + /// Follows only workspace-internal links; previews deduplicate canonical files. + #[serde(default)] + pub follow_symlinks: bool, /// Same request-local path and glob expression used by content search. #[serde(default)] pub scope_expression: String, diff --git a/rust/crates/project/src/files/search.rs b/rust/crates/project/src/files/search.rs index 6a43ec37..f8b3a380 100644 --- a/rust/crates/project/src/files/search.rs +++ b/rust/crates/project/src/files/search.rs @@ -67,6 +67,100 @@ pub fn search(request: SearchRequest) -> Result { search_with_page(request, None) } +/// Counts every matching occurrence without retaining previews or delaying a result page. +pub fn search_counts( + mut request: SearchRequest, + count_paths: &[String], +) -> Result { + parse_search_scope( + &request.scope_expression, + &mut request.scope_paths, + &mut request.include_path_patterns, + &mut request.exclude_path_patterns, + )?; + let root = existing_root(&request.root)?; + let rules = VisibilityRules::new( + request.hidden_directory_names.clone(), + request.hidden_file_patterns.clone(), + ) + .with_workspace_roots(&root, &request.workspace_roots) + .with_search_options(request.max_file_bytes, request.include_ignored)? + .with_search_visibility( + request.include_generated, + request.follow_symlinks, + &request.hidden_directory_names, + ); + let index = search_index::get_for_text(&root, &rules)?; + let index = index + .read() + .map_err(|_| CoreError::new(ErrorCode::Unknown, "Search index lock was poisoned"))?; + let matcher = Matcher::new( + request.query.trim(), + request.case_sensitive, + request.whole_words, + request.regular_expression, + )?; + let masks = parse_file_mask(&request.file_mask); + let filters = SearchPathFilters::new( + &request.include_path_patterns, + &request.exclude_path_patterns, + &request.path_filter_prefix, + )?; + let mut file_occurrences = std::collections::BTreeMap::new(); + let aliases = canonical_text_overrides(&root, &request.text_overrides, request.follow_symlinks); + let (mut files, mut lines, mut occurrences) = (0usize, 0usize, 0usize); + if count_paths.len() > 200 { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Too many file count paths", + )); + } + if !request.query.trim().is_empty() { + for id in index.all_file_ids() { + lithe_protocol::cancellation::check()?; + let Some(file) = index.file(id) else { continue }; + let path = &file.path; + if !scope_allows(&request.scope_paths, path) + || !file_mask_allows(&masks, path) + || !filters.allows(path) + { + continue; + } + let Ok(absolute) = safe_relative_path(&root, path) else { + continue; + }; + let text = request + .text_overrides + .get(path) + .map(String::as_str) + .or_else(|| aliases.get(&absolute).copied()) + .map(str::to_owned) + .or_else(|| read_searchable_text_limit(&absolute, rules.max_file_bytes)); + let Some(text) = text else { continue }; + let mut count = 0; + for line in text.split('\n').map(line_content) { + lithe_protocol::cancellation::check()?; + let n = matcher.occurrence_count(line); + lines += usize::from(n > 0); + count += n; + } + if count > 0 { + files += 1; + occurrences += count; + if count_paths.contains(path) { + file_occurrences.insert(path.clone(), count); + } + } + } + } + if let Some(policy) = crate::indexing::context(&root) { + policy.check()?; + } + Ok( + serde_json::json!({"files":files, "lines":lines, "occurrences":occurrences, "fileOccurrences":file_occurrences}), + ) +} + /// Continues a content query inside the matcher, before applying its page budget. pub(crate) fn search_with_page( mut request: SearchRequest, @@ -92,8 +186,19 @@ pub(crate) fn search_with_page( request.hidden_file_patterns.clone(), ) .with_workspace_roots(&root, &request.workspace_roots) - .with_search_options(request.max_file_bytes, request.include_ignored)?; - let index = search_index::get_or_build(&root, &rules)?; + .with_search_options(request.max_file_bytes, request.include_ignored)? + .with_search_visibility( + request.include_generated, + request.follow_symlinks, + &request.hidden_directory_names, + ); + // Interactive pages must not build trigrams for every file before the first + // result. Reuse warmed postings, or read candidates from the names inventory. + let index = if page.is_some() { + search_index::get_for_text(&root, &rules)? + } else { + search_index::get_or_build(&root, &rules)? + }; let index = index .read() .map_err(|_| CoreError::new(ErrorCode::Unknown, "Search index lock was poisoned"))?; @@ -170,7 +275,13 @@ pub(crate) fn search_with_index( } let mut content_matches = 0; - let mut candidates = index.candidate_ids(query, request.regular_expression); + let aliases = canonical_text_overrides(root, &request.text_overrides, request.follow_symlinks); + let mut candidates = if aliases.is_empty() { + index.candidate_ids(query, request.regular_expression) + } else { + // An alias may have no disk posting for a word present only in its editor snapshot. + index.all_file_ids() + }; for path in request.text_overrides.keys() { if let Some(id) = index.id_for_path(path) { if !candidates.contains(&id) { @@ -197,13 +308,21 @@ pub(crate) fn search_with_index( { continue; } - let file = root.join(path); - let text = request.text_overrides.get(path).cloned().or_else(|| { - read_searchable_text_limit( - &file, - request.max_file_bytes.unwrap_or(MAX_SEARCH_FILE_SIZE), - ) - }); + let Ok(file) = safe_relative_path(root, path) else { + continue; + }; + let text = request + .text_overrides + .get(path) + .map(String::as_str) + .or_else(|| aliases.get(&file).copied()) + .map(str::to_owned) + .or_else(|| { + read_searchable_text_limit( + &file, + request.max_file_bytes.unwrap_or(MAX_SEARCH_FILE_SIZE), + ) + }); let Some(text) = text else { continue }; for (index, line) in text.split('\n').map(line_content).enumerate() { lithe_protocol::cancellation::check()?; diff --git a/rust/crates/project/src/files/search_everywhere.rs b/rust/crates/project/src/files/search_everywhere.rs index 8a2478bd..ab1f1b2e 100644 --- a/rust/crates/project/src/files/search_everywhere.rs +++ b/rust/crates/project/src/files/search_everywhere.rs @@ -41,7 +41,12 @@ pub(crate) fn search_everywhere_with_page( request.hidden_file_patterns.clone(), ) .with_workspace_roots(&root, &request.workspace_roots) - .with_search_options(request.max_file_bytes, request.include_ignored)?; + .with_search_options(request.max_file_bytes, request.include_ignored)? + .with_search_visibility( + request.include_generated, + request.follow_symlinks, + &request.hidden_directory_names, + ); let matcher = Matcher::new( &query, request.case_sensitive, @@ -95,9 +100,13 @@ pub(crate) fn search_everywhere_with_page( .hidden_directories .iter() .filter(|name| { - !generated + request + .hidden_directory_names .iter() - .any(|generated| generated.eq_ignore_ascii_case(name)) + .any(|explicit| explicit.eq_ignore_ascii_case(name)) + || !generated + .iter() + .any(|generated| generated.eq_ignore_ascii_case(name)) }) .cloned() .collect(), @@ -105,6 +114,7 @@ pub(crate) fn search_everywhere_with_page( delegated_roots: rules.delegated_roots.clone(), max_file_bytes: rules.max_file_bytes, include_ignored: rules.include_ignored, + follow_symlinks: rules.follow_symlinks, }; let names = search_index::get_names(&root, &name_rules)?; let names = names diff --git a/rust/crates/project/src/files/snapshot.rs b/rust/crates/project/src/files/snapshot.rs index c3763bf5..e0f5d945 100644 --- a/rust/crates/project/src/files/snapshot.rs +++ b/rust/crates/project/src/files/snapshot.rs @@ -62,7 +62,8 @@ pub fn list_directories( request: DirectoryListingRequest, ) -> Result { let root = existing_root(&request.root)?; - let rules = VisibilityRules::new(request.hidden_directory_names, request.hidden_file_patterns); + let rules = VisibilityRules::new(request.hidden_directory_names, request.hidden_file_patterns) + .with_search_visibility(false, true, &[]); let mut directories = Vec::new(); for relative in request.paths { lithe_protocol::cancellation::check()?; @@ -81,6 +82,8 @@ pub fn list_directories( } Err(error) => return Err(error), }; + let linked = + directory != fs::canonicalize(&directory).unwrap_or_else(|_| directory.clone()); let children = listing .children .into_iter() @@ -101,6 +104,7 @@ pub fn list_directories( directories.push(DirectoryListing { path: relative_path(&directory, &root), children, + linked, nested_worktrees: listing .nested_worktrees .iter() @@ -111,8 +115,7 @@ pub fn list_directories( Ok(DirectoryListingResponse { directories }) } -/// Resolves a requested directory without following symlinks, so a listing -/// never reaches outside the workspace or into a directory scans skip. +/// Resolves internal aliases without leaving the root, bypassing exclusions or entering cycles. fn listable_directory(root: &Path, relative: &str, rules: &VisibilityRules) -> Option { if relative.is_empty() { return Some(root.to_path_buf()); @@ -123,9 +126,23 @@ fn listable_directory(root: &Path, relative: &str, rules: &VisibilityRules) -> O return None; } let mut current = root.to_path_buf(); - for component in relative.split('/') { + for component in relative + .split('/') + .filter(|component| !component.is_empty()) + { + let entry = fs::read_dir(¤t) + .ok()? + .filter_map(Result::ok) + .find(|entry| entry.file_name() == component)?; + visible_child( + entry, + root, + rules, + &mut Vec::new(), + fs::canonicalize(¤t).ok()? != current, + )?; current.push(component); - let metadata = fs::symlink_metadata(¤t).ok()?; + let metadata = fs::metadata(¤t).ok()?; if !metadata.is_dir() || rules.is_hidden(&relative_path(¤t, root), true) { return None; } diff --git a/rust/crates/project/src/files/visibility.rs b/rust/crates/project/src/files/visibility.rs index dc39b342..51f44f2b 100644 --- a/rust/crates/project/src/files/visibility.rs +++ b/rust/crates/project/src/files/visibility.rs @@ -16,6 +16,8 @@ pub struct VisibilityRules { pub(crate) max_file_bytes: u64, /// Git visibility can be widened for a search without changing project policy. pub(crate) include_ignored: bool, + /// Search traversal follows workspace-internal links only when explicitly requested. + pub(crate) follow_symlinks: bool, } impl VisibilityRules { @@ -28,6 +30,7 @@ impl VisibilityRules { delegated_roots: Vec::new(), max_file_bytes: MAX_SEARCH_FILE_SIZE, include_ignored: false, + follow_symlinks: false, } } @@ -48,6 +51,28 @@ impl VisibilityRules { Ok(self) } + /// Widens only query-local generated-folder and internal-link visibility. + pub(crate) fn with_search_visibility( + mut self, + generated: bool, + links: bool, + explicit: &[String], + ) -> Self { + if generated { + let names = plugin_generated_directories(); + self.hidden_directories.retain(|name| { + explicit + .iter() + .any(|value| value.eq_ignore_ascii_case(name)) + || !names + .iter() + .any(|generated| generated.eq_ignore_ascii_case(name)) + }); + } + self.follow_symlinks = links; + self + } + /// Binds scan ownership to the caller's workspace without changing directory browsing. pub(crate) fn with_workspace_roots(mut self, root: &Path, roots: &[String]) -> Self { for value in roots { @@ -123,10 +148,12 @@ pub(crate) fn visible_children( } }); let mut nested_worktrees = Vec::new(); + let linked_parent = + rules.follow_symlinks && fs::canonicalize(path).is_ok_and(|canonical| canonical != path); let mut children = fs::read_dir(path) .map_err(CoreError::from)? .filter_map(Result::ok) - .filter_map(|entry| visible_child(entry, root, rules, &mut nested_worktrees)) + .filter_map(|entry| visible_child(entry, root, rules, &mut nested_worktrees, linked_parent)) .collect::>(); match order { // Siblings follow IDEA's Project view: directories first, then natural file-name @@ -172,36 +199,75 @@ pub(crate) fn directory_is_visibly_empty( root: &Path, rules: &VisibilityRules, ) -> bool { + let linked_parent = + rules.follow_symlinks && fs::canonicalize(path).is_ok_and(|canonical| canonical != path); let Ok(mut entries) = fs::read_dir(path) else { return false; }; !entries.any(|entry| match entry { - Ok(entry) => visible_child(entry, root, rules, &mut Vec::new()).is_some(), + Ok(entry) => visible_child(entry, root, rules, &mut Vec::new(), linked_parent).is_some(), Err(_) => true, }) } /// Applies the same visibility boundary to full listings and leaf probes. -fn visible_child( +pub(super) fn visible_child( entry: fs::DirEntry, root: &Path, rules: &VisibilityRules, nested_worktrees: &mut Vec, + linked_parent: bool, ) -> Option<(PathBuf, bool)> { let child_path = entry.path(); // Both native and remote readDir already supplied the non-following type; // re-statting every file would cost one network round trip per entry. let file_type = entry.file_type().ok()?; - if file_type.is_symlink() - || rules.is_hidden(&relative_path(&child_path, root), file_type.is_dir()) - { + let is_directory = if file_type.is_symlink() || linked_parent { + if !rules.follow_symlinks { + return None; + } + let target = fs::canonicalize(&child_path).ok()?; + let metadata = fs::metadata(&target).ok()?; + if !target.starts_with(root) + || rules.is_hidden(&relative_path(&target, root), metadata.is_dir()) + || rules.is_delegated(&target) + || crate::indexing::context(root) + .map(|policy| { + policy.search_reason( + &relative_path(&target, root), + metadata.is_dir(), + rules.include_ignored, + ) + }) + .transpose() + .ok()? + .flatten() + .is_some() + { + return None; + } + if metadata.is_dir() { + // Keep aliases in results, but never descend back into a canonical ancestor. + let mut ancestor = child_path.parent(); + while let Some(parent) = ancestor.filter(|parent| parent.starts_with(root)) { + if fs::canonicalize(parent).ok()? == target { + return None; + } + ancestor = parent.parent(); + } + } + metadata.is_dir() + } else { + file_type.is_dir() + }; + if rules.is_hidden(&relative_path(&child_path, root), is_directory) { return None; } - if file_type.is_dir() && is_nested_linked_worktree(&child_path) { + if is_directory && is_nested_linked_worktree(&child_path) { nested_worktrees.push(child_path); return None; } - Some((child_path, file_type.is_dir())) + Some((child_path, is_directory)) } /// A `.git` pointer file is a single `gitdir:` line; anything larger is not one. diff --git a/rust/crates/project/src/history.rs b/rust/crates/project/src/history.rs index 20322c37..441055ca 100644 --- a/rust/crates/project/src/history.rs +++ b/rust/crates/project/src/history.rs @@ -749,6 +749,7 @@ fn ignored_rule(rules: &HistoryIgnoreRules, relative_path: &str) -> Option>; @@ -83,6 +84,7 @@ fn key(root: &Path, rules: &VisibilityRules) -> IndexKey { policy_revision: super::indexing::context(root).map_or(0, |policy| policy.revision), max_file_bytes: rules.max_file_bytes, include_ignored: rules.include_ignored, + follow_symlinks: rules.follow_symlinks, } } @@ -158,9 +160,10 @@ pub(crate) fn invalidate_root(root: &Path) { pub(crate) fn update_cached_file(root: &Path, path: &Path) { let entries = { - let Ok(indexes) = cache().lock() else { + let Ok(mut indexes) = cache().lock() else { return; }; + indexes.retain(|key, _| key.host != workspace::identity_key(root) || !key.follow_symlinks); indexes .iter() .filter(|(key, _)| key.host == workspace::identity_key(root)) @@ -191,6 +194,7 @@ pub(crate) fn update_cached_file(root: &Path, path: &Path) { delegated_roots: cache_key.delegated_roots, max_file_bytes: cache_key.max_file_bytes, include_ignored: cache_key.include_ignored, + follow_symlinks: cache_key.follow_symlinks, }; let excluded = match super::indexing::context(root) { Some(policy) => policy @@ -241,6 +245,11 @@ pub(crate) fn update_paths( if cache_key.policy_revision != revision { return UpdateOutcome::RequiresRebuild; } + // One physical change can affect several lexical aliases. Re-enumerate + // link-aware inventories rather than leaving an alias's children stale. + if cache_key.follow_symlinks { + return UpdateOutcome::RequiresRebuild; + } let Ok(slot) = slot.lock() else { return UpdateOutcome::RequiresRebuild; }; @@ -256,6 +265,7 @@ pub(crate) fn update_paths( delegated_roots: cache_key.delegated_roots, max_file_bytes: cache_key.max_file_bytes, include_ignored: cache_key.include_ignored, + follow_symlinks: cache_key.follow_symlinks, }; for value in paths { let Some(absolute) = normalized_update_path(root, value) else { @@ -588,6 +598,46 @@ mod tests { use super::*; use std::fs; + #[test] + fn project_pages_search_cold_files_without_building_content_postings() { + let root = crate::test_support::temporary_root("project-page-cold-index"); + fs::create_dir_all(&root).unwrap(); + let root = root.canonicalize().unwrap(); + struct Cleanup(PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + invalidate_root(&self.0); + fs::remove_dir_all(&self.0).unwrap(); + } + } + let _cleanup = Cleanup(root.clone()); + fs::write( + root.join("a.txt"), + "needle first\nneedle second\nneedle third\n", + ) + .unwrap(); + let result = crate::project_search_page( + serde_json::from_value(serde_json::json!({ + "root": root, "query": "needle", "projectPage": true, "pageSize": 2 + })) + .unwrap(), + ) + .unwrap(); + assert_eq!(result["matches"].as_array().unwrap().len(), 2); + assert!(result["nextCursor"].is_string()); + let indexes = cache().lock().unwrap(); + let entries: Vec<_> = indexes.iter().filter(|(key, _)| key.root == root).collect(); + assert!(!entries.is_empty()); + assert!(entries.iter().all(|(key, _)| key.names_only)); + for (_, slot) in entries { + let slot = slot.lock().unwrap(); + assert_eq!( + slot.as_ref().unwrap().read().unwrap().stats().posting_count, + 0 + ); + } + } + #[test] fn names_and_cold_text_do_not_wait_for_content_build_and_invalidation_discards_its_slot() { let root = crate::test_support::temporary_root("independent-search-sources"); @@ -607,6 +657,7 @@ mod tests { delegated_roots: Vec::new(), max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, include_ignored: false, + follow_symlinks: false, }; let slot = Arc::new(std::sync::Mutex::new(None)); cache() @@ -622,6 +673,7 @@ mod tests { delegated_roots: Vec::new(), max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, include_ignored: false, + follow_symlinks: false, }; let worker = std::thread::spawn(move || { let names = get_names(&worker_root, &worker_rules).unwrap(); @@ -745,6 +797,7 @@ mod tests { delegated_roots: Vec::new(), max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, include_ignored: false, + follow_symlinks: false, hidden_file_patterns: vec![], }; let mut paths = Vec::new(); @@ -822,6 +875,7 @@ mod tests { delegated_roots: Vec::new(), max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, include_ignored: false, + follow_symlinks: false, hidden_file_patterns: vec![], }; let mut paths = Vec::new(); @@ -867,6 +921,7 @@ mod tests { delegated_roots: Vec::new(), max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, include_ignored: false, + follow_symlinks: false, hidden_file_patterns: fixture["hiddenFilePatterns"] .as_array() .unwrap() @@ -939,6 +994,7 @@ mod tests { delegated_roots: Vec::new(), max_file_bytes: crate::files::MAX_SEARCH_FILE_SIZE, include_ignored: false, + follow_symlinks: false, hidden_file_patterns: vec![format!("exclude-{index}/")], }; let content = get_or_build(&root, &rules).unwrap(); diff --git a/rust/crates/project/src/search_languages.rs b/rust/crates/project/src/search_languages.rs new file mode 100644 index 00000000..a8c3a6ff --- /dev/null +++ b/rust/crates/project/src/search_languages.rs @@ -0,0 +1,79 @@ +//! Selects language providers from declared file selectors and actual workspace names. + +use crate::files::{existing_root, SearchRequest, VisibilityRules}; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::Deserialize; + +/// A host-read language declaration; Core owns its matching against workspace paths. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchLanguageSource { + /// Opaque language identifier returned unchanged to the provider adapter. + pub language_id: String, + /// Case-insensitive filename suffixes, including their leading dot. + #[serde(default)] + pub file_extensions: Vec, + /// Case-insensitive exact base names, including project markers. + #[serde(default)] + pub file_names: Vec, +} + +/// Finds relevant providers without opening documents or returning the file inventory. +pub fn search_languages( + request: SearchRequest, + sources: Vec, +) -> Result { + if sources.len() > 1024 + || sources.iter().any(|source| { + source.language_id.len() > 256 + || source.file_extensions.len() + source.file_names.len() > 1024 + || source + .file_extensions + .iter() + .chain(&source.file_names) + .any(|selector| selector.len() > 1024) + }) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Too many search language sources", + )); + } + let root = existing_root(&request.root)?; + let rules = VisibilityRules::new(request.hidden_directory_names, request.hidden_file_patterns) + .with_workspace_roots(&root, &request.workspace_roots); + let index = crate::search_index::get_names(&root, &rules)?; + let index = index + .read() + .map_err(|_| CoreError::new(ErrorCode::Unknown, "Search index lock was poisoned"))?; + let mut remaining: Vec<_> = sources.into_iter().collect(); + let mut languages = std::collections::BTreeSet::new(); + for id in index.all_file_ids() { + lithe_protocol::cancellation::check()?; + let Some(file) = index.file(id) else { continue }; + let name = file + .path + .rsplit('/') + .next() + .unwrap_or(&file.path) + .to_lowercase(); + remaining.retain(|source| { + let matched = source + .file_names + .iter() + .any(|file| file.to_lowercase() == name) + || source.file_extensions.iter().any(|extension| { + let extension = extension.trim_start_matches('.').to_lowercase(); + !extension.is_empty() && name.ends_with(&format!(".{extension}")) + }); + if matched { + languages.insert(source.language_id.clone()); + } + !matched + }); + if remaining.is_empty() { + break; + } + } + Ok(serde_json::json!({"languages":languages})) +} diff --git a/rust/crates/project/src/search_paging.rs b/rust/crates/project/src/search_paging.rs index 6a98b728..6305857e 100644 --- a/rust/crates/project/src/search_paging.rs +++ b/rust/crates/project/src/search_paging.rs @@ -21,6 +21,15 @@ pub struct SearchPageRequest { /// Returns `{ matches, nextCursor }` pages for a Find in Files query. #[serde(default)] project_page: bool, + /// Scans counts without returning source lines, independently of interactive pages. + #[serde(default)] + count_only: bool, + /// Only these loaded file headings receive per-file totals (at most 200). + #[serde(default)] + count_paths: Vec, + /// Requests provider discovery against workspace names without opening files. + #[serde(default)] + language_sources: Option>, } #[derive(Serialize)] @@ -122,6 +131,12 @@ impl SearchPage { /// Workspace search keeps its original literal semantics for synchronous consumers. pub fn project_search_page(request: SearchPageRequest) -> Result { + if let Some(sources) = request.language_sources { + return crate::search_languages::search_languages(request.search, sources); + } + if request.count_only { + return super::files::search_counts(request.search, &request.count_paths); + } if !request.project_page { return super::files::search(request.search) .map(|response| serde_json::to_value(response).unwrap()); diff --git a/rust/crates/project/src/search_tests.rs b/rust/crates/project/src/search_tests.rs index b44a559d..b1fe1320 100644 --- a/rust/crates/project/src/search_tests.rs +++ b/rust/crates/project/src/search_tests.rs @@ -84,6 +84,78 @@ fn changing_file_budget_rebuilds_postings_and_replacement_reads_the_same_text() ); } +#[test] +fn complete_counts_include_occurrences_outside_the_first_page_and_unsaved_text() { + let workspace = Workspace::new(); + let fixture: Value = + serde_json::from_str(include_str!("../../../fixtures/search/idea-search-v1.json")).unwrap(); + let case = &fixture["completeCounts"]; + for (path, text) in case["files"].as_object().unwrap() { + workspace.write(path, text.as_str().unwrap()); + } + assert_eq!(workspace.page(case["request"].clone()), case["expected"]); +} + +#[cfg(unix)] +#[test] +fn search_follows_internal_links_without_cycles_or_external_targets() { + let workspace = Workspace::new(); + let outside = Workspace::new(); + workspace.write("source/a.txt", "needle\n"); + workspace.write("source/private/secret.txt", "needle\n"); + crate::indexing::configure( + serde_json::from_value( + json!({"root":workspace.0,"manualExcludedDirectories":["source/private"],"includedDirectories":[],"gitIgnoreEnabled":false}), + ) + .unwrap(), + |_| Ok(()), + ) + .unwrap(); + outside.write("private.txt", "needle\n"); + std::os::unix::fs::symlink(workspace.0.join("source"), workspace.0.join("alias")).unwrap(); + std::os::unix::fs::symlink(&workspace.0, workspace.0.join("source/loop")).unwrap(); + std::os::unix::fs::symlink(&outside.0, workspace.0.join("outside")).unwrap(); + let page = workspace.page(json!({"query":"needle", "followSymlinks":true})); + let paths: Vec<_> = page["matches"] + .as_array() + .unwrap() + .iter() + .map(|item| item["path"].as_str().unwrap()) + .collect(); + assert_eq!(paths, ["alias/a.txt", "source/a.txt"]); + let listing = files::list_directories( + serde_json::from_value( + json!({"root":workspace.0,"paths":["", "alias", "source/loop", "outside"]}), + ) + .unwrap(), + ) + .unwrap(); + assert_eq!(listing.directories.len(), 2); + assert_eq!(listing.directories[1].path, "alias"); + assert!(listing.directories[1].linked); + assert_eq!(listing.directories[1].children[0].path, "alias/a.txt"); + let ordinary = workspace.page(json!({"query":"needle"})); + assert_eq!(ordinary["matches"].as_array().unwrap().len(), 1); + let unsaved = json!({"query":"unsaved", "followSymlinks":true, + "textOverrides":{"source/a.txt":"unsaved unsaved\n"}}); + assert_eq!( + workspace.page(unsaved.clone())["matches"] + .as_array() + .unwrap() + .len(), + 2 + ); + let mut counts = unsaved.clone(); + counts["countOnly"] = json!(true); + assert_eq!(workspace.page(counts)["occurrences"], 4); + let mut replacement = unsaved; + replacement["root"] = json!(workspace.0); + replacement["replacement"] = json!("edited"); + let preview = files::replace_preview(serde_json::from_value(replacement).unwrap()).unwrap(); + assert_eq!(preview.files.len(), 1); + assert_eq!(preview.files[0].replacement_text, "edited edited\n"); +} + #[test] fn idea_name_queries_and_line_suffix_find_real_paths() { let workspace = Workspace::new(); @@ -150,3 +222,15 @@ fn search_preferences_and_presentation_follow_the_shared_fixture() { .unwrap(); assert_eq!(serde_json::to_value(actual).unwrap(), case["expected"]); } + +#[test] +fn provider_discovery_uses_real_names_without_opening_source_files() { + let workspace = Workspace::new(); + let fixture: Value = + serde_json::from_str(include_str!("../../../fixtures/search/idea-search-v1.json")).unwrap(); + let case = &fixture["languageDiscovery"]; + for (path, text) in case["files"].as_object().unwrap() { + workspace.write(path, text.as_str().unwrap()); + } + assert_eq!(workspace.page(case["request"].clone()), case["expected"]); +} diff --git a/rust/fixtures/search/idea-search-v1.json b/rust/fixtures/search/idea-search-v1.json index 9d6fc6b1..ab2ce1aa 100644 --- a/rust/fixtures/search/idea-search-v1.json +++ b/rust/fixtures/search/idea-search-v1.json @@ -62,5 +62,66 @@ } ] } + }, + "completeCounts": { + "files": { + "a.txt": "needle needle\nneedle\n", + "b.txt": "absent\n" + }, + "request": { + "query": "needle", + "countOnly": true, + "countPaths": [ + "a.txt", + "b.txt" + ], + "textOverrides": { + "b.txt": "needle needle needle\n" + } + }, + "expected": { + "files": 2, + "lines": 3, + "occurrences": 6, + "fileOccurrences": { + "a.txt": 3, + "b.txt": 3 + } + } + }, + "languageDiscovery": { + "files": { + "src/one.Example": "source", + "Exampleproject": "marker" + }, + "request": { + "query": "", + "languageSources": [ + { + "languageId": "example-language", + "fileExtensions": [ + ".example" + ] + }, + { + "languageId": "project-language", + "fileNames": [ + "Exampleproject" + ] + }, + { + "languageId": "unrelated", + "fileExtensions": [ + ".other" + ] + } + ] + }, + "expected": { + "languages": [ + "example-language", + "project-language" + ] + } } }