agent-file-tools 0.30.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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Integration tests for `inline_symbol` through the binary protocol.
//!
//! Uses temp-dir isolation (copy fixtures, mutate copies, verify results)
//! to test the full inline pipeline: argument substitution, scope conflict
//! detection, multiple-return rejection, and error paths.

use crate::helpers::{fixture_path, AftProcess};

/// Copy the `tests/fixtures/inline_symbol/` directory into a temp dir.
/// Returns `(TempDir, root_path)`.
fn setup_inline_fixture() -> (tempfile::TempDir, String) {
    let fixtures = fixture_path("inline_symbol");
    let tmp = tempfile::tempdir().expect("create temp dir");

    for entry in std::fs::read_dir(&fixtures).expect("read fixtures dir") {
        let entry = entry.expect("read entry");
        let src = entry.path();
        if src.is_file() {
            let dst = tmp.path().join(entry.file_name());
            std::fs::copy(&src, &dst).expect("copy fixture file");
        }
    }

    let root = tmp.path().display().to_string();
    (tmp, root)
}

/// Helper: configure aft with the given project root and assert success.
fn configure(aft: &mut AftProcess, root: &str) {
    let resp = aft.send(&format!(
        r#"{{"id":"cfg","command":"configure","harness":"opencode","project_root":"{}"}}"#,
        root
    ));
    assert_eq!(
        resp["success"], true,
        "configure should succeed: {:?}",
        resp
    );
}

// ---------------------------------------------------------------------------
// Success path tests
// ---------------------------------------------------------------------------

/// Inline an exported TS function. After the v0.30.x parser fix that
/// included the `export` keyword in symbol ranges (commit 57d48d9), the
/// inline path was unable to descend from `export_statement` to the inner
/// `function_declaration` and returned a `symbol_not_found` error.
#[test]
fn inline_symbol_exported_function() {
    let tmp = tempfile::tempdir().expect("create temp dir");
    let file = tmp.path().join("exported.ts");
    std::fs::write(
        &file,
        "export function double(n: number): number {\n  return n * 2;\n}\n\nexport function useIt(x: number): number {\n  return double(x);\n}\n",
    )
    .expect("write test file");

    let root = tmp.path().display().to_string();
    let mut aft = AftProcess::spawn();
    configure(&mut aft, &root);

    let resp = aft.send(&format!(
        r#"{{"id":"1","command":"inline_symbol","file":"{}","symbol":"double","call_site_line":6}}"#,
        file.display()
    ));

    assert_eq!(
        resp["success"], true,
        "inline of exported function should succeed: {:?}",
        resp
    );
    assert_eq!(resp["symbol"], "double");

    let content = std::fs::read_to_string(&file).expect("read file");
    assert!(
        !content.contains("double(x)"),
        "call should be replaced:\n{}",
        content
    );
    assert!(
        content.contains("x * 2"),
        "body should be substituted with argument:\n{}",
        content
    );

    aft.shutdown();
}

/// Basic inline: TS helper function call replaced with body.
#[test]
fn inline_symbol_basic_ts() {
    let (_tmp, root) = setup_inline_fixture();
    let mut aft = AftProcess::spawn();
    configure(&mut aft, &root);

    let file = format!("{}/sample.ts", root);

    // Inline `add` at line 10 (const result = add(x, y))
    let resp = aft.send(&format!(
        r#"{{"id":"1","command":"inline_symbol","file":"{}","symbol":"add","call_site_line":11}}"#,
        file
    ));

    assert_eq!(resp["success"], true, "inline should succeed: {:?}", resp);
    assert_eq!(resp["symbol"], "add");
    assert_eq!(resp["call_context"], "assignment");
    assert!(
        resp["substitutions"].as_u64().unwrap() > 0,
        "should have substitutions"
    );

    // Verify call was replaced
    let content = std::fs::read_to_string(&file).expect("read file");
    assert!(
        !content.contains("add(x, y)"),
        "call should be replaced:\n{}",
        content
    );

    aft.shutdown();
}

/// Expression-body arrow function: implicit return inlined correctly.
#[test]
fn inline_symbol_expression_body() {
    let (_tmp, root) = setup_inline_fixture();
    let mut aft = AftProcess::spawn();
    configure(&mut aft, &root);

    let file = format!("{}/sample.ts", root);

    // Inline `double` at line 17 (const val = double(5)) — 0-indexed
    let resp = aft.send(&format!(
        r#"{{"id":"1","command":"inline_symbol","file":"{}","symbol":"double","call_site_line":18}}"#,
        file
    ));

    assert_eq!(
        resp["success"], true,
        "inline expression body should succeed: {:?}",
        resp
    );
    assert_eq!(resp["symbol"], "double");

    // Verify call was replaced
    let content = std::fs::read_to_string(&file).expect("read file");
    assert!(
        !content.contains("double(5)"),
        "call should be replaced:\n{}",
        content
    );

    aft.shutdown();
}

/// Python inline.
#[test]
fn inline_symbol_python() {
    let (_tmp, root) = setup_inline_fixture();
    let mut aft = AftProcess::spawn();
    configure(&mut aft, &root);

    let file = format!("{}/sample.py", root);

    // Inline `add` at line 9 (result = add(x, y)) — 0-indexed
    let resp = aft.send(&format!(
        r#"{{"id":"1","command":"inline_symbol","file":"{}","symbol":"add","call_site_line":10}}"#,
        file
    ));

    assert_eq!(
        resp["success"], true,
        "python inline should succeed: {:?}",
        resp
    );
    assert_eq!(resp["symbol"], "add");

    // Verify call was replaced
    let content = std::fs::read_to_string(&file).expect("read file");
    assert!(
        !content.contains("add(x, y)"),
        "call should be replaced:\n{}",
        content
    );

    aft.shutdown();
}

// ---------------------------------------------------------------------------
// Error path tests
// ---------------------------------------------------------------------------

/// Multiple-returns error: function with 2 returns rejected.
#[test]
fn inline_symbol_multiple_returns() {
    let (_tmp, root) = setup_inline_fixture();
    let mut aft = AftProcess::spawn();
    configure(&mut aft, &root);

    let file = format!("{}/sample_multi.ts", root);

    // multiReturn has 2 return statements
    let resp = aft.send(&format!(
        r#"{{"id":"1","command":"inline_symbol","file":"{}","symbol":"multiReturn","call_site_line":9}}"#,
        file
    ));

    assert_eq!(resp["success"], false, "should fail: {:?}", resp);
    assert_eq!(resp["code"], "multiple_returns");
    assert!(
        resp["return_count"].as_u64().unwrap() >= 2,
        "should report return count"
    );

    aft.shutdown();
}

/// Scope-conflict error: response includes conflicting variable names and suggestions.
#[test]
fn inline_symbol_scope_conflict() {
    let (_tmp, root) = setup_inline_fixture();
    let mut aft = AftProcess::spawn();
    configure(&mut aft, &root);

    let file = format!("{}/sample_conflict.ts", root);

    // compute() body declares `temp` and `result`, both exist at call site
    let resp = aft.send(&format!(
        r#"{{"id":"1","command":"inline_symbol","file":"{}","symbol":"compute","call_site_line":9}}"#,
        file
    ));

    assert_eq!(
        resp["success"], false,
        "should fail with scope_conflict: {:?}",
        resp
    );
    assert_eq!(resp["code"], "scope_conflict");

    let conflicting = resp["conflicting_names"]
        .as_array()
        .expect("conflicting_names array");
    assert!(
        !conflicting.is_empty(),
        "should report at least one conflicting name: {:?}",
        conflicting
    );

    let suggestions = resp["suggestions"].as_array().expect("suggestions array");
    assert!(
        !suggestions.is_empty(),
        "should include rename suggestions: {:?}",
        suggestions
    );
    // Each suggestion should have original and suggested fields
    for s in suggestions {
        assert!(
            s["original"].as_str().is_some(),
            "suggestion should have 'original': {:?}",
            s
        );
        assert!(
            s["suggested"].as_str().is_some(),
            "suggestion should have 'suggested': {:?}",
            s
        );
    }

    aft.shutdown();
}

/// Inline preserves the original line indentation. Without the leading-
/// whitespace expansion fix, the replacement text's indent prefix would be
/// inserted AFTER the original indent on the line, doubling it (e.g. a
/// 2-space-indented line became 4-space-indented).
#[test]
fn inline_symbol_preserves_call_site_indent() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let file = tmp.path().join("indent.ts");
    std::fs::write(
        &file,
        "function helper(x: number): number {\n  return x * 2;\n}\n\nexport function main() {\n  const result = helper(5);\n  console.log(result);\n}\n",
    )
    .expect("write fixture");

    let mut aft = AftProcess::spawn();
    configure(&mut aft, &tmp.path().display().to_string());

    let resp = aft.send(&format!(
        r#"{{"id":"1","command":"inline_symbol","file":"{}","symbol":"helper","call_site_line":6}}"#,
        file.display()
    ));
    assert_eq!(resp["success"], true, "inline should succeed: {:?}", resp);

    let content = std::fs::read_to_string(&file).expect("read file");
    // The replacement line must keep its original 2-space indent. If the
    // bug regressed, this would be 4 spaces.
    assert!(
        content.contains("\n  const result = 5 * 2;\n"),
        "expected 2-space indent on inlined line, got:\n{}",
        content
    );
    assert!(
        !content.contains("    const result"),
        "indent should not be doubled, got:\n{}",
        content
    );

    aft.shutdown();
}

/// Parameter substitution should rewrite only references bound to the inlined
/// function's parameters. Nested arrow parameters that shadow the same name must
/// stay untouched.
#[test]
fn inline_symbol_does_not_substitute_shadowed_arrow_parameter() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let file = tmp.path().join("shadowed_arrow.ts");
    std::fs::write(
        &file,
        "function f(x: number): number {\n  return x + items.map(x => x + 1)[0];\n}\n\nconst items = [1, 2];\n\nfunction main() {\n  const result = f(5);\n}\n",
    )
    .expect("write fixture");

    let mut aft = AftProcess::spawn();
    configure(&mut aft, &tmp.path().display().to_string());

    let resp = aft.send(&format!(
        r#"{{"id":"1","command":"inline_symbol","file":"{}","symbol":"f","call_site_line":8}}"#,
        file.display()
    ));
    assert_eq!(resp["success"], true, "inline should succeed: {:?}", resp);

    let content = std::fs::read_to_string(&file).expect("read file");
    let expected = "  const result = 5 + items.map(x => x + 1)[0];";
    assert!(
        content.contains(expected),
        "outer `x` should be substituted while nested arrow `x` remains:\n{}",
        content
    );
    assert!(
        !content.contains("items.map(5 => 5 + 1)"),
        "nested arrow parameter must not be substituted:\n{}",
        content
    );

    aft.shutdown();
}

/// `inline_symbol` should accept a target call_site_line that points at the
/// first line of a multiline call (e.g. `helper(\n  a,\n  b,\n)`), rather than
/// rejecting it as call_not_found.
#[test]
fn inline_symbol_matches_multiline_call_starting_on_target_line() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let file = tmp.path().join("multiline.ts");
    std::fs::write(
        &file,
        "function helper(a: number, b: number): number {\n  return a + b;\n}\n\nexport function main() {\n  const result = helper(\n    1,\n    2,\n  );\n  console.log(result);\n}\n",
    )
    .expect("write fixture");

    let mut aft = AftProcess::spawn();
    configure(&mut aft, &tmp.path().display().to_string());

    let resp = aft.send(&format!(
        r#"{{"id":"multiline","command":"inline_symbol","file":"{}","symbol":"helper","call_site_line":6}}"#,
        file.display()
    ));
    assert_eq!(
        resp["success"], true,
        "inline should match multiline call by start line: {:?}",
        resp
    );

    let content = std::fs::read_to_string(&file).expect("read file");
    assert!(
        !content.contains("helper(\n"),
        "multiline call should be replaced:\n{}",
        content
    );
    assert!(
        content.contains("\n  const result = 1 + 2;\n"),
        "expected inlined expression, got:\n{}",
        content
    );

    aft.shutdown();
}

#[test]
fn inline_symbol_preserves_nested_multiline_indentation() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let file = tmp.path().join("nested_indent.ts");
    std::fs::write(
        &file,
        r#"function helper(items: number[]): void {
  for (const item of items) {
    if (item > 0) {
      console.log(item);
    }
  }
}

const values = [1, 2];

export function main() {
  helper(values);
}
"#,
    )
    .expect("write fixture");

    let mut aft = AftProcess::spawn();
    configure(&mut aft, &tmp.path().display().to_string());

    let resp = aft.send(&format!(
        r#"{{"id":"nested-indent","command":"inline_symbol","file":"{}","symbol":"helper","call_site_line":12}}"#,
        file.display()
    ));
    assert_eq!(resp["success"], true, "inline should succeed: {resp:?}");

    let content = std::fs::read_to_string(&file).expect("read file");
    let expected =
        "  for (const item of values) {\n    if (item > 0) {\n      console.log(item);\n    }\n  }";
    assert!(
        content.contains(expected),
        "nested relative indentation should be preserved:\n{content}"
    );

    aft.shutdown();
}

#[test]
fn inline_symbol_standalone_return_expression_becomes_expression_statement() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let file = tmp.path().join("standalone_return.ts");
    std::fs::write(
        &file,
        r#"function helper(): number {
  audit();
  return sideEffect();
}

function audit(): void {}
function sideEffect(): number { return 1; }

export function main() {
  helper();
}
"#,
    )
    .expect("write fixture");

    let mut aft = AftProcess::spawn();
    configure(&mut aft, &tmp.path().display().to_string());

    let resp = aft.send(&format!(
        r#"{{"id":"standalone-return","command":"inline_symbol","file":"{}","symbol":"helper","call_site_line":10}}"#,
        file.display()
    ));
    assert_eq!(resp["success"], true, "inline should succeed: {resp:?}");

    let content = std::fs::read_to_string(&file).expect("read file");
    assert!(
        content.contains("  audit();\n  sideEffect();"),
        "return expression should be kept as an expression statement:\n{content}"
    );
    aft.shutdown();
}

#[test]
fn inline_symbol_maps_destructured_default_and_rest_parameters() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let file = tmp.path().join("params.ts");
    std::fs::write(
        &file,
        r#"type Point = { x: number; y: number };

function describe({ x, y }: Point, [first, second]: number[], label = 'pt', ...rest: string[]): string {
  return `${label}:${x + y}:${first + second}:${rest.join(',')}`;
}

const point = { x: 1, y: 2 };
const pair = [3, 4];

export function main() {
  const result = describe(point, pair, 'p', 'a', 'b');
  console.log(result);
}
"#,
    )
    .expect("write fixture");

    let mut aft = AftProcess::spawn();
    configure(&mut aft, &tmp.path().display().to_string());

    let resp = aft.send(&format!(
        r#"{{"id":"params","command":"inline_symbol","file":"{}","symbol":"describe","call_site_line":11}}"#,
        file.display()
    ));
    assert_eq!(resp["success"], true, "inline should succeed: {resp:?}");

    let content = std::fs::read_to_string(&file).expect("read file");
    assert!(
        content.contains("point.x + point.y"),
        "object destructuring bindings should map to variable properties:\n{content}"
    );
    assert!(
        content.contains("pair[0] + pair[1]"),
        "array destructuring bindings should map to indexed accesses:\n{content}"
    );
    assert!(
        content.contains("['a', 'b'].join(',')"),
        "rest parameter should map to an array literal of remaining args:\n{content}"
    );
    assert!(
        !content.contains("describe(point"),
        "call should be replaced:\n{content}"
    );

    aft.shutdown();
}

#[test]
fn inline_symbol_refuses_destructuring_from_non_variable_argument() {
    let tmp = tempfile::tempdir().expect("temp dir");
    let file = tmp.path().join("params_mismatch.ts");
    std::fs::write(
        &file,
        r#"type Point = { x: number; y: number };

function sumPoint({ x, y }: Point): number {
  return x + y;
}

export function main() {
  const result = sumPoint({ x: 1, y: 2 });
  console.log(result);
}
"#,
    )
    .expect("write fixture");

    let mut aft = AftProcess::spawn();
    configure(&mut aft, &tmp.path().display().to_string());

    let resp = aft.send(&format!(
        r#"{{"id":"params-mismatch","command":"inline_symbol","file":"{}","symbol":"sumPoint","call_site_line":8}}"#,
        file.display()
    ));
    assert_eq!(resp["success"], false, "inline should fail: {resp:?}");
    assert_eq!(resp["code"], "param_mismatch", "wrong error: {resp:?}");

    aft.shutdown();
}