agent-file-tools 0.47.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
use std::fs;
use std::path::{Path, PathBuf};

use serde_json::{json, Value};

use super::helpers::AftProcess;

fn configured_aft(project: &Path) -> AftProcess {
    let mut aft = AftProcess::spawn();
    let configure = aft.send(
        &json!({
            "id": "cfg-apply-patch",
            "command": "configure",
            "harness": "opencode",
            "project_root": project,
        })
        .to_string(),
    );
    assert_eq!(
        configure["success"], true,
        "configure failed: {configure:?}"
    );
    aft
}

fn write_file(root: &Path, relative: &str, content: &str) -> PathBuf {
    let path = root.join(relative);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).unwrap();
    }
    fs::write(&path, content).unwrap();
    path
}

fn apply(aft: &mut AftProcess, id: &str, patch_text: &str) -> Value {
    aft.send(
        &json!({
            "id": id,
            "command": "apply_patch",
            "params": { "patch_text": patch_text },
        })
        .to_string(),
    )
}

fn preview(aft: &mut AftProcess, id: &str, patch_text: &str) -> Value {
    aft.send(
        &json!({
            "id": id,
            "command": "apply_patch",
            "params": { "patch_text": patch_text, "preview": true },
        })
        .to_string(),
    )
}

#[test]
fn apply_patch_full_multifile_and_single_undo_reverts_all() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    write_file(root, "update.txt", "alpha\nold\nomega\n");
    write_file(root, "delete.txt", "remove me\n");
    let mut aft = configured_aft(root);

    let patch = r#"*** Begin Patch
*** Add File: add.txt
+created
*** Update File: update.txt
@@
 alpha
-old
+new
 omega
*** Delete File: delete.txt
*** End Patch"#;

    let resp = apply(&mut aft, "apply-full", patch);
    assert_eq!(resp["success"], true, "patch failed: {resp:?}");
    assert_eq!(resp["complete"], true);
    assert_eq!(resp["partial"], false);
    assert_eq!(resp["metadata"]["files"].as_array().unwrap().len(), 3);
    assert_eq!(
        fs::read_to_string(root.join("add.txt")).unwrap(),
        "created\n"
    );
    assert_eq!(
        fs::read_to_string(root.join("update.txt")).unwrap(),
        "alpha\nnew\nomega\n"
    );
    assert!(!root.join("delete.txt").exists());

    let undo = aft.send(&json!({ "id": "undo-full", "command": "undo" }).to_string());
    assert_eq!(undo["success"], true, "undo failed: {undo:?}");
    assert_eq!(undo["operation"], true);
    assert_eq!(
        undo["restored_count"], 2,
        "content backups restored: {undo:?}"
    );
    assert!(!root.join("add.txt").exists());
    assert_eq!(
        fs::read_to_string(root.join("update.txt")).unwrap(),
        "alpha\nold\nomega\n"
    );
    assert_eq!(
        fs::read_to_string(root.join("delete.txt")).unwrap(),
        "remove me\n"
    );

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

#[test]
fn apply_patch_update_uses_reflow_fuzzy_hunk() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    write_file(
        root,
        "reflow.txt",
        "const message = first + second + third;\n",
    );
    let mut aft = configured_aft(root);

    let patch = r#"*** Begin Patch
*** Update File: reflow.txt
@@
-const message = first +
-  second +
-  third;
+const message = first + second + fourth;
*** End Patch"#;

    let resp = apply(&mut aft, "apply-reflow", patch);
    assert_eq!(resp["success"], true, "reflow patch failed: {resp:?}");
    assert_eq!(
        fs::read_to_string(root.join("reflow.txt")).unwrap(),
        "const message = first + second + fourth;\n"
    );

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

#[test]
fn apply_patch_move_happy_path_and_undo_restores_source() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    write_file(root, "source.txt", "before\nkeep\n");
    let mut aft = configured_aft(root);

    let patch = r#"*** Begin Patch
*** Update File: source.txt
*** Move to: nested/dest.txt
@@
-before
+after
 keep
*** End Patch"#;

    let resp = apply(&mut aft, "apply-move", patch);
    assert_eq!(resp["success"], true, "move failed: {resp:?}");
    let file = &resp["metadata"]["files"][0];
    assert_eq!(file["type"], "move");
    assert_eq!(file["relativePath"], "nested/dest.txt");
    assert!(file["movePath"]
        .as_str()
        .unwrap()
        .ends_with("nested/dest.txt"));
    assert!(!root.join("source.txt").exists());
    assert_eq!(
        fs::read_to_string(root.join("nested/dest.txt")).unwrap(),
        "after\nkeep\n"
    );

    let undo = aft.send(&json!({ "id": "undo-move", "command": "undo" }).to_string());
    assert_eq!(undo["success"], true, "undo failed: {undo:?}");
    assert_eq!(
        fs::read_to_string(root.join("source.txt")).unwrap(),
        "before\nkeep\n"
    );
    assert!(!root.join("nested/dest.txt").exists());

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

#[test]
fn apply_patch_same_path_move_is_an_in_place_update_and_undoable() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    write_file(root, "source.txt", "before\nkeep\n");
    let mut aft = configured_aft(root);

    let patch = r#"*** Begin Patch
*** Update File: source.txt
*** Move to: source.txt
@@
-before
+after
 keep
*** End Patch"#;

    let resp = apply(&mut aft, "apply-same-path-move", patch);
    assert_eq!(resp["success"], true, "same-path update failed: {resp:?}");
    assert_eq!(resp["output"], "Updated source.txt");
    let file = &resp["metadata"]["files"][0];
    assert_eq!(file["type"], "update");
    assert_eq!(file["relativePath"], "source.txt");
    assert!(file.get("movePath").is_none());
    assert_eq!(
        fs::read_to_string(root.join("source.txt")).unwrap(),
        "after\nkeep\n"
    );

    let undo = aft.send(&json!({ "id": "undo-same-path", "command": "undo" }).to_string());
    assert_eq!(undo["success"], true, "undo failed: {undo:?}");
    assert_eq!(
        fs::read_to_string(root.join("source.txt")).unwrap(),
        "before\nkeep\n"
    );

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

#[test]
fn apply_patch_same_path_move_alias_is_an_in_place_update() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    write_file(root, "source.txt", "before\n");
    let mut aft = configured_aft(root);

    let patch = r#"*** Begin Patch
*** Update File: source.txt
*** Move to: ./source.txt
@@
-before
+after
*** End Patch"#;

    let resp = apply(&mut aft, "apply-same-path-alias", patch);
    assert_eq!(resp["success"], true, "aliased update failed: {resp:?}");
    assert_eq!(resp["output"], "Updated source.txt");
    let file = &resp["metadata"]["files"][0];
    assert_eq!(file["type"], "update");
    assert!(file.get("movePath").is_none());
    assert_eq!(
        fs::read_to_string(root.join("source.txt")).unwrap(),
        "after\n"
    );

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

#[test]
fn apply_patch_same_path_move_preview_is_an_in_place_diff() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    write_file(root, "source.txt", "before\nkeep\n");
    let mut aft = configured_aft(root);

    let patch = r#"*** Begin Patch
*** Update File: source.txt
*** Move to: source.txt
@@
-before
+after
 keep
*** End Patch"#;

    let resp = preview(&mut aft, "preview-same-path-move", patch);
    assert_eq!(resp["success"], true, "preview failed: {resp:?}");
    assert_eq!(resp["preview"], true);
    assert_eq!(resp["affected_rel_paths"], json!(["source.txt"]));
    assert!(resp["preview_diff"]
        .as_str()
        .unwrap()
        .contains("-before\n+after"));
    assert_eq!(
        fs::read_to_string(root.join("source.txt")).unwrap(),
        "before\nkeep\n"
    );

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

#[test]
fn apply_patch_partial_keeps_successful_hunks_and_reports_failure() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    write_file(root, "one.txt", "old\n");
    write_file(
        root,
        "two.txt",
        "header\nfunction two() {\n  const first = 1;\n  const actual = 2;\n  return first;\n}\n",
    );
    let mut aft = configured_aft(root);

    let patch = r#"*** Begin Patch
*** Update File: one.txt
@@
-old
+new
*** Update File: two.txt
@@
 function two() {
   const first = 1;
-  const expected = 2;
+  const replacement = 2;
   return first;
 }
*** End Patch"#;

    let resp = apply(&mut aft, "apply-partial", patch);
    assert_eq!(
        resp["success"], true,
        "partial should be success envelope: {resp:?}"
    );
    assert_eq!(resp["complete"], false);
    assert_eq!(resp["partial"], true);
    assert_eq!(resp["all_failed"], false);
    assert_eq!(fs::read_to_string(root.join("one.txt")).unwrap(), "new\n");
    assert_eq!(
        fs::read_to_string(root.join("two.txt")).unwrap(),
        "header\nfunction two() {\n  const first = 1;\n  const actual = 2;\n  return first;\n}\n"
    );
    let failure = resp["failures"][0]["error"].as_str().unwrap();
    assert!(failure.contains("Failed to find expected lines"));
    assert!(failure.contains("Nearest miss at lines 2-6 (matched 4/5 context lines)"));
    assert!(failure.contains("  4 |   const actual = 2;"));
    assert!(failure.contains(
        "First divergence: wanted line 3 `  const expected = 2;` vs file line 4 `  const actual = 2;`"
    ));
    assert!(resp["output"].as_str().unwrap().contains("Nearest miss"));

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

#[test]
fn apply_patch_total_failure_returns_error_envelope_without_writes() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    let original = "preamble\nfn target() {\n  let first = 1;\n  let actual = 2;\n  return first;\n}\ntrailer\n";
    write_file(root, "target.txt", original);
    let mut aft = configured_aft(root);

    let patch = r#"*** Begin Patch
*** Update File: target.txt
@@
 fn target() {
   let first = 1;
-  let expected = 2;
+  let replacement = 2;
   return first;
 }
*** End Patch"#;

    let resp = apply(&mut aft, "apply-total-failure", patch);
    assert_eq!(
        resp["success"], false,
        "total failure should be error: {resp:?}"
    );
    assert_eq!(resp["code"], "apply_patch_failed");
    assert_eq!(resp["complete"], false);
    assert_eq!(resp["all_failed"], true);
    assert_eq!(resp["partial"], false);
    assert_eq!(resp["metadata"]["files"].as_array().unwrap().len(), 0);
    assert_eq!(
        fs::read_to_string(root.join("target.txt")).unwrap(),
        original
    );

    let nearest_block = "Nearest miss at lines 2-6 (matched 4/5 context lines):";
    assert!(resp["message"].as_str().unwrap().contains(nearest_block));
    assert!(resp["output"].as_str().unwrap().contains(nearest_block));
    let failure = resp["failures"][0]["error"].as_str().unwrap();
    assert!(failure.contains(nearest_block));
    assert!(failure.contains("  4 |   let actual = 2;"));
    assert!(failure.contains(
        "First divergence: wanted line 3 `  let expected = 2;` vs file line 4 `  let actual = 2;`"
    ));

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

#[test]
fn apply_patch_preview_reports_diff_and_leaves_disk_unchanged() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    write_file(root, "existing.txt", "old\n");
    let mut aft = configured_aft(root);

    let patch = r#"*** Begin Patch
*** Add File: preview-new.txt
+created
*** Update File: existing.txt
@@
-old
+new
*** End Patch"#;

    let resp = preview(&mut aft, "preview-valid", patch);
    assert_eq!(resp["success"], true, "preview failed: {resp:?}");
    assert_eq!(resp["preview"], true);
    assert!(resp["preview_diff"]
        .as_str()
        .unwrap()
        .contains("preview-new.txt"));
    assert_eq!(resp["affected_rel_paths"].as_array().unwrap().len(), 2);
    assert!(!root.join("preview-new.txt").exists());
    assert_eq!(
        fs::read_to_string(root.join("existing.txt")).unwrap(),
        "old\n"
    );

    let invalid = r#"*** Begin Patch
*** Update File: existing.txt
@@
-missing
+new
*** End Patch"#;
    let err = preview(&mut aft, "preview-invalid", invalid);
    assert_eq!(
        err["success"], false,
        "invalid preview should fail: {err:?}"
    );
    assert_eq!(
        fs::read_to_string(root.join("existing.txt")).unwrap(),
        "old\n"
    );

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

#[test]
fn apply_patch_add_existing_fails_and_syntax_rollback_does_not_poison_undo() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path();
    write_file(root, "exists.txt", "already\n");
    write_file(root, "good.ts", "const good = 1;\n");
    write_file(root, "bad.ts", "const value = 1;\n");
    let mut aft = configured_aft(root);

    let add_existing = r#"*** Begin Patch
*** Add File: exists.txt
+replacement
*** End Patch"#;
    let add_resp = apply(&mut aft, "add-existing", add_existing);
    assert_eq!(
        add_resp["success"], false,
        "add existing should fail: {add_resp:?}"
    );
    assert!(add_resp["failures"][0]["error"]
        .as_str()
        .unwrap()
        .contains("file already exists"));
    assert_eq!(
        fs::read_to_string(root.join("exists.txt")).unwrap(),
        "already\n"
    );

    let mixed = r#"*** Begin Patch
*** Update File: good.ts
@@
-const good = 1;
+const good = 2;
*** Update File: bad.ts
@@
-const value = 1;
+const value = {;
*** End Patch"#;
    let resp = apply(&mut aft, "syntax-rollback", mixed);
    assert_eq!(
        resp["success"], true,
        "mixed patch should be partial: {resp:?}"
    );
    assert_eq!(resp["partial"], true);
    assert_eq!(
        fs::read_to_string(root.join("good.ts")).unwrap(),
        "const good = 2;\n"
    );
    assert_eq!(
        fs::read_to_string(root.join("bad.ts")).unwrap(),
        "const value = 1;\n"
    );

    let undo = aft.send(&json!({ "id": "undo-syntax", "command": "undo" }).to_string());
    assert_eq!(
        undo["success"], true,
        "undo should restore only successful hunk: {undo:?}"
    );
    assert_eq!(
        fs::read_to_string(root.join("good.ts")).unwrap(),
        "const good = 1;\n"
    );
    assert_eq!(
        fs::read_to_string(root.join("bad.ts")).unwrap(),
        "const value = 1;\n"
    );

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