agent-file-tools 0.50.0

Agent File Tools — tree-sitter powered code analysis for AI agents
Documentation
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
use std::path::{Path, PathBuf};

use globset::Glob;

use crate::lsp::registry::ServerKind;

pub fn find_workspace_root<S>(file_path: &Path, markers: &[S]) -> Option<PathBuf>
where
    S: AsRef<str>,
{
    find_workspace_root_within(file_path, markers, None)
}

/// Find a marker root without walking above an optional session project root.
pub fn find_workspace_root_within<S>(
    file_path: &Path,
    markers: &[S],
    project_root: Option<&Path>,
) -> Option<PathBuf>
where
    S: AsRef<str>,
{
    // Route canonicalization through `canonicalize_normalized` so the returned
    // root is never a Windows verbatim (`\\?\C:\...`) path. This root flows into
    // `LspClient::spawn` -> `Command::current_dir(&root)`, and `CreateProcess`
    // rejects extended-length verbatim paths as `lpCurrentDirectory` (documented
    // Win32 limitation: "The lpCurrentDirectory string ... must not be a \\?\
    // prefixed path"). Without this strip EVERY LSP spawn on Windows fails
    // with "The system cannot find the path specified" and aft_inspect reports
    // servers as not installed (#174). On Unix `canonicalize_normalized` is
    // identity-equivalent to `fs::canonicalize` followed by lexical `.`/`..`
    // collapse, so non-Windows behavior is unchanged.
    // `canonicalize_normalized` falls back to lexical `.`/`..` collapse when
    // `fs::canonicalize` fails (e.g. the file is gone), matching the prior
    // fallback to the raw `file_path` for paths without `.`/`..` components.
    let resolved_path = crate::inspect::job::canonicalize_normalized(file_path);

    let start_dir = if resolved_path.is_dir() {
        resolved_path
    } else {
        resolved_path.parent()?.to_path_buf()
    };

    let project_root = project_root.map(crate::inspect::job::canonicalize_normalized);
    if project_root
        .as_ref()
        .is_some_and(|boundary| !start_dir.starts_with(boundary))
    {
        return None;
    }

    let mut current = Some(start_dir.as_path());
    while let Some(dir) = current {
        if project_root
            .as_ref()
            .is_some_and(|boundary| !dir.starts_with(boundary))
        {
            break;
        }
        if markers
            .iter()
            .any(|marker| dir.join(marker.as_ref()).exists())
        {
            return Some(dir.to_path_buf());
        }

        if project_root.as_deref() == Some(dir) {
            break;
        }
        current = dir.parent();
    }

    None
}

/// Find the Cargo workspace that owns `file_path`.
///
/// Rust Analyzer loads the complete Cargo workspace supplied by the client. A
/// member crate's manifest is therefore not a suitable server root: opening a
/// second member would otherwise start another full-workspace analyzer. The
/// optional project root bounds the walk so an enclosing checkout cannot claim
/// a nested session as one of its workspaces.
pub fn find_rust_workspace_root(file_path: &Path, project_root: Option<&Path>) -> Option<PathBuf> {
    let resolved_path = crate::inspect::job::canonicalize_normalized(file_path);
    let start_dir = if resolved_path.is_dir() {
        resolved_path
    } else {
        resolved_path.parent()?.to_path_buf()
    };
    let project_root = project_root.map(crate::inspect::job::canonicalize_normalized);

    if project_root
        .as_ref()
        .is_some_and(|boundary| !start_dir.starts_with(boundary))
    {
        return None;
    }

    let crate_root = nearest_cargo_manifest_dir(&start_dir, project_root.as_deref())?;
    let mut current = Some(crate_root.as_path());
    while let Some(dir) = current {
        if project_root
            .as_ref()
            .is_some_and(|boundary| !dir.starts_with(boundary))
        {
            break;
        }
        if cargo_workspace_contains_crate(dir, &crate_root) {
            return Some(crate::inspect::job::canonicalize_normalized(dir));
        }
        if project_root.as_deref() == Some(dir) {
            break;
        }
        current = dir.parent();
    }

    None
}

fn nearest_cargo_manifest_dir(start_dir: &Path, project_root: Option<&Path>) -> Option<PathBuf> {
    let mut current = Some(start_dir);
    while let Some(dir) = current {
        if project_root.is_some_and(|boundary| !dir.starts_with(boundary)) {
            break;
        }
        if dir.join("Cargo.toml").is_file() {
            return Some(dir.to_path_buf());
        }
        if project_root == Some(dir) {
            break;
        }
        current = dir.parent();
    }
    None
}

fn cargo_workspace_contains_crate(workspace_root: &Path, crate_root: &Path) -> bool {
    let Ok(contents) = std::fs::read_to_string(workspace_root.join("Cargo.toml")) else {
        return false;
    };
    let Ok(manifest) = contents.parse::<toml::Value>() else {
        return false;
    };
    let Some(workspace) = manifest.get("workspace").and_then(toml::Value::as_table) else {
        return false;
    };

    if workspace_root == crate_root {
        return true;
    }

    let Ok(crate_relative_path) = crate_root.strip_prefix(workspace_root) else {
        return false;
    };
    if workspace
        .get("exclude")
        .and_then(toml::Value::as_array)
        .is_some_and(|patterns| {
            patterns
                .iter()
                .filter_map(toml::Value::as_str)
                .any(|pattern| cargo_member_pattern_matches(pattern, crate_relative_path))
        })
    {
        return false;
    }

    match workspace.get("members").and_then(toml::Value::as_array) {
        Some(patterns) => patterns
            .iter()
            .filter_map(toml::Value::as_str)
            .any(|pattern| cargo_member_pattern_matches(pattern, crate_relative_path)),
        // Cargo permits a package to be colocated with a `[workspace]` table
        // without listing the package in `members`. Prefer the nearest ancestor
        // manifest that defines a workspace because it still describes the
        // broader Cargo workspace for the analyzer.
        None => true,
    }
}

fn cargo_member_pattern_matches(pattern: &str, crate_relative_path: &Path) -> bool {
    Glob::new(pattern.trim())
        .map(|glob| glob.compile_matcher().is_match(crate_relative_path))
        .unwrap_or(false)
}

/// Composite key for caching server instances.
/// Each unique (ServerKind, workspace_root) pair gets its own server process.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ServerKey {
    pub kind: ServerKind,
    pub root: PathBuf,
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::PathBuf;

    use tempfile::tempdir;

    use super::{
        find_rust_workspace_root, find_workspace_root, find_workspace_root_within, ServerKey,
    };
    use crate::inspect::job::canonicalize_normalized;
    use crate::lsp::registry::ServerKind;

    #[test]
    fn test_find_root_with_cargo_toml() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path().join("workspace");
        let src_dir = root.join("src");
        let file = src_dir.join("lib.rs");

        fs::create_dir_all(&src_dir).unwrap();
        fs::write(root.join("Cargo.toml"), "[package]\nname = \"demo\"\n").unwrap();
        fs::write(&file, "fn main() {}\n").unwrap();

        // Expectations go through the same normalization as production:
        // bare fs::canonicalize returns verbatim (\\?\) paths on Windows,
        // which find_workspace_root deliberately strips.
        let expected_root = crate::inspect::job::canonicalize_normalized(&root);
        assert_eq!(
            find_workspace_root(&file, &["Cargo.toml"]),
            Some(expected_root)
        );
    }

    #[test]
    fn test_find_root_nested() {
        let temp_dir = tempdir().unwrap();
        let repo_root = temp_dir.path().join("repo");
        let crate_root = repo_root.join("crates").join("foo");
        let src_dir = crate_root.join("src");
        let file = src_dir.join("lib.rs");

        fs::create_dir_all(&src_dir).unwrap();
        fs::write(repo_root.join("Cargo.toml"), "[workspace]\n").unwrap();
        fs::write(crate_root.join("Cargo.toml"), "[package]\nname = \"foo\"\n").unwrap();
        fs::write(&file, "fn main() {}\n").unwrap();

        let expected_root = crate::inspect::job::canonicalize_normalized(&crate_root);
        assert_eq!(
            find_workspace_root(&file, &["Cargo.toml"]),
            Some(expected_root)
        );
    }

    #[test]
    fn test_find_root_none() {
        let temp_dir = tempdir().unwrap();
        let src_dir = temp_dir.path().join("src");
        let file = src_dir.join("main.rs");

        fs::create_dir_all(&src_dir).unwrap();
        fs::write(&file, "fn main() {}\n").unwrap();

        assert_eq!(find_workspace_root(&file, &["Cargo.toml"]), None);
    }

    #[test]
    fn test_find_root_multiple_markers() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path().join("web");
        let src_dir = root.join("src");
        let file = src_dir.join("index.ts");

        fs::create_dir_all(&src_dir).unwrap();
        fs::write(root.join("tsconfig.json"), "{}\n").unwrap();
        fs::create_dir(root.join("package.json")).unwrap();
        fs::write(&file, "export {};\n").unwrap();

        let expected_root = crate::inspect::job::canonicalize_normalized(&root);
        assert_eq!(
            find_workspace_root(&file, &["tsconfig.json", "package.json"]),
            Some(expected_root)
        );
    }

    #[test]
    fn test_server_key_equality() {
        let root = PathBuf::from("/tmp/workspace");
        let same = ServerKey {
            kind: ServerKind::Rust,
            root: root.clone(),
        };
        let equal = ServerKey {
            kind: ServerKind::Rust,
            root,
        };
        let different = ServerKey {
            kind: ServerKind::Rust,
            root: PathBuf::from("/tmp/other"),
        };

        assert_eq!(same, equal);
        assert_ne!(same, different);
    }

    /// Regression test for #174: the workspace root returned for a nested file
    /// must never carry a Windows verbatim (`\\?\`) prefix, because it flows
    /// into `LspClient::spawn` -> `Command::current_dir`, and `CreateProcess`
    /// rejects verbatim paths as `lpCurrentDirectory` (every LSP spawn on
    /// Windows would otherwise fail with "The system cannot find the path
    /// specified").
    ///
    /// This runs on every platform (not `cfg(windows)`-gated) because the
    /// normalization is platform-independent: on Unix `canonicalize_normalized`
    /// is identity-equivalent to `fs::canonicalize` plus lexical `.`/`..`
    /// collapse, so the assertion is a no-op there; on Windows (MSVC CI) it
    /// asserts the verbatim strip. The byte-equality check against
    /// `canonicalize_normalized` is the platform-independent property that
    /// fails locally on macOS if the roots.rs chokepoint is reverted to a bare
    /// `fs::canonicalize` (whose output diverges from the normalized form only
    /// on Windows, but the equality contract holds everywhere).
    #[test]
    fn test_find_root_strips_windows_verbatim_prefix() {
        let temp_dir = tempdir().unwrap();
        let root = temp_dir.path().join("workspace");
        let src_dir = root.join("src");
        let nested = src_dir.join("deep").join("lib.rs");

        fs::create_dir_all(nested.parent().unwrap()).unwrap();
        fs::write(root.join("Cargo.toml"), "[package]\nname = \"demo\"\n").unwrap();
        fs::write(&nested, "fn main() {}\n").unwrap();

        let found = find_workspace_root(&nested, &["Cargo.toml"]).expect("root found");

        // No verbatim prefix on any platform.
        let display = found.to_string_lossy();
        assert!(
            !display.starts_with("\\\\?\\"),
            "workspace root must not carry a Windows verbatim prefix: {display}"
        );

        // Byte-for-byte equality with the shared normalizer for the same
        // fixture. This is the platform-independent mutation control: reverting
        // roots.rs to a bare `fs::canonicalize` makes `find_workspace_root`
        // diverge from `canonicalize_normalized` on Windows, and on Unix the
        // equality still holds (both reduce to the canonical form), so the
        // test fails on Windows CI while passing locally on macOS.
        let expected = canonicalize_normalized(&root);
        assert_eq!(found, expected);
    }

    #[test]
    fn rust_workspace_root_prefers_owning_workspace_over_member_manifest() {
        let temp_dir = tempdir().unwrap();
        let workspace = temp_dir.path().join("workspace");
        let crate_root = workspace.join("crates").join("member");
        let source = crate_root.join("src").join("lib.rs");

        fs::create_dir_all(source.parent().unwrap()).unwrap();
        fs::write(
            workspace.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/member\"]\nresolver = \"2\"\n",
        )
        .unwrap();
        fs::write(
            crate_root.join("Cargo.toml"),
            "[package]\nname = \"member\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        fs::write(&source, "pub fn answer() -> u32 { 42 }\n").unwrap();

        assert_eq!(
            find_rust_workspace_root(&source, Some(&workspace)),
            Some(canonicalize_normalized(&workspace))
        );
    }

    #[test]
    fn rust_workspace_root_keeps_crate_excluded_from_parent_workspace_standalone() {
        let temp_dir = tempdir().unwrap();
        let workspace = temp_dir.path().join("workspace");
        let member_root = workspace.join("crates").join("member");
        let standalone_root = workspace.join("tools").join("standalone");
        let source = standalone_root.join("src").join("lib.rs");

        fs::create_dir_all(member_root.join("src")).unwrap();
        fs::create_dir_all(source.parent().unwrap()).unwrap();
        fs::write(
            workspace.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/member\"]\nresolver = \"2\"\n",
        )
        .unwrap();
        fs::write(
            member_root.join("Cargo.toml"),
            "[package]\nname = \"member\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        fs::write(
            standalone_root.join("Cargo.toml"),
            "[package]\nname = \"standalone\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        fs::write(&source, "pub fn answer() -> u32 { 42 }\n").unwrap();

        assert_eq!(
            find_rust_workspace_root(&source, Some(&workspace)),
            None,
            "the parent workspace does not list this crate"
        );
    }

    #[test]
    fn rust_workspace_root_does_not_walk_above_project_root() {
        let temp_dir = tempdir().unwrap();
        let outer_workspace = temp_dir.path().join("outer-workspace");
        let project_root = outer_workspace.join("nested-project");
        let crate_root = project_root.join("crate");
        let source = crate_root.join("src").join("lib.rs");

        fs::create_dir_all(source.parent().unwrap()).unwrap();
        fs::write(
            outer_workspace.join("Cargo.toml"),
            "[workspace]\nmembers = [\"nested-project/crate\"]\nresolver = \"2\"\n",
        )
        .unwrap();
        fs::write(
            crate_root.join("Cargo.toml"),
            "[package]\nname = \"nested\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
        )
        .unwrap();
        fs::write(&source, "pub fn answer() -> u32 { 42 }\n").unwrap();
        let loose_source = project_root.join("loose.rs");
        fs::write(&loose_source, "pub fn loose() {}\n").unwrap();

        assert_eq!(
            find_rust_workspace_root(&source, Some(&project_root)),
            None,
            "the enclosing workspace belongs to a different session root"
        );
        assert_eq!(
            find_workspace_root_within(&loose_source, &["Cargo.toml"], Some(&project_root)),
            None,
            "marker lookup must not cross the session project root"
        );
    }
}