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
use super::*;

#[tokio::test]
async fn edit_file_replaces_unique_match_and_reports_delta() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("f.txt"), "hello world\nsecond line\n").unwrap();
    let caveats = caveats_rw(ws.path());
    let out = run_tool(
        "edit_file",
        serde_json::json!({
            "path": "f.txt",
            "old_string": "world",
            "new_string": "rust\nand more"
        }),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.starts_with("edited f.txt (+1 lines"), "got: {out}");
    assert_eq!(
        std::fs::read_to_string(ws.path().join("f.txt")).unwrap(),
        "hello rust\nand more\nsecond line\n"
    );
}

#[tokio::test]
async fn edit_file_rejects_empty_missing_and_ambiguous_old_string() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("f.txt"), "dup\ndup\n").unwrap();
    let caveats = caveats_rw(ws.path());

    let out = run_tool(
        "edit_file",
        serde_json::json!({"path": "f.txt", "old_string": "", "new_string": "x"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.contains("old_string must not be empty"), "got: {out}");

    let out = run_tool(
        "edit_file",
        serde_json::json!({"path": "f.txt", "old_string": "absent", "new_string": "x"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.contains("old_string not found in f.txt"), "got: {out}");
    // The miss error now shows the file's actual contents so the model can
    // copy the exact text instead of blind-guessing old_string again.
    assert!(out.contains("do not guess again"), "got: {out}");
    assert!(
        out.contains("dup"),
        "miss error must include the file content: {out}"
    );

    let out = run_tool(
        "edit_file",
        serde_json::json!({"path": "f.txt", "old_string": "dup", "new_string": "x"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.contains("matches 2 locations"), "got: {out}");
    // The ambiguous edit must NOT have touched the file.
    assert_eq!(
        std::fs::read_to_string(ws.path().join("f.txt")).unwrap(),
        "dup\ndup\n"
    );
}

#[tokio::test]
async fn edit_file_denied_outside_fs_write_scope_and_missing_file() {
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = Caveats {
        fs_write: Scope::none(),
        ..caveats_rw(ws.path())
    };
    let out = run_tool(
        "edit_file",
        serde_json::json!({"path": "f.txt", "old_string": "a", "new_string": "b"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(
        out.contains("capability denied: fs_write"),
        "denied before any fs access, got: {out}"
    );

    let caveats = caveats_rw(ws.path());
    let out = run_tool(
        "edit_file",
        serde_json::json!({"path": "missing.txt", "old_string": "a", "new_string": "b"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.contains("error: reading missing.txt"), "got: {out}");
}

#[tokio::test]
#[cfg(target_os = "linux")]
async fn edit_file_symlink_under_workspace_escaping_is_denied() {
    // step-52.5: under a CONFINED fs_write, a symlink UNDER the workspace
    // pointing outside must not let edit_file read OR write the outside file.
    // Both the read of `existing` (which could leak the outside head on a
    // no-match) and the write are object-bound; the outside file is unchanged
    // and its contents never appear in the output. Verified red→green.
    let ws = tempfile::TempDir::new().unwrap();
    let outside = tempfile::TempDir::new().unwrap();
    std::fs::write(outside.path().join("secret.txt"), "OUTSIDE SECRET\n").unwrap();
    std::os::unix::fs::symlink(outside.path(), ws.path().join("link")).unwrap();

    let out = run_tool(
        "edit_file",
        serde_json::json!({
            "path": "link/secret.txt",
            "old_string": "OUTSIDE",
            "new_string": "EDITED",
        }),
        ws.path(),
        &caveats_rw(ws.path()),
        None,
    )
    .await;

    assert!(
        !out.contains("OUTSIDE SECRET"),
        "object-bound edit must not leak the outside file: {out}"
    );
    assert_eq!(
        out,
        denied_fs_result(
            "fs_write",
            &ws.path().join("link/secret.txt").to_string_lossy()
        ),
        "the symlink-escape edit must be denied: {out}"
    );
    assert_eq!(
        std::fs::read_to_string(outside.path().join("secret.txt")).unwrap(),
        "OUTSIDE SECRET\n",
        "the outside file must be UNCHANGED"
    );
}

#[tokio::test]
async fn edit_file_appends_build_check_result() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("f.txt"), "old\n").unwrap();
    let caveats = caveats_rw(ws.path());
    let out = run_tool(
        "edit_file",
        serde_json::json!({"path": "f.txt", "old_string": "old", "new_string": "new"}),
        ws.path(),
        &caveats,
        Some(passing_build_check_cmd()),
    )
    .await;
    // build_check runs CONFINED (P4). On Linux+Landlock the check runs and
    // its outcome is reflected; off it (e.g. Windows without the AppContainer
    // launcher) it fails closed — either way the tool APPENDS a build-check
    // line, which is what this test guards.
    let confinable = crate::confined_exec::kernel_fs_fence_available();
    if confinable {
        assert!(out.contains("✓ build check passed"), "got: {out}");
    } else {
        assert!(
            out.contains("build check"),
            "build-check line appended: {out}"
        );
    }

    let failing_check = failing_build_check_cmd("broke");
    let out = run_tool(
        "edit_file",
        serde_json::json!({"path": "f.txt", "old_string": "new", "new_string": "newer"}),
        ws.path(),
        &caveats,
        Some(&failing_check),
    )
    .await;
    if confinable {
        assert!(out.contains("✗ build check failed"), "got: {out}");
        assert!(out.contains("broke"), "model sees the failure text: {out}");
    } else {
        assert!(
            out.contains("build check"),
            "build-check line appended: {out}"
        );
    }
}

#[tokio::test]
async fn write_file_shrink_guard_refuses_large_deletion() {
    let ws = tempfile::TempDir::new().unwrap();
    let big: String = (0..100).map(|i| format!("line {i}\n")).collect();
    std::fs::write(ws.path().join("big.txt"), &big).unwrap();
    let caveats = caveats_rw(ws.path());
    let out = run_tool(
        "write_file",
        serde_json::json!({"path": "big.txt", "content": "tiny\n"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(
        out.contains("would shrink big.txt from 100 → 1 lines"),
        "got: {out}"
    );
    assert!(out.contains("edit_file"), "points at the safer tool: {out}");
    // The guard refused — the original file must be intact.
    assert_eq!(
        std::fs::read_to_string(ws.path().join("big.txt")).unwrap(),
        big
    );
}

#[tokio::test]
async fn write_file_creates_parent_directories() {
    let ws = tempfile::TempDir::new().unwrap();
    let caveats = caveats_rw(ws.path());
    let out = run_tool(
        "write_file",
        serde_json::json!({"path": "a/b/c.txt", "content": "nested"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.starts_with("wrote a/b/c.txt"), "got: {out}");
    assert_eq!(
        std::fs::read_to_string(ws.path().join("a/b/c.txt")).unwrap(),
        "nested"
    );
}

#[tokio::test]
async fn delete_file_removes_one_file_and_appends_build_check() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("old.rs"), "fn main() {}\n").unwrap();
    let caveats = caveats_rw(ws.path());
    let out = run_tool(
        "delete_file",
        serde_json::json!({"path": "old.rs"}),
        ws.path(),
        &caveats,
        Some(passing_build_check_cmd()),
    )
    .await;
    assert!(out.starts_with("deleted old.rs"), "got: {out}");
    // Confined build_check (P4): outcome-checked on Linux+Landlock, else the
    // fail-closed line still counts as an appended build-check result.
    if crate::confined_exec::kernel_fs_fence_available() {
        assert!(out.contains("✓ build check passed"), "got: {out}");
    } else {
        assert!(
            out.contains("build check"),
            "build-check line appended: {out}"
        );
    }
    assert!(
        !ws.path().join("old.rs").exists(),
        "delete_file must remove the target file"
    );
}

#[tokio::test]
async fn delete_file_denies_missing_files_directories_and_fs_write_misses() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("secret.txt"), "x").unwrap();
    std::fs::create_dir(ws.path().join("dir")).unwrap();

    let denied = Caveats {
        fs_write: Scope::none(),
        ..caveats_rw(ws.path())
    };
    let out = run_tool(
        "delete_file",
        serde_json::json!({"path": "secret.txt"}),
        ws.path(),
        &denied,
        None,
    )
    .await;
    assert!(out.contains("capability denied: fs_write"), "got: {out}");
    assert!(
        ws.path().join("secret.txt").exists(),
        "denied delete must not remove the file"
    );

    let caveats = caveats_rw(ws.path());
    let out = run_tool(
        "delete_file",
        serde_json::json!({"path": "missing.txt"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.contains("file does not exist"), "got: {out}");

    let out = run_tool(
        "delete_file",
        serde_json::json!({"path": "dir"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.contains("refuses directories"), "got: {out}");
    assert!(ws.path().join("dir").is_dir(), "directory must remain");
}

#[tokio::test]
#[cfg(target_os = "linux")]
async fn delete_file_symlink_under_workspace_escaping_is_denied() {
    // step-52.6: under a CONFINED fs_write, a symlink UNDER the workspace
    // pointing outside must not let delete_file remove the outside file.
    // Object-bound via `unlinkat` on the resolved parent — the escape is
    // refused and the outside file survives. Before the rewire `remove_file`
    // followed the intermediate symlink and deleted outside. Verified
    // red→green.
    let ws = tempfile::TempDir::new().unwrap();
    let outside = tempfile::TempDir::new().unwrap();
    std::fs::write(outside.path().join("victim.txt"), "keep me\n").unwrap();
    std::os::unix::fs::symlink(outside.path(), ws.path().join("link")).unwrap();

    let out = run_tool(
        "delete_file",
        serde_json::json!({"path": "link/victim.txt"}),
        ws.path(),
        &caveats_rw(ws.path()),
        None,
    )
    .await;

    // step 13.2: a denied delete now also carries the observed-file-state
    // receipt (unconditionally "no content change", since the object fence
    // refused before anything on disk moved). Build the expected value the
    // same way the production delete_file arm does, rather than pinning the
    // receipt's internal formatting as a second, driftable literal.
    let full = ws.path().join("link/victim.txt");
    let read_caveats = caveats_rw(ws.path());
    let before = crate::agentic::tools::file_capture::capture(&read_caveats.fs_read, &full);
    let after = crate::agentic::tools::file_capture::capture(&read_caveats.fs_read, &full);
    let receipt = crate::agentic::tools::file_capture::receipt("link/victim.txt", &before, &after);
    let mut display = crate::agentic::display::ToolDisplay::new(Vec::new(), false, 80, 0, false);
    let expected = receipt.present(
        crate::agentic::tools::file_capture::failure(
            denied_fs_result("fs_write", &full.to_string_lossy()),
            "",
        ),
        "",
        &mut display,
    );
    assert_eq!(
        out, expected,
        "the symlink-escape delete must be denied: {out}"
    );
    assert!(
        outside.path().join("victim.txt").exists(),
        "the outside file must survive — the delete never escaped"
    );
}

#[tokio::test]
async fn read_file_denial_and_missing_file_errors() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("secret.txt"), "x").unwrap();
    let denied = Caveats {
        fs_read: Scope::none(),
        ..caveats_rw(ws.path())
    };
    let out = run_tool(
        "read_file",
        serde_json::json!({"path": "secret.txt"}),
        ws.path(),
        &denied,
        None,
    )
    .await;
    assert!(out.contains("capability denied: fs_read"), "got: {out}");

    let caveats = caveats_rw(ws.path());
    let out = run_tool(
        "read_file",
        serde_json::json!({"path": "nope.txt"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.contains("error: reading nope.txt"), "got: {out}");
}

#[tokio::test]
#[cfg(target_os = "linux")]
async fn read_file_symlink_under_workspace_escaping_is_denied() {
    // step-52.2 (fs-canonical-containment / #522): under a CONFINED fs_read
    // (Only{ws}, not All), a symlink UNDER the workspace whose target is
    // outside it must not let read_file exfiltrate the outside file — even
    // though the lexical gate admits the name `link/secret.txt`. The read is
    // object-bound through `WorkspaceDir` (openat2 RESOLVE_BENEATH), so the
    // escape is refused by the kernel. Before the rewire this returned the
    // secret — the named residual. Real-fs tier (grounds the object gate);
    // Linux-only (openat2).
    let ws = tempfile::TempDir::new().unwrap();
    let outside = tempfile::TempDir::new().unwrap();
    std::fs::write(outside.path().join("secret.txt"), "TOP SECRET").unwrap();
    std::os::unix::fs::symlink(outside.path(), ws.path().join("link")).unwrap();

    let confined = Caveats {
        fs_read: Scope::only([ws.path().to_string_lossy().into_owned()]),
        ..caveats_rw(ws.path())
    };
    let out = run_tool(
        "read_file",
        serde_json::json!({"path": "link/secret.txt"}),
        ws.path(),
        &confined,
        None,
    )
    .await;

    assert!(
        !out.contains("TOP SECRET"),
        "object-bound read must not follow a symlink out of the workspace: {out}"
    );
    assert_eq!(
        out,
        denied_fs_result(
            "fs_read",
            &ws.path().join("link/secret.txt").to_string_lossy()
        ),
        "a contained-read escape must surface as an fs_read denial: {out}"
    );
}

#[tokio::test]
async fn list_dir_denial_and_missing_dir_errors() {
    let ws = tempfile::TempDir::new().unwrap();
    let denied = Caveats {
        fs_read: Scope::none(),
        ..caveats_rw(ws.path())
    };
    let out = run_tool(
        "list_dir",
        serde_json::json!({"path": "."}),
        ws.path(),
        &denied,
        None,
    )
    .await;
    assert!(out.contains("capability denied: fs_read"), "got: {out}");

    let caveats = caveats_rw(ws.path());
    let out = run_tool(
        "list_dir",
        serde_json::json!({"path": "not-a-dir"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.starts_with("error:"), "got: {out}");
}

#[tokio::test]
#[cfg(target_os = "linux")]
async fn list_dir_symlink_under_workspace_escaping_is_denied() {
    // step-52.3: object-bound listing. Under a CONFINED fs_read (Only{ws}), a
    // symlink UNDER the workspace pointing to an outside directory must not
    // let list_dir enumerate the outside dir — even though the lexical gate
    // admits the name `link`. Before the rewire the outside entries were
    // listed (the #522 residual). Real-fs tier; Linux-only.
    let ws = tempfile::TempDir::new().unwrap();
    let outside = tempfile::TempDir::new().unwrap();
    std::fs::write(outside.path().join("outside_secret.txt"), "x").unwrap();
    std::os::unix::fs::symlink(outside.path(), ws.path().join("link")).unwrap();

    let confined = Caveats {
        fs_read: Scope::only([ws.path().to_string_lossy().into_owned()]),
        ..caveats_rw(ws.path())
    };
    let out = run_tool(
        "list_dir",
        serde_json::json!({"path": "link"}),
        ws.path(),
        &confined,
        None,
    )
    .await;

    assert!(
        !out.contains("outside_secret.txt"),
        "object-bound list_dir must not enumerate a directory outside the workspace: {out}"
    );
    assert_eq!(
        out,
        denied_fs_result("fs_read", &ws.path().join("link").to_string_lossy()),
        "got: {out}"
    );
}

/// Permission to write an external file must not bypass the existing shrink
/// protection. Grounds the scripted approval in a real file that must survive.
#[tokio::test]
async fn approved_external_write_retains_shrink_guard() {
    let ws = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let path = outside.path().join("large.txt");
    let original = "original line\n".repeat(100);
    std::fs::write(&path, &original).unwrap();
    let caveats = caveats_rw(ws.path());
    let mut gate = MockGate::new(true, &caveats);
    let output = run_tool_gated(
        "write_file",
        serde_json::json!({"path":path, "content":"tiny\n"}),
        ws.path(),
        &caveats,
        &mut gate,
    )
    .await;
    assert_eq!(gate.asks.len(), 1);
    assert!(output.contains("would shrink"), "{output}");
    assert_eq!(std::fs::read_to_string(path).unwrap(), original);
}

/// Real filesystem grounding for `cli_fs_grants_widen_read_and_write_scopes`:
/// the CLI's exact-file scope must permit the actual read, without granting
/// sibling files or following a replacement link through the permitted name.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
async fn cli_exact_file_read_grant_reads_only_the_named_object() {
    let ws = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let granted = outside.path().join("allowed.txt");
    let sibling = outside.path().join("sibling.txt");
    std::fs::write(&granted, "allowed contents\n").unwrap();
    std::fs::write(&sibling, "ungranted sibling contents\n").unwrap();
    let workspace = ws.path().to_string_lossy();
    let mut caveats = crate::ToolPermissions {
        preset: crate::PermissionPreset::ReadOnly,
        ..Default::default()
    }
    .to_caveats(&workspace);
    crate::caveats::lock_fs_to_workspace(
        &mut caveats,
        &workspace,
        &[granted.to_string_lossy().into_owned()],
        &[],
    );

    let out = run_tool(
        "read_file",
        serde_json::json!({"path": granted}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert_eq!(out, "allowed contents\n", "exact-file read failed: {out}");

    let out = run_tool(
        "read_file",
        serde_json::json!({"path": sibling}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.starts_with("capability denied: fs_read"), "{out}");
    assert!(!out.contains("ungranted sibling contents"), "{out}");

    std::fs::remove_file(&granted).unwrap();
    std::os::unix::fs::symlink("sibling.txt", &granted).unwrap();
    let out = run_tool(
        "read_file",
        serde_json::json!({"path": granted}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.starts_with("capability denied: fs_read"), "{out}");
    assert!(!out.contains("ungranted sibling contents"), "{out}");
}

/// Real filesystem grounding for the CLI write-implies-read scope contract:
/// an exact target may be created and updated, while siblings and a replacement
/// symlink remain outside the grant. No scripted permission gate is involved.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
async fn cli_exact_file_write_grant_creates_and_updates_only_the_named_object() {
    let ws = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let granted = outside.path().join("allowed.txt");
    let sibling = outside.path().join("sibling.txt");
    std::fs::write(&sibling, "unchanged sibling\n").unwrap();
    let workspace = ws.path().to_string_lossy();
    let mut caveats = crate::ToolPermissions {
        preset: crate::PermissionPreset::ReadOnly,
        ..Default::default()
    }
    .to_caveats(&workspace);
    crate::caveats::lock_fs_to_workspace(
        &mut caveats,
        &workspace,
        &[],
        &[granted.to_string_lossy().into_owned()],
    );

    for content in ["created contents\n", "updated contents\n"] {
        let out = run_tool(
            "write_file",
            serde_json::json!({"path": granted, "content": content}),
            ws.path(),
            &caveats,
            None,
        )
        .await;
        assert!(out.starts_with("wrote "), "exact-file write failed: {out}");
        assert_eq!(std::fs::read_to_string(&granted).unwrap(), content);
        let out = run_tool(
            "read_file",
            serde_json::json!({"path": granted}),
            ws.path(),
            &caveats,
            None,
        )
        .await;
        assert_eq!(out, content, "write grant must also permit read: {out}");
    }

    let large = (0..100)
        .map(|line| format!("line {line}\n"))
        .collect::<String>();
    std::fs::write(&granted, &large).unwrap();
    let out = run_tool(
        "write_file",
        serde_json::json!({"path": granted, "content": "too short\n"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(
        out.contains("would shrink"),
        "exact-file preimage must retain the shrink guard: {out}"
    );
    assert_eq!(std::fs::read_to_string(&granted).unwrap(), large);

    let out = run_tool(
        "write_file",
        serde_json::json!({"path": sibling, "content": "forbidden change\n"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.starts_with("capability denied: fs_write"), "{out}");
    assert_eq!(
        std::fs::read_to_string(&sibling).unwrap(),
        "unchanged sibling\n"
    );

    std::fs::remove_file(&granted).unwrap();
    std::os::unix::fs::symlink("sibling.txt", &granted).unwrap();
    let out = run_tool(
        "write_file",
        serde_json::json!({"path": granted, "content": "forbidden change\n"}),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(out.starts_with("capability denied: fs_write"), "{out}");
    assert_eq!(
        std::fs::read_to_string(&sibling).unwrap(),
        "unchanged sibling\n"
    );
}

/// P0 U5: a small model sent `\n` as two characters, on one line, and the edit
/// landed silently, leaving a file that did not compile. The edit still applies
/// (a string literal may legitimately hold `\n`), but the success result says
/// what it saw so the model can re-send with real newlines.
#[tokio::test]
async fn edit_file_warns_when_new_string_has_literal_backslash_n_and_no_newline() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("f.rs"), "let a = 1;\nlet b = 2;\n").unwrap();
    let caveats = caveats_rw(ws.path());
    let out = run_tool(
        "edit_file",
        serde_json::json!({
            "path": "f.rs",
            "old_string": "let a = 1;",
            "new_string": "let a = 1;\\n    let c = 3;"
        }),
        ws.path(),
        &caveats,
        None,
    )
    .await;
    assert!(
        out.starts_with("edited f.rs"),
        "the edit still applies: {out}"
    );
    assert!(
        out.contains("literal `\\n`") && out.contains("real newlines"),
        "a warning must accompany the success: {out}"
    );
    assert_eq!(
        std::fs::read_to_string(ws.path().join("f.rs")).unwrap(),
        "let a = 1;\\n    let c = 3;\nlet b = 2;\n",
        "the model's text is applied verbatim, never rewritten"
    );
}

/// The warning must not fire on ordinary edits: real newlines present, no
/// backslash-n, or the file already used the escape at that spot.
#[tokio::test]
async fn edit_file_does_not_warn_on_ordinary_or_pre_existing_escapes() {
    let ws = tempfile::TempDir::new().unwrap();
    std::fs::write(ws.path().join("f.rs"), "print(\"a\\n\");\nlet b = 2;\n").unwrap();
    let caveats = caveats_rw(ws.path());
    for (old, new) in [
        ("let b = 2;", "let b = 2;\nlet c = 3;\\n"), // real newline present
        ("let b = 2;", "let b = 9;"),                // no escape at all
        ("print(\"a\\n\");", "print(\"b\\n\");"),    // escape already in old_string
    ] {
        let out = run_tool(
            "edit_file",
            serde_json::json!({"path": "f.rs", "old_string": old, "new_string": new}),
            ws.path(),
            &caveats,
            None,
        )
        .await;
        assert!(out.starts_with("edited f.rs"), "{out}");
        assert!(!out.contains("real newlines"), "spurious warning: {out}");
    }
}