| 1 | //! Repo-aware working set tracking and prompt context packing. |
| 2 | //! |
| 3 | //! The goal of this module is to keep a small, high-signal list of |
| 4 | //! "active" paths that the assistant should prioritize. It observes |
| 5 | //! user messages and tool calls, extracts likely paths, and produces: |
| 6 | //! - a compact working-set summary block for the system prompt |
| 7 | //! - pinned message indices that compaction should preserve |
| 8 | |
| 9 | use crate::workspace_discovery::{ |
| 10 | DISCOVERY_ALWAYS_DIRS, path_is_excluded_from_discovery, should_skip_unignored_discovery_entry, |
| 11 | }; |
| 12 | use codewhale_models::turn_classify::{ |
| 13 | UserTurnPromptKind, classify_user_turn_prompt, turn_metadata_text, |
| 14 | }; |
| 15 | use codewhale_models::{ContentBlock, Message}; |
| 16 | use ignore::WalkBuilder; |
| 17 | use regex::Regex; |
| 18 | use serde::{Deserialize, Serialize}; |
| 19 | use serde_json::Value; |
| 20 | use std::collections::{HashMap, HashSet}; |
| 21 | use std::ffi::OsStr; |
| 22 | use std::fs; |
| 23 | use std::path::{Component, Path, PathBuf}; |
| 24 | use std::sync::OnceLock; |
| 25 | |
| 26 | /// Repo-aware resolver for `@`-mentions and file pickers. |
| 27 | /// |
| 28 | /// `cwd` is captured at construction; if the host's current directory changes |
| 29 | /// during a session, build a fresh `Workspace`. Composer discovery callers run |
| 30 | /// its bounded walkers on a background worker; [`Workspace::resolve_exact`] |
| 31 | /// deliberately performs no fuzzy tree traversal. |
| 32 | #[derive(Debug)] |
| 33 | pub struct Workspace { |
| 34 | pub root: PathBuf, |
| 35 | cwd: Option<PathBuf>, |
| 36 | #[cfg(any(test, feature = "test-support"))] |
| 37 | file_index: OnceLock<HashMap<String, Vec<PathBuf>>>, |
| 38 | completion_walk_depth: Option<usize>, |
| 39 | /// Follow symbolic links during file discovery walks. When `true`, |
| 40 | /// symlinked directories are traversed, enabling multi-project workspaces |
| 41 | /// where project directories are symlinked into a hub directory. |
| 42 | follow_links: bool, |
| 43 | } |
| 44 | |
| 45 | struct SearchContext<'a> { |
| 46 | needle: &'a str, |
| 47 | limit: usize, |
| 48 | prefix_hits: &'a mut Vec<String>, |
| 49 | substring_hits: &'a mut Vec<String>, |
| 50 | seen: &'a mut HashSet<PathBuf>, |
| 51 | cancelled: &'a dyn Fn() -> bool, |
| 52 | } |
| 53 | |
| 54 | impl SearchContext<'_> { |
| 55 | fn is_full(&self) -> bool { |
| 56 | self.prefix_hits.len() + self.substring_hits.len() >= self.limit |
| 57 | } |
| 58 | |
| 59 | fn should_stop(&self) -> bool { |
| 60 | self.is_full() || (self.cancelled)() |
| 61 | } |
| 62 | |
| 63 | fn remember(&mut self, path: PathBuf) -> bool { |
| 64 | self.seen.insert(path) |
| 65 | } |
| 66 | |
| 67 | fn push_match(&mut self, candidate: String) { |
| 68 | let lower = candidate.to_lowercase(); |
| 69 | if self.needle.is_empty() || lower.starts_with(self.needle) { |
| 70 | self.prefix_hits.push(candidate); |
| 71 | } else if lower.contains(self.needle) { |
| 72 | self.substring_hits.push(candidate); |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | impl Workspace { |
| 78 | /// Construct a workspace anchored at `root`, capturing the process CWD as |
| 79 | /// the secondary resolution pass. Convenience entry point intended for |
| 80 | /// callers that don't already have a CWD on hand; the App routes through |
| 81 | /// [`Workspace::with_cwd`] with its own captured launch directory. |
| 82 | pub fn new(root: PathBuf) -> Self { |
| 83 | Self::with_cwd(root, std::env::current_dir().ok()) |
| 84 | } |
| 85 | |
| 86 | /// Construct with an explicit cwd. Used by tests that need deterministic |
| 87 | /// resolution against a known directory without depending on (and |
| 88 | /// mutating) the process's real working directory. |
| 89 | pub fn with_cwd(root: PathBuf, cwd: Option<PathBuf>) -> Self { |
| 90 | Self::with_cwd_and_depth(root, cwd, DEFAULT_COMPLETIONS_WALK_DEPTH) |
| 91 | } |
| 92 | |
| 93 | /// Construct with an explicit completion walk depth. A depth of `0` |
| 94 | /// disables the depth limit for users with deeply nested workspaces. |
| 95 | pub fn with_cwd_and_depth(root: PathBuf, cwd: Option<PathBuf>, walk_depth: usize) -> Self { |
| 96 | Self::with_cwd_depth_and_follow_links(root, cwd, walk_depth, false) |
| 97 | } |
| 98 | |
| 99 | /// Construct with an explicit completion walk depth and symlink-following |
| 100 | /// preference. See `Workspace::follow_links`. |
| 101 | pub fn with_cwd_depth_and_follow_links( |
| 102 | root: PathBuf, |
| 103 | cwd: Option<PathBuf>, |
| 104 | walk_depth: usize, |
| 105 | follow_links: bool, |
| 106 | ) -> Self { |
| 107 | Self { |
| 108 | root, |
| 109 | cwd, |
| 110 | #[cfg(any(test, feature = "test-support"))] |
| 111 | file_index: OnceLock::new(), |
| 112 | completion_walk_depth: normalize_completion_walk_depth(walk_depth), |
| 113 | follow_links, |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | /// Two-pass resolution: workspace, then cwd, then fuzzy fallback. |
| 118 | #[cfg(any(test, feature = "test-support"))] |
| 119 | pub fn resolve(&self, raw_path: &str) -> Result<PathBuf, PathBuf> { |
| 120 | let literal = self.resolve_exact(raw_path); |
| 121 | if literal.is_ok() { |
| 122 | return literal; |
| 123 | } |
| 124 | let path = expand_mention_home(raw_path); |
| 125 | if let Some(fuzzy) = self.fuzzy_resolve(&path) { |
| 126 | return Ok(fuzzy); |
| 127 | } |
| 128 | literal |
| 129 | } |
| 130 | |
| 131 | /// Resolve only the path the user actually typed: workspace, then cwd. |
| 132 | /// |
| 133 | /// Composer send-time resolution uses this path because fuzzy fallback |
| 134 | /// builds a full basename index. Fuzzy tree discovery is instead confined |
| 135 | /// to the bounded background completion worker (#4365). |
| 136 | pub fn resolve_exact(&self, raw_path: &str) -> Result<PathBuf, PathBuf> { |
| 137 | let path = expand_mention_home(raw_path); |
| 138 | if path.is_absolute() { |
| 139 | if path.exists() { |
| 140 | return Ok(path); |
| 141 | } |
| 142 | return Err(path); |
| 143 | } |
| 144 | |
| 145 | let ws_path = self.root.join(&path); |
| 146 | if ws_path.exists() { |
| 147 | return Ok(ws_path); |
| 148 | } |
| 149 | |
| 150 | if let Some(cwd) = self.cwd.as_ref() { |
| 151 | let cwd_path = cwd.join(&path); |
| 152 | if cwd_path.exists() { |
| 153 | return Ok(cwd_path); |
| 154 | } |
| 155 | } |
| 156 | Err(ws_path) |
| 157 | } |
| 158 | |
| 159 | #[cfg(any(test, feature = "test-support"))] |
| 160 | fn fuzzy_resolve(&self, path: &Path) -> Option<PathBuf> { |
| 161 | let needle = path.file_name()?.to_string_lossy().to_lowercase(); |
| 162 | if needle.is_empty() { |
| 163 | return None; |
| 164 | } |
| 165 | |
| 166 | let index = self.file_index.get_or_init(|| self.build_file_index()); |
| 167 | index.get(&needle).and_then(|paths| paths.first()).cloned() |
| 168 | } |
| 169 | |
| 170 | #[cfg(any(test, feature = "test-support"))] |
| 171 | fn build_file_index(&self) -> HashMap<String, Vec<PathBuf>> { |
| 172 | let mut index: HashMap<String, Vec<PathBuf>> = HashMap::new(); |
| 173 | let mut total: usize = 0; |
| 174 | let builder = |
| 175 | discovery_walk_builder(&self.root, self.completion_walk_depth, self.follow_links); |
| 176 | |
| 177 | for entry in builder.build().flatten() { |
| 178 | if total >= FILE_INDEX_MAX_ENTRIES { |
| 179 | tracing::warn!( |
| 180 | target: "working_set", |
| 181 | limit = FILE_INDEX_MAX_ENTRIES, |
| 182 | "file-index discovery hit the entry cap; truncating to keep first-turn latency bounded (#697)" |
| 183 | ); |
| 184 | return index; |
| 185 | } |
| 186 | if entry |
| 187 | .file_type() |
| 188 | .is_some_and(|ft| ft.is_file() || ft.is_dir()) |
| 189 | { |
| 190 | let name = entry.file_name().to_string_lossy().to_lowercase(); |
| 191 | index |
| 192 | .entry(name) |
| 193 | .or_default() |
| 194 | .push(entry.path().to_path_buf()); |
| 195 | total += 1; |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | // Also index AI-tool dot-directories with gitignore disabled. |
| 200 | for dir_name in DISCOVERY_ALWAYS_DIRS { |
| 201 | if total >= FILE_INDEX_MAX_ENTRIES { |
| 202 | break; |
| 203 | } |
| 204 | let dot_dir = self.root.join(dir_name); |
| 205 | if !dot_dir.is_dir() { |
| 206 | continue; |
| 207 | } |
| 208 | let mut dot_builder = WalkBuilder::new(&dot_dir); |
| 209 | dot_builder |
| 210 | .hidden(true) |
| 211 | .follow_links(self.follow_links) |
| 212 | .git_ignore(false) |
| 213 | .ignore(false); |
| 214 | if let Some(depth) = child_completion_walk_depth(self.completion_walk_depth) { |
| 215 | dot_builder.max_depth(Some(depth)); |
| 216 | } |
| 217 | for entry in dot_builder.build().flatten() { |
| 218 | if total >= FILE_INDEX_MAX_ENTRIES { |
| 219 | break; |
| 220 | } |
| 221 | // Exclude machine-generated bulk (e.g. .deepseek/snapshots/). |
| 222 | if path_is_excluded_from_discovery(&self.root, entry.path()) { |
| 223 | continue; |
| 224 | } |
| 225 | if entry |
| 226 | .file_type() |
| 227 | .is_some_and(|ft| ft.is_file() || ft.is_dir()) |
| 228 | { |
| 229 | let name = entry.file_name().to_string_lossy().to_lowercase(); |
| 230 | index |
| 231 | .entry(name) |
| 232 | .or_default() |
| 233 | .push(entry.path().to_path_buf()); |
| 234 | total += 1; |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | // Beyond the curated dot-dir whitelist above, also index any explicit |
| 240 | // hidden/ignored path the user might `@`-mention (e.g. a project's |
| 241 | // own `.generated/specs/`). `local_reference_paths` walks with |
| 242 | // gitignore disabled but still honors `.deepseekignore`. |
| 243 | for path in local_reference_paths( |
| 244 | &self.root, |
| 245 | LOCAL_REFERENCE_SCAN_LIMIT, |
| 246 | self.completion_walk_depth, |
| 247 | self.follow_links, |
| 248 | ) { |
| 249 | if total >= FILE_INDEX_MAX_ENTRIES { |
| 250 | break; |
| 251 | } |
| 252 | let Some(name) = path |
| 253 | .file_name() |
| 254 | .map(|name| name.to_string_lossy().to_lowercase()) |
| 255 | else { |
| 256 | continue; |
| 257 | }; |
| 258 | index.entry(name).or_default().push(path); |
| 259 | total += 1; |
| 260 | } |
| 261 | index |
| 262 | } |
| 263 | |
| 264 | /// Walk the workspace (and the recorded `cwd` when it diverges) and |
| 265 | /// return relative paths whose representation matches `partial`. |
| 266 | /// |
| 267 | /// Ranking: a candidate matches when its case-insensitive display string |
| 268 | /// starts with `partial` (prefix hit) or contains it as a substring; prefix |
| 269 | /// hits sort first so `docs/de` lands `docs/deepseek_v4.pdf` ahead of any |
| 270 | /// path that merely shares those bytes. |
| 271 | /// |
| 272 | /// Display strings are workspace-relative for files under `root`, and |
| 273 | /// cwd-relative for files only under the recorded `cwd` — so what the user |
| 274 | /// Tab-completes matches what their shell would have shown them. |
| 275 | /// |
| 276 | /// Honors `.gitignore`, `.git/info/exclude`, `.ignore`, and |
| 277 | /// `.deepseekignore`. Capped at `limit` results. |
| 278 | #[must_use] |
| 279 | #[cfg(any(test, feature = "test-support"))] |
| 280 | pub fn completions(&self, partial: &str, limit: usize) -> Vec<String> { |
| 281 | if limit == 0 { |
| 282 | return Vec::new(); |
| 283 | } |
| 284 | let needle = partial.to_lowercase(); |
| 285 | let mut prefix_hits: Vec<String> = Vec::new(); |
| 286 | let mut substring_hits: Vec<String> = Vec::new(); |
| 287 | let mut seen: HashSet<PathBuf> = HashSet::new(); |
| 288 | let never_cancelled = || false; |
| 289 | |
| 290 | // Walk the recorded cwd first when it diverges from the workspace |
| 291 | // root, so cwd-relative entries appear ahead of duplicates surfaced by |
| 292 | // the workspace walk. |
| 293 | { |
| 294 | let mut ctx = SearchContext { |
| 295 | needle: &needle, |
| 296 | limit, |
| 297 | prefix_hits: &mut prefix_hits, |
| 298 | substring_hits: &mut substring_hits, |
| 299 | seen: &mut seen, |
| 300 | cancelled: &never_cancelled, |
| 301 | }; |
| 302 | |
| 303 | let cwd_diverges = self |
| 304 | .cwd |
| 305 | .as_deref() |
| 306 | .map(|c| c != self.root.as_path()) |
| 307 | .unwrap_or(false); |
| 308 | if cwd_diverges && let Some(cwd) = self.cwd.as_deref() { |
| 309 | walk_for_completions( |
| 310 | cwd, |
| 311 | cwd, |
| 312 | &mut ctx, |
| 313 | self.completion_walk_depth, |
| 314 | self.follow_links, |
| 315 | ); |
| 316 | add_local_reference_completions( |
| 317 | cwd, |
| 318 | cwd, |
| 319 | &mut ctx, |
| 320 | self.completion_walk_depth, |
| 321 | self.follow_links, |
| 322 | ); |
| 323 | } |
| 324 | walk_for_completions( |
| 325 | &self.root, |
| 326 | &self.root, |
| 327 | &mut ctx, |
| 328 | self.completion_walk_depth, |
| 329 | self.follow_links, |
| 330 | ); |
| 331 | add_local_reference_completions( |
| 332 | &self.root, |
| 333 | &self.root, |
| 334 | &mut ctx, |
| 335 | self.completion_walk_depth, |
| 336 | self.follow_links, |
| 337 | ); |
| 338 | } |
| 339 | |
| 340 | prefix_hits.sort(); |
| 341 | substring_hits.sort(); |
| 342 | prefix_hits.extend(substring_hits); |
| 343 | prefix_hits.truncate(limit); |
| 344 | prefix_hits |
| 345 | } |
| 346 | |
| 347 | /// One full completion walk with no needle: every discoverable display |
| 348 | /// string from the workspace walk plus the divergent-cwd walk (and the |
| 349 | /// always-discoverable AI dot-directories), deduped, in walk order. |
| 350 | /// Pair with [`rank_completion_candidates`] so the composer can filter |
| 351 | /// per keystroke without re-walking the filesystem (#3757). |
| 352 | /// |
| 353 | /// Needle-gated local path-reference completions are NOT included; |
| 354 | /// callers must fall back to [`Workspace::completions`] for path-like |
| 355 | /// needles (starting with `.` or containing a separator). |
| 356 | #[must_use] |
| 357 | #[cfg(any(test, feature = "test-support"))] |
| 358 | pub fn completion_candidates(&self) -> Vec<String> { |
| 359 | let never_cancelled = || false; |
| 360 | self.completion_candidates_inner(usize::MAX, false, &never_cancelled) |
| 361 | } |
| 362 | |
| 363 | /// Candidate collection used by the composer background worker. The walk |
| 364 | /// is hard-capped and checks `cancelled` between filesystem iterator |
| 365 | /// steps. A single slow iterator step may still return late, but it runs on |
| 366 | /// the discovery worker and can never park terminal input (#4365). |
| 367 | pub fn completion_discovery_candidates( |
| 368 | &self, |
| 369 | limit: usize, |
| 370 | cancelled: &dyn Fn() -> bool, |
| 371 | ) -> Vec<String> { |
| 372 | self.completion_candidates_inner(limit, true, cancelled) |
| 373 | } |
| 374 | |
| 375 | fn completion_candidates_inner( |
| 376 | &self, |
| 377 | limit: usize, |
| 378 | include_local_references: bool, |
| 379 | cancelled: &dyn Fn() -> bool, |
| 380 | ) -> Vec<String> { |
| 381 | if limit == 0 || cancelled() { |
| 382 | return Vec::new(); |
| 383 | } |
| 384 | let mut prefix_hits: Vec<String> = Vec::new(); |
| 385 | let mut substring_hits: Vec<String> = Vec::new(); |
| 386 | let mut seen: HashSet<PathBuf> = HashSet::new(); |
| 387 | { |
| 388 | let mut ctx = SearchContext { |
| 389 | needle: "", |
| 390 | limit, |
| 391 | prefix_hits: &mut prefix_hits, |
| 392 | substring_hits: &mut substring_hits, |
| 393 | seen: &mut seen, |
| 394 | cancelled, |
| 395 | }; |
| 396 | let cwd_diverges = self |
| 397 | .cwd |
| 398 | .as_deref() |
| 399 | .map(|c| c != self.root.as_path()) |
| 400 | .unwrap_or(false); |
| 401 | if cwd_diverges && let Some(cwd) = self.cwd.as_deref() { |
| 402 | walk_for_completions( |
| 403 | cwd, |
| 404 | cwd, |
| 405 | &mut ctx, |
| 406 | self.completion_walk_depth, |
| 407 | self.follow_links, |
| 408 | ); |
| 409 | if include_local_references { |
| 410 | add_all_local_reference_completions( |
| 411 | cwd, |
| 412 | cwd, |
| 413 | &mut ctx, |
| 414 | self.completion_walk_depth, |
| 415 | self.follow_links, |
| 416 | ); |
| 417 | } |
| 418 | } |
| 419 | walk_for_completions( |
| 420 | &self.root, |
| 421 | &self.root, |
| 422 | &mut ctx, |
| 423 | self.completion_walk_depth, |
| 424 | self.follow_links, |
| 425 | ); |
| 426 | if include_local_references { |
| 427 | add_all_local_reference_completions( |
| 428 | &self.root, |
| 429 | &self.root, |
| 430 | &mut ctx, |
| 431 | self.completion_walk_depth, |
| 432 | self.follow_links, |
| 433 | ); |
| 434 | } |
| 435 | } |
| 436 | // Empty needle routes everything into prefix_hits. |
| 437 | prefix_hits |
| 438 | } |
| 439 | |
| 440 | /// Deterministic directory-browser completions for `@` mentions. |
| 441 | /// |
| 442 | /// Unlike [`Workspace::completions`], this mode does not fuzzy-rank across |
| 443 | /// the full workspace. It locks onto the directory part of `partial` and |
| 444 | /// returns only that directory's immediate children in case-insensitive |
| 445 | /// alphabetical order. |
| 446 | #[must_use] |
| 447 | #[cfg(any(test, feature = "test-support"))] |
| 448 | pub fn browser_completions(&self, partial: &str, limit: usize) -> Vec<String> { |
| 449 | if limit == 0 { |
| 450 | return Vec::new(); |
| 451 | } |
| 452 | let never_cancelled = || false; |
| 453 | let mut entries = |
| 454 | self.browser_completion_candidates_inner(partial, usize::MAX, &never_cancelled); |
| 455 | entries.truncate(limit); |
| 456 | entries |
| 457 | } |
| 458 | |
| 459 | /// Background-worker directory-browser collection. It stops at `limit` |
| 460 | /// before sorting, so a directory with millions of direct children cannot |
| 461 | /// grow the cache without bound. |
| 462 | pub fn browser_completion_discovery_candidates( |
| 463 | &self, |
| 464 | partial: &str, |
| 465 | limit: usize, |
| 466 | cancelled: &dyn Fn() -> bool, |
| 467 | ) -> Vec<String> { |
| 468 | self.browser_completion_candidates_inner(partial, limit, cancelled) |
| 469 | } |
| 470 | |
| 471 | fn browser_completion_candidates_inner( |
| 472 | &self, |
| 473 | partial: &str, |
| 474 | limit: usize, |
| 475 | cancelled: &dyn Fn() -> bool, |
| 476 | ) -> Vec<String> { |
| 477 | if limit == 0 || cancelled() { |
| 478 | return Vec::new(); |
| 479 | } |
| 480 | |
| 481 | let normalized = partial.replace('\\', "/"); |
| 482 | let trimmed = normalized.trim_start_matches('/'); |
| 483 | let (dir_part, name_part) = match trimmed.rsplit_once('/') { |
| 484 | Some((dir, name)) => (dir.trim_end_matches('/'), name), |
| 485 | None => ("", trimmed), |
| 486 | }; |
| 487 | let Some(safe_dir_part) = browser_completion_dir_part(dir_part) else { |
| 488 | return Vec::new(); |
| 489 | }; |
| 490 | let dir = if safe_dir_part.as_os_str().is_empty() { |
| 491 | self.root.clone() |
| 492 | } else { |
| 493 | self.root.join(&safe_dir_part) |
| 494 | }; |
| 495 | if !dir.is_dir() { |
| 496 | return Vec::new(); |
| 497 | } |
| 498 | let display_dir_part = safe_dir_part.to_string_lossy().replace('\\', "/"); |
| 499 | |
| 500 | let show_hidden = name_part.starts_with('.'); |
| 501 | let needle = name_part.to_lowercase(); |
| 502 | let mut entries = Vec::new(); |
| 503 | |
| 504 | let mut builder = WalkBuilder::new(&dir); |
| 505 | builder |
| 506 | .hidden(!show_hidden) |
| 507 | .follow_links(self.follow_links) |
| 508 | .max_depth(Some(1)); |
| 509 | let _ = builder.add_custom_ignore_filename(".deepseekignore"); |
| 510 | |
| 511 | let mut visited = 0usize; |
| 512 | for entry in builder.build().flatten() { |
| 513 | if visited >= limit || cancelled() { |
| 514 | break; |
| 515 | } |
| 516 | visited = visited.saturating_add(1); |
| 517 | let path = entry.path(); |
| 518 | if path == dir || path_is_excluded_from_discovery(&self.root, path) { |
| 519 | continue; |
| 520 | } |
| 521 | let Some(file_type) = entry.file_type() else { |
| 522 | continue; |
| 523 | }; |
| 524 | if !file_type.is_file() && !file_type.is_dir() { |
| 525 | continue; |
| 526 | } |
| 527 | let name = entry.file_name().to_string_lossy(); |
| 528 | if !needle.is_empty() && !name.to_lowercase().starts_with(&needle) { |
| 529 | continue; |
| 530 | } |
| 531 | let mut candidate = if display_dir_part.is_empty() { |
| 532 | name.to_string() |
| 533 | } else { |
| 534 | format!("{display_dir_part}/{name}") |
| 535 | }; |
| 536 | if file_type.is_dir() { |
| 537 | candidate.push('/'); |
| 538 | } |
| 539 | entries.push(candidate); |
| 540 | } |
| 541 | |
| 542 | entries.sort_by_cached_key(|entry| entry.to_lowercase()); |
| 543 | entries |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | fn browser_completion_dir_part(dir_part: &str) -> Option<PathBuf> { |
| 548 | let mut safe = PathBuf::new(); |
| 549 | for component in Path::new(dir_part).components() { |
| 550 | match component { |
| 551 | Component::CurDir => {} |
| 552 | Component::Normal(part) => safe.push(part), |
| 553 | Component::Prefix(_) | Component::RootDir | Component::ParentDir => return None, |
| 554 | } |
| 555 | } |
| 556 | Some(safe) |
| 557 | } |
| 558 | |
| 559 | /// Default directory depth walked when surfacing file-mention completions. |
| 560 | /// Set high enough that conventionally nested source trees (Java/.NET/web |
| 561 | /// projects routinely reach 7-9 levels) stay reachable, while a `0` override |
| 562 | /// removes the limit entirely. Keeps Tab snappy in deep monorepos via the |
| 563 | /// `.gitignore`-aware walk and per-keypress candidate caps (#2488). |
| 564 | pub const DEFAULT_COMPLETIONS_WALK_DEPTH: usize = 10; |
| 565 | |
| 566 | fn normalize_completion_walk_depth(depth: usize) -> Option<usize> { |
| 567 | if depth == 0 { None } else { Some(depth) } |
| 568 | } |
| 569 | |
| 570 | #[cfg(any(test, feature = "test-support"))] |
| 571 | fn child_completion_walk_depth(depth: Option<usize>) -> Option<usize> { |
| 572 | depth.map(|depth| depth.saturating_sub(1)) |
| 573 | } |
| 574 | |
| 575 | /// Hard cap on the number of `(file or directory)` entries indexed by |
| 576 | /// [`Workspace::build_file_index`]. The fuzzy-resolve index is a |
| 577 | /// convenience for [`Workspace::fuzzy_resolve`]; missing entries fall |
| 578 | /// back to literal-path resolution. Capping here keeps the first |
| 579 | /// `fuzzy_resolve` call bounded on huge workspaces (#697 reported a |
| 580 | /// ~10s hang on the first turn). For typical projects 50K is well |
| 581 | /// above the actual entry count and the cap is a no-op. |
| 582 | #[cfg(any(test, feature = "test-support"))] |
| 583 | const FILE_INDEX_MAX_ENTRIES: usize = 50_000; |
| 584 | |
| 585 | /// Configure a `WalkBuilder` for workspace discovery: hidden files, |
| 586 | /// depth-limited, custom `.deepseekignore` honored, and gitignore overrides |
| 587 | /// for AI-tool dot-directories so `@`-completion finds them even when |
| 588 | /// they're gitignored. Symlink following is controlled by `follow_links`. |
| 589 | fn discovery_walk_builder( |
| 590 | root: &Path, |
| 591 | max_depth: Option<usize>, |
| 592 | follow_links: bool, |
| 593 | ) -> WalkBuilder { |
| 594 | let mut builder = WalkBuilder::new(root); |
| 595 | builder.hidden(true).follow_links(follow_links); |
| 596 | if let Some(depth) = max_depth { |
| 597 | builder.max_depth(Some(depth)); |
| 598 | } |
| 599 | let _ = builder.add_custom_ignore_filename(".deepseekignore"); |
| 600 | builder |
| 601 | } |
| 602 | |
| 603 | /// Walk the AI-tool dot-directories (`.deepseek/`, `.cursor/`, `.claude/`, |
| 604 | /// `.agents/`) with gitignore disabled so their contents are discoverable |
| 605 | /// even when the project's `.gitignore` / `.ignore` excludes them. |
| 606 | fn walk_always_discoverable_dirs( |
| 607 | walk_root: &Path, |
| 608 | display_root: &Path, |
| 609 | ctx: &mut SearchContext<'_>, |
| 610 | max_depth: Option<usize>, |
| 611 | follow_links: bool, |
| 612 | ) { |
| 613 | for dir_name in DISCOVERY_ALWAYS_DIRS { |
| 614 | if ctx.should_stop() { |
| 615 | break; |
| 616 | } |
| 617 | let dot_dir = walk_root.join(dir_name); |
| 618 | // A walker follows a symlink passed as its root even when ordinary |
| 619 | // symlink following is off. Keep that opt-out for the extra roots too. |
| 620 | if !dot_dir.is_dir() || (!follow_links && dot_dir.is_symlink()) { |
| 621 | continue; |
| 622 | } |
| 623 | let mut builder = WalkBuilder::new(&dot_dir); |
| 624 | builder |
| 625 | .hidden(true) |
| 626 | .follow_links(follow_links) |
| 627 | .git_ignore(false) |
| 628 | .ignore(false); |
| 629 | if let Some(depth) = max_depth { |
| 630 | builder.max_depth(Some(depth.saturating_sub(1))); |
| 631 | } |
| 632 | for entry in builder.build().flatten() { |
| 633 | if ctx.should_stop() { |
| 634 | break; |
| 635 | } |
| 636 | let path = entry.path(); |
| 637 | // Exclude machine-generated bulk (e.g. .deepseek/snapshots/) |
| 638 | // even though gitignore is disabled for this walk. |
| 639 | if path_is_excluded_from_discovery(walk_root, path) { |
| 640 | continue; |
| 641 | } |
| 642 | let Ok(rel) = path.strip_prefix(display_root) else { |
| 643 | continue; |
| 644 | }; |
| 645 | let rel_str = rel.to_string_lossy().replace('\\', "/"); |
| 646 | if rel_str.is_empty() { |
| 647 | continue; |
| 648 | } |
| 649 | let abs = path.to_path_buf(); |
| 650 | if !ctx.remember(abs) { |
| 651 | continue; |
| 652 | } |
| 653 | let is_dir = entry.file_type().is_some_and(|ft| ft.is_dir()); |
| 654 | let candidate = if is_dir { |
| 655 | format!("{rel_str}/") |
| 656 | } else { |
| 657 | rel_str.clone() |
| 658 | }; |
| 659 | ctx.push_match(candidate); |
| 660 | } |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | fn walk_for_completions( |
| 665 | walk_root: &Path, |
| 666 | display_root: &Path, |
| 667 | ctx: &mut SearchContext<'_>, |
| 668 | max_depth: Option<usize>, |
| 669 | follow_links: bool, |
| 670 | ) { |
| 671 | let builder = discovery_walk_builder(walk_root, max_depth, follow_links); |
| 672 | |
| 673 | for entry in builder.build().flatten() { |
| 674 | if ctx.should_stop() { |
| 675 | break; |
| 676 | } |
| 677 | let path = entry.path(); |
| 678 | let Ok(rel) = path.strip_prefix(display_root) else { |
| 679 | continue; |
| 680 | }; |
| 681 | let rel_str = rel.to_string_lossy().replace('\\', "/"); |
| 682 | if rel_str.is_empty() { |
| 683 | continue; |
| 684 | } |
| 685 | // Dedup across the (cwd, workspace) double-walk by absolute path; we |
| 686 | // want the cwd-relative display when both walks see the same file. |
| 687 | let abs = path.to_path_buf(); |
| 688 | if !ctx.remember(abs) { |
| 689 | continue; |
| 690 | } |
| 691 | let is_dir = entry.file_type().is_some_and(|ft| ft.is_dir()); |
| 692 | let candidate = if is_dir { |
| 693 | format!("{rel_str}/") |
| 694 | } else { |
| 695 | rel_str.clone() |
| 696 | }; |
| 697 | ctx.push_match(candidate); |
| 698 | } |
| 699 | |
| 700 | // Also walk the AI-tool dot-directories with gitignore disabled so |
| 701 | // `.deepseek/`, `.cursor/`, etc. are always discoverable. |
| 702 | walk_always_discoverable_dirs(walk_root, display_root, ctx, max_depth, follow_links); |
| 703 | } |
| 704 | |
| 705 | const LOCAL_REFERENCE_SCAN_LIMIT: usize = 4096; |
| 706 | |
| 707 | #[cfg(any(test, feature = "test-support"))] |
| 708 | fn add_local_reference_completions( |
| 709 | root: &Path, |
| 710 | display_root: &Path, |
| 711 | ctx: &mut SearchContext<'_>, |
| 712 | max_depth: Option<usize>, |
| 713 | follow_links: bool, |
| 714 | ) { |
| 715 | if !should_try_local_reference_completion(ctx.needle) { |
| 716 | return; |
| 717 | } |
| 718 | |
| 719 | for path in local_reference_paths(root, LOCAL_REFERENCE_SCAN_LIMIT, max_depth, follow_links) { |
| 720 | if ctx.should_stop() { |
| 721 | break; |
| 722 | } |
| 723 | let Ok(rel) = path.strip_prefix(display_root) else { |
| 724 | continue; |
| 725 | }; |
| 726 | let rel_str = rel.to_string_lossy().replace('\\', "/"); |
| 727 | if rel_str.is_empty() || !ctx.remember(path.clone()) { |
| 728 | continue; |
| 729 | } |
| 730 | ctx.push_match(rel_str); |
| 731 | } |
| 732 | } |
| 733 | |
| 734 | /// Add hidden/ignored candidates to the background cache even when the |
| 735 | /// current needle is empty. The old UI path could defer this walk until a |
| 736 | /// path-like query existed; the background cache must be self-contained so no |
| 737 | /// later keystroke falls back to synchronous discovery. |
| 738 | fn add_all_local_reference_completions( |
| 739 | root: &Path, |
| 740 | display_root: &Path, |
| 741 | ctx: &mut SearchContext<'_>, |
| 742 | max_depth: Option<usize>, |
| 743 | follow_links: bool, |
| 744 | ) { |
| 745 | if ctx.should_stop() { |
| 746 | return; |
| 747 | } |
| 748 | let paths = local_reference_paths_with_cancel( |
| 749 | root, |
| 750 | LOCAL_REFERENCE_SCAN_LIMIT, |
| 751 | max_depth, |
| 752 | follow_links, |
| 753 | ctx.cancelled, |
| 754 | ); |
| 755 | for path in paths { |
| 756 | if ctx.should_stop() { |
| 757 | break; |
| 758 | } |
| 759 | let Ok(rel) = path.strip_prefix(display_root) else { |
| 760 | continue; |
| 761 | }; |
| 762 | let rel_str = rel.to_string_lossy().replace('\\', "/"); |
| 763 | if rel_str.is_empty() || !ctx.remember(path.clone()) { |
| 764 | continue; |
| 765 | } |
| 766 | ctx.push_match(rel_str); |
| 767 | } |
| 768 | } |
| 769 | |
| 770 | /// Rank pre-collected completion candidates for `partial` the same way |
| 771 | /// `Workspace::completions` ranks live walk hits: case-insensitive prefix |
| 772 | /// matches first, then substring matches, each bucket alphabetical, truncated |
| 773 | /// to `limit` (#3757). |
| 774 | #[must_use] |
| 775 | pub fn rank_completion_candidates( |
| 776 | candidates: &[String], |
| 777 | partial: &str, |
| 778 | limit: usize, |
| 779 | ) -> Vec<String> { |
| 780 | if limit == 0 { |
| 781 | return Vec::new(); |
| 782 | } |
| 783 | let needle = partial.to_lowercase(); |
| 784 | let mut prefix_hits: Vec<String> = Vec::new(); |
| 785 | let mut substring_hits: Vec<String> = Vec::new(); |
| 786 | for candidate in candidates { |
| 787 | let lower = candidate.to_lowercase(); |
| 788 | if needle.is_empty() || lower.starts_with(&needle) { |
| 789 | prefix_hits.push(candidate.clone()); |
| 790 | } else if lower.contains(&needle) { |
| 791 | substring_hits.push(candidate.clone()); |
| 792 | } |
| 793 | } |
| 794 | prefix_hits.sort(); |
| 795 | substring_hits.sort(); |
| 796 | prefix_hits.extend(substring_hits); |
| 797 | prefix_hits.truncate(limit); |
| 798 | prefix_hits |
| 799 | } |
| 800 | |
| 801 | #[cfg(any(test, feature = "test-support"))] |
| 802 | fn should_try_local_reference_completion(needle: &str) -> bool { |
| 803 | if needle.is_empty() { |
| 804 | return false; |
| 805 | } |
| 806 | // A bare separator or dot isn't an actionable path yet. Without this |
| 807 | // guard, a single `@/` keystroke triggers a `LOCAL_REFERENCE_SCAN_LIMIT` |
| 808 | // (4096-path) walk on the UI thread for #1921 — on WSL2 with a |
| 809 | // `/mnt/c/...` workspace each entry crosses Windows-host I/O and the |
| 810 | // composer appears frozen for seconds to minutes. |
| 811 | if matches!(needle, "/" | "\\" | "." | "..") { |
| 812 | return false; |
| 813 | } |
| 814 | needle.starts_with('.') || needle.contains('/') || needle.contains('\\') |
| 815 | } |
| 816 | |
| 817 | #[cfg(any(test, feature = "test-support"))] |
| 818 | fn local_reference_paths( |
| 819 | root: &Path, |
| 820 | limit: usize, |
| 821 | max_depth: Option<usize>, |
| 822 | follow_links: bool, |
| 823 | ) -> Vec<PathBuf> { |
| 824 | let never_cancelled = || false; |
| 825 | local_reference_paths_with_cancel(root, limit, max_depth, follow_links, &never_cancelled) |
| 826 | } |
| 827 | |
| 828 | fn local_reference_paths_with_cancel( |
| 829 | root: &Path, |
| 830 | limit: usize, |
| 831 | max_depth: Option<usize>, |
| 832 | follow_links: bool, |
| 833 | cancelled: &dyn Fn() -> bool, |
| 834 | ) -> Vec<PathBuf> { |
| 835 | let mut out = Vec::new(); |
| 836 | let mut builder = WalkBuilder::new(root); |
| 837 | builder |
| 838 | .hidden(false) |
| 839 | .follow_links(follow_links) |
| 840 | .git_ignore(false) |
| 841 | .git_global(false) |
| 842 | .git_exclude(false); |
| 843 | if let Some(depth) = max_depth { |
| 844 | builder.max_depth(Some(depth)); |
| 845 | } |
| 846 | let _ = builder.add_custom_ignore_filename(".deepseekignore"); |
| 847 | let root_for_filter = root.to_path_buf(); |
| 848 | builder.filter_entry(move |entry| { |
| 849 | !should_skip_unignored_discovery_entry(&root_for_filter, entry.path()) |
| 850 | }); |
| 851 | |
| 852 | for entry in builder.build().flatten() { |
| 853 | if out.len() >= limit || cancelled() { |
| 854 | break; |
| 855 | } |
| 856 | let path = entry.path(); |
| 857 | if path == root { |
| 858 | continue; |
| 859 | } |
| 860 | if entry |
| 861 | .file_type() |
| 862 | .is_some_and(|ft| ft.is_file() || ft.is_dir()) |
| 863 | { |
| 864 | out.push(path.to_path_buf()); |
| 865 | } |
| 866 | } |
| 867 | out |
| 868 | } |
| 869 | |
| 870 | impl Clone for Workspace { |
| 871 | fn clone(&self) -> Self { |
| 872 | // Don't carry the cached file_index — clones get a fresh OnceLock so |
| 873 | // they don't pin a stale snapshot of the previous owner's tree. |
| 874 | Self { |
| 875 | root: self.root.clone(), |
| 876 | cwd: self.cwd.clone(), |
| 877 | #[cfg(any(test, feature = "test-support"))] |
| 878 | file_index: OnceLock::new(), |
| 879 | completion_walk_depth: self.completion_walk_depth, |
| 880 | follow_links: self.follow_links, |
| 881 | } |
| 882 | } |
| 883 | } |
| 884 | |
| 885 | fn expand_mention_home(path: &str) -> PathBuf { |
| 886 | if path == "~" |
| 887 | && let Some(home) = std::env::var_os("HOME") |
| 888 | { |
| 889 | return PathBuf::from(home); |
| 890 | } |
| 891 | if let Some(rest) = path.strip_prefix("~/") |
| 892 | && let Some(home) = std::env::var_os("HOME") |
| 893 | { |
| 894 | return PathBuf::from(home).join(rest); |
| 895 | } |
| 896 | PathBuf::from(path) |
| 897 | } |
| 898 | |
| 899 | /// Truncate `s` to at most `max_bytes`, snapping down to a UTF-8 char |
| 900 | /// boundary so the result is always valid. Returns the slice and whether any |
| 901 | /// truncation happened. |
| 902 | fn truncate_on_char_boundary(s: &str, max_bytes: usize) -> (&str, bool) { |
| 903 | if s.len() <= max_bytes { |
| 904 | return (s, false); |
| 905 | } |
| 906 | let mut end = max_bytes; |
| 907 | while end > 0 && !s.is_char_boundary(end) { |
| 908 | end -= 1; |
| 909 | } |
| 910 | (&s[..end], true) |
| 911 | } |
| 912 | |
| 913 | /// Configuration for working-set tracking. |
| 914 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 915 | pub struct WorkingSetConfig { |
| 916 | /// Maximum number of entries to keep. |
| 917 | pub max_entries: usize, |
| 918 | /// Maximum number of paths to pin during compaction. |
| 919 | pub max_pinned_paths: usize, |
| 920 | /// Maximum characters to scan per text block when pinning messages. |
| 921 | pub max_scan_chars: usize, |
| 922 | /// Maximum entries to show in the system prompt block. |
| 923 | pub max_prompt_entries: usize, |
| 924 | /// Cache-maximal context mode (#528): when enabled, the working-set block |
| 925 | /// materializes the full current contents of the top active files into the |
| 926 | /// system prompt (deterministic order, size-bounded) instead of only a |
| 927 | /// path list. The contents stay byte-stable while the files are unchanged, |
| 928 | /// so DeepSeek's KV prefix cache keeps hitting; editing a file cache-misses |
| 929 | /// from that file's block onward. Off by default — existing behavior is the |
| 930 | /// path list only. |
| 931 | #[serde(default)] |
| 932 | pub cache_maximal: bool, |
| 933 | /// Per-file byte cap for materialized contents in cache-maximal mode. |
| 934 | #[serde(default = "default_max_resident_file_bytes")] |
| 935 | pub max_resident_file_bytes: usize, |
| 936 | /// Total byte cap across all materialized files in cache-maximal mode. |
| 937 | #[serde(default = "default_max_total_resident_bytes")] |
| 938 | pub max_total_resident_bytes: usize, |
| 939 | } |
| 940 | |
| 941 | fn default_max_resident_file_bytes() -> usize { |
| 942 | 24_000 |
| 943 | } |
| 944 | |
| 945 | fn default_max_total_resident_bytes() -> usize { |
| 946 | 96_000 |
| 947 | } |
| 948 | |
| 949 | impl Default for WorkingSetConfig { |
| 950 | fn default() -> Self { |
| 951 | Self { |
| 952 | max_entries: 16, |
| 953 | max_pinned_paths: 8, |
| 954 | max_scan_chars: 2_000, |
| 955 | max_prompt_entries: 8, |
| 956 | cache_maximal: false, |
| 957 | max_resident_file_bytes: default_max_resident_file_bytes(), |
| 958 | max_total_resident_bytes: default_max_total_resident_bytes(), |
| 959 | } |
| 960 | } |
| 961 | } |
| 962 | |
| 963 | /// The source that most recently updated an entry. |
| 964 | #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] |
| 965 | pub enum WorkingSetSource { |
| 966 | UserMessage, |
| 967 | ToolInput, |
| 968 | ToolOutput, |
| 969 | Rebuild, |
| 970 | } |
| 971 | |
| 972 | /// A single working-set entry. |
| 973 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 974 | pub struct WorkingSetEntry { |
| 975 | /// Workspace-relative path string. |
| 976 | pub path: String, |
| 977 | /// Whether the path is a directory (best-effort). |
| 978 | pub is_dir: bool, |
| 979 | /// Whether the path exists on disk (best-effort). |
| 980 | pub exists: bool, |
| 981 | /// Number of times this path was observed. |
| 982 | pub touches: u32, |
| 983 | /// The last observed turn index. |
| 984 | pub last_turn: u64, |
| 985 | /// The last update source. |
| 986 | pub last_source: WorkingSetSource, |
| 987 | } |
| 988 | |
| 989 | impl WorkingSetEntry { |
| 990 | fn new(path: String, exists: bool, is_dir: bool, turn: u64, source: WorkingSetSource) -> Self { |
| 991 | Self { |
| 992 | path, |
| 993 | is_dir, |
| 994 | exists, |
| 995 | touches: 1, |
| 996 | last_turn: turn, |
| 997 | last_source: source, |
| 998 | } |
| 999 | } |
| 1000 | } |
| 1001 | |
| 1002 | /// Repo-aware working-set state. |
| 1003 | #[derive(Debug, Clone, Serialize, Deserialize, Default)] |
| 1004 | pub struct WorkingSet { |
| 1005 | /// Tracking configuration. |
| 1006 | pub config: WorkingSetConfig, |
| 1007 | /// Monotonic turn counter (increments on user messages). |
| 1008 | pub turn: u64, |
| 1009 | /// Path entries keyed by workspace-relative path. |
| 1010 | pub entries: HashMap<String, WorkingSetEntry>, |
| 1011 | } |
| 1012 | |
| 1013 | impl WorkingSet { |
| 1014 | /// Advance to the next turn. |
| 1015 | pub fn next_turn(&mut self) { |
| 1016 | self.turn = self.turn.saturating_add(1); |
| 1017 | } |
| 1018 | |
| 1019 | /// Observe a user message and update the working set. |
| 1020 | pub fn observe_user_message(&mut self, text: &str, workspace: &Path) { |
| 1021 | self.next_turn(); |
| 1022 | let paths = extract_paths_from_text(text); |
| 1023 | self.record_candidates(paths, workspace, WorkingSetSource::UserMessage); |
| 1024 | } |
| 1025 | |
| 1026 | /// Observe a tool call (input and optional output). |
| 1027 | pub fn observe_tool_call( |
| 1028 | &mut self, |
| 1029 | tool_name: &str, |
| 1030 | input: &Value, |
| 1031 | output: Option<&str>, |
| 1032 | workspace: &Path, |
| 1033 | ) { |
| 1034 | let input_candidates = extract_paths_from_tool_input(tool_name, input); |
| 1035 | self.record_candidates(input_candidates, workspace, WorkingSetSource::ToolInput); |
| 1036 | |
| 1037 | if is_patch_tool(tool_name, input) |
| 1038 | && let Some(text) = output |
| 1039 | { |
| 1040 | let receipt_candidates = extract_paths_from_mutation_receipt(text); |
| 1041 | self.record_candidates(receipt_candidates, workspace, WorkingSetSource::ToolOutput); |
| 1042 | } |
| 1043 | } |
| 1044 | |
| 1045 | /// Rebuild the working set from existing messages (best effort). |
| 1046 | /// |
| 1047 | /// This is used when syncing a resumed session. |
| 1048 | pub fn rebuild_from_messages(&mut self, messages: &[Message], workspace: &Path) { |
| 1049 | self.entries.clear(); |
| 1050 | self.turn = 0; |
| 1051 | let mut patch_calls = HashSet::new(); |
| 1052 | |
| 1053 | for message in messages { |
| 1054 | let prompt_kind = classify_user_turn_prompt(message); |
| 1055 | if prompt_kind != UserTurnPromptKind::NotPrompt { |
| 1056 | self.next_turn(); |
| 1057 | } |
| 1058 | let candidates = extract_paths_from_message(message, prompt_kind, &mut patch_calls); |
| 1059 | if candidates.is_empty() { |
| 1060 | continue; |
| 1061 | } |
| 1062 | self.record_candidates(candidates, workspace, WorkingSetSource::Rebuild); |
| 1063 | } |
| 1064 | } |
| 1065 | |
| 1066 | /// Render a compact working-set block for the system prompt. |
| 1067 | /// |
| 1068 | /// Byte-stable across `next_turn()` calls when no new paths are observed |
| 1069 | /// (#280): the rendered lines drop the turn-relative `touches` and |
| 1070 | /// `last seen N turn(s) ago` fields, and the order is taken from |
| 1071 | /// `sorted_for_prompt` (turn-agnostic) instead of `sorted_entries`. |
| 1072 | /// The block lands in the system prompt before the historical |
| 1073 | /// conversation; any byte that drifts here cache-misses everything that |
| 1074 | /// follows in DeepSeek's KV prefix cache. |
| 1075 | pub fn summary_block( |
| 1076 | &self, |
| 1077 | workspace: &Path, |
| 1078 | read_allowed: &dyn Fn(&Path) -> bool, |
| 1079 | ) -> Option<String> { |
| 1080 | // Only stat-verified paths reach the model. Prose observation happily |
| 1081 | // records tokens that merely look like paths ("120x40", |
| 1082 | // "codewhale-hq/CodeWhale"), and a fabricated Active-paths line teaches the |
| 1083 | // model false workspace facts it then spends turns disproving. |
| 1084 | // Re-statting at render time also drops files deleted mid-session. |
| 1085 | // Bytes only change when the filesystem genuinely changed — the same |
| 1086 | // exception the #280 stability contract already makes for newly |
| 1087 | // observed paths. |
| 1088 | let prompt_entries: Vec<(&WorkingSetEntry, bool)> = self |
| 1089 | .sorted_for_prompt() |
| 1090 | .into_iter() |
| 1091 | .filter_map(|entry| { |
| 1092 | let abs = workspace.join(&entry.path); |
| 1093 | if !read_allowed(&abs) { |
| 1094 | return None; |
| 1095 | } |
| 1096 | let metadata = fs::metadata(abs).ok()?; |
| 1097 | Some((entry, metadata.is_dir())) |
| 1098 | }) |
| 1099 | .take(self.config.max_prompt_entries) |
| 1100 | .collect(); |
| 1101 | |
| 1102 | let repo_summary = summarize_repo_root(workspace); |
| 1103 | |
| 1104 | if repo_summary.is_none() && prompt_entries.is_empty() { |
| 1105 | return None; |
| 1106 | } |
| 1107 | |
| 1108 | let mut lines: Vec<String> = Vec::new(); |
| 1109 | lines.push("## Repo Working Set".to_string()); |
| 1110 | |
| 1111 | if let Some(summary) = repo_summary { |
| 1112 | lines.push(summary); |
| 1113 | } |
| 1114 | |
| 1115 | if !prompt_entries.is_empty() { |
| 1116 | lines.push("Active paths (prioritize these):".to_string()); |
| 1117 | for (entry, is_dir) in &prompt_entries { |
| 1118 | let kind = if *is_dir { "dir" } else { "file" }; |
| 1119 | lines.push(format!("- {} ({kind})", entry.path)); |
| 1120 | } |
| 1121 | } |
| 1122 | |
| 1123 | lines.push( |
| 1124 | "When in doubt, use tools to verify and keep changes focused on the working set." |
| 1125 | .to_string(), |
| 1126 | ); |
| 1127 | |
| 1128 | // Cache-maximal mode (#528): append the full current contents of the |
| 1129 | // top active files so the model reads live source each turn instead of |
| 1130 | // re-fetching it with tools. Kept after the path list and bounded by |
| 1131 | // per-file and total byte caps; order follows `sorted_for_prompt` so |
| 1132 | // the block is byte-stable while the files are unchanged. |
| 1133 | if self.cache_maximal_enabled() && !prompt_entries.is_empty() { |
| 1134 | let content_entries: Vec<&WorkingSetEntry> = |
| 1135 | prompt_entries.iter().map(|(entry, _)| *entry).collect(); |
| 1136 | self.append_resident_file_contents( |
| 1137 | &mut lines, |
| 1138 | workspace, |
| 1139 | &content_entries, |
| 1140 | read_allowed, |
| 1141 | ); |
| 1142 | } |
| 1143 | |
| 1144 | Some(lines.join("\n")) |
| 1145 | } |
| 1146 | |
| 1147 | /// Whether cache-maximal context mode is active: explicit config, or the |
| 1148 | /// `CODEWHALE_CACHE_MAXIMAL` env toggle (`1`/`true`/`on`/`yes`). The env |
| 1149 | /// value is constant for the process, so the rendered block stays |
| 1150 | /// byte-stable turn-over-turn. |
| 1151 | fn cache_maximal_enabled(&self) -> bool { |
| 1152 | if self.config.cache_maximal { |
| 1153 | return true; |
| 1154 | } |
| 1155 | match std::env::var("CODEWHALE_CACHE_MAXIMAL") { |
| 1156 | Ok(v) => matches!( |
| 1157 | v.trim().to_ascii_lowercase().as_str(), |
| 1158 | "1" | "true" | "on" | "yes" |
| 1159 | ), |
| 1160 | Err(_) => false, |
| 1161 | } |
| 1162 | } |
| 1163 | |
| 1164 | /// Render `### Active file contents` blocks for the resident files, honoring |
| 1165 | /// the per-file and total byte caps. Unreadable or non-UTF-8 files are noted |
| 1166 | /// rather than skipped silently so the omission is visible to the model. |
| 1167 | fn append_resident_file_contents( |
| 1168 | &self, |
| 1169 | lines: &mut Vec<String>, |
| 1170 | workspace: &Path, |
| 1171 | prompt_entries: &[&WorkingSetEntry], |
| 1172 | read_allowed: &dyn Fn(&Path) -> bool, |
| 1173 | ) { |
| 1174 | let mut header_pushed = false; |
| 1175 | let mut total_bytes: usize = 0; |
| 1176 | let mut omitted: usize = 0; |
| 1177 | |
| 1178 | for entry in prompt_entries { |
| 1179 | if entry.is_dir || !entry.exists { |
| 1180 | continue; |
| 1181 | } |
| 1182 | if total_bytes >= self.config.max_total_resident_bytes { |
| 1183 | omitted += 1; |
| 1184 | continue; |
| 1185 | } |
| 1186 | |
| 1187 | let abs = workspace.join(&entry.path); |
| 1188 | if !read_allowed(&abs) { |
| 1189 | if !header_pushed { |
| 1190 | lines.push("### Active file contents (cache-resident)".to_string()); |
| 1191 | header_pushed = true; |
| 1192 | } |
| 1193 | lines.push(format!( |
| 1194 | "<!-- file: {} (read deny-list, skipped) -->", |
| 1195 | entry.path |
| 1196 | )); |
| 1197 | continue; |
| 1198 | } |
| 1199 | let read_cap = self.config.max_resident_file_bytes.min( |
| 1200 | self.config |
| 1201 | .max_total_resident_bytes |
| 1202 | .saturating_sub(total_bytes), |
| 1203 | ) as u64; |
| 1204 | let (body, file_len) = match read_resident_prefix(&abs, read_cap) { |
| 1205 | Ok(read) => read, |
| 1206 | Err(_) => { |
| 1207 | if !header_pushed { |
| 1208 | lines.push("### Active file contents (cache-resident)".to_string()); |
| 1209 | header_pushed = true; |
| 1210 | } |
| 1211 | lines.push(format!( |
| 1212 | "<!-- file: {} (unreadable, skipped) -->", |
| 1213 | entry.path |
| 1214 | )); |
| 1215 | continue; |
| 1216 | } |
| 1217 | }; |
| 1218 | |
| 1219 | if !header_pushed { |
| 1220 | lines.push("### Active file contents (cache-resident)".to_string()); |
| 1221 | header_pushed = true; |
| 1222 | } |
| 1223 | |
| 1224 | let remaining_total = self |
| 1225 | .config |
| 1226 | .max_total_resident_bytes |
| 1227 | .saturating_sub(total_bytes); |
| 1228 | let cap = self.config.max_resident_file_bytes.min(remaining_total); |
| 1229 | let (shown, truncated) = truncate_on_char_boundary(&body, cap); |
| 1230 | total_bytes += shown.len(); |
| 1231 | |
| 1232 | lines.push(format!("<!-- file: {} -->", entry.path)); |
| 1233 | lines.push("```".to_string()); |
| 1234 | lines.push(shown.to_string()); |
| 1235 | if truncated { |
| 1236 | lines.push(format!( |
| 1237 | "<!-- ...{} more bytes truncated for prompt budget -->", |
| 1238 | file_len.saturating_sub(shown.len() as u64) |
| 1239 | )); |
| 1240 | } |
| 1241 | lines.push("```".to_string()); |
| 1242 | } |
| 1243 | |
| 1244 | if omitted > 0 { |
| 1245 | lines.push(format!( |
| 1246 | "<!-- {omitted} additional active file(s) omitted from the cache-resident budget -->" |
| 1247 | )); |
| 1248 | } |
| 1249 | } |
| 1250 | |
| 1251 | fn record_candidates( |
| 1252 | &mut self, |
| 1253 | candidates: Vec<String>, |
| 1254 | workspace: &Path, |
| 1255 | source: WorkingSetSource, |
| 1256 | ) { |
| 1257 | if candidates.is_empty() { |
| 1258 | return; |
| 1259 | } |
| 1260 | |
| 1261 | let workspace_canon = workspace.canonicalize().ok(); |
| 1262 | |
| 1263 | for raw in candidates { |
| 1264 | let Some(normalized) = normalize_candidate(&raw) else { |
| 1265 | continue; |
| 1266 | }; |
| 1267 | let Some((rel, exists, is_dir)) = |
| 1268 | relativize_candidate(&normalized, workspace, workspace_canon.as_deref()) |
| 1269 | else { |
| 1270 | continue; |
| 1271 | }; |
| 1272 | self.record_path(rel, exists, is_dir, source); |
| 1273 | } |
| 1274 | |
| 1275 | self.prune(); |
| 1276 | } |
| 1277 | |
| 1278 | fn record_path(&mut self, rel: String, exists: bool, is_dir: bool, source: WorkingSetSource) { |
| 1279 | match self.entries.get_mut(&rel) { |
| 1280 | Some(entry) => { |
| 1281 | entry.exists |= exists; |
| 1282 | entry.is_dir |= is_dir; |
| 1283 | entry.touches = entry.touches.saturating_add(1); |
| 1284 | entry.last_turn = self.turn; |
| 1285 | entry.last_source = source; |
| 1286 | } |
| 1287 | None => { |
| 1288 | let entry = WorkingSetEntry::new(rel.clone(), exists, is_dir, self.turn, source); |
| 1289 | let _ = self.entries.insert(rel, entry); |
| 1290 | } |
| 1291 | } |
| 1292 | } |
| 1293 | |
| 1294 | fn prune(&mut self) { |
| 1295 | let max_entries = self.config.max_entries; |
| 1296 | if self.entries.len() <= max_entries { |
| 1297 | return; |
| 1298 | } |
| 1299 | |
| 1300 | // Rank by score ascending and drop the lowest until within bounds. |
| 1301 | let mut ranked: Vec<(String, i64)> = self |
| 1302 | .entries |
| 1303 | .values() |
| 1304 | .map(|entry| (entry.path.clone(), score_entry(entry, self.turn))) |
| 1305 | .collect(); |
| 1306 | ranked.sort_by_key(|a| a.1); |
| 1307 | |
| 1308 | let to_remove = self.entries.len().saturating_sub(max_entries); |
| 1309 | for (path, _) in ranked.into_iter().take(to_remove) { |
| 1310 | let _ = self.entries.remove(&path); |
| 1311 | } |
| 1312 | } |
| 1313 | |
| 1314 | /// `sorted_entries` mixes in a recency bonus from `self.turn`, so its |
| 1315 | /// output reorders as turns advance even when no new paths are touched — |
| 1316 | /// that movement would cross `max_prompt_entries` boundaries and bust the |
| 1317 | /// KV prefix cache (#280). Compaction pinning still uses the recency-aware |
| 1318 | /// `sorted_entries`; only the prompt-facing surface is stabilised here. |
| 1319 | fn sorted_for_prompt(&self) -> Vec<&WorkingSetEntry> { |
| 1320 | let mut entries: Vec<&WorkingSetEntry> = self.entries.values().collect(); |
| 1321 | entries.sort_by(|a, b| b.touches.cmp(&a.touches).then_with(|| a.path.cmp(&b.path))); |
| 1322 | entries |
| 1323 | } |
| 1324 | } |
| 1325 | |
| 1326 | fn score_entry(entry: &WorkingSetEntry, current_turn: u64) -> i64 { |
| 1327 | let age = current_turn.saturating_sub(entry.last_turn); |
| 1328 | let recency_bonus = match age { |
| 1329 | 0 => 6, |
| 1330 | 1 => 4, |
| 1331 | 2 => 3, |
| 1332 | 3..=5 => 2, |
| 1333 | 6..=10 => 1, |
| 1334 | _ => 0, |
| 1335 | }; |
| 1336 | i64::from(entry.touches) * 4 + recency_bonus |
| 1337 | } |
| 1338 | |
| 1339 | fn normalize_candidate(raw: &str) -> Option<String> { |
| 1340 | let trimmed = raw.trim().trim_matches(|c: char| { |
| 1341 | matches!( |
| 1342 | c, |
| 1343 | '"' | '\'' | '`' | ',' | ';' | ':' | '(' | ')' | '[' | ']' |
| 1344 | ) |
| 1345 | }); |
| 1346 | if trimmed.is_empty() { |
| 1347 | return None; |
| 1348 | } |
| 1349 | Some(trimmed.to_string()) |
| 1350 | } |
| 1351 | |
| 1352 | fn relativize_candidate( |
| 1353 | candidate: &str, |
| 1354 | workspace: &Path, |
| 1355 | workspace_canon: Option<&Path>, |
| 1356 | ) -> Option<(String, bool, bool)> { |
| 1357 | let candidate_path = Path::new(candidate); |
| 1358 | |
| 1359 | // Reject obvious URLs and non-paths early. |
| 1360 | if candidate.contains("://") { |
| 1361 | return None; |
| 1362 | } |
| 1363 | |
| 1364 | let (rel_path, abs_path) = if candidate_path.is_absolute() { |
| 1365 | let within_workspace = workspace_canon |
| 1366 | .map(|ws| candidate_path.starts_with(ws)) |
| 1367 | .unwrap_or_else(|| candidate_path.starts_with(workspace)); |
| 1368 | if !within_workspace { |
| 1369 | return None; |
| 1370 | } |
| 1371 | let rel = candidate_path.strip_prefix(workspace).ok()?.to_path_buf(); |
| 1372 | (rel, candidate_path.to_path_buf()) |
| 1373 | } else { |
| 1374 | if starts_with_parent_dir(candidate_path) { |
| 1375 | return None; |
| 1376 | } |
| 1377 | let rel = clean_relative(candidate_path); |
| 1378 | let abs = workspace.join(&rel); |
| 1379 | (rel, abs) |
| 1380 | }; |
| 1381 | |
| 1382 | let metadata = fs::metadata(&abs_path).ok(); |
| 1383 | let exists = metadata.is_some(); |
| 1384 | let is_dir = metadata |
| 1385 | .as_ref() |
| 1386 | .map(fs::Metadata::is_dir) |
| 1387 | .unwrap_or_else(|| candidate.ends_with('/')); |
| 1388 | |
| 1389 | if rel_path.as_os_str().is_empty() { |
| 1390 | return None; |
| 1391 | } |
| 1392 | let rel_string = path_to_string(&rel_path)?; |
| 1393 | Some((rel_string, exists, is_dir)) |
| 1394 | } |
| 1395 | |
| 1396 | fn starts_with_parent_dir(path: &Path) -> bool { |
| 1397 | matches!( |
| 1398 | path.components().next(), |
| 1399 | Some(std::path::Component::ParentDir) |
| 1400 | ) |
| 1401 | } |
| 1402 | |
| 1403 | fn clean_relative(path: &Path) -> PathBuf { |
| 1404 | use std::path::Component; |
| 1405 | |
| 1406 | let mut parts: Vec<PathBuf> = Vec::new(); |
| 1407 | for comp in path.components() { |
| 1408 | match comp { |
| 1409 | Component::CurDir => {} |
| 1410 | Component::ParentDir => { |
| 1411 | let _ = parts.pop(); |
| 1412 | } |
| 1413 | Component::Normal(p) => parts.push(PathBuf::from(p)), |
| 1414 | Component::RootDir | Component::Prefix(_) => {} |
| 1415 | } |
| 1416 | } |
| 1417 | let mut out = PathBuf::new(); |
| 1418 | for part in parts { |
| 1419 | out.push(part); |
| 1420 | } |
| 1421 | out |
| 1422 | } |
| 1423 | |
| 1424 | fn path_to_string(path: &Path) -> Option<String> { |
| 1425 | path.as_os_str().to_str().map(|s| s.replace('\\', "/")) |
| 1426 | } |
| 1427 | |
| 1428 | fn extract_paths_from_message<'a>( |
| 1429 | message: &'a Message, |
| 1430 | prompt_kind: UserTurnPromptKind, |
| 1431 | patch_calls: &mut HashSet<&'a str>, |
| 1432 | ) -> Vec<String> { |
| 1433 | let metadata_index = turn_metadata_text(message).map(|(index, _)| index); |
| 1434 | let mut paths = Vec::new(); |
| 1435 | for (index, block) in message.content.iter().enumerate() { |
| 1436 | match block { |
| 1437 | ContentBlock::Text { text, .. } |
| 1438 | if prompt_kind == UserTurnPromptKind::Editable |
| 1439 | && metadata_index != Some(index) |
| 1440 | && !codewhale_core::prefix_cache::is_context_update_envelope(text.trim()) => |
| 1441 | { |
| 1442 | paths.extend(extract_paths_from_text(text)); |
| 1443 | } |
| 1444 | ContentBlock::ToolUse { |
| 1445 | id, name, input, .. |
| 1446 | } => { |
| 1447 | patch_calls.remove(id.as_str()); |
| 1448 | if is_patch_tool(name, input) { |
| 1449 | patch_calls.insert(id); |
| 1450 | } |
| 1451 | paths.extend(extract_paths_from_tool_input(name, input)); |
| 1452 | } |
| 1453 | ContentBlock::ToolResult { |
| 1454 | tool_use_id, |
| 1455 | content, |
| 1456 | is_error, |
| 1457 | .. |
| 1458 | } if patch_calls.remove(tool_use_id.as_str()) && *is_error != Some(true) => { |
| 1459 | paths.extend(extract_paths_from_mutation_receipt(content)); |
| 1460 | } |
| 1461 | _ => {} |
| 1462 | } |
| 1463 | } |
| 1464 | paths |
| 1465 | } |
| 1466 | |
| 1467 | fn is_patch_tool(tool_name: &str, input: &Value) -> bool { |
| 1468 | tool_name == "apply_patch" || (tool_name == "File" && input["action"] == "patch") |
| 1469 | } |
| 1470 | |
| 1471 | fn extract_paths_from_tool_input(tool_name: &str, input: &Value) -> Vec<String> { |
| 1472 | if tool_name == "present" { |
| 1473 | return input["files"] |
| 1474 | .as_array() |
| 1475 | .into_iter() |
| 1476 | .flatten() |
| 1477 | .filter_map(Value::as_str) |
| 1478 | .map(str::to_owned) |
| 1479 | .collect(); |
| 1480 | } |
| 1481 | |
| 1482 | let patch = is_patch_tool(tool_name, input); |
| 1483 | let targets_path = patch |
| 1484 | || match tool_name { |
| 1485 | "read" | "read_file" | "read_media" | "write" | "write_file" | "edit" | "edit_file" |
| 1486 | | "fim_edit" | "lsp" => true, |
| 1487 | "File" => matches!(input["action"].as_str(), Some("read" | "write" | "edit")), |
| 1488 | _ => false, |
| 1489 | }; |
| 1490 | if !targets_path { |
| 1491 | return Vec::new(); |
| 1492 | } |
| 1493 | |
| 1494 | let mut paths: Vec<_> = input["path"] |
| 1495 | .as_str() |
| 1496 | .map(str::to_owned) |
| 1497 | .into_iter() |
| 1498 | .collect(); |
| 1499 | if patch { |
| 1500 | paths.extend( |
| 1501 | input["replace"] |
| 1502 | .as_array() |
| 1503 | .or_else(|| input["changes"].as_array()) |
| 1504 | .into_iter() |
| 1505 | .flatten() |
| 1506 | .filter_map(|entry| entry["path"].as_str().map(str::to_owned)), |
| 1507 | ); |
| 1508 | } |
| 1509 | paths |
| 1510 | } |
| 1511 | |
| 1512 | fn extract_paths_from_mutation_receipt(output: &str) -> Vec<String> { |
| 1513 | let json = output |
| 1514 | .split_once("\n\n[hook context] ") |
| 1515 | .map_or(output, |(json, _)| json); |
| 1516 | let Ok(receipt) = serde_json::from_str::<Value>(json) else { |
| 1517 | return Vec::new(); |
| 1518 | }; |
| 1519 | if receipt["success"] != true { |
| 1520 | return Vec::new(); |
| 1521 | } |
| 1522 | receipt["touched_files"] |
| 1523 | .as_array() |
| 1524 | .into_iter() |
| 1525 | .flatten() |
| 1526 | .filter_map(Value::as_str) |
| 1527 | .map(str::to_owned) |
| 1528 | .collect() |
| 1529 | } |
| 1530 | |
| 1531 | fn looks_like_path(text: &str) -> bool { |
| 1532 | let trimmed = text.trim(); |
| 1533 | if trimmed.is_empty() { |
| 1534 | return false; |
| 1535 | } |
| 1536 | if trimmed.contains('/') || trimmed.contains('\\') { |
| 1537 | return true; |
| 1538 | } |
| 1539 | match Path::new(trimmed).extension().and_then(OsStr::to_str) { |
| 1540 | Some(ext) => COMMON_EXTENSIONS.contains(&ext), |
| 1541 | None => false, |
| 1542 | } |
| 1543 | } |
| 1544 | |
| 1545 | const COMMON_EXTENSIONS: &[&str] = &[ |
| 1546 | "rs", "toml", "md", "txt", "json", "yaml", "yml", "ts", "tsx", "js", "jsx", "py", "go", "java", |
| 1547 | "c", "cc", "cpp", "h", "hpp", "sh", "bash", "zsh", "sql", "html", "css", "scss", |
| 1548 | ]; |
| 1549 | |
| 1550 | fn extract_paths_from_text(text: &str) -> Vec<String> { |
| 1551 | if text.trim().is_empty() { |
| 1552 | return Vec::new(); |
| 1553 | } |
| 1554 | |
| 1555 | let re = path_regex(); |
| 1556 | text.split(['\n', ';', ',']) |
| 1557 | .flat_map(|line| line.split(". ")) |
| 1558 | .filter(|clause| !is_negated_path_clause(clause)) |
| 1559 | .flat_map(|clause| re.find_iter(clause)) |
| 1560 | .map(|m| m.as_str().to_string()) |
| 1561 | .filter(|s| looks_like_path(s)) |
| 1562 | .collect() |
| 1563 | } |
| 1564 | |
| 1565 | fn is_negated_path_clause(clause: &str) -> bool { |
| 1566 | const MARKERS: &[&str] = &[ |
| 1567 | "never ", |
| 1568 | "do not ", |
| 1569 | "don't ", |
| 1570 | "dont ", |
| 1571 | "must not ", |
| 1572 | "should not ", |
| 1573 | "shouldn't ", |
| 1574 | "off-limits", |
| 1575 | "off limits", |
| 1576 | "forbidden", |
| 1577 | "not allowed", |
| 1578 | ]; |
| 1579 | let lower = clause.to_lowercase(); |
| 1580 | MARKERS.iter().any(|marker| lower.contains(marker)) |
| 1581 | } |
| 1582 | |
| 1583 | fn path_regex() -> &'static Regex { |
| 1584 | static RE: OnceLock<Regex> = OnceLock::new(); |
| 1585 | RE.get_or_init(|| { |
| 1586 | // Path-ish tokens with separators or file extensions. |
| 1587 | Regex::new( |
| 1588 | r#"(?x) |
| 1589 | (?: |
| 1590 | (?:[A-Za-z]:\\)? # optional Windows drive |
| 1591 | (?:\./|\../|/)? # optional leading |
| 1592 | [A-Za-z0-9._-]+ |
| 1593 | (?:[/\\][A-Za-z0-9._-]+)+ |
| 1594 | (?:\.[A-Za-z0-9]{1,8})? # optional extension |
| 1595 | ) |
| 1596 | | |
| 1597 | (?: |
| 1598 | [A-Za-z0-9._-]+\.[A-Za-z0-9]{1,8} |
| 1599 | ) |
| 1600 | "#, |
| 1601 | ) |
| 1602 | .expect("path regex should compile") |
| 1603 | }) |
| 1604 | } |
| 1605 | |
| 1606 | fn summarize_repo_root(workspace: &Path) -> Option<String> { |
| 1607 | let key_files = detect_key_files(workspace); |
| 1608 | let (top_dirs, hidden_dirs) = list_top_level_dirs(workspace, 8); |
| 1609 | |
| 1610 | if key_files.is_empty() && top_dirs.is_empty() { |
| 1611 | return None; |
| 1612 | } |
| 1613 | |
| 1614 | let mut parts: Vec<String> = Vec::new(); |
| 1615 | if !key_files.is_empty() { |
| 1616 | parts.push(format!("Key files: {}", key_files.join(", "))); |
| 1617 | } |
| 1618 | if !top_dirs.is_empty() { |
| 1619 | let more = if hidden_dirs > 0 { |
| 1620 | format!(" (+{hidden_dirs} more)") |
| 1621 | } else { |
| 1622 | String::new() |
| 1623 | }; |
| 1624 | parts.push(format!("Top-level dirs: {}{more}", top_dirs.join(", "))); |
| 1625 | } |
| 1626 | Some(parts.join("\n")) |
| 1627 | } |
| 1628 | |
| 1629 | fn detect_key_files(workspace: &Path) -> Vec<String> { |
| 1630 | const CANDIDATES: &[&str] = &[ |
| 1631 | "Cargo.toml", |
| 1632 | "README.md", |
| 1633 | "AGENTS.md", |
| 1634 | "CLAUDE.md", |
| 1635 | "package.json", |
| 1636 | "pyproject.toml", |
| 1637 | "go.mod", |
| 1638 | "Makefile", |
| 1639 | ]; |
| 1640 | |
| 1641 | CANDIDATES |
| 1642 | .iter() |
| 1643 | .filter_map(|name| { |
| 1644 | let path = workspace.join(name); |
| 1645 | if path.exists() { |
| 1646 | Some((*name).to_string()) |
| 1647 | } else { |
| 1648 | None |
| 1649 | } |
| 1650 | }) |
| 1651 | .collect() |
| 1652 | } |
| 1653 | |
| 1654 | fn list_top_level_dirs(workspace: &Path, limit: usize) -> (Vec<String>, usize) { |
| 1655 | let Ok(entries) = fs::read_dir(workspace) else { |
| 1656 | return (Vec::new(), 0); |
| 1657 | }; |
| 1658 | let mut dirs: Vec<String> = entries |
| 1659 | .flatten() |
| 1660 | .filter_map(|entry| { |
| 1661 | let name = entry.file_name().to_str()?.to_string(); |
| 1662 | if name.starts_with('.') || IGNORED_ROOT_DIRS.contains(&name.as_str()) { |
| 1663 | return None; |
| 1664 | } |
| 1665 | entry |
| 1666 | .metadata() |
| 1667 | .ok() |
| 1668 | .filter(fs::Metadata::is_dir) |
| 1669 | .map(|_| name) |
| 1670 | }) |
| 1671 | .collect(); |
| 1672 | dirs.sort(); |
| 1673 | let hidden = dirs.len().saturating_sub(limit); |
| 1674 | dirs.truncate(limit); |
| 1675 | (dirs, hidden) |
| 1676 | } |
| 1677 | |
| 1678 | const IGNORED_ROOT_DIRS: &[&str] = &["target", "node_modules", "dist", "build", ".git"]; |
| 1679 | |
| 1680 | fn read_resident_prefix(path: &Path, cap: u64) -> std::io::Result<(String, u64)> { |
| 1681 | use std::io::Read as _; |
| 1682 | let file = std::fs::File::open(path)?; |
| 1683 | let file_len = file.metadata()?.len(); |
| 1684 | let mut bytes = Vec::new(); |
| 1685 | file.take(cap.saturating_add(4)).read_to_end(&mut bytes)?; |
| 1686 | let file_len = file_len.max(bytes.len() as u64); |
| 1687 | match String::from_utf8(bytes) { |
| 1688 | Ok(text) => Ok((text, file_len)), |
| 1689 | Err(error) if error.utf8_error().error_len().is_none() => { |
| 1690 | let valid = error.utf8_error().valid_up_to(); |
| 1691 | let mut bytes = error.into_bytes(); |
| 1692 | bytes.truncate(valid); |
| 1693 | Ok((String::from_utf8(bytes).expect("valid prefix"), file_len)) |
| 1694 | } |
| 1695 | Err(error) => Err(std::io::Error::new(std::io::ErrorKind::InvalidData, error)), |
| 1696 | } |
| 1697 | } |
| 1698 | |
| 1699 | #[cfg(test)] |
| 1700 | mod tests { |
| 1701 | use super::*; |
| 1702 | use codewhale_models::Role; |
| 1703 | use tempfile::TempDir; |
| 1704 | |
| 1705 | #[cfg(unix)] |
| 1706 | #[test] |
| 1707 | fn workspace_file_search_discovery_respects_symlink_opt_out_for_ai_directories() { |
| 1708 | let workspace = TempDir::new().unwrap(); |
| 1709 | let external = TempDir::new().unwrap(); |
| 1710 | fs::write(external.path().join("outside.rs"), "").unwrap(); |
| 1711 | std::os::unix::fs::symlink(external.path(), workspace.path().join(".agents")).unwrap(); |
| 1712 | for follow_links in [false, true] { |
| 1713 | let resolver = Workspace::with_cwd_depth_and_follow_links( |
| 1714 | workspace.path().to_path_buf(), |
| 1715 | None, |
| 1716 | DEFAULT_COMPLETIONS_WALK_DEPTH, |
| 1717 | follow_links, |
| 1718 | ); |
| 1719 | let candidates = resolver.completion_discovery_candidates(100, &|| false); |
| 1720 | assert_eq!( |
| 1721 | candidates.iter().any(|path| path == ".agents/outside.rs"), |
| 1722 | follow_links |
| 1723 | ); |
| 1724 | } |
| 1725 | } |
| 1726 | |
| 1727 | #[test] |
| 1728 | fn observe_user_message_tracks_paths() { |
| 1729 | let tmp = TempDir::new().expect("tempdir"); |
| 1730 | let src = tmp.path().join("src"); |
| 1731 | let file = src.join("lib.rs"); |
| 1732 | fs::create_dir_all(&src).expect("mkdir"); |
| 1733 | fs::write(&file, "pub fn x() {}").expect("write"); |
| 1734 | |
| 1735 | let mut ws = WorkingSet::default(); |
| 1736 | ws.observe_user_message("Please check src/lib.rs", tmp.path()); |
| 1737 | |
| 1738 | assert!(ws.entries.contains_key("src/lib.rs")); |
| 1739 | let entry = ws.entries.get("src/lib.rs").expect("entry"); |
| 1740 | assert!(entry.exists); |
| 1741 | assert!(!entry.is_dir); |
| 1742 | } |
| 1743 | |
| 1744 | #[test] |
| 1745 | fn workspace_root_is_not_an_active_path() { |
| 1746 | let tmp = TempDir::new().expect("tempdir"); |
| 1747 | let root = tmp.path().canonicalize().expect("canonical root"); |
| 1748 | fs::write(root.join("笔记 📝.md"), "旧").expect("write"); |
| 1749 | |
| 1750 | let mut ws = WorkingSet::default(); |
| 1751 | let mention = format!("<file path=\"{}/笔记 📝.md\">", root.display()); |
| 1752 | ws.observe_user_message(&mention, &root); |
| 1753 | |
| 1754 | assert!(!ws.entries.contains_key(""), "{:?}", ws.entries.keys()); |
| 1755 | } |
| 1756 | |
| 1757 | #[test] |
| 1758 | fn observe_tool_call_extracts_paths_from_input() { |
| 1759 | let tmp = TempDir::new().expect("tempdir"); |
| 1760 | let file = tmp.path().join("Cargo.toml"); |
| 1761 | fs::write(&file, "[package]\nname = \"x\"").expect("write"); |
| 1762 | |
| 1763 | let mut ws = WorkingSet::default(); |
| 1764 | let input = serde_json::json!({ "path": "Cargo.toml" }); |
| 1765 | ws.observe_tool_call("read_file", &input, None, tmp.path()); |
| 1766 | |
| 1767 | assert!(ws.entries.contains_key("Cargo.toml")); |
| 1768 | } |
| 1769 | |
| 1770 | #[test] |
| 1771 | fn summary_block_includes_repo_and_working_set() { |
| 1772 | let tmp = TempDir::new().expect("tempdir"); |
| 1773 | fs::write(tmp.path().join("Cargo.toml"), "[package]\nname = \"x\"").expect("write"); |
| 1774 | let src = tmp.path().join("src"); |
| 1775 | fs::create_dir_all(&src).expect("mkdir"); |
| 1776 | fs::write(src.join("lib.rs"), "pub fn x() {}").expect("write"); |
| 1777 | |
| 1778 | let mut ws = WorkingSet::default(); |
| 1779 | ws.observe_user_message("src/lib.rs", tmp.path()); |
| 1780 | let block = ws.summary_block(tmp.path(), &|_| true).expect("block"); |
| 1781 | |
| 1782 | assert!(block.contains("Repo Working Set")); |
| 1783 | assert!(!block.contains("Workspace:")); |
| 1784 | assert!(block.contains("Cargo.toml")); |
| 1785 | assert!(block.contains("src")); |
| 1786 | assert!(block.contains("src/lib.rs")); |
| 1787 | } |
| 1788 | |
| 1789 | /// #280 regression: `summary_block` must produce byte-identical output |
| 1790 | /// across `next_turn()` advances when no new paths are touched. Prior to |
| 1791 | /// the fix, the rendered lines interpolated `entry.touches` and |
| 1792 | /// `self.turn - entry.last_turn`, both of which drift turn-over-turn even |
| 1793 | /// when the path set is unchanged. The drift busted DeepSeek's KV prefix |
| 1794 | /// cache on every user message because the working-set block lands in the |
| 1795 | /// system prompt before the historical conversation. |
| 1796 | #[test] |
| 1797 | fn summary_block_is_byte_stable_across_next_turn_when_no_new_paths_observed() { |
| 1798 | use crate::test_support::assert_byte_identical; |
| 1799 | |
| 1800 | let tmp = TempDir::new().expect("tempdir"); |
| 1801 | fs::write(tmp.path().join("Cargo.toml"), "[package]\nname = \"x\"").expect("write"); |
| 1802 | let src = tmp.path().join("src"); |
| 1803 | fs::create_dir_all(&src).expect("mkdir"); |
| 1804 | fs::write(src.join("a.rs"), "a").expect("write"); |
| 1805 | fs::write(src.join("b.rs"), "b").expect("write"); |
| 1806 | |
| 1807 | let mut ws = WorkingSet::default(); |
| 1808 | ws.observe_user_message("Edit src/a.rs and src/b.rs", tmp.path()); |
| 1809 | |
| 1810 | let before = ws |
| 1811 | .summary_block(tmp.path(), &|_| true) |
| 1812 | .expect("block before"); |
| 1813 | ws.next_turn(); |
| 1814 | let after = ws |
| 1815 | .summary_block(tmp.path(), &|_| true) |
| 1816 | .expect("block after"); |
| 1817 | |
| 1818 | assert_byte_identical( |
| 1819 | "summary_block must be stable across next_turn when no new paths touched", |
| 1820 | &before, |
| 1821 | &after, |
| 1822 | ); |
| 1823 | } |
| 1824 | |
| 1825 | /// Companion to the byte-stability test: a fresh path *should* invalidate |
| 1826 | /// the block (the KV cache is allowed to miss when there's genuinely new |
| 1827 | /// signal), so the model still sees newly touched paths after the block |
| 1828 | /// stabilises across no-op turns. |
| 1829 | #[test] |
| 1830 | fn summary_block_changes_when_a_new_path_is_observed() { |
| 1831 | let tmp = TempDir::new().expect("tempdir"); |
| 1832 | fs::write(tmp.path().join("Cargo.toml"), "[package]\nname = \"x\"").expect("write"); |
| 1833 | let src = tmp.path().join("src"); |
| 1834 | fs::create_dir_all(&src).expect("mkdir"); |
| 1835 | fs::write(src.join("a.rs"), "a").expect("write"); |
| 1836 | fs::write(src.join("c.rs"), "c").expect("write"); |
| 1837 | |
| 1838 | let mut ws = WorkingSet::default(); |
| 1839 | ws.observe_user_message("src/a.rs", tmp.path()); |
| 1840 | let before = ws |
| 1841 | .summary_block(tmp.path(), &|_| true) |
| 1842 | .expect("block before"); |
| 1843 | |
| 1844 | ws.observe_user_message("src/c.rs", tmp.path()); |
| 1845 | let after = ws |
| 1846 | .summary_block(tmp.path(), &|_| true) |
| 1847 | .expect("block after"); |
| 1848 | |
| 1849 | assert_ne!(before, after, "new path must update the rendered summary"); |
| 1850 | assert!(after.contains("src/c.rs")); |
| 1851 | } |
| 1852 | |
| 1853 | #[test] |
| 1854 | fn summary_block_renders_only_paths_that_stat_verify() { |
| 1855 | // Prose observation records tokens that merely look like paths |
| 1856 | // ("120x40", "codewhale-hq/CodeWhale"); the rendered Active-paths list must |
| 1857 | // never teach the model a workspace fact the filesystem contradicts. |
| 1858 | let tmp = TempDir::new().expect("tempdir"); |
| 1859 | let src = tmp.path().join("src"); |
| 1860 | fs::create_dir_all(&src).expect("mkdir"); |
| 1861 | fs::write(src.join("real.rs"), "real").expect("write"); |
| 1862 | |
| 1863 | let mut ws = WorkingSet::default(); |
| 1864 | ws.observe_user_message( |
| 1865 | "Fix src/real.rs, test at 120x40/80x24, and check codewhale-hq/CodeWhale", |
| 1866 | tmp.path(), |
| 1867 | ); |
| 1868 | |
| 1869 | let block = ws.summary_block(tmp.path(), &|_| true).expect("block"); |
| 1870 | assert!(block.contains("- src/real.rs (file)"), "{block}"); |
| 1871 | assert!(!block.contains("120x40"), "{block}"); |
| 1872 | assert!(!block.contains("codewhale-hq/CodeWhale"), "{block}"); |
| 1873 | |
| 1874 | // A file deleted mid-session falls out on the next render — the same |
| 1875 | // filesystem-changed exception #280 makes for newly observed paths. |
| 1876 | fs::remove_file(src.join("real.rs")).expect("remove"); |
| 1877 | let after_delete = ws.summary_block(tmp.path(), &|_| true); |
| 1878 | assert!( |
| 1879 | after_delete |
| 1880 | .as_deref() |
| 1881 | .is_none_or(|block| !block.contains("src/real.rs")), |
| 1882 | "{after_delete:?}" |
| 1883 | ); |
| 1884 | } |
| 1885 | |
| 1886 | #[test] |
| 1887 | fn summary_block_skips_forbidden_paths_and_lists_dirs_deterministically() { |
| 1888 | let tmp = TempDir::new().expect("tempdir"); |
| 1889 | for dir in [ |
| 1890 | "zeta", "alpha", "secrets", "beta", "gamma", "delta", "eta", "iota", "kappa", |
| 1891 | ] { |
| 1892 | fs::create_dir_all(tmp.path().join(dir)).expect("mkdir"); |
| 1893 | } |
| 1894 | fs::write(tmp.path().join("secrets/STATUS.md"), "x").expect("write"); |
| 1895 | fs::write(tmp.path().join("alpha/keep.rs"), "x").expect("write"); |
| 1896 | fs::write(tmp.path().join("beta/denied.rs"), "x").expect("write"); |
| 1897 | |
| 1898 | let mut ws = WorkingSet::default(); |
| 1899 | ws.observe_user_message( |
| 1900 | "Fix alpha/keep.rs and beta/denied.rs. Never read secrets/STATUS.md; it is off-limits.", |
| 1901 | tmp.path(), |
| 1902 | ); |
| 1903 | let denied = tmp.path().join("beta/denied.rs"); |
| 1904 | let block = ws |
| 1905 | .summary_block(tmp.path(), &|path| path != denied.as_path()) |
| 1906 | .expect("block"); |
| 1907 | assert!(block.contains("- alpha/keep.rs (file)"), "{block}"); |
| 1908 | assert!(!block.contains("secrets/STATUS.md"), "{block}"); |
| 1909 | assert!(!block.contains("beta/denied.rs"), "{block}"); |
| 1910 | assert!( |
| 1911 | block.contains( |
| 1912 | "Top-level dirs: alpha, beta, delta, eta, gamma, iota, kappa, secrets (+1 more)" |
| 1913 | ), |
| 1914 | "{block}" |
| 1915 | ); |
| 1916 | } |
| 1917 | |
| 1918 | // ── Cache-maximal context mode (#528) ── |
| 1919 | // Tests drive the flag through `config.cache_maximal` directly so they |
| 1920 | // don't touch the process-wide `CODEWHALE_CACHE_MAXIMAL` env var (which |
| 1921 | // would race with parallel tests). |
| 1922 | |
| 1923 | fn cache_maximal_ws() -> WorkingSet { |
| 1924 | let mut ws = WorkingSet::default(); |
| 1925 | ws.config.cache_maximal = true; |
| 1926 | ws |
| 1927 | } |
| 1928 | |
| 1929 | #[test] |
| 1930 | fn cache_maximal_off_keeps_path_list_only() { |
| 1931 | let tmp = TempDir::new().expect("tempdir"); |
| 1932 | let src = tmp.path().join("src"); |
| 1933 | fs::create_dir_all(&src).expect("mkdir"); |
| 1934 | fs::write(src.join("lib.rs"), "pub fn hello() {}").expect("write"); |
| 1935 | |
| 1936 | let mut ws = WorkingSet::default(); // cache_maximal defaults to false |
| 1937 | ws.observe_user_message("src/lib.rs", tmp.path()); |
| 1938 | let block = ws.summary_block(tmp.path(), &|_| true).expect("block"); |
| 1939 | |
| 1940 | assert!(block.contains("src/lib.rs"), "path list still present"); |
| 1941 | assert!( |
| 1942 | !block.contains("Active file contents"), |
| 1943 | "no materialized contents when the flag is off" |
| 1944 | ); |
| 1945 | assert!(!block.contains("pub fn hello")); |
| 1946 | } |
| 1947 | |
| 1948 | #[test] |
| 1949 | fn cache_maximal_on_materializes_file_contents() { |
| 1950 | let tmp = TempDir::new().expect("tempdir"); |
| 1951 | let src = tmp.path().join("src"); |
| 1952 | fs::create_dir_all(&src).expect("mkdir"); |
| 1953 | fs::write(src.join("lib.rs"), "pub fn hello() {}").expect("write"); |
| 1954 | |
| 1955 | let mut ws = cache_maximal_ws(); |
| 1956 | ws.observe_user_message("src/lib.rs", tmp.path()); |
| 1957 | let block = ws.summary_block(tmp.path(), &|_| true).expect("block"); |
| 1958 | |
| 1959 | assert!(block.contains("Active file contents (cache-resident)")); |
| 1960 | assert!(block.contains("<!-- file: src/lib.rs -->")); |
| 1961 | assert!(block.contains("pub fn hello() {}")); |
| 1962 | } |
| 1963 | |
| 1964 | #[test] |
| 1965 | fn cache_maximal_directories_are_not_materialized() { |
| 1966 | let tmp = TempDir::new().expect("tempdir"); |
| 1967 | let src = tmp.path().join("src"); |
| 1968 | fs::create_dir_all(&src).expect("mkdir"); |
| 1969 | |
| 1970 | let mut ws = cache_maximal_ws(); |
| 1971 | ws.observe_user_message("look in src/", tmp.path()); |
| 1972 | let block = ws.summary_block(tmp.path(), &|_| true).expect("block"); |
| 1973 | |
| 1974 | // `src` is a dir; it appears in the path list but has no content block. |
| 1975 | assert!(!block.contains("<!-- file: src -->")); |
| 1976 | } |
| 1977 | |
| 1978 | #[test] |
| 1979 | fn cache_maximal_respects_per_file_byte_cap() { |
| 1980 | let tmp = TempDir::new().expect("tempdir"); |
| 1981 | let src = tmp.path().join("src"); |
| 1982 | fs::create_dir_all(&src).expect("mkdir"); |
| 1983 | let big = "x".repeat(10_000); |
| 1984 | fs::write(src.join("big.rs"), &big).expect("write"); |
| 1985 | |
| 1986 | let mut ws = cache_maximal_ws(); |
| 1987 | ws.config.max_resident_file_bytes = 100; |
| 1988 | ws.config.max_total_resident_bytes = 10_000; |
| 1989 | ws.observe_user_message("src/big.rs", tmp.path()); |
| 1990 | let block = ws.summary_block(tmp.path(), &|_| true).expect("block"); |
| 1991 | |
| 1992 | assert!(block.contains("<!-- ...9900 more bytes truncated for prompt budget -->")); |
| 1993 | // The full 10k body must not be inlined. |
| 1994 | assert!(!block.contains(&big)); |
| 1995 | } |
| 1996 | |
| 1997 | #[test] |
| 1998 | fn read_resident_prefix_does_not_read_past_cap() { |
| 1999 | let tmp = TempDir::new().expect("tempdir"); |
| 2000 | let path = tmp.path().join("tail-invalid.txt"); |
| 2001 | let mut bytes = vec![b'a'; 128]; |
| 2002 | bytes.extend_from_slice(&[0xff, 0xfe, 0xfd, 0xfc]); |
| 2003 | fs::write(&path, &bytes).expect("write"); |
| 2004 | |
| 2005 | let (prefix, file_len) = read_resident_prefix(&path, 64).expect("bounded prefix read"); |
| 2006 | assert_eq!(file_len, bytes.len() as u64); |
| 2007 | assert!(prefix.len() <= 68); |
| 2008 | assert!(prefix.starts_with(&"a".repeat(64))); |
| 2009 | } |
| 2010 | |
| 2011 | #[test] |
| 2012 | fn cache_maximal_total_cap_omits_extra_files() { |
| 2013 | let tmp = TempDir::new().expect("tempdir"); |
| 2014 | let src = tmp.path().join("src"); |
| 2015 | fs::create_dir_all(&src).expect("mkdir"); |
| 2016 | fs::write(src.join("a.rs"), "a".repeat(200)).expect("write"); |
| 2017 | fs::write(src.join("b.rs"), "b".repeat(200)).expect("write"); |
| 2018 | |
| 2019 | let mut ws = cache_maximal_ws(); |
| 2020 | ws.config.max_resident_file_bytes = 200; |
| 2021 | ws.config.max_total_resident_bytes = 200; // only one file fits |
| 2022 | ws.observe_user_message("Edit src/a.rs and src/b.rs", tmp.path()); |
| 2023 | let block = ws.summary_block(tmp.path(), &|_| true).expect("block"); |
| 2024 | |
| 2025 | assert!( |
| 2026 | block.contains("omitted from the cache-resident budget"), |
| 2027 | "second file should be reported as omitted:\n{block}" |
| 2028 | ); |
| 2029 | } |
| 2030 | |
| 2031 | #[test] |
| 2032 | fn cache_maximal_is_byte_stable_when_files_unchanged() { |
| 2033 | use crate::test_support::assert_byte_identical; |
| 2034 | |
| 2035 | let tmp = TempDir::new().expect("tempdir"); |
| 2036 | let src = tmp.path().join("src"); |
| 2037 | fs::create_dir_all(&src).expect("mkdir"); |
| 2038 | fs::write(src.join("a.rs"), "fn a() {}").expect("write"); |
| 2039 | |
| 2040 | let mut ws = cache_maximal_ws(); |
| 2041 | ws.observe_user_message("src/a.rs", tmp.path()); |
| 2042 | let before = ws.summary_block(tmp.path(), &|_| true).expect("before"); |
| 2043 | ws.next_turn(); |
| 2044 | let after = ws.summary_block(tmp.path(), &|_| true).expect("after"); |
| 2045 | |
| 2046 | assert_byte_identical( |
| 2047 | "cache-maximal block must be stable while files are unchanged (KV cache hit)", |
| 2048 | &before, |
| 2049 | &after, |
| 2050 | ); |
| 2051 | } |
| 2052 | |
| 2053 | #[test] |
| 2054 | fn cache_maximal_changes_when_file_edited() { |
| 2055 | let tmp = TempDir::new().expect("tempdir"); |
| 2056 | let src = tmp.path().join("src"); |
| 2057 | fs::create_dir_all(&src).expect("mkdir"); |
| 2058 | let file = src.join("a.rs"); |
| 2059 | fs::write(&file, "fn a() {}").expect("write"); |
| 2060 | |
| 2061 | let mut ws = cache_maximal_ws(); |
| 2062 | ws.observe_user_message("src/a.rs", tmp.path()); |
| 2063 | let before = ws.summary_block(tmp.path(), &|_| true).expect("before"); |
| 2064 | |
| 2065 | fs::write(&file, "fn a() { todo!() }").expect("rewrite"); |
| 2066 | let after = ws.summary_block(tmp.path(), &|_| true).expect("after"); |
| 2067 | |
| 2068 | assert_ne!(before, after, "editing the file must change the block"); |
| 2069 | assert!(after.contains("todo!()")); |
| 2070 | } |
| 2071 | |
| 2072 | #[test] |
| 2073 | fn observe_tool_call_ignores_search_read_outputs_and_tracks_explicit_inputs_and_mutations() { |
| 2074 | let tmp = TempDir::new().expect("tempdir"); |
| 2075 | let src = tmp.path().join("src"); |
| 2076 | fs::create_dir_all(&src).expect("mkdir"); |
| 2077 | fs::write(src.join("target.rs"), "pub fn target() {}").expect("write"); |
| 2078 | fs::write(src.join("edited.rs"), "pub fn edited() {}").expect("write"); |
| 2079 | fs::write(src.join("patched.rs"), "pub fn patched() {}").expect("write"); |
| 2080 | fs::write(src.join("budget_handback_tests.rs"), "test").expect("write"); |
| 2081 | fs::write(src.join("task_ownership.rs"), "test").expect("write"); |
| 2082 | fs::write(src.join("test_cases_02.rs"), "test").expect("write"); |
| 2083 | fs::write(src.join("decoy.rs"), "decoy").expect("write"); |
| 2084 | |
| 2085 | let mut ws = WorkingSet::default(); |
| 2086 | ws.observe_tool_call( |
| 2087 | "grep_files", |
| 2088 | &serde_json::json!({ "pattern": "budget", "path": "src" }), |
| 2089 | Some( |
| 2090 | "src/budget_handback_tests.rs:12:budget\nsrc/task_ownership.rs:34:budget\nsrc/test_cases_02.rs:56:budget", |
| 2091 | ), |
| 2092 | tmp.path(), |
| 2093 | ); |
| 2094 | ws.observe_tool_call( |
| 2095 | "file_search", |
| 2096 | &serde_json::json!({ "query": "test" }), |
| 2097 | Some("src/budget_handback_tests.rs\nsrc/test_cases_02.rs"), |
| 2098 | tmp.path(), |
| 2099 | ); |
| 2100 | ws.observe_tool_call( |
| 2101 | "list_dir", |
| 2102 | &serde_json::json!({ "path": "src" }), |
| 2103 | Some("src/decoy.rs\nsrc/task_ownership.rs"), |
| 2104 | tmp.path(), |
| 2105 | ); |
| 2106 | ws.observe_tool_call( |
| 2107 | "bash", |
| 2108 | &serde_json::json!({ "command": "cargo test" }), |
| 2109 | Some("FAILED src/test_cases_02.rs:99"), |
| 2110 | tmp.path(), |
| 2111 | ); |
| 2112 | ws.observe_tool_call( |
| 2113 | "tool_search", |
| 2114 | &serde_json::json!({ "query": "session" }), |
| 2115 | Some("src/decoy.rs"), |
| 2116 | tmp.path(), |
| 2117 | ); |
| 2118 | ws.observe_tool_call( |
| 2119 | "session_search", |
| 2120 | &serde_json::json!({ "session_id": "abc" }), |
| 2121 | Some("user: check src/decoy.rs"), |
| 2122 | tmp.path(), |
| 2123 | ); |
| 2124 | ws.observe_tool_call( |
| 2125 | "retrieve_tool_result", |
| 2126 | &serde_json::json!({ "id": "1" }), |
| 2127 | Some("src/decoy.rs"), |
| 2128 | tmp.path(), |
| 2129 | ); |
| 2130 | |
| 2131 | assert!(ws.entries.is_empty(), "{:?}", ws.entries.keys()); |
| 2132 | |
| 2133 | ws.observe_tool_call( |
| 2134 | "read", |
| 2135 | &serde_json::json!({ "path": "src/target.rs" }), |
| 2136 | Some("mod decoy; // see src/decoy.rs and src/test_cases_02.rs"), |
| 2137 | tmp.path(), |
| 2138 | ); |
| 2139 | ws.observe_tool_call( |
| 2140 | "edit", |
| 2141 | &serde_json::json!({ |
| 2142 | "path": "src/edited.rs", |
| 2143 | "edits": [{"oldText": "// src/decoy.rs", "newText": "// src/task_ownership.rs"}] |
| 2144 | }), |
| 2145 | Some("--- src/edited.rs\n+++ src/edited.rs\n@@ -1 +1 @@\n-// src/decoy.rs\n+// src/task_ownership.rs\nReplaced 1 occurrence in src/edited.rs"), |
| 2146 | tmp.path(), |
| 2147 | ); |
| 2148 | ws.observe_tool_call( |
| 2149 | "apply_patch", |
| 2150 | &serde_json::json!({ |
| 2151 | "patch": "--- a/src/patched.rs\n+++ b/src/patched.rs\n@@ -1 +1 @@\n-old\n+new // src/decoy.rs\n" |
| 2152 | }), |
| 2153 | Some(r#"{"success":true,"touched_files":["src/patched.rs"],"message":"Applied patch"}"#), |
| 2154 | tmp.path(), |
| 2155 | ); |
| 2156 | |
| 2157 | assert!(ws.entries.contains_key("src/target.rs")); |
| 2158 | assert!(ws.entries.contains_key("src/edited.rs")); |
| 2159 | assert!(ws.entries.contains_key("src/patched.rs")); |
| 2160 | assert!(!ws.entries.contains_key("src/budget_handback_tests.rs")); |
| 2161 | assert!(!ws.entries.contains_key("src/task_ownership.rs")); |
| 2162 | assert!(!ws.entries.contains_key("src/test_cases_02.rs")); |
| 2163 | assert!(!ws.entries.contains_key("src/decoy.rs")); |
| 2164 | } |
| 2165 | |
| 2166 | #[test] |
| 2167 | fn rebuild_from_messages_skips_grep_results_and_keeps_mutation_receipts() { |
| 2168 | let tmp = TempDir::new().expect("tempdir"); |
| 2169 | let src = tmp.path().join("src"); |
| 2170 | fs::create_dir_all(&src).expect("mkdir"); |
| 2171 | fs::write(src.join("compaction.rs"), "fn c() {}").expect("write"); |
| 2172 | fs::write(src.join("noise.rs"), "fn n() {}").expect("write"); |
| 2173 | |
| 2174 | let messages = vec![ |
| 2175 | Message { |
| 2176 | role: Role::Assistant, |
| 2177 | content: vec![ |
| 2178 | ContentBlock::ToolUse { |
| 2179 | execution_id: None, |
| 2180 | id: "grep_1".to_string(), |
| 2181 | name: "grep_files".to_string(), |
| 2182 | input: serde_json::json!({ "pattern": "fn", "path": "src" }), |
| 2183 | caller: None, |
| 2184 | thought_signature: None, |
| 2185 | }, |
| 2186 | ContentBlock::ToolUse { |
| 2187 | execution_id: None, |
| 2188 | id: "patch_1".to_string(), |
| 2189 | name: "apply_patch".to_string(), |
| 2190 | input: serde_json::json!({ "patch": "" }), |
| 2191 | caller: None, |
| 2192 | thought_signature: None, |
| 2193 | }, |
| 2194 | ], |
| 2195 | }, |
| 2196 | Message { |
| 2197 | role: Role::User, |
| 2198 | content: vec![ |
| 2199 | ContentBlock::ToolResult { |
| 2200 | execution_id: None, |
| 2201 | tool_use_id: "grep_1".to_string(), |
| 2202 | content: r#"{"success":true,"touched_files":["src/noise.rs"]}"#.to_string(), |
| 2203 | is_error: None, |
| 2204 | content_blocks: None, |
| 2205 | }, |
| 2206 | ContentBlock::ToolResult { |
| 2207 | execution_id: None, |
| 2208 | tool_use_id: "patch_1".to_string(), |
| 2209 | content: "{\"success\":true,\"touched_files\":[\"src/compaction.rs\"]}\n\n[hook context] src/noise.rs".to_string(), |
| 2210 | is_error: None, |
| 2211 | content_blocks: None, |
| 2212 | }, |
| 2213 | ], |
| 2214 | }, |
| 2215 | ]; |
| 2216 | |
| 2217 | let mut ws = WorkingSet::default(); |
| 2218 | ws.rebuild_from_messages(&messages, tmp.path()); |
| 2219 | assert_eq!(ws.turn, 0); |
| 2220 | assert!(ws.entries.contains_key("src/compaction.rs")); |
| 2221 | assert!(!ws.entries.contains_key("src/noise.rs")); |
| 2222 | } |
| 2223 | |
| 2224 | #[test] |
| 2225 | fn pinning_prefers_high_signal_paths() { |
| 2226 | let tmp = TempDir::new().expect("tempdir"); |
| 2227 | fs::create_dir_all(tmp.path().join("src")).expect("mkdir"); |
| 2228 | fs::write(tmp.path().join("src/a.rs"), "a").expect("write"); |
| 2229 | fs::write(tmp.path().join("src/b.rs"), "b").expect("write"); |
| 2230 | |
| 2231 | let mut ws = WorkingSet::default(); |
| 2232 | ws.observe_user_message("src/a.rs", tmp.path()); |
| 2233 | ws.observe_tool_call( |
| 2234 | "read_file", |
| 2235 | &serde_json::json!({ "path": "src/a.rs" }), |
| 2236 | Some("src/a.rs"), |
| 2237 | tmp.path(), |
| 2238 | ); |
| 2239 | ws.observe_user_message("src/b.rs", tmp.path()); |
| 2240 | |
| 2241 | let a_score = score_entry(ws.entries.get("src/a.rs").expect("a"), ws.turn); |
| 2242 | let b_score = score_entry(ws.entries.get("src/b.rs").expect("b"), ws.turn); |
| 2243 | assert!(a_score >= b_score); |
| 2244 | } |
| 2245 | |
| 2246 | #[test] |
| 2247 | fn workspace_resolve_respects_cwd_and_workspace() { |
| 2248 | let tmp = TempDir::new().unwrap(); |
| 2249 | |
| 2250 | let sub = tmp.path().join("sub"); |
| 2251 | std::fs::create_dir_all(&sub).unwrap(); |
| 2252 | let bar = sub.join("bar.txt"); |
| 2253 | std::fs::write(&bar, "bar").unwrap(); |
| 2254 | |
| 2255 | let nested = tmp.path().join("nested/deep"); |
| 2256 | std::fs::create_dir_all(&nested).unwrap(); |
| 2257 | let file_md = nested.join("file.md"); |
| 2258 | std::fs::write(&file_md, "md").unwrap(); |
| 2259 | |
| 2260 | // Construct with an explicit cwd so the test doesn't race with other |
| 2261 | // tests that mutate the real process cwd. |
| 2262 | let ws = Workspace::with_cwd(tmp.path().to_path_buf(), Some(sub.clone())); |
| 2263 | |
| 2264 | // #101 repro #1: @bar.txt with cwd=sub MUST resolve via the cwd pass, |
| 2265 | // never to the bogus workspace path tmp/bar.txt (which doesn't exist). |
| 2266 | let res1 = ws.resolve("bar.txt").unwrap(); |
| 2267 | assert_eq!( |
| 2268 | res1.canonicalize().unwrap_or(res1.clone()), |
| 2269 | bar.canonicalize().unwrap_or(bar.clone()) |
| 2270 | ); |
| 2271 | let wrong = tmp.path().join("bar.txt"); |
| 2272 | assert_ne!(res1, wrong, "must not have routed to workspace fallback"); |
| 2273 | |
| 2274 | // #101 repro #2: @nested/deep/file.md falls through to workspace root. |
| 2275 | let res2 = ws.resolve("nested/deep/file.md").unwrap(); |
| 2276 | assert_eq!( |
| 2277 | res2.canonicalize().unwrap_or(res2), |
| 2278 | file_md.canonicalize().unwrap_or(file_md) |
| 2279 | ); |
| 2280 | } |
| 2281 | |
| 2282 | /// Negative test (#101): a truly missing path returns `Err` with a path |
| 2283 | /// that callers can show to the user as a signal of failure. |
| 2284 | #[test] |
| 2285 | fn workspace_resolve_returns_err_for_truly_missing_path() { |
| 2286 | let tmp = TempDir::new().unwrap(); |
| 2287 | let ws = Workspace::with_cwd(tmp.path().to_path_buf(), Some(tmp.path().to_path_buf())); |
| 2288 | |
| 2289 | let res = ws.resolve("does/not/exist.txt"); |
| 2290 | assert!(res.is_err(), "expected Err for missing path, got: {res:?}"); |
| 2291 | } |
| 2292 | |
| 2293 | /// `Workspace::completions` returns workspace-relative entries for files |
| 2294 | /// under the root, and cwd-relative entries when the cwd-only file lives |
| 2295 | /// outside the workspace tree. Honors `.gitignore`. |
| 2296 | #[test] |
| 2297 | fn workspace_completions_walk_surfaces_workspace_and_cwd() { |
| 2298 | let tmp = TempDir::new().unwrap(); |
| 2299 | // Two trees: a workspace under `ws/` and a cwd under `cwd/` that is |
| 2300 | // NOT inside the workspace, so the two walks are disjoint and we can |
| 2301 | // assert each branch contributed. |
| 2302 | let ws_root = tmp.path().join("ws"); |
| 2303 | let cwd_root = tmp.path().join("cwd"); |
| 2304 | std::fs::create_dir_all(&ws_root).unwrap(); |
| 2305 | std::fs::create_dir_all(&cwd_root).unwrap(); |
| 2306 | std::fs::write(ws_root.join("alpha.txt"), "a").unwrap(); |
| 2307 | std::fs::write(cwd_root.join("alphabeta.txt"), "b").unwrap(); |
| 2308 | |
| 2309 | let ws = Workspace::with_cwd(ws_root.clone(), Some(cwd_root.clone())); |
| 2310 | let entries = ws.completions("alpha", 16); |
| 2311 | assert!( |
| 2312 | entries.iter().any(|e| e == "alpha.txt"), |
| 2313 | "expected workspace entry alpha.txt; got: {entries:?}", |
| 2314 | ); |
| 2315 | assert!( |
| 2316 | entries.iter().any(|e| e == "alphabeta.txt"), |
| 2317 | "expected cwd entry alphabeta.txt; got: {entries:?}", |
| 2318 | ); |
| 2319 | } |
| 2320 | |
| 2321 | #[test] |
| 2322 | fn workspace_completions_honor_configured_walk_depth() { |
| 2323 | let tmp = TempDir::new().unwrap(); |
| 2324 | // Sits at component depth 12, past the default walk depth (10) but |
| 2325 | // within the explicit deeper walk (16) below. |
| 2326 | let deep_dir = tmp.path().join("a/b/c/d/e/f/g/h/i/j/k"); |
| 2327 | std::fs::create_dir_all(&deep_dir).unwrap(); |
| 2328 | std::fs::write(deep_dir.join("target.txt"), "target").unwrap(); |
| 2329 | |
| 2330 | let default_ws = Workspace::with_cwd(tmp.path().to_path_buf(), None); |
| 2331 | let default_entries = default_ws.completions("target", 16); |
| 2332 | assert!( |
| 2333 | !default_entries |
| 2334 | .iter() |
| 2335 | .any(|entry| entry.ends_with("target.txt")), |
| 2336 | "default depth should keep very deep entries out of the hot completion path: {default_entries:?}", |
| 2337 | ); |
| 2338 | |
| 2339 | let deep_ws = Workspace::with_cwd_and_depth(tmp.path().to_path_buf(), None, 16); |
| 2340 | let deep_entries = deep_ws.completions("target", 16); |
| 2341 | assert!( |
| 2342 | deep_entries |
| 2343 | .iter() |
| 2344 | .any(|entry| entry.ends_with("target.txt")), |
| 2345 | "configured deeper walk should surface the nested file: {deep_entries:?}", |
| 2346 | ); |
| 2347 | |
| 2348 | let unlimited_ws = Workspace::with_cwd_and_depth(tmp.path().to_path_buf(), None, 0); |
| 2349 | let unlimited_entries = unlimited_ws.completions("target", 16); |
| 2350 | assert!( |
| 2351 | unlimited_entries |
| 2352 | .iter() |
| 2353 | .any(|entry| entry.ends_with("target.txt")), |
| 2354 | "depth 0 should disable the completion walk depth limit: {unlimited_entries:?}", |
| 2355 | ); |
| 2356 | } |
| 2357 | |
| 2358 | #[test] |
| 2359 | fn browser_completions_show_only_immediate_children() { |
| 2360 | let tmp = TempDir::new().unwrap(); |
| 2361 | std::fs::create_dir_all(tmp.path().join("src/nested")).unwrap(); |
| 2362 | std::fs::write(tmp.path().join("src/lib.rs"), "lib").unwrap(); |
| 2363 | std::fs::write(tmp.path().join("src/nested/deep.rs"), "deep").unwrap(); |
| 2364 | std::fs::write(tmp.path().join("README.md"), "readme").unwrap(); |
| 2365 | |
| 2366 | let ws = Workspace::with_cwd(tmp.path().to_path_buf(), None); |
| 2367 | |
| 2368 | let root_entries = ws.browser_completions("", 16); |
| 2369 | assert_eq!(root_entries, vec!["README.md", "src/"]); |
| 2370 | |
| 2371 | let src_entries = ws.browser_completions("src/", 16); |
| 2372 | assert_eq!(src_entries, vec!["src/lib.rs", "src/nested/"]); |
| 2373 | assert!( |
| 2374 | !src_entries.iter().any(|entry| entry.ends_with("deep.rs")), |
| 2375 | "browser mode must not walk past immediate children: {src_entries:?}", |
| 2376 | ); |
| 2377 | } |
| 2378 | |
| 2379 | #[test] |
| 2380 | fn browser_completions_hide_dot_entries_until_dot_query() { |
| 2381 | let tmp = TempDir::new().unwrap(); |
| 2382 | std::fs::create_dir_all(tmp.path().join(".agents")).unwrap(); |
| 2383 | std::fs::write(tmp.path().join(".env"), "secret-ish fixture").unwrap(); |
| 2384 | std::fs::write(tmp.path().join("app.rs"), "app").unwrap(); |
| 2385 | |
| 2386 | let ws = Workspace::with_cwd(tmp.path().to_path_buf(), None); |
| 2387 | |
| 2388 | let default_entries = ws.browser_completions("", 16); |
| 2389 | assert_eq!(default_entries, vec!["app.rs"]); |
| 2390 | |
| 2391 | let dot_entries = ws.browser_completions(".", 16); |
| 2392 | assert_eq!(dot_entries, vec![".agents/", ".env"]); |
| 2393 | } |
| 2394 | |
| 2395 | #[test] |
| 2396 | fn browser_completions_reject_path_escape_segments() { |
| 2397 | let tmp = TempDir::new().unwrap(); |
| 2398 | let workspace = tmp.path().join("workspace"); |
| 2399 | let sibling = tmp.path().join("outside"); |
| 2400 | std::fs::create_dir_all(&workspace).unwrap(); |
| 2401 | std::fs::create_dir_all(&sibling).unwrap(); |
| 2402 | std::fs::write(workspace.join("inside.rs"), "inside").unwrap(); |
| 2403 | std::fs::write(sibling.join("secret.rs"), "outside").unwrap(); |
| 2404 | |
| 2405 | let ws = Workspace::with_cwd(workspace, None); |
| 2406 | |
| 2407 | assert_eq!(ws.browser_completions("", 16), vec!["inside.rs"]); |
| 2408 | assert!( |
| 2409 | ws.browser_completions("../", 16).is_empty(), |
| 2410 | "browser mode must not list workspace siblings", |
| 2411 | ); |
| 2412 | assert!( |
| 2413 | ws.browser_completions("../outside", 16).is_empty(), |
| 2414 | "browser mode must not complete names from outside the workspace", |
| 2415 | ); |
| 2416 | } |
| 2417 | |
| 2418 | #[test] |
| 2419 | fn workspace_completions_surface_explicit_hidden_and_ignored_paths() { |
| 2420 | let tmp = TempDir::new().unwrap(); |
| 2421 | std::fs::write(tmp.path().join(".gitignore"), ".deepseek/\n.generated/\n").unwrap(); |
| 2422 | std::fs::write( |
| 2423 | tmp.path().join(".deepseekignore"), |
| 2424 | ".generated/specs/secrets.env\n", |
| 2425 | ) |
| 2426 | .unwrap(); |
| 2427 | let deepseek_commands = tmp.path().join(".deepseek").join("commands"); |
| 2428 | let generated_specs = tmp.path().join(".generated").join("specs"); |
| 2429 | std::fs::create_dir_all(&deepseek_commands).unwrap(); |
| 2430 | std::fs::create_dir_all(&generated_specs).unwrap(); |
| 2431 | std::fs::write(deepseek_commands.join("start-task.md"), "start").unwrap(); |
| 2432 | std::fs::write(generated_specs.join("device-layout.md"), "layout").unwrap(); |
| 2433 | std::fs::write(generated_specs.join("secrets.env"), "secret").unwrap(); |
| 2434 | |
| 2435 | let ws = Workspace::with_cwd(tmp.path().to_path_buf(), Some(tmp.path().to_path_buf())); |
| 2436 | |
| 2437 | let start_entries = ws.completions(".deepseek/commands", 16); |
| 2438 | assert!( |
| 2439 | start_entries |
| 2440 | .iter() |
| 2441 | .any(|e| e == ".deepseek/commands/start-task.md"), |
| 2442 | "expected explicitly addressed hidden command file in completions: {start_entries:?}", |
| 2443 | ); |
| 2444 | |
| 2445 | let generated_entries = ws.completions(".generated/specs", 16); |
| 2446 | assert!( |
| 2447 | generated_entries |
| 2448 | .iter() |
| 2449 | .any(|e| e == ".generated/specs/device-layout.md"), |
| 2450 | "expected explicitly addressed ignored user folder in completions: {generated_entries:?}", |
| 2451 | ); |
| 2452 | assert!( |
| 2453 | !generated_entries |
| 2454 | .iter() |
| 2455 | .any(|e| e == ".generated/specs/secrets.env"), |
| 2456 | ".deepseekignore entries must not be reintroduced by local fallback: {generated_entries:?}", |
| 2457 | ); |
| 2458 | } |
| 2459 | |
| 2460 | #[test] |
| 2461 | fn workspace_completions_skip_hidden_worktrees_and_build_bulk() { |
| 2462 | let tmp = TempDir::new().unwrap(); |
| 2463 | let root = tmp.path(); |
| 2464 | std::fs::write(root.join(".gitignore"), ".worktrees/\n.generated/\n").unwrap(); |
| 2465 | |
| 2466 | std::fs::create_dir_all(root.join(".worktrees/release/src")).unwrap(); |
| 2467 | std::fs::write( |
| 2468 | root.join(".worktrees/release/src/worktree-only.rs"), |
| 2469 | "fn main() {}", |
| 2470 | ) |
| 2471 | .unwrap(); |
| 2472 | std::fs::create_dir_all(root.join(".worktrees/release/target/debug")).unwrap(); |
| 2473 | std::fs::write( |
| 2474 | root.join(".worktrees/release/target/debug/generated.o"), |
| 2475 | "object", |
| 2476 | ) |
| 2477 | .unwrap(); |
| 2478 | |
| 2479 | std::fs::create_dir_all(root.join(".claude/worktrees/agent/src")).unwrap(); |
| 2480 | std::fs::write( |
| 2481 | root.join(".claude/worktrees/agent/src/agent-only.md"), |
| 2482 | "agent note", |
| 2483 | ) |
| 2484 | .unwrap(); |
| 2485 | std::fs::create_dir_all(root.join(".claude/commands")).unwrap(); |
| 2486 | std::fs::write(root.join(".claude/commands/keep.md"), "command").unwrap(); |
| 2487 | |
| 2488 | std::fs::create_dir_all(root.join(".generated/specs")).unwrap(); |
| 2489 | std::fs::write(root.join(".generated/specs/device-layout.md"), "layout").unwrap(); |
| 2490 | |
| 2491 | let ws = Workspace::with_cwd(root.to_path_buf(), Some(root.to_path_buf())); |
| 2492 | |
| 2493 | let worktree_entries = ws.completions(".worktrees", 32); |
| 2494 | assert!( |
| 2495 | worktree_entries |
| 2496 | .iter() |
| 2497 | .all(|entry| !entry.starts_with(".worktrees/")), |
| 2498 | "hidden release worktrees must stay out of completions: {worktree_entries:?}", |
| 2499 | ); |
| 2500 | |
| 2501 | let claude_worktree_entries = ws.completions(".claude/worktrees", 32); |
| 2502 | assert!( |
| 2503 | claude_worktree_entries |
| 2504 | .iter() |
| 2505 | .all(|entry| !entry.starts_with(".claude/worktrees/")), |
| 2506 | ".claude/worktrees must stay out of completions: {claude_worktree_entries:?}", |
| 2507 | ); |
| 2508 | |
| 2509 | let generated_entries = ws.completions(".generated/specs", 32); |
| 2510 | assert!( |
| 2511 | generated_entries |
| 2512 | .iter() |
| 2513 | .any(|entry| entry == ".generated/specs/device-layout.md"), |
| 2514 | "explicit user-generated hidden folders should still complete: {generated_entries:?}", |
| 2515 | ); |
| 2516 | |
| 2517 | let command_entries = ws.completions(".claude/commands", 32); |
| 2518 | assert!( |
| 2519 | command_entries |
| 2520 | .iter() |
| 2521 | .any(|entry| entry == ".claude/commands/keep.md"), |
| 2522 | "normal .claude command files should still complete: {command_entries:?}", |
| 2523 | ); |
| 2524 | |
| 2525 | assert!( |
| 2526 | ws.resolve("worktree-only.rs").is_err(), |
| 2527 | "fuzzy resolution must not index files from hidden release worktrees" |
| 2528 | ); |
| 2529 | assert!( |
| 2530 | ws.resolve("agent-only.md").is_err(), |
| 2531 | "fuzzy resolution must not index files from .claude/worktrees" |
| 2532 | ); |
| 2533 | assert!(ws.resolve("keep.md").is_ok()); |
| 2534 | } |
| 2535 | |
| 2536 | #[test] |
| 2537 | fn fuzzy_index_resolves_hidden_and_ignored_files_except_deepseekignored() { |
| 2538 | let tmp = TempDir::new().unwrap(); |
| 2539 | std::fs::write(tmp.path().join(".gitignore"), ".generated/\n").unwrap(); |
| 2540 | std::fs::write( |
| 2541 | tmp.path().join(".deepseekignore"), |
| 2542 | ".generated/specs/secrets.env\n", |
| 2543 | ) |
| 2544 | .unwrap(); |
| 2545 | let generated_specs = tmp.path().join(".generated").join("specs"); |
| 2546 | std::fs::create_dir_all(&generated_specs).unwrap(); |
| 2547 | std::fs::write(generated_specs.join("device-layout.md"), "layout").unwrap(); |
| 2548 | std::fs::write(generated_specs.join("secrets.env"), "secret").unwrap(); |
| 2549 | |
| 2550 | let ws = Workspace::with_cwd(tmp.path().to_path_buf(), None); |
| 2551 | let resolved = ws.resolve("device-layout.md").unwrap(); |
| 2552 | |
| 2553 | assert!(resolved.ends_with(".generated/specs/device-layout.md")); |
| 2554 | assert!( |
| 2555 | ws.resolve("secrets.env").is_err(), |
| 2556 | "basename fuzzy resolution must honor .deepseekignore" |
| 2557 | ); |
| 2558 | assert!( |
| 2559 | ws.resolve(".generated/specs/secrets.env").is_ok(), |
| 2560 | "exact user-specified paths should still resolve" |
| 2561 | ); |
| 2562 | } |
| 2563 | |
| 2564 | #[test] |
| 2565 | fn fuzzy_index_finds_files_and_directories() { |
| 2566 | let tmp = TempDir::new().unwrap(); |
| 2567 | std::fs::create_dir_all(tmp.path().join("a/b/target_dir")).unwrap(); |
| 2568 | std::fs::write(tmp.path().join("a/b/needle.rs"), "fn main(){}").unwrap(); |
| 2569 | |
| 2570 | let ws = Workspace::with_cwd(tmp.path().to_path_buf(), None); |
| 2571 | |
| 2572 | // Basename-only mention triggers fuzzy fallback for both files and dirs. |
| 2573 | let f = ws.resolve("needle.rs").unwrap(); |
| 2574 | assert!(f.ends_with("a/b/needle.rs")); |
| 2575 | let d = ws.resolve("target_dir").unwrap(); |
| 2576 | assert!(d.ends_with("a/b/target_dir")); |
| 2577 | |
| 2578 | // Index was populated exactly once (subsequent lookups reuse it). |
| 2579 | assert!(ws.file_index.get().is_some()); |
| 2580 | } |
| 2581 | |
| 2582 | /// Regression: `@`-mention completion must discover files inside |
| 2583 | /// `.deepseek/`, `.cursor/`, `.claude/`, `.agents/` even when |
| 2584 | /// those directories are excluded by `.gitignore` (or `.ignore`). |
| 2585 | /// The `discovery_walk_builder` override un-ignores them. |
| 2586 | #[test] |
| 2587 | fn completions_discovers_files_inside_gitignored_dot_dirs() { |
| 2588 | let tmp = TempDir::new().unwrap(); |
| 2589 | let root = tmp.path(); |
| 2590 | |
| 2591 | // `.ignore` works even outside a git repo; use it to simulate |
| 2592 | // a project that gitignores its AI-tool dot-directories. |
| 2593 | std::fs::write( |
| 2594 | root.join(".ignore"), |
| 2595 | ".deepseek/\n.cursor/\n.claude/\n.agents/\n", |
| 2596 | ) |
| 2597 | .unwrap(); |
| 2598 | |
| 2599 | // Create files inside each dot-dir. |
| 2600 | std::fs::create_dir_all(root.join(".deepseek/commands")).unwrap(); |
| 2601 | std::fs::write(root.join(".deepseek/commands/build.md"), "build cmd").unwrap(); |
| 2602 | std::fs::create_dir_all(root.join(".cursor/commands")).unwrap(); |
| 2603 | std::fs::write(root.join(".cursor/commands/run.md"), "run cmd").unwrap(); |
| 2604 | std::fs::create_dir_all(root.join(".claude/commands")).unwrap(); |
| 2605 | std::fs::write(root.join(".claude/commands/test.md"), "test cmd").unwrap(); |
| 2606 | std::fs::create_dir_all(root.join(".agents/skills/example")).unwrap(); |
| 2607 | std::fs::write( |
| 2608 | root.join(".agents/skills/example/SKILL.md"), |
| 2609 | "name: example\n", |
| 2610 | ) |
| 2611 | .unwrap(); |
| 2612 | |
| 2613 | let ws = Workspace::with_cwd(root.to_path_buf(), None); |
| 2614 | |
| 2615 | // Completions should find entries inside the dot-dirs. |
| 2616 | { |
| 2617 | let entries = ws.completions("build", 16); |
| 2618 | assert!( |
| 2619 | entries.iter().any(|e| e.contains("build.md")), |
| 2620 | "expected build.md in completions although .deepseek/ is ignored; got: {entries:?}" |
| 2621 | ); |
| 2622 | } |
| 2623 | { |
| 2624 | let entries = ws.completions("run", 16); |
| 2625 | assert!( |
| 2626 | entries.iter().any(|e| e.contains("run.md")), |
| 2627 | "expected run.md from .cursor/; got: {entries:?}" |
| 2628 | ); |
| 2629 | } |
| 2630 | { |
| 2631 | let entries = ws.completions("test", 16); |
| 2632 | assert!( |
| 2633 | entries.iter().any(|e| e.contains("test.md")), |
| 2634 | "expected test.md from .claude/; got: {entries:?}" |
| 2635 | ); |
| 2636 | } |
| 2637 | |
| 2638 | // Fuzzy resolution should also work. |
| 2639 | let f = ws.resolve("build.md").unwrap(); |
| 2640 | assert!(f.ends_with("build.md")); |
| 2641 | let f2 = ws.resolve("SKILL.md").unwrap(); |
| 2642 | assert!(f2.ends_with("SKILL.md")); |
| 2643 | } |
| 2644 | |
| 2645 | /// Regression: the dot-dir walk must NOT index `.deepseek/snapshots/`, |
| 2646 | /// which is the snapshot side repo that can grow to hundreds of GB. |
| 2647 | /// Indexing it would re-create the same OOM/hang that #1112 was built |
| 2648 | /// to prevent. |
| 2649 | #[test] |
| 2650 | fn dot_dir_walk_excludes_snapshot_side_repo() { |
| 2651 | let tmp = TempDir::new().unwrap(); |
| 2652 | let root = tmp.path(); |
| 2653 | |
| 2654 | // Create a snapshot-like directory tree. |
| 2655 | std::fs::create_dir_all(root.join(".deepseek/snapshots/deadbeef/deadbeef/.git/objects")) |
| 2656 | .unwrap(); |
| 2657 | std::fs::write( |
| 2658 | root.join(".deepseek/snapshots/deadbeef/deadbeef/.git/objects/snapshot.pack"), |
| 2659 | b"fake pack data", |
| 2660 | ) |
| 2661 | .unwrap(); |
| 2662 | // Also create a legitimate file in .deepseek/ that should be found. |
| 2663 | std::fs::create_dir_all(root.join(".deepseek/commands")).unwrap(); |
| 2664 | std::fs::write(root.join(".deepseek/commands/build.md"), "build cmd").unwrap(); |
| 2665 | |
| 2666 | let ws = Workspace::with_cwd(root.to_path_buf(), None); |
| 2667 | |
| 2668 | // Searching for "build" must find build.md. |
| 2669 | let entries = ws.completions("build", 16); |
| 2670 | assert!( |
| 2671 | entries.iter().any(|e| e.contains("build.md")), |
| 2672 | "build.md must still be found; got: {entries:?}" |
| 2673 | ); |
| 2674 | // Searching for "snapshot" must NOT return snapshot files. |
| 2675 | let snap_entries = ws.completions("snapshot", 16); |
| 2676 | assert!( |
| 2677 | !snap_entries.iter().any(|e| e.contains("snapshot")), |
| 2678 | "snapshot files must NOT appear in completions; got: {snap_entries:?}" |
| 2679 | ); |
| 2680 | |
| 2681 | // Fuzzy index must also exclude snapshots. |
| 2682 | let f = ws.resolve("build.md").unwrap(); |
| 2683 | assert!(f.ends_with("build.md")); |
| 2684 | // snapshot.pack should NOT resolve. |
| 2685 | let result = ws.resolve("snapshot.pack"); |
| 2686 | assert!( |
| 2687 | result.is_err(), |
| 2688 | "snapshot.pack must not resolve via fuzzy index" |
| 2689 | ); |
| 2690 | } |
| 2691 | |
| 2692 | /// Regression for #1921 — typing `@/` (or `@.`) must NOT trigger the |
| 2693 | /// `local_reference_paths` walk, which scans up to |
| 2694 | /// `LOCAL_REFERENCE_SCAN_LIMIT` paths on the UI thread. On WSL2 with a |
| 2695 | /// `/mnt/c/...` workspace this hangs the composer for seconds to minutes. |
| 2696 | #[test] |
| 2697 | fn should_try_local_reference_completion_skips_bare_separators_and_dots() { |
| 2698 | // The trigger gate must reject bare separators/dots. |
| 2699 | assert!(!should_try_local_reference_completion("/")); |
| 2700 | assert!(!should_try_local_reference_completion("\\")); |
| 2701 | assert!(!should_try_local_reference_completion(".")); |
| 2702 | assert!(!should_try_local_reference_completion("..")); |
| 2703 | // Empty string was already rejected; keep that. |
| 2704 | assert!(!should_try_local_reference_completion("")); |
| 2705 | |
| 2706 | // Actionable references must still trigger. |
| 2707 | assert!(should_try_local_reference_completion("./foo")); |
| 2708 | assert!(should_try_local_reference_completion("../bar")); |
| 2709 | assert!(should_try_local_reference_completion(".env")); |
| 2710 | assert!(should_try_local_reference_completion("path/")); |
| 2711 | assert!(should_try_local_reference_completion("path/to/file")); |
| 2712 | assert!(should_try_local_reference_completion("/usr")); |
| 2713 | } |
| 2714 | |
| 2715 | #[test] |
| 2716 | fn cached_candidates_rank_like_live_completions() { |
| 2717 | // #3757: the composer caches one full candidate walk and ranks per |
| 2718 | // keystroke in memory; the ranked result must match what the live |
| 2719 | // walk would return for non-path-like needles. |
| 2720 | let tmp = TempDir::new().unwrap(); |
| 2721 | let root = tmp.path(); |
| 2722 | std::fs::create_dir_all(root.join("src")).unwrap(); |
| 2723 | std::fs::write(root.join("src/main.rs"), "fn main() {}").unwrap(); |
| 2724 | std::fs::write(root.join("src/mention.rs"), "// m").unwrap(); |
| 2725 | std::fs::write(root.join("README.md"), "# readme").unwrap(); |
| 2726 | std::fs::write(root.join("Makefile"), "all:").unwrap(); |
| 2727 | |
| 2728 | let ws = Workspace::with_cwd(root.to_path_buf(), None); |
| 2729 | let candidates = ws.completion_candidates(); |
| 2730 | assert!( |
| 2731 | candidates.iter().any(|c| c == "src/main.rs"), |
| 2732 | "{candidates:?}" |
| 2733 | ); |
| 2734 | |
| 2735 | for needle in ["ma", "readme", "men", ""] { |
| 2736 | let live = ws.completions(needle, 16); |
| 2737 | let ranked = rank_completion_candidates(&candidates, needle, 16); |
| 2738 | assert_eq!(ranked, live, "needle {needle:?}"); |
| 2739 | } |
| 2740 | |
| 2741 | // Limit truncation applies after prefix/substring bucketing. |
| 2742 | let ranked = rank_completion_candidates(&candidates, "ma", 1); |
| 2743 | assert_eq!(ranked.len(), 1); |
| 2744 | assert!(ranked[0].to_lowercase().starts_with("ma"), "{ranked:?}"); |
| 2745 | } |
| 2746 | |
| 2747 | #[test] |
| 2748 | fn background_completion_discovery_is_hard_capped_on_large_trees() { |
| 2749 | let tmp = TempDir::new().unwrap(); |
| 2750 | for i in 0..256 { |
| 2751 | std::fs::write(tmp.path().join(format!("candidate_{i:03}.rs")), "x").unwrap(); |
| 2752 | } |
| 2753 | let ws = Workspace::with_cwd(tmp.path().to_path_buf(), None); |
| 2754 | let never_cancelled = || false; |
| 2755 | |
| 2756 | let candidates = ws.completion_discovery_candidates(32, &never_cancelled); |
| 2757 | |
| 2758 | assert_eq!( |
| 2759 | candidates.len(), |
| 2760 | 32, |
| 2761 | "the background cache must stop at its hard candidate limit" |
| 2762 | ); |
| 2763 | } |
| 2764 | |
| 2765 | /// Regression for #1921 — `completions("/", N)` must return without |
| 2766 | /// invoking `local_reference_paths`, even on a workspace large enough |
| 2767 | /// to expose the original 4096-path walk. We can't assert "doesn't |
| 2768 | /// touch the disk", but we can assert the call completes promptly and |
| 2769 | /// stays within the requested limit. |
| 2770 | #[test] |
| 2771 | fn completions_for_bare_slash_does_not_trigger_local_reference_walk() { |
| 2772 | let tmp = TempDir::new().unwrap(); |
| 2773 | let root = tmp.path(); |
| 2774 | // Lay out enough files that a runaway walk would be visibly slow, |
| 2775 | // but the bounded path returns near-instantly. Depth-1 entries are |
| 2776 | // enough; we don't need to stress the filesystem. |
| 2777 | for i in 0..40 { |
| 2778 | std::fs::write(root.join(format!("file_{i}.txt")), "x").unwrap(); |
| 2779 | } |
| 2780 | let ws = Workspace::with_cwd(root.to_path_buf(), None); |
| 2781 | |
| 2782 | let start = std::time::Instant::now(); |
| 2783 | let entries = ws.completions("/", 64); |
| 2784 | let elapsed = start.elapsed(); |
| 2785 | |
| 2786 | // Behavioral assertions: |
| 2787 | // 1. The call returns within a generous bound. Real freezes on |
| 2788 | // WSL2 were tens of seconds; a 2s budget is comfortable for a |
| 2789 | // 40-file tmp dir on any CI host. |
| 2790 | assert!( |
| 2791 | elapsed < std::time::Duration::from_secs(2), |
| 2792 | "completions(\"/\") took too long: {elapsed:?} (likely re-introduced #1921)" |
| 2793 | ); |
| 2794 | // 2. Results stay within the requested cap. |
| 2795 | assert!(entries.len() <= 64); |
| 2796 | } |
| 2797 | } |
| 2798 |