agent-file-tools 0.47.2

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
use super::helpers::{user_config, AftProcess};

#[cfg(unix)]
fn shell_quote_path(path: &std::path::Path) -> String {
    format!("'{}'", path.display().to_string().replace('\'', "'\\''"))
}

#[cfg(unix)]
fn write_executable_shim(path: &std::path::Path, body: &str) {
    use std::os::unix::fs::PermissionsExt;

    std::fs::write(path, body).unwrap();
    let mut permissions = std::fs::metadata(path).unwrap().permissions();
    permissions.set_mode(0o755);
    std::fs::set_permissions(path, permissions).unwrap();
}

#[cfg(unix)]
fn wait_for_terminal_status(aft: &mut AftProcess, task_id: &str) -> serde_json::Value {
    let started = std::time::Instant::now();
    loop {
        let status = aft.send(
            &serde_json::json!({
                "id": format!("status-{task_id}"),
                "method": "bash_status",
                "params": { "task_id": task_id }
            })
            .to_string(),
        );
        if matches!(
            status["status"].as_str(),
            Some("completed" | "failed" | "killed" | "timed_out")
        ) {
            return status;
        }
        assert!(
            started.elapsed() < std::time::Duration::from_secs(5),
            "timed out waiting for terminal bash status: {status:?}"
        );
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
}

#[cfg(unix)]
#[test]
fn bash_inherits_login_shell_enriched_path() {
    let dir = tempfile::tempdir().unwrap();
    let home = dir.path().join("home");
    let custom_bin = home.join(".custom/bin");
    let cargo_bin = home.join(".cargo/bin");
    let local_bin = home.join(".local/bin");
    let fake_shell = dir.path().join("bin/zsh");
    std::fs::create_dir_all(&custom_bin).unwrap();
    std::fs::create_dir_all(&cargo_bin).unwrap();
    std::fs::create_dir_all(&local_bin).unwrap();
    std::fs::create_dir_all(fake_shell.parent().unwrap()).unwrap();

    let tool_name = format!("aft-path-probe-{}", std::process::id());
    let tool_path = custom_bin.join(&tool_name);
    write_executable_shim(&tool_path, "#!/bin/sh\nexit 0\n");
    std::fs::write(
        home.join(".zshrc"),
        format!(
            "printf 'banner before\\n'; export PATH=\"$PATH:{}\"; printf 'banner after\\n'\\n",
            custom_bin.display()
        ),
    )
    .unwrap();

    write_executable_shim(
        &fake_shell,
        r#"#!/bin/sh
if [ "$1" != '-lic' ]; then
  exit 64
fi
if [ -f "$ZDOTDIR/.zshrc" ]; then
  . "$ZDOTDIR/.zshrc"
fi
eval "$2"
"#,
    );

    // Pay the macOS first-exec assessment for the freshly written shims HERE,
    // in setup. The login-shell probe inside aft runs under a 3s timeout; on a
    // busy syspolicyd the first exec of a new inode can take longer than
    // that, which times out the probe and fails the test spuriously.
    let _ = std::process::Command::new(&fake_shell).status();
    let _ = std::process::Command::new(&tool_path).status();

    let daemon_path = format!(
        "/opt/homebrew/bin:/usr/local/bin:{}:{}:/usr/bin:/bin",
        cargo_bin.display(),
        local_bin.display()
    );
    let mut aft = AftProcess::spawn_with_env(&[
        // The harness defaults AFT_TEST_RAW_PATH=1 (PATH isolation for
        // formatter/checker tests); this test IS the PATH feature, so opt back
        // in to the real probe+enrichment pipeline.
        ("AFT_TEST_RAW_PATH", std::ffi::OsStr::new("0")),
        ("PATH", std::ffi::OsStr::new(&daemon_path)),
        ("HOME", home.as_os_str()),
        ("ZDOTDIR", home.as_os_str()),
        ("SHELL", fake_shell.as_os_str()),
    ]);

    let response = aft.send(
        &serde_json::json!({
            "id": "bash-login-path",
            "method": "bash",
            "params": { "command": format!("command -v {tool_name}") }
        })
        .to_string(),
    );
    assert_eq!(response["success"], true, "bash spawn failed: {response:?}");
    let task_id = response["task_id"].as_str().unwrap();
    let status = wait_for_terminal_status(&mut aft, task_id);

    assert_eq!(status["status"], "completed", "bash failed: {status:?}");
    assert_eq!(status["exit_code"], 0, "bash failed: {status:?}");
    assert_eq!(
        status["output_preview"].as_str().unwrap().trim(),
        tool_path.to_string_lossy(),
        "bash child did not inherit the rc-enriched PATH: {status:?}"
    );

    assert!(aft.shutdown().success());
}

#[cfg(unix)]
fn process_exists(pid: i32) -> bool {
    let output = std::process::Command::new("ps")
        .args(["-o", "stat=", "-p", &pid.to_string()])
        .output()
        .unwrap();
    if !output.status.success() {
        return false;
    }
    !String::from_utf8_lossy(&output.stdout).contains('Z')
}

#[cfg(unix)]
fn wait_until_process_exits(pid: i32) -> bool {
    let started = std::time::Instant::now();
    while started.elapsed() < std::time::Duration::from_secs(2) {
        if !process_exists(pid) {
            return true;
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    false
}

#[test]
fn bash_streams_progress_and_returns_final_response() {
    let mut aft = AftProcess::spawn();

    let response = aft.send(r#"{"id":"bash-1","method":"bash","params":{"command":"echo hello"}}"#);
    assert_eq!(response["id"], "bash-1");
    assert_eq!(response["success"], true);
    assert_eq!(response["status"], "running");

    let task_id = response["task_id"].as_str().unwrap();
    let started = std::time::Instant::now();
    let status = loop {
        let status = aft.send(
            &serde_json::json!({
                "id": "bash-1-status",
                "method": "bash_status",
                "params": { "task_id": task_id }
            })
            .to_string(),
        );
        if status["status"] == "completed" {
            break status;
        }
        assert!(started.elapsed() < std::time::Duration::from_secs(5));
        std::thread::sleep(std::time::Duration::from_millis(50));
    };
    assert_eq!(
        status["output_preview"]
            .as_str()
            .unwrap()
            .replace("\r\n", "\n"),
        "hello\n"
    );
    assert_eq!(status["exit_code"], 0);
    assert!(status["duration_ms"].is_u64());

    let status = aft.shutdown();
    assert!(status.success());
}

#[test]
fn bash_rejects_blocked_env_vars() {
    let mut aft = AftProcess::spawn();

    let response = aft.send(
        &serde_json::json!({
            "id": "bash-blocked-env",
            "method": "bash",
            "params": {
                "command": "echo should-not-run",
                "env": { "LD_PRELOAD": "foo" }
            }
        })
        .to_string(),
    );

    assert_eq!(response["success"], false, "response: {response:?}");
    assert_eq!(response["code"], "blocked_env_var");
    assert!(response["message"].as_str().unwrap().contains("LD_PRELOAD"));

    assert!(aft.shutdown().success());
}

#[test]
fn bash_rejects_invalid_pty_dimensions() {
    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let configure = aft.send(
        &serde_json::json!({
            "id": "cfg-bg",
            "command": "configure",
            "harness": "opencode",
            "project_root": dir.path(),
            "storage_dir": dir.path().join("storage"),
            "config": user_config(serde_json::json!({
                "experimental": { "bash": { "background": true } }
            })),
        })
        .to_string(),
    );
    assert_eq!(
        configure["success"], true,
        "configure failed: {configure:?}"
    );

    let cases = [
        (
            "pty-rows-too-large",
            serde_json::json!({
                "command": "echo nope",
                "background": true,
                "pty": true,
                "pty_rows": 61,
            }),
            "ptyRows must be an integer between 1 and 60",
        ),
        (
            "pty-cols-too-large",
            serde_json::json!({
                "command": "echo nope",
                "background": true,
                "pty": true,
                "pty_cols": 141,
            }),
            "ptyCols must be an integer between 1 and 140",
        ),
        (
            "pty-rows-float",
            serde_json::json!({
                "command": "echo nope",
                "background": true,
                "pty": true,
                "pty_rows": 1.5,
            }),
            "invalid params",
        ),
    ];

    for (id, params, message) in cases {
        let response = aft.send(
            &serde_json::json!({
                "id": id,
                "method": "bash",
                "params": params
            })
            .to_string(),
        );
        assert_eq!(response["success"], false, "case {id}: {response:?}");
        assert_eq!(
            response["code"], "invalid_request",
            "case {id}: {response:?}"
        );
        assert!(
            response["message"].as_str().unwrap().contains(message),
            "case {id}: expected message containing {message:?}, got {response:?}"
        );
    }

    assert!(aft.shutdown().success());
}

#[cfg(unix)]
#[test]
fn bash_piped_runner_exit_status_is_not_hidden() {
    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let bin_dir = dir.path().join("bin");
    std::fs::create_dir_all(&bin_dir).unwrap();
    write_executable_shim(
        &bin_dir.join("cargo"),
        "#!/bin/sh\nprintf 'fake cargo line\\n'\nexit 0\n",
    );
    write_executable_shim(
        &bin_dir.join("pytest"),
        "#!/bin/sh\nprintf 'fake pytest line\\n'\nexit 0\n",
    );
    let path_prefix = shell_quote_path(&bin_dir);
    let cases = [
        (
            "grep-v-empty",
            format!("PATH={path_prefix}:$PATH cargo test | grep -v '^'"),
        ),
        (
            "awk-end-exit",
            format!("PATH={path_prefix}:$PATH cargo test | awk 'END{{exit 1}}'"),
        ),
        (
            "pytest-grep-sentinel",
            format!("PATH={path_prefix}:$PATH pytest -q | grep SENTINEL || exit 1"),
        ),
    ];

    for (id, command) in cases {
        let response = aft.send(
            &serde_json::json!({
                "id": id,
                "method": "bash",
                "params": { "command": command }
            })
            .to_string(),
        );
        assert_eq!(
            response["success"], true,
            "spawn failed for {id}: {response:?}"
        );
        assert_eq!(
            response["status"], "running",
            "unexpected spawn status for {id}: {response:?}"
        );
        let task_id = response["task_id"].as_str().unwrap();
        let status = wait_for_terminal_status(&mut aft, task_id);
        assert_eq!(
            status["status"], "failed",
            "{id} should preserve pipeline failure: {status:?}"
        );
        assert_eq!(
            status["exit_code"], 1,
            "{id} should report the shell pipeline exit code: {status:?}"
        );
    }

    assert!(aft.shutdown().success());
}

#[cfg(unix)]
#[test]
fn bash_timeout_terminates_shell_process_group_grandchild() {
    let mut aft = AftProcess::spawn();
    let dir = tempfile::tempdir().unwrap();
    let pid_file = dir.path().join("sleep.pid");
    let command = format!("sleep 30 & echo $! > {}; wait", pid_file.display());

    let response = aft.send(
        &serde_json::json!({
            "id": "bash-timeout-pgroup",
            "method": "bash",
            "params": { "command": command, "timeout": 200 }
        })
        .to_string(),
    );

    assert_eq!(response["success"], true, "bash failed: {response:?}");
    assert_eq!(response["status"], "running");
    let task_id = response["task_id"].as_str().unwrap();
    let started = std::time::Instant::now();
    loop {
        let status = aft.send(
            &serde_json::json!({
                "id": "bash-timeout-pgroup-status",
                "method": "bash_status",
                "params": { "task_id": task_id }
            })
            .to_string(),
        );
        if status["status"] == "timed_out" {
            break;
        }
        assert!(started.elapsed() < std::time::Duration::from_secs(5));
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    let pid: i32 = std::fs::read_to_string(&pid_file)
        .unwrap()
        .trim()
        .parse()
        .unwrap();
    assert!(
        wait_until_process_exits(pid),
        "grandchild sleep process {pid} survived foreground timeout"
    );

    assert!(aft.shutdown().success());
}