aboutsummaryrefslogtreecommitdiffstats
path: root/tests/tools.rs
blob: 4a8176e8da603186c67f5151145e9daa8e1aa76e (plain) (blame)
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
use std::fs;
use std::path::PathBuf;
use std::time::Duration;

use serde_json::json;

use agent686::tools::{self, shell};
use std::sync::atomic::AtomicBool;

fn run(name: &str, args: &serde_json::Value) -> Result<String, String> {
    tools::run(name, args, &AtomicBool::new(false))
}

fn temp_dir(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("agent686-test-{tag}-{}", std::process::id()));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).unwrap();
    dir
}

#[test]
fn edit_refuses_ambiguous_and_missing_text() {
    let dir = temp_dir("edit-ambiguous");
    let path = dir.join("a.txt");
    fs::write(&path, "alpha\nbeta\nalpha\n").unwrap();

    let error = tools::plan("edit", &json!({ "path": path, "old": "alpha", "new": "gamma" }))
        .err()
        .expect("ambiguous edit must fail");
    assert!(error.contains("appears 2 times"), "{error}");
    assert!(error.contains("lines 1, 3"), "{error}");

    let error = tools::plan("edit", &json!({ "path": path, "old": "nope", "new": "x" }))
        .err()
        .expect("missing text must fail");
    assert!(error.contains("was not found"), "{error}");

    // The file is untouched by a refused plan.
    assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta\nalpha\n");
}

#[test]
fn edit_applies_exactly_one_replacement() {
    let dir = temp_dir("edit-apply");
    let path = dir.join("main.c");
    fs::write(&path, "int main(void) {\n    return 0;\n}\n").unwrap();

    let change = tools::plan(
        "edit",
        &json!({ "path": path, "old": "    return 0;", "new": "    return 1;" }),
    )
    .expect("unique edit should plan");

    let preview = change.preview().unwrap();
    assert!(preview.contains("-     return 0;"), "{preview}");
    assert!(preview.contains("+     return 1;"), "{preview}");

    let outcome = change.apply().expect("apply should succeed");
    assert!(outcome.contains("1 replacement at line 2"), "{outcome}");
    assert_eq!(
        fs::read_to_string(&path).unwrap(),
        "int main(void) {\n    return 1;\n}\n"
    );
}

#[test]
fn write_does_not_create_parent_directories() {
    let dir = temp_dir("write-parent");
    let path = dir.join("missing").join("file.txt");
    let change = tools::plan("write", &json!({ "path": path, "content": "hi" })).unwrap();
    let error = change.apply().err().expect("apply must fail");
    assert!(error.contains("parent directory does not exist"), "{error}");
}

#[test]
fn read_numbers_lines_and_reports_truncation() {
    let dir = temp_dir("read");
    let path = dir.join("f.txt");
    fs::write(&path, "one\ntwo\nthree\nfour\n").unwrap();

    let text = run("read", &json!({ "path": path, "limit": 2 })).unwrap();
    assert!(text.contains("     1\tone"), "{text}");
    assert!(text.contains("     2\ttwo"), "{text}");
    assert!(text.contains("continue with offset=3"), "{text}");
    assert!(!text.contains("three"), "{text}");
}

#[test]
fn grep_finds_lines_and_honours_case() {
    let dir = temp_dir("grep");
    let path = dir.join("f.txt");
    fs::write(&path, "alpha\nbeta\nALPHA\n").unwrap();

    let text = run("grep", &json!({ "pattern": "alpha", "path": dir })).unwrap();
    assert_eq!(text.lines().count(), 1, "{text}");

    let text = run(
        "grep",
        &json!({ "pattern": "alpha", "path": dir, "ignore_case": true }),
    )
    .unwrap();
    assert_eq!(text.lines().count(), 2, "{text}");
}

#[test]
fn glob_supports_double_star_and_bare_names() {
    let dir = temp_dir("glob");
    fs::create_dir_all(dir.join("sub/deep")).unwrap();
    fs::write(dir.join("a.rs"), "").unwrap();
    fs::write(dir.join("sub/b.rs"), "").unwrap();
    fs::write(dir.join("sub/deep/c.rs"), "").unwrap();
    fs::write(dir.join("sub/note.txt"), "").unwrap();

    let text = run("glob", &json!({ "pattern": "**/*.rs", "path": dir })).unwrap();
    assert_eq!(text.lines().count(), 3, "{text}");

    let text = run("glob", &json!({ "pattern": "*.rs", "path": dir })).unwrap();
    assert_eq!(text.lines().count(), 3, "{text}");

    let text = run("glob", &json!({ "pattern": "sub/*.rs", "path": dir })).unwrap();
    assert_eq!(text.lines().count(), 1, "{text}");
    assert!(text.contains("b.rs"), "{text}");
}

#[test]
fn bash_reports_exit_code_and_times_out() {
    let text = run("bash", &json!({ "cmd": "echo hi; exit 3" })).unwrap();
    assert!(text.contains("hi"), "{text}");
    assert!(text.contains("[exit 3]"), "{text}");

    let text = shell::bash(&json!({ "cmd": "sleep 5" }), Duration::from_millis(150), &AtomicBool::new(false)).unwrap();
    assert!(text.contains("timed out after"), "{text}");
}

#[test]
fn bash_rejects_a_missing_cwd() {
    let error = run("bash", &json!({ "cmd": "true", "cwd": "/nonexistent-dir-xyz" }))
        .err()
        .expect("missing cwd must fail");
    assert!(error.contains("cwd is not a directory"), "{error}");
}

#[test]
fn unknown_tool_is_an_error_not_a_panic() {
    let error = run("teleport", &json!({})).err().unwrap();
    assert!(error.contains("unknown tool"), "{error}");
}

#[test]
fn read_streams_large_files_and_reports_the_next_offset() {
    let dir = temp_dir("read-large");
    let path = dir.join("big.txt");
    let mut body = String::new();
    for n in 1..=1000 {
        body.push_str(&format!("line {n}\n"));
    }
    fs::write(&path, body).unwrap();

    let text = run("read", &json!({ "path": path, "offset": 990, "limit": 5 })).unwrap();
    assert!(text.contains("   990\tline 990"), "{text}");
    assert!(text.contains("   994\tline 994"), "{text}");
    assert!(!text.contains("line 995"), "{text}");
    assert!(text.contains("continue with offset=995"), "{text}");
}

#[test]
fn read_clips_a_single_enormous_line() {
    let dir = temp_dir("read-huge-line");
    let path = dir.join("one-line.txt");
    fs::write(&path, "x".repeat(5 * 1024 * 1024)).unwrap();

    let text = run("read", &json!({ "path": path })).unwrap();
    assert!(text.starts_with("     1\tx"), "{text}");
    assert!(text.contains("line truncated"), "{text}");
    // Bounded by the per-line cap, not by the file size.
    assert!(text.len() < 1000, "read produced {} bytes", text.len());
}

#[test]
fn read_reports_an_offset_past_the_end() {
    let dir = temp_dir("read-eof");
    let path = dir.join("short.txt");
    fs::write(&path, "only\n").unwrap();
    let text = run("read", &json!({ "path": path, "offset": 9 })).unwrap();
    assert!(text.contains("fewer than 9 lines"), "{text}");
}

#[test]
fn read_refuses_binaries_and_directories() {
    let dir = temp_dir("read-binary");
    let binary = dir.join("blob.bin");
    fs::write(&binary, [0u8, 1, 2, 3, 0, 9]).unwrap();
    let error = run("read", &json!({ "path": binary })).err().unwrap();
    assert!(error.contains("binary"), "{error}");

    let error = run("read", &json!({ "path": dir })).err().unwrap();
    assert!(error.contains("is a directory"), "{error}");
}

#[test]
fn read_handles_a_missing_trailing_newline() {
    let dir = temp_dir("read-no-newline");
    let path = dir.join("f.txt");
    fs::write(&path, "one\ntwo").unwrap();
    let text = run("read", &json!({ "path": path })).unwrap();
    assert!(text.contains("     2\ttwo"), "{text}");
    assert!(!text.contains("continue with offset"), "{text}");
}

#[test]
fn grep_uses_regular_expressions_by_default() {
    let dir = temp_dir("grep-regex");
    fs::write(
        dir.join("f.rs"),
        "fn main() {\n    fn    other() {\n}\n",
    )
    .unwrap();

    let text = run("grep", &json!({ "pattern": r"fn\s+main", "path": dir })).unwrap();
    assert_eq!(text.lines().count(), 1, "{text}");

    let text = run("grep", &json!({ "pattern": r"fn\s+\w+", "path": dir })).unwrap();
    assert_eq!(text.lines().count(), 2, "{text}");

    let text = run(
        "grep",
        &json!({ "pattern": r"FN\s+MAIN", "path": dir, "ignore_case": true }),
    )
    .unwrap();
    assert_eq!(text.lines().count(), 1, "{text}");
}

#[test]
fn grep_fixed_matches_literally_and_bad_patterns_explain_themselves() {
    let dir = temp_dir("grep-fixed");
    fs::write(dir.join("f.txt"), "cost is a+b\nand ab\n").unwrap();

    // As a regex, `a+b` matches the "ab" on line 2, not the literal "a+b".
    let text = run("grep", &json!({ "pattern": "a+b", "path": dir })).unwrap();
    assert_eq!(text.lines().count(), 1, "{text}");
    assert!(text.contains("and ab"), "{text}");

    let text = run(
        "grep",
        &json!({ "pattern": "a+b", "path": dir, "fixed": true }),
    )
    .unwrap();
    assert_eq!(text.lines().count(), 1, "{text}");
    assert!(text.contains("cost is a+b"), "{text}");

    let error = run("grep", &json!({ "pattern": "(", "path": dir }))
        .err()
        .expect("invalid regex must fail");
    assert!(error.contains("invalid regex"), "{error}");
    assert!(error.contains("fixed"), "{error}");
}

fn running(pid: i32) -> bool {
    // A zombie has already exited; anything but Z means still alive.
    match fs::read_to_string(format!("/proc/{pid}/stat")) {
        Ok(stat) => stat
            .rsplit(')')
            .next()
            .and_then(|rest| rest.split_whitespace().next())
            .map(|state| state != "Z")
            .unwrap_or(false),
        Err(_) => false,
    }
}

#[test]
fn bash_timeout_kills_the_whole_process_group() {
    let dir = temp_dir("bash-group");
    let pidfile = dir.join("pid");
    let cmd = format!("sleep 30 & echo $! > {}; wait", pidfile.display());

    let text = shell::bash(
        &json!({ "cmd": cmd }),
        Duration::from_millis(300),
        &AtomicBool::new(false),
    )
    .unwrap();
    assert!(text.contains("timed out"), "{text}");

    std::thread::sleep(Duration::from_millis(300));
    let pid: i32 = fs::read_to_string(&pidfile).unwrap().trim().parse().unwrap();
    assert!(!running(pid), "grandchild {pid} survived the timeout");
}

#[test]
fn bash_stops_promptly_when_the_turn_is_cancelled() {
    let started = std::time::Instant::now();
    let text = shell::bash(
        &json!({ "cmd": "sleep 30" }),
        Duration::from_secs(20),
        &AtomicBool::new(true),
    )
    .unwrap();
    assert!(text.contains("aborted by the user"), "{text}");
    assert!(started.elapsed() < Duration::from_secs(2));
}

#[test]
fn bash_does_not_inherit_the_api_key() {
    std::env::set_var("OPENCODE_API_KEY", "do-not-leak-me");
    let text = run(
        "bash",
        &json!({ "cmd": "env | grep -c '^OPENCODE_API_KEY=' || true" }),
    )
    .unwrap();
    std::env::remove_var("OPENCODE_API_KEY");
    assert!(text.contains('0'), "the key was visible to the child: {text}");
}

#[test]
fn edit_matches_crlf_files_without_visible_carriage_returns() {
    let dir = temp_dir("edit-crlf");
    let path = dir.join("win.c");
    fs::write(&path, "int main(void) {\r\n    return 0;\r\n}\r\n").unwrap();

    // The model copies what `read` showed it: plain newlines.
    let change = tools::plan(
        "edit",
        &json!({
            "path": path,
            "old": "int main(void) {\n    return 0;\n",
            "new": "int main(void) {\n    return 1;\n"
        }),
    )
    .expect("CRLF file should still match");

    change.apply().expect("apply should succeed");
    assert_eq!(
        fs::read_to_string(&path).unwrap(),
        "int main(void) {\r\n    return 1;\r\n}\r\n"
    );
}

#[test]
fn edit_refuses_when_the_file_changed_while_waiting_for_approval() {
    let dir = temp_dir("edit-concurrent");
    let path = dir.join("f.txt");
    fs::write(&path, "alpha\n").unwrap();

    let change = tools::plan("edit", &json!({ "path": path, "old": "alpha", "new": "beta" }))
        .unwrap();
    // Something else (cargo fmt, the user's editor) ran before approval.
    fs::write(&path, "alpha\nalpha\n").unwrap();

    let error = change.apply().err().expect("apply must refuse");
    assert!(error.contains("appears 2 times"), "{error}");
    assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nalpha\n");
}

#[test]
fn write_preserves_the_existing_file_mode() {
    use std::os::unix::fs::PermissionsExt;
    let dir = temp_dir("write-mode");
    let path = dir.join("script.sh");
    fs::write(&path, "old").unwrap();
    fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();

    tools::plan("write", &json!({ "path": path, "content": "new" }))
        .unwrap()
        .apply()
        .unwrap();

    let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
    assert_eq!(mode, 0o755);
    assert_eq!(fs::read_to_string(&path).unwrap(), "new");
}

#[test]
fn read_refuses_special_files() {
    let dir = temp_dir("read-fifo");
    let path = dir.join("fifo");
    let name = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
    let made = unsafe { libc::mkfifo(name.as_ptr(), 0o600) };
    assert_eq!(made, 0, "could not create a fifo");

    let error = run("read", &json!({ "path": path })).err().unwrap();
    assert!(error.contains("not a regular file"), "{error}");
}

#[test]
fn grep_errors_on_a_missing_path_instead_of_reporting_no_matches() {
    let dir = temp_dir("grep-missing");
    let error = run(
        "grep",
        &json!({ "pattern": "needle", "path": dir.join("does-not-exist") }),
    )
    .err()
    .expect("missing path must be an error");
    assert!(error.contains("no such file or directory"), "{error}");
}

#[test]
fn grep_says_when_it_skipped_files() {
    let dir = temp_dir("grep-skip");
    let mut body = String::from("needle\n");
    body.push_str(&"x".repeat(5 * 1024 * 1024));
    fs::write(dir.join("big.txt"), body).unwrap();

    let text = run("grep", &json!({ "pattern": "needle", "path": dir })).unwrap();
    assert!(text.contains("not searched"), "{text}");
}

#[test]
fn glob_follows_file_symlinks_but_not_directories() {
    let dir = temp_dir("glob-symlink");
    fs::create_dir_all(dir.join("real-dir")).unwrap();
    fs::write(dir.join("real-dir/inner.rs"), "").unwrap();
    fs::write(dir.join("real.rs"), "").unwrap();
    std::os::unix::fs::symlink(dir.join("real.rs"), dir.join("link.rs")).unwrap();
    std::os::unix::fs::symlink(dir.join("real-dir"), dir.join("link-dir")).unwrap();

    let text = run("glob", &json!({ "pattern": "*.rs", "path": dir })).unwrap();
    assert!(text.contains("real.rs"), "{text}");
    assert!(text.contains("link.rs"), "{text}");
    assert!(text.contains("inner.rs"), "{text}");
}

#[test]
fn validate_rejects_calls_that_cannot_run() {
    use agent686::tools::validate;

    assert!(validate("bash", &json!({ "cmd": "" })).is_err());
    assert!(validate("bash", &json!({})).is_err());
    assert!(validate("bash", &json!({ "cmd": "ls" })).is_ok());

    assert!(validate("read", &json!({ "path": "  " })).is_err());
    assert!(validate("edit", &json!({ "path": "a", "old": "" })).is_err());
    assert!(validate("grep", &json!({ "pattern": "" })).is_err());
    // Empty content is how you create an empty file.
    assert!(validate("write", &json!({ "path": "a", "content": "" })).is_ok());
}

#[test]
fn bash_keeps_stderr_separate_from_stdout() {
    let text = run(
        "bash",
        &json!({ "cmd": "printf 'out\\n'; printf 'err\\n' >&2; exit 2" }),
    )
    .unwrap();

    assert!(text.contains("[stdout]"), "{text}");
    assert!(text.contains("[stderr]"), "{text}");
    assert!(text.contains("[exit 2]"), "{text}");
    let stdout_at = text.find("[stdout]").unwrap();
    let stderr_at = text.find("[stderr]").unwrap();
    assert!(stdout_at < stderr_at, "{text}");
    assert!(text.contains("out"), "{text}");
    assert!(text.contains("err"), "{text}");
}

#[test]
fn bash_stdout_alone_is_not_labelled() {
    let text = run("bash", &json!({ "cmd": "echo hello" })).unwrap();
    assert!(!text.contains("[stdout]"), "no label needed: {text}");
    assert!(text.contains("hello"), "{text}");
}

#[test]
fn bash_stderr_alone_is_labelled() {
    let text = run("bash", &json!({ "cmd": "echo problem >&2" })).unwrap();
    assert!(text.contains("[stderr]"), "{text}");
    assert!(text.contains("problem"), "{text}");
}

#[test]
fn bash_honours_a_per_call_timeout() {
    let started = std::time::Instant::now();
    let text = run(
        "bash",
        &json!({ "cmd": "sleep 5", "timeout_seconds": 1 }),
    )
    .unwrap();
    assert!(text.contains("timed out after 1.0s"), "{text}");
    assert!(started.elapsed() < std::time::Duration::from_secs(4));
}

#[test]
fn bash_honours_a_per_call_output_budget() {
    let text = run(
        "bash",
        &json!({ "cmd": "yes | head -c 200000", "max_bytes": 4096 }),
    )
    .unwrap();
    assert!(text.contains("bytes omitted"), "{text}");
    assert!(text.contains("output truncated"), "{text}");
    assert!(text.len() < 10_000, "output was {} bytes", text.len());
}

#[test]
fn validate_requires_content_and_new_but_allows_empty() {
    use agent686::tools::validate;

    // Missing, not empty.
    assert!(validate("write", &json!({ "path": "a" })).is_err());
    assert!(validate("edit", &json!({ "path": "a", "old": "b" })).is_err());
    // Present but empty is legitimate (empty file, deletion).
    assert!(validate("write", &json!({ "path": "a", "content": "" })).is_ok());
    assert!(validate("edit", &json!({ "path": "a", "old": "b", "new": "" })).is_ok());
}

#[test]
fn a_pipeline_that_exceeds_the_file_limit_is_reported() {
    // 70 MiB through a pipeline: the grandchild (head) is the writer, so only the
    // file-length check can detect the limit.
    let text = run(
        "bash",
        &json!({ "cmd": "yes | head -c 70000000" }),
    )
    .unwrap();
    assert!(
        text.contains("output exceeded 64 MiB"),
        "should report the file limit: {text}"
    );
}