Skip to main content

codewhale_runtime/
working_set.rs

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