newt-core 0.8.0

Newt-Agent core types, errors, and the NeMoCode-style tier router
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
//! Real-resource witnesses for the pure file-change version-to-patch contract:
//! actual files, confirmation timing, mutation outcomes, and the production
//! terminal dispatcher establish that observations and safe display agree.

use super::*;

/// What the MODEL got and what the OPERATOR saw, separately. Color off prints
/// the display text verbatim (the plain-terminal fallback), so each side is
/// asserted on its own: on success the model gets a one-line headline
/// ("Modified (+1 -1)"), the operator keeps the full diff (pi's content vs
/// details split; Codex's "Updated the following files"). Live 2026-09-23:
/// echoing a 1,497-line new file back to the model spilled it, and the model
/// spent a round reading its own write back.
async fn model_and_display(
    name: &str,
    args: serde_json::Value,
    ws: &std::path::Path,
    caveats: &Caveats,
    collab: ToolCollaborators<'_, '_>,
) -> (String, String) {
    let mut display = ToolDisplay::new(Vec::new(), false, 4096, 0, false);
    let model = execute_tool_with_display_cancellable(
        &mut display,
        name,
        &args,
        &ws.to_string_lossy(),
        false,
        20,
        caveats,
        &mut NoMcp,
        collab,
        false,
        PromptDisposition::Act,
        None,
    )
    .await
    .unwrap()
    .unwrap();
    (model, String::from_utf8(display.into_inner()).unwrap())
}

#[tokio::test]
async fn a_successful_mutation_gives_the_model_a_headline_and_the_operator_the_diff() {
    let ws = tempfile::TempDir::new().unwrap();
    let path = "state.rs";
    for (name, args, kind) in [
        (
            "write_file",
            serde_json::json!({"path": path, "content": "let new = 2;\n"}),
            "Modified",
        ),
        (
            "edit_file",
            serde_json::json!({"path": path, "old_string": "old", "new_string": "new"}),
            "Modified",
        ),
        ("delete_file", serde_json::json!({"path": path}), "Deleted"),
    ] {
        std::fs::write(ws.path().join(path), "let old = 1;\n").unwrap();
        let mut display = ToolDisplay::new(Vec::new(), true, 100, 0, false);
        let raw = execute_tool_with_display_cancellable(
            &mut display,
            name,
            &args,
            &ws.path().to_string_lossy(),
            true,
            20,
            &caveats_rw(ws.path()),
            &mut NoMcp,
            ToolCollaborators::default(),
            false,
            PromptDisposition::Act,
            None,
        )
        .await
        .unwrap()
        .unwrap();
        assert!(
            !raw.contains("```diff"),
            "the model gets a headline, not the patch: {raw}"
        );
        assert!(raw.contains(&format!("{kind} (+")), "{raw}");
        let visible = String::from_utf8(display.into_inner()).unwrap();
        assert!(
            visible.contains(&format!("{kind} \"state.rs\"")),
            "{name} did not project actual captured model: {visible:?}"
        );
        assert!(
            visible.contains("\x1b[48;"),
            "source changes have semantic backgrounds"
        );
        assert!(
            !visible.contains("```diff"),
            "the display consumes the receipt once"
        );
    }
}

#[cfg(unix)]
#[tokio::test]
async fn nonregular_file_errors_escape_path_controls_in_the_production_display() {
    let ws = tempfile::TempDir::new().unwrap();
    let path = "directory-\u{1b}[31m\tname";
    std::fs::create_dir(ws.path().join(path)).unwrap();
    for (name, args) in [
        (
            "write_file",
            serde_json::json!({"path": path, "content": "new\n"}),
        ),
        (
            "edit_file",
            serde_json::json!({"path": path, "old_string": "old", "new_string": "new"}),
        ),
    ] {
        let mut display = ToolDisplay::new(Vec::new(), false, 4096, 0, false);
        let raw = execute_tool_with_display_cancellable(
            &mut display,
            name,
            &args,
            &ws.path().to_string_lossy(),
            false,
            20,
            &caveats_rw(ws.path()),
            &mut NoMcp,
            ToolCollaborators::default(),
            false,
            PromptDisposition::Act,
            None,
        )
        .await
        .unwrap()
        .unwrap();
        assert!(raw.starts_with("error:"), "{raw:?}");
        assert!(raw.contains("nonregular target"), "{raw:?}");
        assert!(raw.contains(path), "raw result retains the actual path");
        let visible = String::from_utf8(display.into_inner()).unwrap();
        assert!(
            visible.chars().all(|ch| !ch.is_control() || ch == '\n'),
            "{name} early error leaked pathname controls: {visible:?}"
        );
        assert!(visible.contains("directory-<U+001B>[31m<U+0009>name"));
        assert!(visible.contains("display escapes control characters"));
        assert!(ws.path().join(path).is_dir());
    }
}

#[cfg(unix)]
#[tokio::test]
async fn pathname_controls_are_safe_in_file_headers_and_result_prefixes() {
    let ws = tempfile::TempDir::new().unwrap();
    let path = "file-\u{1b}[31m\tname.rs";
    for (name, args) in [
        (
            "write_file",
            serde_json::json!({"path": path, "content": "new\n"}),
        ),
        (
            "edit_file",
            serde_json::json!({"path": path, "old_string": "old", "new_string": "new"}),
        ),
        ("delete_file", serde_json::json!({"path": path})),
    ] {
        std::fs::write(ws.path().join(path), "old\n").unwrap();
        let mut display = ToolDisplay::new(Vec::new(), false, 4096, 0, false);
        let raw = execute_tool_with_display_cancellable(
            &mut display,
            name,
            &args,
            &ws.path().to_string_lossy(),
            false,
            20,
            &caveats_rw(ws.path()),
            &mut NoMcp,
            ToolCollaborators::default(),
            false,
            PromptDisposition::Act,
            None,
        )
        .await
        .unwrap()
        .unwrap();
        assert!(raw.contains(path), "raw result retains the actual path");
        let visible = String::from_utf8(display.into_inner()).unwrap();
        assert!(
            visible.chars().all(|ch| !ch.is_control() || ch == '\n'),
            "{name} leaked pathname controls: {visible:?}"
        );
        assert!(
            visible.contains("file-<U+001B>[31m<U+0009>name.rs"),
            "{visible}"
        );
        assert!(
            visible.contains("display escapes control characters"),
            "{visible}"
        );
    }
}

#[tokio::test]
async fn file_receipts_keep_raw_source_but_neutralize_terminal_controls() {
    let ws = tempfile::TempDir::new().unwrap();
    let original = "start\u{1b}]8;;https://example.test/\u{7}link\u{1b}]8;;\u{7}\u{1b}]52;c;c2VjcmV0\u{1b}\\\r\tend\n";
    let replacement = "\tnew\u{1b}[31m\r\n";
    for (name, args, after) in [
        (
            "write_file",
            serde_json::json!({"path": "state.txt", "content": replacement}),
            Some(replacement.to_string()),
        ),
        (
            "edit_file",
            serde_json::json!({"path": "state.txt", "old_string": "start", "new_string": "changed"}),
            Some(original.replacen("start", "changed", 1)),
        ),
        (
            "delete_file",
            serde_json::json!({"path": "state.txt"}),
            None,
        ),
    ] {
        std::fs::write(ws.path().join("state.txt"), original).unwrap();
        let mut display = ToolDisplay::new(Vec::new(), false, 4096, 0, false);
        let raw = execute_tool_with_display_cancellable(
            &mut display,
            name,
            &args,
            &ws.path().to_string_lossy(),
            false,
            20,
            &caveats_rw(ws.path()),
            &mut NoMcp,
            ToolCollaborators::default(),
            false,
            PromptDisposition::Act,
            None,
        )
        .await
        .unwrap()
        .unwrap();
        let expected_receipt = crate::agentic::tools::file_change::receipt(
            "state.txt",
            Some(original),
            after.as_deref(),
        )
        .unwrap();
        let headline = expected_receipt.lines().next().unwrap();
        assert!(raw.contains(headline), "{name} headline missing: {raw:?}");
        assert!(
            !raw.contains("\u{1b}]52;"),
            "the model gets no file bytes on success: {raw:?}"
        );
        let visible = String::from_utf8(display.into_inner()).unwrap();
        assert!(
            visible.chars().all(|ch| !ch.is_control() || ch == '\n'),
            "{name} terminal bytes still contain source controls: {visible:?}"
        );
        assert!(visible.contains("<U+001B>]8;"), "{visible}");
        assert!(visible.contains("<U+001B>]52;"), "{visible}");
        assert!(visible.contains("<U+000D>"), "{visible}");
        assert!(visible.contains("<U+0009>"), "{visible}");
        assert!(
            visible.contains("display escapes control characters"),
            "{visible}"
        );
        assert!(visible.contains("not a raw patch"), "{visible}");
        assert!(!raw.contains("display escapes control characters"));
    }
}

#[cfg(unix)]
#[test]
fn file_mutations_refuse_a_fifo_before_the_legacy_reads_can_block() {
    const CHILD: &str = "NEWT_RECEIPT_FIFO_CHILD";
    if let Some(done) = std::env::var_os(CHILD) {
        let ws = tempfile::TempDir::new().unwrap();
        let path = ws.path().join("fifo");
        let path_c = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
        // SAFETY: the live path is NUL-terminated; mkfifo does not retain it.
        assert_eq!(unsafe { libc::mkfifo(path_c.as_ptr(), 0o600) }, 0);
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        for (tool, args) in [
            (
                "write_file",
                serde_json::json!({"path": "fifo", "content": "text"}),
            ),
            (
                "edit_file",
                serde_json::json!({"path": "fifo", "old_string": "a", "new_string": "b"}),
            ),
        ] {
            let output = runtime.block_on(run_tool(
                tool,
                args,
                ws.path(),
                &caveats_rw(ws.path()),
                None,
            ));
            assert!(output.starts_with("error:"), "{output}");
            assert!(output.contains("nonregular target"), "{output}");
        }
        assert!(matches!(
            crate::agentic::tools::file_capture::capture(&Scope::All, &path),
            crate::agentic::tools::file_capture::TextSnapshot::Unavailable(_)
        ));
        std::fs::write(done, "passed").unwrap();
        return;
    }
    let parent = tempfile::TempDir::new().unwrap();
    let done = parent.path().join("child-passed");
    let mut child = std::process::Command::new(std::env::current_exe().unwrap())
        .args([
            "--exact",
            "agentic::tools::execute_tool_branch_tests::file_receipts::file_mutations_refuse_a_fifo_before_the_legacy_reads_can_block",
            "--nocapture",
        ])
        .env(CHILD, &done)
        .spawn()
        .unwrap();
    // The child's exit is the event; a mutation blocked on the FIFO never
    // produces it, and the shared hang guard names that. The former 10 s
    // deadline also had to cover exec of this whole test binary under load,
    // and called a slow start a FIFO block.
    let pid = child.id();
    let (exited_tx, exited_rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let _ = exited_tx.send(child.wait().unwrap());
    });
    let status = match exited_rx.recv_timeout(crate::test_guard::HANG_GUARD) {
        Ok(status) => status,
        Err(_) => {
            // SAFETY: `pid` is the child this test spawned and still owns
            // through the waiter thread, so the signal cannot reach another
            // process's reused id.
            unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };
            panic!(
                "a file mutation blocked on a FIFO with no writer: the child ran past the {}s hang guard",
                crate::test_guard::HANG_GUARD.as_secs()
            );
        }
    };
    assert!(status.success(), "FIFO tool child failed: {status}");
    assert!(done.exists(), "the exact FIFO child test did not run");
}

struct ChangeWhileConfirming {
    path: std::path::PathBuf,
}

impl PermissionGate for ChangeWhileConfirming {
    fn ask(&mut self, _: &[PermissionRequest]) -> PermissionDecision {
        panic!("the configured scope already permits this write")
    }

    fn ask_question(&mut self, _: &str) -> HumanQuestionOutcome {
        std::fs::write(&self.path, "changed while confirming\n").unwrap();
        HumanQuestionOutcome::Answer("y".into())
    }
}

#[tokio::test]
async fn a_write_captures_its_preimage_after_confirmation() {
    use super::super::disable_ocap_tests::{env_lock, EnvVar};

    let _lock = env_lock().await;
    let _normal_mode = EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let ws = tempfile::TempDir::new().unwrap();
    let path = ws.path().join("state.txt");
    std::fs::write(&path, "before confirmation\n").unwrap();
    let mut gate = ChangeWhileConfirming { path };
    let caveats = Caveats {
        fs_write: Scope::All,
        ..caveats_rw(ws.path())
    };
    let (model, seen) = model_and_display(
        "write_file",
        serde_json::json!({"path": "state.txt", "content": "written\n"}),
        ws.path(),
        &caveats,
        ToolCollaborators {
            permission_gate: Some(&mut gate),
            ..ToolCollaborators::default()
        },
    )
    .await;
    assert!(model.contains("Modified (+1 -1)"), "{model}");
    assert!(seen.contains("-changed while confirming"), "{seen}");
    assert!(seen.contains("+written"), "{seen}");
    assert!(!seen.contains("-before confirmation"), "{seen}");
}

#[tokio::test]
async fn sequential_file_tools_show_the_immediate_change_without_an_artifact_sink() {
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_rw(ws.path());
    let (added, seen) = model_and_display(
        "write_file",
        serde_json::json!({"path": "state.txt", "content": "one\n"}),
        ws.path(),
        &caveats,
        ToolCollaborators::default(),
    )
    .await;
    assert!(added.starts_with("wrote state.txt"), "{added}");
    assert!(added.contains("Added (+1 -0)"), "{added}");
    assert!(
        !added.contains("--- /dev/null"),
        "no patch to the model: {added}"
    );
    assert!(seen.contains("--- /dev/null"), "{seen}");
    assert!(seen.contains("+one"), "{seen}");

    let (edited, seen) = model_and_display(
        "edit_file",
        serde_json::json!({"path": "state.txt", "old_string": "one", "new_string": "two"}),
        ws.path(),
        &caveats,
        ToolCollaborators::default(),
    )
    .await;
    assert!(edited.starts_with("edited state.txt"), "{edited}");
    assert!(edited.contains("Modified (+1 -1)"), "{edited}");
    assert!(seen.contains("-one") && seen.contains("+two"), "{seen}");
    assert!(!seen.contains("--- /dev/null"), "{seen}");

    let (deleted, seen) = model_and_display(
        "delete_file",
        serde_json::json!({"path": "state.txt"}),
        ws.path(),
        &caveats,
        ToolCollaborators::default(),
    )
    .await;
    assert!(deleted.starts_with("deleted state.txt"), "{deleted}");
    assert!(deleted.contains("Deleted (+0 -1)"), "{deleted}");
    assert!(seen.contains("-two"), "{seen}");
    assert!(!ws.path().join("state.txt").exists());
}

#[cfg(unix)]
#[tokio::test]
async fn a_failed_build_check_keeps_the_verified_tool_change() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("state.txt"), "old\n").unwrap();
    let caveats = Caveats {
        // This tests the write receipt; macOS cannot admit restricted networking.
        #[cfg(target_os = "macos")]
        net: Scope::All,
        ..caveats_rw(ws.path())
    };
    let (output, seen) = model_and_display(
        "write_file",
        serde_json::json!({"path": "state.txt", "content": "tool bytes\n"}),
        ws.path(),
        &caveats,
        ToolCollaborators {
            build_check_cmd: Some("printf 'build bytes\\n' > state.txt; exit 1"),
            ..ToolCollaborators::default()
        },
    )
    .await;
    assert!(output.contains("Modified (+1 -1)"), "{output}");
    assert!(output.contains("build check failed"), "{output}");
    assert!(
        seen.contains("-old") && seen.contains("+tool bytes"),
        "{seen}"
    );
    assert!(!seen.contains("+build bytes"), "{seen}");
    assert_eq!(
        std::fs::read_to_string(ws.path().join("state.txt")).unwrap(),
        "build bytes\n"
    );
}

#[tokio::test]
async fn unavailable_preimages_do_not_become_added_file_receipts() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("state.txt"), "private old bytes\n").unwrap();
    let caveats = Caveats {
        fs_read: Scope::none(),
        ..caveats_rw(ws.path())
    };
    let output = run_tool(
        "write_file",
        serde_json::json!({"path": "state.txt", "content": "public result\n"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(output.starts_with("wrote state.txt"), "{output}");
    assert!(
        output.contains("File operation succeeded; optional change preview unavailable"),
        "{output}"
    );
    assert!(!output.contains("private old bytes"), "{output}");
    assert!(!output.contains("```diff"), "{output}");

    std::fs::write(ws.path().join("binary.txt"), [0xff, 0xfe]).unwrap();
    let binary = run_tool(
        "write_file",
        serde_json::json!({"path": "binary.txt", "content": "text\n"}),
        ws.path(),
        &caveats_rw(ws.path()),
        None,
    )
    .await;
    assert!(
        binary.contains("File operation succeeded; optional change preview unavailable"),
        "{binary}"
    );
    assert!(!binary.contains("Added (+"), "{binary}");
}

#[tokio::test]
async fn unavailable_receipt_preview_preserves_mutation_outcome() {
    let ws = tempfile::TempDir::new().unwrap();
    let content = "x".repeat(crate::agentic::tools::file_change::MAX_VERSION_BYTES + 1);
    let (model, display) = model_and_display(
        "write_file",
        serde_json::json!({"path": "large.txt", "content": content}),
        ws.path(),
        &caveats_rw(ws.path()),
        ToolCollaborators::default(),
    )
    .await;
    assert_eq!(
        std::fs::read_to_string(ws.path().join("large.txt")).unwrap(),
        content
    );
    assert!(tool_result_ok(&model), "{model}");
    assert!(model.starts_with("wrote large.txt"), "{model}");
    assert!(
        model.contains("File operation succeeded; optional change preview unavailable"),
        "{model}"
    );
    assert!(!model.contains("receipt capture limit"), "{model}");
    assert!(
        display.contains(
            "file-change receipt unavailable: receipt capture limit exceeded (256 KiB per version)"
        ),
        "{display}"
    );

    // The parent is a regular file, so the actual authorized write fails.
    // Its unavailable receipt must not acquire success wording or hide failure.
    std::fs::write(ws.path().join("blocked"), "keep these bytes").unwrap();
    let (failed, display) = model_and_display(
        "write_file",
        serde_json::json!({"path": "blocked/child.txt", "content": "not written"}),
        ws.path(),
        &caveats_rw(ws.path()),
        ToolCollaborators::default(),
    )
    .await;
    assert!(!tool_result_ok(&failed), "{failed}");
    assert!(!failed.contains("File operation succeeded"), "{failed}");
    assert!(
        failed.contains("file-change receipt unavailable"),
        "{failed}"
    );
    assert!(
        display.contains("file-change receipt unavailable"),
        "{display}"
    );
    assert_eq!(
        std::fs::read_to_string(ws.path().join("blocked")).unwrap(),
        "keep these bytes"
    );
}

/// A precise file grant remains sufficient to verify its own deletion after
/// the path cannot be canonicalized any more. This is a Windows-only witness:
/// the fallback physical-containment probe must not turn a successful,
/// authorized delete into an unverified mutation merely because its exact
/// scope root has disappeared.
#[cfg(windows)]
#[tokio::test]
async fn exact_file_grant_verifies_its_deleted_leaf() {
    let ws = tempfile::TempDir::new().unwrap();
    let file = ws.path().join("state.txt");
    std::fs::write(&file, "before\n").unwrap();
    let granted = file.to_string_lossy().into_owned();
    let caveats = Caveats {
        fs_read: Scope::only([granted.clone()]),
        fs_write: Scope::only([granted]),
        ..Caveats::top()
    };

    let output = run_tool(
        "delete_file",
        serde_json::json!({"path": "state.txt"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(output.starts_with("deleted state.txt"), "{output}");
    assert!(output.contains("Deleted (+0 -1)"), "{output}");
    assert!(!file.exists());
}

/// Windows maps both a missing leaf and a regular-file-parent traversal to
/// `NotFound`; only the former may prove an absent postimage. An existing
/// directory is likewise unreadable as a regular file, not absent.
#[cfg(windows)]
#[test]
fn windows_not_found_receipts_require_a_missing_leaf_below_a_directory() {
    let ws = tempfile::TempDir::new().unwrap();
    let blocked = ws.path().join("blocked");
    std::fs::write(&blocked, "regular file").unwrap();
    let workspace_scope = Scope::only([ws.path().to_string_lossy().into_owned()]);
    let through_regular_file = blocked.join("child.txt");
    assert!(matches!(
        crate::agentic::tools::file_capture::capture(&workspace_scope, &through_regular_file),
        crate::agentic::tools::file_capture::TextSnapshot::Unavailable(_)
    ));
    assert!(!crate::agentic::tools::file_capture::absent(
        &workspace_scope,
        &through_regular_file
    ));

    let through_missing_parent = ws.path().join("missing-parent/child.txt");
    assert!(matches!(
        crate::agentic::tools::file_capture::capture(&workspace_scope, &through_missing_parent),
        crate::agentic::tools::file_capture::TextSnapshot::Unavailable(_)
    ));
    assert!(!crate::agentic::tools::file_capture::absent(
        &workspace_scope,
        &through_missing_parent
    ));

    let directory = ws.path().join("directory");
    std::fs::create_dir(&directory).unwrap();
    let exact_directory_scope = Scope::only([directory.to_string_lossy().into_owned()]);
    assert!(matches!(
        crate::agentic::tools::file_capture::capture(&exact_directory_scope, &directory),
        crate::agentic::tools::file_capture::TextSnapshot::Unavailable(_)
    ));
    assert!(!crate::agentic::tools::file_capture::absent(
        &exact_directory_scope,
        &directory
    ));
}

#[cfg(unix)]
#[tokio::test]
async fn deleting_a_final_symlink_does_not_report_its_target_contents_as_deleted() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("target.txt"), "target remains\n").unwrap();
    std::os::unix::fs::symlink("target.txt", ws.path().join("link.txt")).unwrap();
    let output = run_tool(
        "delete_file",
        serde_json::json!({"path": "link.txt"}),
        ws.path(),
        &caveats_rw(ws.path()),
        None,
    )
    .await;
    assert!(output.starts_with("deleted link.txt"), "{output}");
    assert!(
        output.contains("File operation succeeded; optional change preview unavailable"),
        "{output}"
    );
    assert!(!output.contains("-target remains"), "{output}");
    assert!(!output.contains("```diff"), "{output}");
    assert_eq!(
        std::fs::read_to_string(ws.path().join("target.txt")).unwrap(),
        "target remains\n"
    );
}

// -- moving code by line range: no retyping, no shell dialect -------------
//
// Live 2026-09-23: a retyped 1,263-line move fabricated symbols; a shell sed
// range copy then failed on BSD-vs-GNU syntax and left `mod.rs-e` behind.

#[tokio::test]
async fn copy_from_moves_a_line_range_byte_exact_after_a_typed_header() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(
        ws.path().join("src.rs"),
        "l1\nfn moved() {\n    body();\n}\nl5\n",
    )
    .unwrap();
    let (model, _) = model_and_display(
        "write_file",
        serde_json::json!({"path": "dst.rs", "content": "use x;\n",
            "copy_from": {"path": "src.rs", "start_line": 2, "end_line": 4}}),
        ws.path(),
        &caveats_rw(ws.path()),
        ToolCollaborators::default(),
    )
    .await;
    assert!(model.contains("Added (+4 -0)"), "{model}");
    assert_eq!(
        std::fs::read_to_string(ws.path().join("dst.rs")).unwrap(),
        "use x;\nfn moved() {\n    body();\n}\n"
    );
}

/// `copy_from` reads through read_file's own fence: a source outside the
/// fs_read scope is refused, and nothing is written.
#[tokio::test]
async fn copy_from_a_source_outside_the_read_scope_is_denied_and_writes_nothing() {
    let ws = tempfile::TempDir::new().unwrap();
    let outside = tempfile::TempDir::new().unwrap();
    let secret = outside.path().join("secret.txt");
    std::fs::write(&secret, "private\n").unwrap();
    let caveats = Caveats {
        fs_read: Scope::only([ws.path().to_string_lossy().into_owned()]),
        ..caveats_rw(ws.path())
    };
    let (model, _) = model_and_display(
        "write_file",
        serde_json::json!({"path": "dst.txt", "content": "",
            "copy_from": {"path": secret.to_string_lossy(), "start_line": 1, "end_line": 1}}),
        ws.path(),
        &caveats,
        ToolCollaborators::default(),
    )
    .await;
    assert!(
        model.contains("fs_read"),
        "refusal names the denied axis: {model}"
    );
    assert!(!model.contains("private"), "{model}");
    assert!(!ws.path().join("dst.txt").exists(), "nothing written");
}

// -- an incomplete edit must never become a deletion ------------------------
//
// `new_string` was read with `unwrap_or("")` since Step 9.7 (#253): an edit
// that arrived WITHOUT it silently deleted its target. Under context pressure
// a weak model does drop keys (live, 2026-09-23: nine `edit_file` calls
// carrying only {path, new_string} in one run), and the line-range mode added
// in #2553 made the failure easy to hit — `{path, start_line, end_line}` alone
// deleted those lines. The harness now validates the call before touching the
// file: `new_string` must be present and a string; an explicit "" still
// deletes on purpose. The range mode is removed (it was also unbound to the
// version the model observed, so a stale range hit the wrong lines).

const EDIT_FIXTURE: &str = "line a\nline b\nline c\nline d\nline e\n";

async fn edit_outcome(args: serde_json::Value) -> (String, String) {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("fixture.rs"), EDIT_FIXTURE).unwrap();
    let (model, _) = model_and_display(
        "edit_file",
        args,
        ws.path(),
        &caveats_rw(ws.path()),
        ToolCollaborators::default(),
    )
    .await;
    let after = std::fs::read_to_string(ws.path().join("fixture.rs")).unwrap();
    (model, after)
}

#[tokio::test]
async fn an_edit_without_a_string_new_string_fails_and_changes_nothing() {
    for args in [
        // The review's exact reproduction: a valid range, no new_string.
        serde_json::json!({"path": "fixture.rs", "start_line": 2, "end_line": 4}),
        // The older path: a matching old_string, no new_string.
        serde_json::json!({"path": "fixture.rs", "old_string": "line b"}),
        serde_json::json!({"path": "fixture.rs", "old_string": "line b", "new_string": null}),
        serde_json::json!({"path": "fixture.rs", "old_string": "line b", "new_string": 7}),
        serde_json::json!({"path": "fixture.rs", "old_string": "line b", "new_string": false}),
        serde_json::json!({"path": "fixture.rs", "old_string": "line b", "new_string": ["x"]}),
        serde_json::json!({"path": "fixture.rs", "old_string": "line b", "new_string": {"x": 1}}),
    ] {
        let (model, after) = edit_outcome(args.clone()).await;
        assert!(
            !tool_result_ok(&model),
            "must be a FAILED call: {args} -> {model}"
        );
        assert!(
            model.contains("new_string"),
            "names the missing field: {model}"
        );
        assert_eq!(after, EDIT_FIXTURE, "bytes unchanged for {args}");
    }
}

#[tokio::test]
async fn a_line_range_selector_is_refused_and_changes_nothing() {
    for args in [
        serde_json::json!({"path": "fixture.rs", "start_line": 2, "end_line": 4, "new_string": "x"}),
        serde_json::json!({"path": "fixture.rs", "start_line": 2, "new_string": ""}),
        serde_json::json!({"path": "fixture.rs", "old_string": "line b", "end_line": 4, "new_string": "x"}),
    ] {
        let (model, after) = edit_outcome(args.clone()).await;
        assert!(
            !tool_result_ok(&model),
            "must be a FAILED call: {args} -> {model}"
        );
        assert!(
            model.contains("line range"),
            "says ranges are not supported: {model}"
        );
        assert_eq!(after, EDIT_FIXTURE, "bytes unchanged for {args}");
    }
}

#[tokio::test]
async fn an_explicit_empty_new_string_still_deletes_on_purpose() {
    let (model, after) = edit_outcome(
        serde_json::json!({"path": "fixture.rs", "old_string": "line b\n", "new_string": ""}),
    )
    .await;
    assert!(tool_result_ok(&model), "{model}");
    assert_eq!(after, "line a\nline c\nline d\nline e\n");
}

// -- write_file: the same dropped-key bug ----------------------------------
//
// `content` was read with `unwrap_or("")`, so a write that dropped it emptied
// the file and reported success. The shrink guard only fires past 30 lines
// and 30%, so a small file was wiped silently and a new path created empty.

#[tokio::test]
async fn a_write_without_a_string_content_fails_and_changes_nothing() {
    for args in [
        serde_json::json!({"path": "fixture.rs"}),
        serde_json::json!({"path": "fixture.rs", "content": null}),
        serde_json::json!({"path": "fixture.rs", "content": 7}),
        serde_json::json!({"path": "new.rs"}),
    ] {
        let ws = tempfile::TempDir::new().unwrap();
        std::fs::write(ws.path().join("fixture.rs"), EDIT_FIXTURE).unwrap();
        let (model, _) = model_and_display(
            "write_file",
            args.clone(),
            ws.path(),
            &caveats_rw(ws.path()),
            ToolCollaborators::default(),
        )
        .await;
        assert!(
            !tool_result_ok(&model),
            "must be a FAILED call: {args} -> {model}"
        );
        assert!(
            model.contains("content"),
            "names the missing field: {model}"
        );
        let after = std::fs::read_to_string(ws.path().join("fixture.rs")).unwrap();
        assert_eq!(after, EDIT_FIXTURE, "bytes unchanged for {args}");
        assert!(
            !ws.path().join("new.rs").exists(),
            "no empty file created for {args}"
        );
    }
}

/// A malformed call is refused before the operator is asked to approve it:
/// approving an edit that is then refused anyway wastes the human's consent.
struct NeverAsked;

impl PermissionGate for NeverAsked {
    fn ask(&mut self, requests: &[PermissionRequest]) -> PermissionDecision {
        panic!("a malformed call reached the permission gate: {requests:?}")
    }

    fn ask_question(&mut self, question: &str) -> HumanQuestionOutcome {
        panic!("a malformed call reached the confirm prompt: {question}")
    }
}

#[tokio::test]
async fn malformed_mutations_are_refused_before_the_permission_gate() {
    for (tool, args, names) in [
        (
            "edit_file",
            serde_json::json!({"path": "fixture.rs", "old_string": "", "new_string": "x"}),
            "old_string",
        ),
        (
            "edit_file",
            serde_json::json!({"path": "fixture.rs", "new_string": "x"}),
            "old_string",
        ),
        (
            "edit_file",
            serde_json::json!({"old_string": "line b", "new_string": "x"}),
            "path",
        ),
        ("write_file", serde_json::json!({"content": "x"}), "path"),
        (
            "write_file",
            serde_json::json!({"path": "fixture.rs"}),
            "content",
        ),
    ] {
        let ws = tempfile::TempDir::new().unwrap();
        std::fs::write(ws.path().join("fixture.rs"), EDIT_FIXTURE).unwrap();
        // Writes are outside scope, so a well-formed call WOULD ask the gate.
        let caveats = Caveats {
            fs_write: Scope::none(),
            ..caveats_rw(ws.path())
        };
        let mut gate = NeverAsked;
        let (model, _) = model_and_display(
            tool,
            args.clone(),
            ws.path(),
            &caveats,
            ToolCollaborators {
                permission_gate: Some(&mut gate),
                ..ToolCollaborators::default()
            },
        )
        .await;
        assert!(
            !tool_result_ok(&model),
            "must be a FAILED call: {tool} {args} -> {model}"
        );
        assert!(model.contains(names), "names `{names}`: {model}");
        let after = std::fs::read_to_string(ws.path().join("fixture.rs")).unwrap();
        assert_eq!(after, EDIT_FIXTURE, "bytes unchanged for {tool} {args}");
    }
}

/// #2724: grounds the pure extraction validator in the actual write_file
/// dispatcher: invalid move_from must not fall through to an ordinary write.
#[tokio::test]
async fn move_from_rejects_duplicate_items_before_mutation() {
    let ws = tempfile::tempdir().unwrap();
    let source = "fn helper() -> u8 { 7 }\n";
    std::fs::write(ws.path().join("lib.rs"), source).unwrap();
    std::fs::write(
        ws.path().join("Cargo.toml"),
        "[package]\nname=\"move_fixture\"\nversion=\"0.1.0\"\n[lib]\npath=\"lib.rs\"\n",
    )
    .unwrap();
    let (output, _) = model_and_display(
        "write_file",
        serde_json::json!({"path":"child.rs", "content":"", "move_from":{
            "path":"lib.rs", "items":["helper", "helper"]
        }}),
        ws.path(),
        &Caveats::top(),
        ToolCollaborators::default(),
    )
    .await;
    assert!(output.starts_with("error:"), "{output}");
    #[cfg(feature = "ast")]
    assert!(output.contains("unique, nonempty item names"), "{output}");
    assert_eq!(
        std::fs::read_to_string(ws.path().join("lib.rs")).unwrap(),
        source
    );
    assert!(!ws.path().join("child.rs").exists());
}