atomwrite 0.1.35

Atomic file operations CLI for LLM agents — read, write, edit, search, replace with NDJSON output
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
//! Contract e2e for atomwrite v0.1.35 residual gaps (G-024 expanded).
#![cfg(unix)]

use assert_cmd::cargo::cargo_bin;
use assert_cmd::Command;
use predicates::prelude::*;
use std::fs;
use std::path::PathBuf;
use tempfile::tempdir;

fn bin() -> Command {
    Command::new(cargo_bin("atomwrite"))
}

#[test]
fn doctor_strict_ok_without_feature_warns() {
    let dir = tempdir().unwrap();
    let mut cmd = bin();
    cmd.args(["--workspace", dir.path().to_str().unwrap(), "doctor", "--strict"])
        .assert()
        .success()
        .stdout(predicate::str::contains("doctor_report"));
}

#[test]
fn ready_file_cli_not_env() {
    let dir = tempdir().unwrap();
    let ready = dir.path().join("ready");
    let mut cmd = bin();
    cmd.args([
        "--workspace",
        dir.path().to_str().unwrap(),
        "--ready-file",
        ready.to_str().unwrap(),
        "locale",
    ])
    .assert()
    .success();
    assert!(ready.exists(), "ready-file should be written without env");
}

#[test]
fn fuzzy_off_exact_only_cli() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("f.txt");
    fs::write(&path, "hello world\n").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "edit",
            path.to_str().unwrap(),
            "--old",
            "world",
            "--new",
            "rust",
            "--fuzzy",
            "off",
        ])
        .assert()
        .success();
    assert_eq!(fs::read_to_string(&path).unwrap(), "hello rust\n");
}

#[test]
fn calc_comment_only_fails_empty() {
    // B-009: comments are skipped; comment-only stdin has no expressions → error.
    let dir = tempdir().unwrap();
    let mut cmd = bin();
    cmd.args(["--workspace", dir.path().to_str().unwrap(), "calc", "--stdin"])
        .write_stdin("# not an expression\n")
        .assert()
        .failure()
        .stdout(predicate::str::contains("INVALID_INPUT").or(predicate::str::contains("error")));
}

#[test]
fn calc_comment_then_expression_ok() {
    // B-009: comments skipped; following expression evaluates.
    let dir = tempdir().unwrap();
    bin()
        .args(["--workspace", dir.path().to_str().unwrap(), "calc", "--stdin"])
        .write_stdin("# ignore\n2 + 2\n")
        .assert()
        .success()
        .stdout(predicate::str::contains("calc").and(predicate::str::contains("4")));
}

#[test]
fn no_color_env_ignored_cli_controls() {
    let dir = tempdir().unwrap();
    let mut cmd = bin();
    cmd.env("NO_COLOR", "1")
        .env("CLICOLOR_FORCE", "1")
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "--color",
            "never",
            "locale",
        ])
        .assert()
        .success();
}

#[test]
fn delete_confirm_rejected_still_exists() {
    // B-005: --confirm is fail-closed (not silent plan).
    let dir = tempdir().unwrap();
    let path = dir.path().join("keep.txt");
    fs::write(&path, "x\n").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "delete",
            "--confirm",
            path.to_str().unwrap(),
        ])
        .assert()
        .failure()
        .code(65);
    assert!(path.exists(), "delete --confirm must not delete");
}

#[test]
fn delete_plan_only_still_exists() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("keep.txt");
    fs::write(&path, "x\n").unwrap();
    let out = bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "delete",
            "--plan",
            path.to_str().unwrap(),
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let s = String::from_utf8_lossy(&out);
    assert!(path.exists(), "delete --plan must not delete");
    assert!(
        s.contains("\"files_modified\":0") || s.contains("files_modified\":0") || s.contains("plan"),
        "plan/files_modified=0 expected, got {s}"
    );
}

#[test]
fn delete_yes_rejected() {
    // B-015
    let dir = tempdir().unwrap();
    let path = dir.path().join("keep.txt");
    fs::write(&path, "x\n").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "delete",
            "-y",
            path.to_str().unwrap(),
        ])
        .assert()
        .failure()
        .code(65);
    assert!(path.exists());
}

#[test]
fn diff_stdin_as_file_a() {
    // B-001
    let dir = tempdir().unwrap();
    let b = dir.path().join("b.txt");
    fs::write(&b, "one\n").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "diff",
            "-",
            b.to_str().unwrap(),
        ])
        .write_stdin("two\n")
        .assert()
        .success()
        .stdout(predicate::str::contains("diff").or(predicate::str::contains("type")));
}

#[test]
fn write_content_risk_rm_rf() {
    // B-013
    let dir = tempdir().unwrap();
    let path = dir.path().join("risky.sh");
    let out = bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "write",
            path.to_str().unwrap(),
        ])
        .write_stdin("rm -rf /\n")
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let s = String::from_utf8_lossy(&out);
    assert!(
        s.contains("risk_assessment") && s.contains("content_pattern"),
        "expected content risk_assessment, got {s}"
    );
}

#[test]
fn diff_file_vs_stdin() {
    let dir = tempdir().unwrap();
    let a = dir.path().join("a.txt");
    fs::write(&a, "one\n").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "diff",
            a.to_str().unwrap(),
            "-",
        ])
        .write_stdin("two\n")
        .assert()
        .success()
        .stdout(predicate::str::contains("diff").or(predicate::str::contains("type")));
}

#[test]
fn move_directory_same_fs() {
    let dir = tempdir().unwrap();
    let src = dir.path().join("d1");
    let dst = dir.path().join("d2");
    fs::create_dir(&src).unwrap();
    fs::write(src.join("f.txt"), "hi\n").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "move",
            src.to_str().unwrap(),
            dst.to_str().unwrap(),
        ])
        .assert()
        .success();
    assert!(dst.join("f.txt").exists());
    assert!(!src.exists());
}

#[test]
fn read_raw_nontty_is_bytes() {
    // B-006: --format raw always emits file bytes
    let dir = tempdir().unwrap();
    let path = dir.path().join("r.txt");
    fs::write(&path, "hello raw\n").unwrap();
    let out = bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "read",
            "--format",
            "raw",
            path.to_str().unwrap(),
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let s = String::from_utf8_lossy(&out);
    assert_eq!(s, "hello raw\n");
    assert!(
        !s.contains("\"type\""),
        "raw must not be NDJSON envelope, got: {s}"
    );
}

#[test]
fn set_json_trailing_newline() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("c.json");
    fs::write(&path, "{\n  \"a\": 1\n}").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "set",
            path.to_str().unwrap(),
            "a",
            "2",
        ])
        .assert()
        .success();
    let body = fs::read_to_string(&path).unwrap();
    assert!(body.ends_with('\n'), "G-022 trailing newline: {body:?}");
}

#[test]
fn write_large_default_deny_requires_ack_overwrite() {
    // A-WRITE-001: large overwrite is default-deny (no --confirm required to trigger).
    let dir = tempdir().unwrap();
    let path = dir.path().join("big.txt");
    // >100KB
    fs::write(&path, vec![b'x'; 120_000]).unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "write",
            path.to_str().unwrap(),
        ])
        .write_stdin("new payload\n")
        .assert()
        .failure()
        .code(65)
        .stdout(predicate::str::contains("ack-overwrite"));
    // A-WRITE-002: --confirm and --require-large-ack may be combined (no clap multi-use).
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "write",
            "--confirm",
            "--require-large-ack",
            "--ack-overwrite",
            "--allow-shrink",
            path.to_str().unwrap(),
        ])
        .write_stdin("new payload\n")
        .assert()
        .success();
    assert_eq!(fs::read_to_string(&path).unwrap(), "new payload\n");
}

#[test]
fn fuzzy_match_failed_code() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("m.txt");
    fs::write(&path, "alpha beta\n").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "edit",
            path.to_str().unwrap(),
            "--old",
            "zzzz-not-present-qqq",
            "--new",
            "x",
            "--fuzzy",
            "off",
        ])
        .assert()
        .failure()
        .stdout(
            predicate::str::contains("MATCH_FAILED")
                .or(predicate::str::contains("match failed"))
                .or(predicate::str::contains("NoMatches"))
                .or(predicate::str::contains("error")),
        );
}


#[test]
fn replace_binary_exits_binary_file_not_no_matches() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("bin.dat");
    fs::write(&path, b"a\x00b").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "replace",
            "-F",
            "a",
            "A",
            path.to_str().unwrap(),
            "--no-backup",
        ])
        .assert()
        .failure()
        .code(65)
        .stdout(
            predicate::str::contains("BINARY_FILE")
                .or(predicate::str::contains("binary file rejected")),
        );
}

#[test]
fn case_requires_subvert_clap() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("id.rs");
    fs::write(&path, "snake_ident\n").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "case",
            path.to_str().unwrap(),
            "--to",
            "camel",
            "--dry-run",
        ])
        .assert()
        .failure()
        .code(2);
}

#[test]
fn prune_requires_policy_group() {
    let dir = tempdir().unwrap();
    let path = dir.path().join("f.txt");
    fs::write(&path, "x\n").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "prune-backups",
            path.to_str().unwrap(),
            "--dry-run",
        ])
        .assert()
        .failure()
        .code(2);
}

#[test]
fn write_large_before_shrink_mentions_ack() {
    // A-WRITE-001: ack is required even without --confirm; message before shrink path.
    let dir = tempdir().unwrap();
    let path = dir.path().join("L.bin");
    fs::write(&path, vec![b'A'; 120 * 1024]).unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "write",
            path.to_str().unwrap(),
            "--no-backup",
        ])
        .write_stdin("x")
        .assert()
        .failure()
        .code(65)
        .stdout(predicate::str::contains("ack-overwrite"));
}

#[test]
fn watch_idle_emits_watch_summary() {
    // A-WATCH-001: idle exit must not leave stdout empty.
    let dir = tempdir().unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "--timeout-secs",
            "5",
            "watch",
            dir.path().to_str().unwrap(),
            "--idle-exit-ms",
            "100",
            "--max-events",
            "5",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("watch_summary"))
        .stdout(predicate::str::contains("\"reason\":\"idle\""));
}

#[test]
fn semantic_merge_conflict_writes_markers_by_default() {
    // A-MERGE-001: conflict markers default ON.
    let dir = tempdir().unwrap();
    let base = dir.path().join("base.txt");
    let ours = dir.path().join("ours.txt");
    let theirs = dir.path().join("theirs.txt");
    let out = dir.path().join("out.txt");
    fs::write(&base, "line1\nshared\nline3\n").unwrap();
    fs::write(&ours, "line1\nOURS\nline3\n").unwrap();
    fs::write(&theirs, "line1\nTHEIRS\nline3\n").unwrap();
    bin()
        .args([
            "--workspace",
            dir.path().to_str().unwrap(),
            "semantic-merge",
            "--base",
            base.to_str().unwrap(),
            "--ours",
            ours.to_str().unwrap(),
            "--theirs",
            theirs.to_str().unwrap(),
            "--output",
            out.to_str().unwrap(),
            "--no-backup",
        ])
        .assert()
        .success()
        .stdout(predicate::str::contains("conflict"));
    let body = fs::read_to_string(&out).unwrap();
    assert!(
        body.contains("<<<<<<< ours"),
        "expected conflict markers in output, got: {body:?}"
    );
}

#[test]
fn agent_surface_case_schema_hint_not_write_output() {
    let dir = tempdir().unwrap();
    let out = bin()
        .args(["--workspace", dir.path().to_str().unwrap(), "agent-surface"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let s = String::from_utf8_lossy(&out);
    // G-037: hints must match docs/schemas/*.schema.json basenames.
    assert!(
        s.contains("\"name\":\"case\"") && s.contains("case-result"),
        "case should use case-result schema_hint"
    );
    assert!(
        s.contains("\"name\":\"set\"") && s.contains("set-result"),
        "set should use set-result"
    );
    assert!(
        s.contains("\"name\":\"del\"") && s.contains("del-result"),
        "del should use del-result"
    );
    assert!(
        s.contains("\"name\":\"get\"") && s.contains("get-result"),
        "get should use get-result"
    );
    assert!(
        s.contains("\"name\":\"verify\"") && s.contains("hash-output"),
        "verify should use hash-output (G-041; same NDJSON as hash)"
    );
    assert!(
        !s.contains("case-output") && !s.contains("set-output"),
        "legacy *-output hints for case/set must not appear"
    );
}

/// G-037/G-041/G-042: every `schema_hint` must resolve to
/// `docs/schemas/{hint}.schema.json` in a source checkout (no allowlist).
#[test]
fn agent_surface_schema_hints_have_schema_files_in_repo() {
    let dir = tempdir().unwrap();
    let out = bin()
        .args(["--workspace", dir.path().to_str().unwrap(), "agent-surface"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let s = String::from_utf8_lossy(&out);
    let schemas_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("docs/schemas");
    if !schemas_dir.is_dir() {
        return;
    }
    // G-042: zero missing-schema allowlist — every hint has a published file.
    let allow_missing: &[&str] = &[];
    // agent-surface emits one envelope with tools:[] (not per-line NDJSON tools).
    let v: serde_json::Value =
        serde_json::from_str(s.lines().next().expect("agent-surface stdout")).expect("json");
    let tools = v
        .get("tools")
        .and_then(|t| t.as_array())
        .expect("tools array");
    assert!(!tools.is_empty(), "agent-surface must list tools");
    for tool in tools {
        let Some(hint) = tool.get("schema_hint").and_then(|h| h.as_str()) else {
            continue;
        };
        if allow_missing.contains(&hint) {
            continue;
        }
        let path = schemas_dir.join(format!("{hint}.schema.json"));
        assert!(
            path.is_file(),
            "schema_hint {hint:?} for tool {:?} missing file {}",
            tool.get("name"),
            path.display()
        );
    }
}