agent-file-tools 0.56.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
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
#![cfg(unix)]

use std::ffi::OsStr;
use std::fs;
use std::io::Write;
use std::os::unix::fs::{MetadataExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use filetime::FileTime;
use serde_json::{json, Value};

const LIVENESS_CEILING: Duration = Duration::from_secs(30);

fn aft_binary() -> PathBuf {
    std::env::var_os("AFT_TEST_AFT_BINARY")
        .or_else(|| std::env::var_os("NEXTEST_BIN_EXE_aft"))
        .or_else(|| std::env::var_os("CARGO_BIN_EXE_aft"))
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from(env!("CARGO_BIN_EXE_aft")))
}

fn write_executable(path: &Path, body: &str) {
    fs::write(path, body).unwrap();
    let mut permissions = fs::metadata(path).unwrap().permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(path, permissions).unwrap();
}

fn input_stamp(path: PathBuf) -> Value {
    match fs::metadata(&path) {
        Ok(metadata) => json!({
            "file": path,
            "mtime_ns": i128::from(metadata.mtime()) * 1_000_000_000 + i128::from(metadata.mtime_nsec()),
            "size": metadata.len(),
        }),
        Err(_) => json!({ "file": path, "mtime_ns": null, "size": null }),
    }
}

fn write_cache(storage: &Path, shell: &Path, home: &Path, path: Option<&str>) -> PathBuf {
    let inputs = [
        PathBuf::from("/etc/profile"),
        home.join(".bash_profile"),
        home.join(".bash_login"),
        home.join(".profile"),
        home.join(".bashrc"),
    ]
    .into_iter()
    .map(input_stamp)
    .collect::<Vec<_>>();
    let cache_path = storage.join("aft/effective-path.json");
    fs::create_dir_all(cache_path.parent().unwrap()).unwrap();
    fs::write(
        &cache_path,
        serde_json::to_vec(&json!({
            "schema": 1,
            "shell": shell,
            "path": path,
            "probed_at_unix": SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(),
            "inputs": inputs,
        }))
        .unwrap(),
    )
    .unwrap();
    cache_path
}

fn read_counter(marker: &Path) -> usize {
    fs::read_to_string(marker)
        .map(|s| s.matches('x').count())
        .unwrap_or(0)
}

fn wait_with_liveness_ceiling(
    mut child: std::process::Child,
    timeout: Duration,
) -> std::process::Output {
    let deadline = Instant::now() + timeout;
    loop {
        match child.try_wait() {
            Ok(Some(_)) => {
                return child.wait_with_output().expect("read output after exit");
            }
            Ok(None) if Instant::now() >= deadline => {
                let _ = child.kill();
                panic!("process exceeded {timeout:?} liveness ceiling");
            }
            Ok(None) => {
                thread::sleep(Duration::from_millis(20));
            }
            Err(error) => {
                let _ = child.kill();
                panic!("failed to wait for child: {error}");
            }
        }
    }
}

fn run_ping(storage: &Path, home: &Path, candidates: &OsStr, marker: &Path) -> Value {
    let mut child = Command::new(aft_binary())
        .env("AFT_CACHE_DIR", storage)
        .env("AFT_TEST_RAW_PATH", "0")
        .env("AFT_TEST_LOGIN_SHELL_CANDIDATES", candidates)
        .env("AFT_TEST_DISABLE_FILE_WATCHER", "1")
        .env("AFT_TEST_PATH_MARKER", marker)
        .env("HOME", home)
        .env("PATH", "/usr/bin:/bin")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn aft binary");
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"{\"id\":\"1\",\"command\":\"ping\"}\n")
        .unwrap();
    let output = wait_with_liveness_ceiling(child, LIVENESS_CEILING);
    assert!(output.status.success(), "aft failed: {output:?}");
    let response = String::from_utf8(output.stdout).unwrap();
    let response = response.lines().last().expect("ping response");
    serde_json::from_str(response).unwrap()
}

fn run_bash_get_path(
    storage: &Path,
    home: &Path,
    candidates: &OsStr,
    marker: &Path,
    output_path: &Path,
) -> Value {
    let mut child = Command::new(aft_binary())
        .env("AFT_CACHE_DIR", storage)
        .env("AFT_TEST_RAW_PATH", "0")
        .env("AFT_TEST_LOGIN_SHELL_CANDIDATES", candidates)
        .env("AFT_TEST_DISABLE_FILE_WATCHER", "1")
        .env("AFT_TEST_PATH_MARKER", marker)
        .env("HOME", home)
        .env("PATH", "/usr/bin:/bin")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn aft binary");

    let cmd = serde_json::json!({
        "id": "1",
        "command": "bash",
        "params": {
            "command": format!("printf %s \"$PATH\" > \"{}\"", output_path.display())
        }
    });
    child
        .stdin
        .take()
        .unwrap()
        .write_all(format!("{cmd}\n").as_bytes())
        .unwrap();

    let output = wait_with_liveness_ceiling(child, LIVENESS_CEILING);
    assert!(output.status.success(), "aft failed: {output:?}");

    let deadline = Instant::now() + LIVENESS_CEILING;
    while !output_path.exists() && Instant::now() < deadline {
        thread::sleep(Duration::from_millis(10));
    }
    assert!(
        output_path.exists(),
        "bash did not write served path within liveness ceiling"
    );

    let response = String::from_utf8(output.stdout).unwrap();
    let response = response.lines().last().expect("bash response");
    serde_json::from_str(response).unwrap()
}

fn wait_for_marker(marker: &Path) {
    let deadline = Instant::now() + LIVENESS_CEILING;
    while !marker.exists() && Instant::now() < deadline {
        thread::sleep(Duration::from_millis(10));
    }
    assert!(
        marker.exists(),
        "detached probe did not execute its shell within liveness ceiling"
    );
}

#[test]
fn valid_cache_skips_sleeping_shell_and_returns_ping_quickly() {
    let fixture = tempfile::tempdir().unwrap();
    let storage = fixture.path().join("storage");
    let home = fixture.path().join("home");
    let shell = fixture.path().join("bash");
    let marker = fixture.path().join("shell-ran");
    let served_path_file = fixture.path().join("served_path.txt");
    fs::create_dir_all(&home).unwrap();
    write_executable(
        &shell,
        "#!/bin/sh\nprintf x >> \"$AFT_TEST_PATH_MARKER\"\nsleep 10\n",
    );
    write_cache(
        &storage,
        &shell,
        &home,
        Some("/cached/login/bin:/usr/bin:/bin"),
    );

    let response = run_bash_get_path(
        &storage,
        &home,
        shell.as_os_str(),
        &marker,
        &served_path_file,
    );

    assert_eq!(response["id"], "1");
    assert_eq!(
        read_counter(&marker),
        0,
        "the cache-hit request executed the sleeping login shell"
    );
    let served_path = fs::read_to_string(&served_path_file).expect("served path file written");
    assert!(
        std::env::split_paths(&served_path).any(|p| p == Path::new("/cached/login/bin")),
        "served PATH {served_path:?} does not include cached entry /cached/login/bin"
    );
}

#[test]
fn changing_or_creating_a_recorded_rc_file_invalidates_the_cache() {
    for initially_exists in [true, false] {
        let fixture = tempfile::tempdir().unwrap();
        let storage = fixture.path().join("storage");
        let home = fixture.path().join("home");
        let shell = fixture.path().join("bash");
        let marker = fixture.path().join("probe-ran");
        let bashrc = home.join(".bashrc");
        fs::create_dir_all(&home).unwrap();
        if initially_exists {
            fs::write(&bashrc, "export PATH=/before\n").unwrap();
        }
        write_executable(
            &shell,
            "#!/bin/sh\nprintf x >> \"$AFT_TEST_PATH_MARKER\"\neval \"$2\"\n",
        );
        let cache_path = write_cache(
            &storage,
            &shell,
            &home,
            Some("/cached/login/bin:/usr/bin:/bin"),
        );
        let initial_cache: Value = serde_json::from_slice(&fs::read(&cache_path).unwrap()).unwrap();
        let initial_inputs = initial_cache["inputs"].clone();

        if initially_exists {
            let future = FileTime::from_unix_time(
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_secs() as i64
                    + 2,
                0,
            );
            filetime::set_file_mtime(&bashrc, future).unwrap();
        } else {
            fs::write(&bashrc, "export PATH=/created\n").unwrap();
        }

        let response = run_ping(&storage, &home, shell.as_os_str(), &marker);

        assert_eq!(response["id"], "1");
        assert_eq!(
            read_counter(&marker),
            1,
            "rc-file change did not run the probe exactly once"
        );
        let updated_cache: Value = serde_json::from_slice(&fs::read(&cache_path).unwrap()).unwrap();
        assert_ne!(
            initial_inputs, updated_cache["inputs"],
            "cache file inputs must change after rc-file modification"
        );
    }
}

#[test]
fn timed_out_probe_is_cached_and_second_binary_start_is_fast() {
    let fixture = tempfile::tempdir().unwrap();
    let storage = fixture.path().join("storage");
    let home = fixture.path().join("home");
    let shell = fixture.path().join("bash");
    let marker = fixture.path().join("probe-count");
    fs::create_dir_all(&home).unwrap();
    write_executable(
        &shell,
        "#!/bin/sh\nprintf x >> \"$AFT_TEST_PATH_MARKER\"\nsleep 10\n",
    );

    let first_response = run_ping(&storage, &home, shell.as_os_str(), &marker);
    assert_eq!(first_response["id"], "1");
    let cache: Value = serde_json::from_slice(
        &fs::read(storage.join("aft/effective-path.json")).expect("timeout cache"),
    )
    .unwrap();
    assert!(cache["path"].is_null(), "timeout must cache null PATH");
    assert!(!cache["inputs"].as_array().unwrap().is_empty());
    let count_after_first = read_counter(&marker);
    assert_eq!(
        count_after_first, 1,
        "first run should have invoked the shell once"
    );

    let second_response = run_ping(&storage, &home, shell.as_os_str(), &marker);
    assert_eq!(second_response["id"], "1");
    let count_after_second = read_counter(&marker);
    let delta = count_after_second - count_after_first;
    assert_eq!(
        delta, 0,
        "cached timeout started another login-shell probe (counter delta {delta})"
    );
}

#[test]
fn fallback_result_is_cached_for_the_requested_hanging_shell() {
    let fixture = tempfile::tempdir().unwrap();
    let storage = fixture.path().join("storage");
    let home = fixture.path().join("home");
    let hanging_shell = fixture.path().join("hanging-bash");
    let fallback_shell = fixture.path().join("fallback-bash");
    let marker = fixture.path().join("hanging-count");
    fs::create_dir_all(&home).unwrap();
    write_executable(
        &hanging_shell,
        "#!/bin/sh\nprintf x >> \"$AFT_TEST_PATH_MARKER\"\nsleep 10\n",
    );
    write_executable(&fallback_shell, "#!/bin/sh\neval \"$2\"\n");
    let candidates = std::env::join_paths([&hanging_shell, &fallback_shell]).unwrap();

    let first_response = run_ping(&storage, &home, &candidates, &marker);
    assert_eq!(first_response["id"], "1");
    let count_after_first = read_counter(&marker);
    assert_eq!(
        count_after_first, 1,
        "first run should have attempted the hanging shell once"
    );
    let cache: Value = serde_json::from_slice(
        &fs::read(storage.join("aft/effective-path.json")).expect("fallback cache"),
    )
    .unwrap();
    assert_eq!(
        cache["shell"],
        hanging_shell.to_string_lossy().as_ref(),
        "fallback must cache against the requested shell"
    );
    assert!(
        cache["path"].is_string(),
        "fallback probe should succeed and cache non-null path"
    );

    let second_response = run_ping(&storage, &home, &candidates, &marker);
    assert_eq!(second_response["id"], "1");
    let count_after_second = read_counter(&marker);
    let delta = count_after_second - count_after_first;
    assert_eq!(
        delta, 0,
        "cached fallback result retried the requested hanging shell (counter delta {delta})"
    );
}

#[test]
fn inline_probe_total_budget_caps_two_hanging_candidates() {
    let fixture = tempfile::tempdir().unwrap();
    let storage = fixture.path().join("storage");
    let home = fixture.path().join("home");
    let first = fixture.path().join("first-bash");
    let second = fixture.path().join("second-bash");
    let first_start = fixture.path().join("first-start");
    let second_start = fixture.path().join("second-start");
    fs::create_dir_all(&home).unwrap();
    write_executable(
        &first,
        &format!(
            "#!/bin/sh\ndate +%s > \"{}\"\nsleep 10\n",
            first_start.display()
        ),
    );
    write_executable(
        &second,
        &format!(
            "#!/bin/sh\ndate +%s > \"{}\"\nsleep 10\n",
            second_start.display()
        ),
    );
    let candidates = std::env::join_paths([&first, &second]).unwrap();

    let response = run_ping(
        &storage,
        &home,
        &candidates,
        &fixture.path().join("probe-ran"),
    );
    assert_eq!(response["id"], "1");

    assert!(
        first_start.exists(),
        "first hanging candidate must have started"
    );
    if second_start.exists() {
        let first_ts: u64 = fs::read_to_string(&first_start)
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        let second_ts: u64 = fs::read_to_string(&second_start)
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        assert!(
            second_ts >= first_ts,
            "second candidate started before first candidate: {second_ts} < {first_ts}"
        );
    }
    let cache: Value = serde_json::from_slice(
        &fs::read(storage.join("aft/effective-path.json")).expect("cache file after probe"),
    )
    .unwrap();
    assert!(
        cache["path"].is_null(),
        "total budget cap on two hanging candidates must cache null PATH"
    );
    assert_eq!(cache["shell"], first.to_string_lossy().as_ref());
}

#[test]
fn cache_hit_starts_a_detached_refresh_helper_in_production() {
    let fixture = tempfile::tempdir().unwrap();
    let storage = fixture.path().join("storage");
    let home = fixture.path().join("home");
    let shell = fixture.path().join("bash");
    let marker = fixture.path().join("helper-ran");
    fs::create_dir_all(&home).unwrap();
    write_executable(
        &shell,
        "#!/bin/sh\nprintf helper-ran > \"$AFT_TEST_PATH_MARKER\"\neval \"$2\"\n",
    );
    write_cache(
        &storage,
        &shell,
        &home,
        Some("/cached/login/bin:/usr/bin:/bin"),
    );

    let mut child = Command::new(aft_binary())
        .env("AFT_CACHE_DIR", &storage)
        .env("AFT_TEST_RAW_PATH", "0")
        .env("AFT_TEST_DISABLE_FILE_WATCHER", "1")
        .env("AFT_TEST_PATH_MARKER", &marker)
        .env("HOME", &home)
        .env("PATH", "/usr/bin:/bin")
        .env("SHELL", &shell)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn aft binary");
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"{\"id\":\"1\",\"command\":\"ping\"}\n")
        .unwrap();
    let output = wait_with_liveness_ceiling(child, LIVENESS_CEILING);
    assert!(output.status.success());

    wait_for_marker(&marker);
}