rho-coding-agent 2.9.0

A fast Rust agent harness with a small footprint and opinionated defaults
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use std::{
    ops::ControlFlow,
    path::{Path, PathBuf},
    sync::Arc,
    time::{Duration, Instant},
};

use rho_tools::workspace_walk::{
    visit_files, HiddenFiles, WalkLimits, WalkOptions, WalkStop, MAX_ENTRIES_SCANNED,
};

use super::picker::fuzzy_match_score;
use crate::paths::home_dir;

const MAX_FILE_PATHS: usize = 100_000;
const FILE_DISCOVERY_TIMEOUT: Duration = Duration::from_millis(750);
const WORKSPACE_PATH_CACHE_TTL: Duration = Duration::from_secs(2);
/// Keep navigation bounded so weak queries stay interactive in large repos.
const MAX_RANKED_FILE_MATCHES: usize = 500;

/// Where a path palette token came from, and so how a picked path is written.
///
/// A mention is written back as `@path`; a shell word is written back as a
/// quoted path the shell can split safely. The shell source never offers MCP
/// resources because a shell command cannot read one.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum PathTokenSource {
    Mention,
    ShellWord,
}

/// The path-palette token under the cursor: which char range an accepted
/// row replaces, and the query to rank paths against.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct FileMention {
    pub(super) start: usize,
    pub(super) end: usize,
    pub(super) query: String,
    pub(super) source: PathTokenSource,
}

/// The directory a `dir/residual` query names, resolved, plus the prefix a
/// candidate found inside it is displayed and inserted with.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct DirectoryScope {
    pub(super) root: PathBuf,
    pub(super) display_prefix: String,
}

/// Workspace paths discovered for `@` mentions, plus whether the walk finished.
#[derive(Clone, Debug)]
pub(super) struct DiscoveredFilePaths {
    pub(super) paths: Arc<Vec<String>>,
    /// True when discovery stopped early (deadline, entry cap, or result cap).
    pub(super) incomplete: bool,
}

/// One row the `@` palette can offer.
///
/// A mention can name something in the workspace or something a connected MCP
/// server holds. The two are told apart here rather than by inspecting a string,
/// because selecting them does entirely different things: one writes a path into
/// the message, the other pulls content into it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum FilePaletteEntry {
    WorkspaceFile(String),
    McpResource(crate::tools::mcp::McpResource),
}

/// The `@` palette's rows: matched server resources, then workspace paths.
///
/// The two sources stay in the lists they arrived in, and a row is built only
/// when something asks for it. Merging them into one vector of entries would
/// cost a heap allocation per path every time the query changes, and a bare `@`
/// on a large repository offers a hundred thousand paths that nobody scrolls to.
/// The workspace list here is the discovery cache's own `Arc`, shared rather
/// than copied.
#[derive(Clone, Debug)]
pub(super) struct FilePaletteMatches {
    resources: Arc<Vec<crate::tools::mcp::McpResource>>,
    paths: Arc<Vec<String>>,
    /// True when workspace discovery stopped early.
    pub(super) incomplete: bool,
    /// How an accepted row is written back into the composer.
    pub(super) source: PathTokenSource,
}

impl FilePaletteMatches {
    pub(super) fn empty() -> Self {
        Self {
            resources: Arc::new(Vec::new()),
            paths: Arc::new(Vec::new()),
            incomplete: false,
            source: PathTokenSource::Mention,
        }
    }

    /// Workspace paths only, for a token the shell will read.
    pub(super) fn shell_words(discovered: DiscoveredFilePaths) -> Self {
        Self {
            resources: Arc::new(Vec::new()),
            paths: discovered.paths,
            incomplete: discovered.incomplete,
            source: PathTokenSource::ShellWord,
        }
    }

    pub(super) fn len(&self) -> usize {
        self.resources.len() + self.paths.len()
    }

    pub(super) fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The row at `index`, counting resources first.
    pub(super) fn get(&self, index: usize) -> Option<FilePaletteEntry> {
        if let Some(resource) = self.resources.get(index) {
            return Some(FilePaletteEntry::McpResource(resource.clone()));
        }
        self.paths
            .get(index - self.resources.len())
            .cloned()
            .map(FilePaletteEntry::WorkspaceFile)
    }

    /// The rows from `start`, at most `count` of them, for a scrolled view.
    pub(super) fn rows(
        &self,
        start: usize,
        count: usize,
    ) -> impl Iterator<Item = (usize, FilePaletteEntry)> + '_ {
        (start..self.len())
            .take(count)
            .filter_map(|index| Some((index, self.get(index)?)))
    }
}

/// Rank the resources connected servers offer, then put them ahead of the
/// workspace files.
///
/// Resources lead because a workspace commonly holds thousands of files and a
/// server offers a handful. Appended, they would sit below a screenful of paths
/// and never be seen. The workspace order itself is left exactly as discovery
/// produced it.
///
/// Resources are matched on their URI, which is also what the palette shows and
/// what a template inserts, so what a person types lines up with what they read.
pub(super) fn file_palette_matches(
    discovered: DiscoveredFilePaths,
    resources: &[crate::tools::mcp::McpResource],
    query: &str,
) -> FilePaletteMatches {
    let keys = resources
        .iter()
        .map(|resource| resource.uri.as_str())
        .collect::<Vec<_>>();
    let matched = fuzzy_matching_indexes(&keys, query)
        .into_iter()
        .map(|index| resources[index].clone())
        .collect::<Vec<_>>();
    FilePaletteMatches {
        resources: Arc::new(matched),
        paths: discovered.paths,
        incomplete: discovered.incomplete,
        source: PathTokenSource::Mention,
    }
}

impl DiscoveredFilePaths {
    /// A listing that was not cut short.
    pub(super) fn complete(paths: Vec<String>) -> Self {
        Self {
            paths: Arc::new(paths),
            incomplete: false,
        }
    }

    pub(super) fn as_slice(&self) -> &[String] {
        self.paths.as_slice()
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct FilePathCacheKey {
    root: PathBuf,
    include_hidden: bool,
}

struct WorkspacePathCacheInner {
    key: FilePathCacheKey,
    discovered: DiscoveredFilePaths,
    cached_at: Instant,
}

/// Query-independent workspace walk, keyed by `(root, include_hidden)`.
///
/// The `@` match cache is query-keyed; this layer is not, so typing `@s` then
/// `@sr` reuses one walk for the TTL instead of rediscovering the tree.
#[derive(Default)]
pub(super) struct WorkspacePathCache {
    inner: Option<WorkspacePathCacheInner>,
}

impl WorkspacePathCache {
    fn file_paths_for_root(&mut self, root: &Path, include_hidden: bool) -> DiscoveredFilePaths {
        let root = normalize_existing_dir(root).unwrap_or_else(|| root.to_path_buf());
        let key = FilePathCacheKey {
            root: root.clone(),
            include_hidden,
        };
        if let Some(cache) = self.inner.as_ref() {
            if cache.key == key && cache.cached_at.elapsed() < WORKSPACE_PATH_CACHE_TTL {
                return cache.discovered.clone();
            }
        }

        let mut discovered = discover_file_paths(&root, include_hidden);
        sort_paths_for_display(Arc::make_mut(&mut discovered.paths).as_mut_slice());
        self.inner = Some(WorkspacePathCacheInner {
            key,
            discovered: discovered.clone(),
            cached_at: Instant::now(),
        });
        discovered
    }

    #[cfg(test)]
    pub(super) fn expire(&mut self) {
        if let Some(cache) = self.inner.as_mut() {
            cache.cached_at = Instant::now() - WORKSPACE_PATH_CACHE_TTL;
        }
    }
}

/// The whitespace-delimited word around `cursor`, in char offsets.
///
/// `head` is the part before the cursor; it is what palettes match on, while
/// `start..end` (which also spans any tail after the cursor) is what an
/// accepted row replaces. Works on slices of `input` instead of collecting
/// characters: the render path calls this several times per frame, so nothing
/// larger than the query itself is ever copied.
#[derive(Clone, Debug, PartialEq, Eq)]
struct CursorWord<'a> {
    start: usize,
    end: usize,
    head: &'a str,
}

fn word_at_cursor(input: &str, cursor: usize) -> CursorWord<'_> {
    let cursor_byte = input
        .char_indices()
        .nth(cursor)
        .map_or(input.len(), |(byte, _)| byte);
    let (before, after) = input.split_at(cursor_byte);
    let head = before
        .rsplit(char::is_whitespace)
        .next()
        .unwrap_or_default();
    let tail = after.split(char::is_whitespace).next().unwrap_or_default();
    CursorWord {
        start: before.chars().count() - head.chars().count(),
        end: before.chars().count() + tail.chars().count(),
        head,
    }
}

/// The `@query` token under the cursor, if any.
pub(super) fn active_file_mention(input: &str, cursor: usize) -> Option<FileMention> {
    let word = word_at_cursor(input, cursor);
    let query = word.head.strip_prefix('@')?;
    if query.contains('@') {
        return None;
    }
    Some(FileMention {
        start: word.start,
        end: word.end,
        query: query.to_string(),
        source: PathTokenSource::Mention,
    })
}

/// The bare word under the cursor as a shell path token, when it still starts
/// at `anchor`. The anchor is where Tab opened completion; once the cursor
/// moves to another word the token, and so the palette, is gone.
pub(super) fn anchored_shell_word(
    input: &str,
    cursor: usize,
    anchor: usize,
) -> Option<FileMention> {
    let word = shell_word_at_cursor(input, cursor);
    (word.start == anchor).then_some(word)
}

#[path = "shell_word.rs"]
mod shell_word;
pub(super) use shell_word::shell_word_at_cursor;

#[cfg(test)]
pub(super) fn matching_file_paths(cwd: &Path, query: &str) -> DiscoveredFilePaths {
    matching_file_paths_cached(cwd, query, &mut WorkspacePathCache::default())
}

pub(super) fn matching_file_paths_cached(
    cwd: &Path,
    query: &str,
    cache: &mut WorkspacePathCache,
) -> DiscoveredFilePaths {
    matching_file_paths_with_home(cwd, query, home_dir().as_deref(), cache)
}

#[cfg(test)]
pub(super) fn matching_file_paths_with_home_for_test(
    cwd: &Path,
    query: &str,
    home: Option<&Path>,
) -> DiscoveredFilePaths {
    matching_file_paths_with_home(cwd, query, home, &mut WorkspacePathCache::default())
}

fn matching_file_paths_with_home(
    cwd: &Path,
    query: &str,
    home: Option<&Path>,
    cache: &mut WorkspacePathCache,
) -> DiscoveredFilePaths {
    let query = query.trim();
    if let Some((scope, residual)) = directory_scope(cwd, query, home) {
        let include_hidden = residual_includes_hidden(&residual);
        let discovered = cache.file_paths_for_root(&scope.root, include_hidden);
        let matches = if residual.is_empty() {
            discovered.as_slice().to_vec()
        } else {
            fuzzy_matching_paths(discovered.as_slice(), &residual)
        };
        return DiscoveredFilePaths {
            paths: Arc::new(
                matches
                    .into_iter()
                    .map(|path| format!("{}{path}", scope.display_prefix))
                    .collect(),
            ),
            incomplete: discovered.incomplete,
        };
    }

    let include_hidden = residual_includes_hidden(query);
    let discovered = cache.file_paths_for_root(cwd, include_hidden);
    if query.is_empty() {
        return discovered;
    }
    DiscoveredFilePaths {
        paths: Arc::new(fuzzy_matching_paths(discovered.as_slice(), query)),
        incomplete: discovered.incomplete,
    }
}

#[cfg(test)]
pub(super) fn workspace_file_paths(cwd: &Path) -> DiscoveredFilePaths {
    WorkspacePathCache::default().file_paths_for_root(cwd, /*include_hidden*/ false)
}

fn residual_includes_hidden(residual: &str) -> bool {
    residual.split('/').any(|part| part.starts_with('.'))
}

/// Split a `dir/residual` query into the existing directory it names and the
/// residual to match inside it. `None` when the query has no `/` (so it is
/// matched against `cwd` with no prefix) or the directory does not exist.
///
/// A leading `/` is the filesystem root; `~` and `~/` are `home`; anything
/// else is relative to `cwd`.
pub(super) fn directory_scope(
    cwd: &Path,
    query: &str,
    home: Option<&Path>,
) -> Option<(DirectoryScope, String)> {
    if query.is_empty() || !query.contains('/') {
        return None;
    }

    let (directory_query, residual) = if query.ends_with('/') {
        (query.trim_end_matches('/'), "")
    } else {
        let (directory, residual) = query.rsplit_once('/')?;
        (directory, residual)
    };

    // Bare "@/" is treated as filesystem root scope.
    let directory_query = if directory_query.is_empty() {
        "/"
    } else {
        directory_query
    };

    let root = resolve_user_path(cwd, directory_query, home);
    let root = normalize_existing_dir(&root)?;
    let display_prefix = directory_display_prefix(directory_query);
    Some((
        DirectoryScope {
            root,
            display_prefix,
        },
        residual.to_string(),
    ))
}

fn resolve_user_path(cwd: &Path, path: &str, home: Option<&Path>) -> PathBuf {
    if path == "~" {
        return home
            .map(Path::to_path_buf)
            .unwrap_or_else(|| PathBuf::from("~"));
    }
    if let Some(rest) = path.strip_prefix("~/") {
        return home
            .map(|home| home.join(rest))
            .unwrap_or_else(|| PathBuf::from(path));
    }

    let candidate = PathBuf::from(path);
    if candidate.is_absolute() {
        candidate
    } else {
        cwd.join(candidate)
    }
}

fn normalize_existing_dir(path: &Path) -> Option<PathBuf> {
    let path = path.canonicalize().ok()?;
    path.is_dir().then_some(path)
}

fn directory_display_prefix(directory_query: &str) -> String {
    if directory_query == "/" {
        "/".into()
    } else {
        format!("{directory_query}/")
    }
}

/// Case-insensitive, then byte order, so listings read the way a file
/// browser sorts them and equal-ignoring-case names still have one order.
pub(super) fn sort_paths_for_display(paths: &mut [String]) {
    paths.sort_by(|left, right| {
        left.to_ascii_lowercase()
            .cmp(&right.to_ascii_lowercase())
            .then_with(|| left.cmp(right))
    });
}

#[cfg(test)]
fn path_to_unix_string(path: &Path) -> String {
    use std::path::Component;

    let mut parts = Vec::new();
    for component in path.components() {
        match component {
            Component::RootDir => parts.push(String::new()),
            Component::Normal(part) => parts.push(part.to_string_lossy().into_owned()),
            Component::CurDir => {}
            Component::ParentDir => parts.push(String::from("..")),
            Component::Prefix(prefix) => {
                parts.push(prefix.as_os_str().to_string_lossy().into_owned())
            }
        }
    }
    if parts.len() == 1 && parts[0].is_empty() {
        "/".into()
    } else {
        parts.join("/")
    }
}

pub(super) fn fuzzy_matching_paths(paths: &[String], query: &str) -> Vec<String> {
    let keys = paths.iter().map(String::as_str).collect::<Vec<_>>();
    fuzzy_matching_indexes(&keys, query)
        .into_iter()
        .map(|index| paths[index].clone())
        .collect()
}

/// Rank `keys` against `query`, best first, returning the positions that
/// survived. Callers that carry more than a string per row map the positions
/// back onto their own rows.
///
/// An empty query keeps every key in its original order, which is what makes a
/// bare `@` list the workspace as discovered.
fn fuzzy_matching_indexes(keys: &[&str], query: &str) -> Vec<usize> {
    let query = query.trim();
    if query.is_empty() {
        return (0..keys.len()).collect();
    }

    let mut matches = keys
        .iter()
        .enumerate()
        .filter_map(|(index, key)| fuzzy_match_score(key, query).map(|score| (index, score)))
        .collect::<Vec<_>>();

    if matches.len() > MAX_RANKED_FILE_MATCHES {
        matches.select_nth_unstable_by(MAX_RANKED_FILE_MATCHES - 1, |left, right| {
            right.1.cmp(&left.1).then_with(|| left.0.cmp(&right.0))
        });
        matches.truncate(MAX_RANKED_FILE_MATCHES);
    }

    matches.sort_by(|(left_index, left_score), (right_index, right_score)| {
        right_score
            .cmp(left_score)
            .then_with(|| left_index.cmp(right_index))
    });
    matches.into_iter().map(|(index, _)| index).collect()
}

pub(super) fn file_palette_scroll_counts(
    match_count: usize,
    selected_index: usize,
    visible_rows: usize,
) -> (usize, usize, usize) {
    if match_count == 0 || visible_rows == 0 {
        return (0, 0, 0);
    }

    let selected_index = selected_index.min(match_count - 1);
    let start = selected_index
        .saturating_add(1)
        .saturating_sub(visible_rows)
        .min(match_count.saturating_sub(1));
    let visible = visible_rows.min(match_count.saturating_sub(start));
    let above = start;
    let below = match_count.saturating_sub(start + visible);
    (start, above, below)
}

pub(super) fn file_palette_scroll_footer(
    above: usize,
    below: usize,
    total: usize,
    incomplete: bool,
) -> Option<String> {
    if above == 0 && below == 0 && !incomplete {
        return None;
    }

    let mut parts = Vec::new();
    if above > 0 {
        parts.push(format!("{above} more"));
    }
    if below > 0 {
        parts.push(format!("{below} more"));
    }
    parts.push(format!("{total} total"));
    if incomplete {
        parts.push("partial".into());
    }
    Some(parts.join(" · "))
}

/// Lists workspace files for `@` mentions using the shared workspace walker,
/// so ignore rules, symlink policy, and path shapes match the `grep` and
/// `glob` tools. Callers sort the result for display.
fn discover_file_paths(root: &Path, include_hidden: bool) -> DiscoveredFilePaths {
    let options = WalkOptions {
        hidden: if include_hidden {
            HiddenFiles::Include
        } else {
            HiddenFiles::Skip
        },
        limits: WalkLimits {
            max_entries: MAX_ENTRIES_SCANNED,
            deadline: Instant::now() + FILE_DISCOVERY_TIMEOUT,
        },
    };

    let mut paths = Vec::new();
    let stop = visit_files(root, &options, |file| {
        paths.push(file.relative);
        if paths.len() >= MAX_FILE_PATHS {
            ControlFlow::Break(WalkStop::ResultLimit)
        } else {
            ControlFlow::Continue(())
        }
    });
    DiscoveredFilePaths {
        paths: Arc::new(paths),
        incomplete: !matches!(stop, WalkStop::Completed),
    }
}

#[cfg(test)]
#[path = "file_picker_tests.rs"]
mod tests;