agent-file-tools 0.55.1

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
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
use std::fs;
use std::path::Path;
use std::time::{Duration, Instant};

use serde_json::{json, Value};

use super::helpers::{user_config, AftProcess};

fn configure_background(aft: &mut AftProcess) -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    let response = aft.send(
        &json!({
            "id": "cfg-watch-bg",
            "command": "configure",
            "harness": "opencode",
            "project_root": dir.path(),
            "config": user_config(serde_json::json!({
                "experimental": { "bash": { "background": true } }
            })),
        })
        .to_string(),
    );
    assert_eq!(response["success"], true, "configure failed: {response:?}");
    dir
}

fn notify(aft: &mut AftProcess, task_id: &str, params: Value) -> Value {
    let mut params = params.as_object().unwrap().clone();
    params.insert("task_id".into(), json!(task_id));
    aft.send(
        &json!({
            "id": "notify-watch",
            "command": "bash_notify",
            "params": params,
        })
        .to_string(),
    )
}

fn spawn(aft: &mut AftProcess, command: &str) -> String {
    let spawn = aft.send(
        &json!({
            "id": "spawn-watch-bg",
            "command": "bash",
            "params": { "command": command, "background": true }
        })
        .to_string(),
    );
    assert_eq!(spawn["success"], true, "spawn failed: {spawn:?}");
    spawn["task_id"].as_str().unwrap().to_string()
}

#[cfg(windows)]
fn print_ready_after_complete_command() -> &'static str {
    "Write-Host -NoNewline READY-AFTER-COMPLETE"
}

#[cfg(not(windows))]
fn print_ready_after_complete_command() -> &'static str {
    "printf READY-AFTER-COMPLETE"
}

#[cfg(not(windows))]
fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

#[cfg(windows)]
fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "''"))
}

#[cfg(not(windows))]
fn release_gate_command(release: &Path, text: &str) -> String {
    format!(
        "while [ ! -f {} ]; do sleep 0.05; done; printf '%s\\n' {}",
        shell_quote(&release.display().to_string()),
        shell_quote(text)
    )
}

#[cfg(windows)]
fn release_gate_command(release: &Path, text: &str) -> String {
    format!(
        "while (-not (Test-Path -LiteralPath {})) {{ Start-Sleep -Milliseconds 50 }}; Write-Output {}",
        shell_quote(&release.display().to_string()),
        shell_quote(text)
    )
}

fn release_task(path: &Path) {
    fs::write(path, "go").expect("release watch task");
}

fn wait_for_pattern_frame(aft: &mut AftProcess, task_id: &str) -> Value {
    let started = Instant::now();
    loop {
        if let Some(frame) = aft.try_read_next_timeout(Duration::from_millis(200)) {
            if frame["type"] == "bash_pattern_match" && frame["task_id"] == task_id {
                return frame;
            }
        }
        assert!(
            started.elapsed() < Duration::from_secs(6),
            "timed out waiting for pattern frame"
        );
    }
}

fn status(aft: &mut AftProcess, task_id: &str) -> Value {
    aft.send(
        &json!({
            "id": "status-watch",
            "command": "bash_status",
            "params": { "task_id": task_id }
        })
        .to_string(),
    )
}

#[test]
fn bash_regex_match_command_uses_multiline_regex_and_byte_offsets() {
    let mut aft = AftProcess::spawn();
    let response = aft.send(
        &json!({
            "id": "regex-match",
            "command": "bash_regex_match",
            "params": { "pattern": "^foo$", "text": "α\nfoo\nbar" }
        })
        .to_string(),
    );

    assert_eq!(
        response["success"], true,
        "regex match failed: {response:?}"
    );
    assert_eq!(response["matched"], true);
    assert_eq!(response["match_text"], "foo");
    assert_eq!(response["match_offset"], 3);
    assert_eq!(response["match_index_chars"], 2);

    let invalid = aft.send(
        &json!({
            "id": "regex-invalid",
            "command": "bash_regex_match",
            "params": { "pattern": "(", "text": "" }
        })
        .to_string(),
    );
    assert_eq!(invalid["success"], false);
    assert_eq!(invalid["code"], "invalid_regex");
    assert!(aft.shutdown().success());
}

#[test]
fn register_pattern_watch_returns_watch_id() {
    let mut aft = AftProcess::spawn();
    let _dir = configure_background(&mut aft);
    let task_id = spawn(&mut aft, "sleep 1; echo READY");
    let response = notify(&mut aft, &task_id, json!({ "pattern": "READY" }));
    assert_eq!(response["success"], true, "notify failed: {response:?}");
    assert!(response["watch_id"].as_str().unwrap().starts_with("watch-"));
    assert!(aft.shutdown().success());
}

#[test]
fn pattern_match_emits_push_frame() {
    let mut aft = AftProcess::spawn();
    let dir = configure_background(&mut aft);
    let release = dir.path().join("pattern-release");
    let command = release_gate_command(&release, "READY");
    let task_id = spawn(&mut aft, &command);
    let response = notify(&mut aft, &task_id, json!({ "pattern": "READY" }));
    assert_eq!(response["success"], true, "notify failed: {response:?}");
    release_task(&release);
    let frame = wait_for_pattern_frame(&mut aft, &task_id);
    assert_eq!(frame["match_text"], "READY");
    assert_eq!(frame["once"], true);
    assert!(aft.shutdown().success());
}

#[cfg(unix)]
#[test]
fn pattern_match_offset_counts_original_bytes_before_invalid_utf8() {
    let mut aft = AftProcess::spawn();
    let dir = configure_background(&mut aft);
    let release = dir.path().join("invalid-utf8-release");
    let payload = dir.path().join("invalid-utf8-output");
    fs::write(&payload, b"\xffREADY\n").unwrap();
    let command = format!(
        "while [ ! -f {} ]; do sleep 0.05; done; cat {}",
        shell_quote(&release.display().to_string()),
        shell_quote(&payload.display().to_string()),
    );
    let task_id = spawn(&mut aft, &command);
    let response = notify(&mut aft, &task_id, json!({ "pattern": "READY" }));
    assert_eq!(response["success"], true, "notify failed: {response:?}");

    release_task(&release);
    let frame = wait_for_pattern_frame(&mut aft, &task_id);

    assert_eq!(frame["match_text"], "READY");
    assert_eq!(frame["match_offset"], 1);
    assert!(aft.shutdown().success());
}

#[test]
fn cap_8_watches_per_task_rejects_9th() {
    let mut aft = AftProcess::spawn();
    let _dir = configure_background(&mut aft);
    let task_id = spawn(&mut aft, "sleep 2");
    for idx in 0..8 {
        let response = notify(&mut aft, &task_id, json!({ "pattern": format!("x{idx}") }));
        assert_eq!(
            response["success"], true,
            "notify {idx} failed: {response:?}"
        );
    }
    let ninth = notify(&mut aft, &task_id, json!({ "pattern": "x9" }));
    assert_eq!(ninth["success"], false);
    assert_eq!(ninth["code"], "too_many_watches");
    assert!(aft.shutdown().success());
}

#[test]
fn regex_pattern_matches_with_capture() {
    let mut aft = AftProcess::spawn();
    let dir = configure_background(&mut aft);
    let release = dir.path().join("regex-release");
    let command = release_gate_command(&release, "port 3000");
    let task_id = spawn(&mut aft, &command);
    let response = notify(&mut aft, &task_id, json!({ "regex": "port (\\d+)" }));
    assert_eq!(response["success"], true, "notify failed: {response:?}");
    release_task(&release);
    let frame = wait_for_pattern_frame(&mut aft, &task_id);
    assert_eq!(frame["match_text"], "port 3000");
    assert!(aft.shutdown().success());
}

#[test]
fn final_output_scan_emits_pattern_before_completion_on_exit_race() {
    let mut aft = AftProcess::spawn();
    let dir = configure_background(&mut aft);
    let release = dir.path().join("exit-race-release");
    let command = release_gate_command(&release, "ready-now");
    let task_id = spawn(&mut aft, &command);
    let response = notify(&mut aft, &task_id, json!({ "pattern": "ready-now" }));
    assert_eq!(response["success"], true, "notify failed: {response:?}");
    release_task(&release);

    let started = Instant::now();
    loop {
        if let Some(frame) = aft.try_read_next_timeout(Duration::from_millis(200)) {
            if frame["task_id"] == task_id {
                assert_eq!(
                    frame["type"], "bash_pattern_match",
                    "watch-controlled task completed before final pattern scan: {frame:?}"
                );
                assert_eq!(frame["match_text"], "ready-now");
                assert_eq!(frame["reason"], "pattern_match");
                break;
            }
        }
        assert!(
            started.elapsed() < Duration::from_secs(6),
            "timed out waiting for first terminal watch frame"
        );
    }
    assert!(aft.shutdown().success());
}

#[test]
fn watch_controlled_exit_emits_exit_safety_net_not_completion() {
    let mut aft = AftProcess::spawn();
    let dir = configure_background(&mut aft);
    let release = dir.path().join("exit-safety-release");
    let command = release_gate_command(&release, "never-matches-output");
    let task_id = spawn(&mut aft, &command);
    let response = notify(&mut aft, &task_id, json!({ "pattern": "not-present" }));
    assert_eq!(response["success"], true, "notify failed: {response:?}");
    release_task(&release);

    let started = Instant::now();
    loop {
        if let Some(frame) = aft.try_read_next_timeout(Duration::from_millis(200)) {
            if frame["task_id"] != task_id {
                continue;
            }
            assert_eq!(
                frame["type"], "bash_pattern_match",
                "watch-controlled task emitted a background completion: {frame:?}"
            );
            assert_eq!(frame["reason"], "task_exit");
            assert!(frame["context"]
                .as_str()
                .unwrap()
                .contains("never-matches-output"));
            break;
        }
        assert!(
            started.elapsed() < Duration::from_secs(6),
            "timed out waiting for exit safety-net frame"
        );
    }

    let drained = aft.send(
        &json!({
            "id": "drain-watch-exit",
            "command": "bash_drain_completions"
        })
        .to_string(),
    );
    assert_eq!(drained["success"], true, "drain failed: {drained:?}");
    assert!(
        drained["bg_completions"]
            .as_array()
            .unwrap()
            .iter()
            .all(|completion| completion["task_id"] != task_id),
        "watch-controlled task also queued a normal completion: {drained:?}"
    );
    assert!(aft.shutdown().success());
}

#[test]
fn erased_watch_target_emits_tombstone_and_terminalizes_watch() {
    let mut aft = AftProcess::spawn();
    let dir = configure_background(&mut aft);
    let release = dir.path().join("erased-watch-release");
    let task_id = spawn(
        &mut aft,
        &release_gate_command(&release, "never-reached-erased-watch"),
    );
    let response = notify(&mut aft, &task_id, json!({ "pattern": "not-present" }));
    assert_eq!(response["success"], true, "notify failed: {response:?}");

    let db_path = aft.cache_dir().join("aft").join("aft.db");
    let conn = aft::db::open(&db_path).expect("open isolated test database");
    let deleted = conn
        .execute(
            "DELETE FROM bash_tasks WHERE harness = 'opencode' AND task_id = ?1",
            [&task_id],
        )
        .expect("erase watched task row");
    assert_eq!(deleted, 1, "armed task row must exist before mutation");

    let frame = wait_for_pattern_frame(&mut aft, &task_id);
    assert_eq!(frame["reason"], "task_exit");
    assert_eq!(frame["match_text"], "watch target erased");
    assert!(
        frame["context"]
            .as_str()
            .unwrap()
            .contains("background task row was erased"),
        "tombstone must explain the storage failure: {frame:?}"
    );
    let watch_state: (i64, i64, Option<String>) = conn
        .query_row(
            "SELECT scanning, pending_match, match_text
             FROM bash_pattern_watches
             WHERE harness = 'opencode' AND task_id = ?1",
            [&task_id],
            |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
        )
        .expect("tombstoned watch row remains pending until ack");
    assert_eq!(watch_state, (0, 1, Some("watch target erased".into())));

    let ack = aft.send(
        &json!({
            "id": "ack-erased-watch",
            "command": "bash_ack_completions",
            "params": { "task_ids": [&task_id] }
        })
        .to_string(),
    );
    assert_eq!(ack["success"], true, "tombstone ack failed: {ack:?}");
    assert_eq!(ack["acked_task_ids"], json!([task_id]));
    let remaining: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM bash_pattern_watches WHERE task_id = ?1",
            [&task_id],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(remaining, 0, "acked tombstone must be terminally removed");

    release_task(&release);
    assert!(aft.shutdown().success());
}

#[test]
fn bash_status_distinguishes_erased_watched_task_from_never_existing_task() {
    let mut aft = AftProcess::spawn();
    let dir = configure_background(&mut aft);
    let release = dir.path().join("erased-status-release");
    let task_id = spawn(
        &mut aft,
        &release_gate_command(&release, "never-reached-erased-status"),
    );
    let response = notify(&mut aft, &task_id, json!({ "pattern": "not-present" }));
    assert_eq!(response["success"], true, "notify failed: {response:?}");

    let conn = aft::db::open(&aft.cache_dir().join("aft").join("aft.db"))
        .expect("open isolated test database");
    assert_eq!(
        conn.execute(
            "DELETE FROM bash_tasks WHERE harness = 'opencode' AND task_id = ?1",
            [&task_id],
        )
        .expect("erase watched task row"),
        1
    );

    let erased = status(&mut aft, &task_id);
    assert_eq!(
        erased["success"], false,
        "erased status must fail: {erased:?}"
    );
    assert_eq!(erased["code"], "task_erased");
    assert!(
        erased["message"]
            .as_str()
            .unwrap()
            .contains("background task row was erased"),
        "erased error must not resemble a phantom id: {erased:?}"
    );

    let unknown = status(&mut aft, "bash-000000000000dead");
    assert_eq!(unknown["success"], false);
    assert_eq!(unknown["code"], "task_not_found");
    assert!(!unknown["message"]
        .as_str()
        .unwrap()
        .contains("row was erased"));

    release_task(&release);
    assert!(aft.shutdown().success());
}

#[test]
fn registering_watch_after_completion_removes_completion_and_emits_one_watch_frame() {
    let mut aft = AftProcess::spawn();
    let _dir = configure_background(&mut aft);
    let task_id = spawn(&mut aft, print_ready_after_complete_command());

    let started = Instant::now();
    loop {
        if let Some(frame) = aft.try_read_next_timeout(Duration::from_millis(200)) {
            if frame["task_id"] == task_id {
                assert_eq!(
                    frame["type"], "bash_completed",
                    "task should first complete normally before watch registration: {frame:?}"
                );
                break;
            }
        }
        assert!(
            started.elapsed() < Duration::from_secs(6),
            "timed out waiting for completion frame before watch registration"
        );
    }

    let response = notify(
        &mut aft,
        &task_id,
        json!({ "pattern": "READY-AFTER-COMPLETE" }),
    );
    assert_eq!(response["success"], true, "notify failed: {response:?}");

    let mut task_frames = Vec::new();
    let started = Instant::now();
    while started.elapsed() < Duration::from_secs(1) || task_frames.is_empty() {
        if let Some(frame) = aft.try_read_next_timeout(Duration::from_millis(100)) {
            if frame["task_id"] == task_id {
                task_frames.push(frame);
            }
        }
        if started.elapsed() > Duration::from_secs(6) {
            break;
        }
    }

    assert_eq!(
        task_frames.len(),
        1,
        "watch-after-completion should emit exactly one task frame: {task_frames:?}"
    );
    assert_eq!(task_frames[0]["type"], "bash_pattern_match");
    assert_eq!(task_frames[0]["reason"], "pattern_match");
    assert_eq!(task_frames[0]["match_text"], "READY-AFTER-COMPLETE");

    let drained = aft.send(
        &json!({
            "id": "drain-after-late-watch",
            "command": "bash_drain_completions"
        })
        .to_string(),
    );
    assert_eq!(drained["success"], true, "drain failed: {drained:?}");
    assert!(
        drained["bg_completions"]
            .as_array()
            .unwrap()
            .iter()
            .all(|completion| completion["task_id"] != task_id),
        "late watch should remove queued normal completion: {drained:?}"
    );
    assert!(aft.shutdown().success());
}