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
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
use super::*;
use crate::agentic::{mcp::NoMcp, smart_harness::SmartHarness};
use crate::caveats::Caveats;
use std::{path::Path, sync::Arc};

fn harness(directory: &Path) -> (SmartHarness, content_addressable::ContentId) {
    let mut session =
        agent_harness::Session::open(directory, crate::test_guard::unbudgeted_session_config())
            .unwrap();
    let source = session
        .retain_tool_output("fixture", b"retained original source")
        .unwrap();
    (
        SmartHarness::new(
            session,
            Arc::new(|_| panic!("filesystem isolation never needs inference")),
            Default::default(),
        )
        .unwrap(),
        source,
    )
}

async fn dispatch(
    harness: &SmartHarness,
    workspace: &Path,
    caveats: &Caveats,
    name: &str,
    args: serde_json::Value,
    permission_gate: Option<&mut dyn PermissionGate>,
) -> String {
    dispatch_with_worktree_session(
        harness,
        workspace,
        caveats,
        name,
        args,
        permission_gate,
        None,
    )
    .await
}

async fn dispatch_with_worktree_session(
    harness: &SmartHarness,
    workspace: &Path,
    caveats: &Caveats,
    name: &str,
    args: serde_json::Value,
    permission_gate: Option<&mut dyn PermissionGate>,
    worktree_session: Option<&crate::worktree_adoption::WorktreeSession>,
) -> String {
    let batch = harness.fixture_tool_batch(name, args.clone());
    let invocation = batch.start(0, None).unwrap();
    let mut display = super::super::display::ToolDisplay::new(Vec::new(), false, 80, 20, false);
    execute_tool_with_display_cancellable(
        &mut display,
        name,
        &args,
        workspace.to_str().unwrap(),
        false,
        20,
        caveats,
        &mut NoMcp,
        ToolCollaborators {
            invocation: Some(&invocation),
            permission_gate,
            worktree_session,
            ..Default::default()
        },
        false,
        PromptDisposition::Act,
        None,
    )
    .await
    .unwrap()
    .unwrap()
}

/// Grounds the smart-session authority gate in actual file operations: a
/// workspace grant must never expose a frame that lies beneath that grant.
#[tokio::test]
#[serial_test::serial]
async fn exposed_frame_refuses_generic_tool_dispatch() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    let workspace = tempfile::tempdir().unwrap();
    let directory = workspace.path().join(".newt/frame");
    let (harness, _) = harness(&directory);
    let marker = directory.join("marker");
    std::fs::write(&marker, "frame contents").unwrap();
    let caveats = crate::confined_exec::workspace_confined_caveats(workspace.path());
    for name in ["read_file", "write_file", "list_dir", "delete_file"] {
        let target = if name == "list_dir" {
            &directory
        } else {
            &marker
        };
        let output = dispatch(
            &harness,
            workspace.path(),
            &caveats,
            name,
            serde_json::json!({"path":target,"content":"changed"}),
            None,
        )
        .await;
        assert!(output.contains("frame isolation"), "{name}: {output}");
        assert_eq!(std::fs::read_to_string(&marker).unwrap(), "frame contents");
    }
}

struct WidenAll;
impl PermissionGate for WidenAll {
    fn ask(&mut self, _: &[PermissionRequest]) -> PermissionDecision {
        PermissionDecision::Allow(Caveats::top())
    }
    fn ask_question(&mut self, _: &str) -> HumanQuestionOutcome {
        HumanQuestionOutcome::Answer("operator answer".into())
    }
}

/// Grounds declaration preflight with a real workspace canary: a request to
/// expose private frame storage must not consult the operator or start a child.
#[cfg(target_os = "macos")]
#[tokio::test]
#[serial_test::serial]
async fn native_once_filesystem_frame_preflight_precedes_consumption_and_spawn() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let _engine = super::disable_ocap_tests::EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    let _ocap = super::disable_ocap_tests::EnvVar::unset("NEWT_DISABLE_OCAP");
    let _full = super::disable_ocap_tests::EnvVar::unset("NEWT_FULL_ACCESS");
    struct CountingGate(usize);
    impl PermissionGate for CountingGate {
        fn ask(&mut self, _: &[PermissionRequest]) -> PermissionDecision {
            self.0 += 1;
            PermissionDecision::Allow(Caveats::top())
        }
        fn ask_with_caveats(
            &mut self,
            _: &Caveats,
            requests: &[PermissionRequest],
        ) -> PermissionDecision {
            self.ask(requests)
        }
        fn ask_question(&mut self, _: &str) -> HumanQuestionOutcome {
            HumanQuestionOutcome::Unavailable
        }
    }
    let workspace = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let unrelated = tempfile::tempdir().unwrap();
    let (harness, _) = harness(directory.path());
    let marker = workspace.path().join("must-not-run");
    let baseline = Caveats {
        exec: crate::caveats::Scope::only(["/usr/bin/touch".into()]),
        ..crate::confined_exec::workspace_confined_caveats(workspace.path())
    };
    let mut gate = CountingGate(0);
    for (target, expected_calls) in [(directory.path(), 0), (unrelated.path(), 1)] {
        let output = dispatch(
            &harness,
            workspace.path(),
            &baseline,
            "run_command",
            serde_json::json!({
                "command": format!("/usr/bin/touch '{}'", marker.display()),
                "fs_read": [target.canonicalize().unwrap()],
            }),
            Some(&mut gate),
        )
        .await;
        assert!(output.contains("frame isolation"), "{output}");
        assert_eq!(
            gate.0, expected_calls,
            "preflight avoids consumption; a broader actual decision is validated afterwards"
        );
        assert!(
            !marker.exists(),
            "the rejected declaration must not spawn a child"
        );
    }
}

/// Grounds passive-refresh rejection in an actual child side effect: a gate's
/// newly recalled authority cannot expose a private frame, even when the
/// requested command itself would fit the old workspace-only policy.
#[cfg(target_os = "macos")]
#[tokio::test]
#[serial_test::serial]
async fn live_permission_refresh_cannot_bypass_frame_isolation() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let _engine = super::disable_ocap_tests::EnvVar::set("NEWT_SHELL_ENGINE", "safe-subset");
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    struct RecalledAll;
    impl PermissionGate for RecalledAll {
        fn ask(&mut self, _: &[PermissionRequest]) -> PermissionDecision {
            panic!("passive refresh must not ask for new authority");
        }
        fn refresh_caveats(&mut self, _: &Caveats) -> PermissionDecision {
            PermissionDecision::Allow(Caveats::top())
        }
        fn ask_question(&mut self, _: &str) -> HumanQuestionOutcome {
            HumanQuestionOutcome::Unavailable
        }
    }
    let workspace = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let (harness, _) = harness(directory.path());
    let marker = workspace.path().join("must-not-run");
    let baseline = crate::confined_exec::workspace_confined_caveats(workspace.path());
    let output = dispatch(
        &harness,
        workspace.path(),
        &baseline,
        "run_command",
        serde_json::json!({"command": format!("/usr/bin/touch '{}'", marker.display())}),
        Some(&mut RecalledAll),
    )
    .await;
    assert!(output.contains("frame isolation"), "{output}");
    assert!(
        !marker.exists(),
        "refused refresh must stop before any child runs"
    );
}

/// Grounds the mocked permission decision against a private payload file:
/// re-minting authority during a turn cannot bypass the frame read boundary.
#[tokio::test]
#[serial_test::serial]
async fn permission_widening_cannot_expose_private_frame() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    let workspace = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let (harness, _) = harness(directory.path());
    let marker = directory.path().join("marker");
    std::fs::write(&marker, "private generated material").unwrap();
    let caveats = crate::confined_exec::workspace_confined_caveats(workspace.path());
    let output = dispatch(
        &harness,
        workspace.path(),
        &caveats,
        "read_file",
        serde_json::json!({"path":marker}),
        Some(&mut WidenAll),
    )
    .await;
    assert!(!output.contains("private generated material"), "{output}");
    assert!(
        output.contains("denied") || output.contains("frame isolation"),
        "{output}"
    );
}

/// Grounds ordinary filesystem denials and mediated retrieval against the
/// same durable source, without granting the primary model raw frame access.
#[tokio::test]
#[serial_test::serial]
async fn private_frame_denies_raw_tools_and_preserves_mediated_reads() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    let workspace = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let (harness, source) = harness(directory.path());
    let marker = directory.path().join("marker");
    std::fs::write(&marker, "private generated material").unwrap();
    let caveats = crate::confined_exec::workspace_confined_caveats(workspace.path());
    if crate::agentic::smart_harness::validate_isolation_runtime().is_err() {
        let output = dispatch(
            &harness,
            workspace.path(),
            &caveats,
            "re_read",
            serde_json::json!({"cid":source.to_string(),"max_bytes":16}),
            None,
        )
        .await;
        assert!(output.contains("frame isolation"), "{output}");
        return;
    }
    for name in ["read_file", "write_file", "list_dir", "delete_file"] {
        let target = if name == "list_dir" {
            directory.path()
        } else {
            &marker
        };
        let output = dispatch(
            &harness,
            workspace.path(),
            &caveats,
            name,
            serde_json::json!({"path":target,"content":"changed"}),
            None,
        )
        .await;
        assert!(output.contains("denied"), "{name}: {output}");
        assert_eq!(
            std::fs::read_to_string(&marker).unwrap(),
            "private generated material"
        );
    }
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    {
        std::os::unix::fs::symlink(directory.path(), workspace.path().join("private-link"))
            .unwrap();
        for name in ["read_file", "write_file", "list_dir", "delete_file"] {
            let path = if name == "list_dir" {
                "private-link"
            } else {
                "private-link/marker"
            };
            let output = dispatch(
                &harness,
                workspace.path(),
                &caveats,
                name,
                serde_json::json!({"path":path,"content":"changed"}),
                None,
            )
            .await;
            assert!(output.contains("denied"), "symlink {name}: {output}");
            assert_eq!(
                std::fs::read_to_string(&marker).unwrap(),
                "private generated material"
            );
        }
    }
    let output = dispatch(
        &harness,
        workspace.path(),
        &caveats,
        "re_read",
        serde_json::json!({"cid":source.to_string(),"max_bytes":16}),
        None,
    )
    .await;
    let receipt: serde_json::Value = serde_json::from_str(&output).unwrap();
    assert_eq!(receipt["text"], "retained origina");
    assert_eq!(receipt["complete"], false);
}

/// Grounds the dispatch scope with a real shell child: the existing kernel
/// fence must deny raw frame reads and writes while allowing workspace work.
/// The Git control explicitly grants GIT_CONFIG_GLOBAL/GIT_CONFIG_SYSTEM=/dev/null
/// and omits HOME through the existing shell environment seam; ambient Git config
/// and ignore files remain unreadable.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
#[serial_test::serial]
async fn real_shell_cannot_read_or_mutate_private_frame() {
    use crate::caveats::Scope;

    let _env = super::disable_ocap_tests::env_lock().await;
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    let _engine = super::disable_ocap_tests::EnvVar::set("NEWT_SHELL_ENGINE", "host");
    // Git's ambient config is outside the grant. Use the existing explicit
    // shell-env seam to select empty config, as hardened_git does for setup.
    let _env_grant = super::disable_ocap_tests::EnvVar::set(
        "NEWT_SHELL_ENV_PASSTHROUGH",
        "GIT_CONFIG_GLOBAL:GIT_CONFIG_SYSTEM",
    );
    let _global = super::disable_ocap_tests::EnvVar::set("GIT_CONFIG_GLOBAL", "/dev/null");
    let _system = super::disable_ocap_tests::EnvVar::set("GIT_CONFIG_SYSTEM", "/dev/null");
    let workspace = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let (harness, _) = harness(directory.path());
    let marker = directory.path().join("marker");
    std::fs::write(&marker, "private generated material").unwrap();
    let mut caveats = crate::confined_exec::workspace_confined_caveats(workspace.path());
    caveats.exec = Scope::All;
    // The host-shell contract requires open network authority; this proof
    // exercises its independent filesystem boundary and performs no network IO.
    caveats.net = Scope::All;
    let command = format!(
        "printf allowed > inside.txt; cat '{}'; printf changed > '{}'; ln '{}' hardlink.txt",
        marker.display(),
        marker.display(),
        marker.display()
    );
    let output = dispatch(
        &harness,
        workspace.path(),
        &caveats,
        "run_command",
        serde_json::json!({"command":command}),
        None,
    )
    .await;
    assert!(!output.contains("private generated material"), "{output}");
    assert_eq!(
        std::fs::read_to_string(&marker).unwrap(),
        "private generated material"
    );
    assert!(!workspace.path().join("hardlink.txt").exists());
    if crate::ocap_l3_backend().1 {
        assert_eq!(
            std::fs::read_to_string(workspace.path().join("inside.txt"))
                .unwrap_or_else(|error| panic!("workspace control failed ({error}): {output}")),
            "allowed"
        );
        let found = dispatch(
            &harness,
            workspace.path(),
            &caveats,
            "run_command",
            serde_json::json!({"command":"find . -name inside.txt"}),
            None,
        )
        .await;
        assert!(
            found.contains("./inside.txt"),
            "confined shell find must run: {found}"
        );
        let initialized = crate::git_hardening::hardened_git(workspace.path(), &["init", "-q"])
            .unwrap()
            .output()
            .unwrap();
        assert!(
            initialized.status.success(),
            "fixture repository initialization failed: {}",
            String::from_utf8_lossy(&initialized.stderr)
        );
        std::fs::write(workspace.path().join("visible.txt"), "visible").unwrap();
        let status = dispatch(
            &harness,
            workspace.path(),
            &caveats,
            "run_command",
            serde_json::json!({"command":"git status --short"}),
            None,
        )
        .await;
        assert!(
            status.contains("?? visible.txt"),
            "scoped shell Git must run: {status}"
        );
        let staged = dispatch(
            &harness,
            workspace.path(),
            &caveats,
            "run_command",
            serde_json::json!({"command":"git add visible.txt"}),
            None,
        )
        .await;
        assert!(!staged.starts_with("error:"), "{staged}");
        let index = crate::git_hardening::hardened_git(workspace.path(), &["ls-files", "--cached"])
            .unwrap()
            .output()
            .unwrap();
        assert!(index.status.success());
        assert_eq!(String::from_utf8(index.stdout).unwrap(), "visible.txt\n");
        let index_before = std::fs::read(workspace.path().join(".git/index")).unwrap();
        let commit = dispatch(
            &harness,
            workspace.path(),
            &caveats,
            "run_command",
            serde_json::json!({"command":"git commit -m fixture"}),
            None,
        )
        .await;
        assert!(
            commit.contains("refusing Git commit publication")
                && commit.contains("native commit attribution/signing policy is unavailable"),
            "{commit}"
        );
        assert_eq!(
            std::fs::read(workspace.path().join(".git/index")).unwrap(),
            index_before,
            "refused commit must leave the staged index unchanged"
        );
        let head = crate::git_hardening::hardened_git(
            workspace.path(),
            &["rev-parse", "--verify", "HEAD"],
        )
        .unwrap()
        .output()
        .unwrap();
        assert!(
            !head.status.success(),
            "refused commit must leave the repository without a commit"
        );
    } else {
        assert!(output.contains("frame isolation"), "{output}");
    }
}

async fn dispatch_with_execution(
    harness: &SmartHarness,
    workspace: &Path,
    caveats: &Caveats,
    name: &str,
    args: serde_json::Value,
) -> (String, Option<crate::ExecOutcome>) {
    let batch = harness.fixture_tool_batch(name, args.clone());
    let invocation = batch.start(0, None).unwrap();
    let mut display = super::super::display::ToolDisplay::new(Vec::new(), false, 80, 20, false);
    let execution = std::sync::OnceLock::new();
    let output = execute_tool_with_display_cancellable(
        &mut display,
        name,
        &args,
        workspace.to_str().unwrap(),
        false,
        20,
        caveats,
        &mut NoMcp,
        ToolCollaborators {
            invocation: Some(&invocation),
            execution: Some(&execution),
            ..Default::default()
        },
        false,
        PromptDisposition::Act,
        None,
    )
    .await
    .unwrap()
    .unwrap();
    (output, execution.get().copied())
}

/// #2561 review (a): a smart-harness refusal is a real failure, and must
/// ledger `ok=false` via a RECORDED `ExecOutcome`, not by the text
/// classifier matching `Error:` (capital E, which it never does —
/// `http_smart_completion.rs:489` pins that the smart harness tells host
/// from tool output by its witness, not by text).
#[tokio::test]
#[serial_test::serial]
async fn smart_harness_refusals_ledger_as_failures() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    let workspace = tempfile::tempdir().unwrap();
    let directory = workspace.path().join(".newt/frame");
    let (harness, _) = harness(&directory);
    let marker = directory.join("marker");
    std::fs::write(&marker, "frame contents").unwrap();
    let caveats = crate::confined_exec::workspace_confined_caveats(workspace.path());

    // frame isolation refusal (validate_tool_authority rejects the call)
    let (output, execution) = dispatch_with_execution(
        &harness,
        workspace.path(),
        &caveats,
        "read_file",
        serde_json::json!({"path":marker}),
    )
    .await;
    assert!(output.contains("frame isolation"), "{output}");
    assert!(
        !tool_ok(&output, execution),
        "frame isolation refusal must ledger ok=false: {output}"
    );

    // re_read refusal outside a smart harness session — re-run with no invocation.
    let mut display = super::super::display::ToolDisplay::new(Vec::new(), false, 80, 20, false);
    let execution2 = std::sync::OnceLock::new();
    let output2 = execute_tool_with_display_cancellable(
        &mut display,
        "re_read",
        &serde_json::json!({}),
        workspace.path().to_str().unwrap(),
        false,
        20,
        &caveats,
        &mut NoMcp,
        ToolCollaborators {
            execution: Some(&execution2),
            ..Default::default()
        },
        false,
        PromptDisposition::Act,
        None,
    )
    .await
    .unwrap()
    .unwrap();
    assert!(output2.contains("re_read is unavailable"), "{output2}");
    assert!(
        !tool_ok(&output2, execution2.get().copied()),
        "re_read-outside-smart-harness must ledger ok=false: {output2}"
    );
}

struct UnconfinedDelegate(std::path::PathBuf);

/// Grounds the find-adapter refusal in its real descriptor-discard boundary:
/// replacing the validated path makes the legacy walker disclose private names.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
#[serial_test::serial]
async fn smart_find_refuses_the_unbound_recursive_walker() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    let workspace = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let (harness, _) = harness(directory.path());
    std::fs::write(directory.path().join("private-frame-record"), "private").unwrap();
    let caveats = crate::confined_exec::workspace_confined_caveats(workspace.path());
    let root = workspace.path().join("search");
    std::fs::create_dir(&root).unwrap();
    assert!(find_root_contained(
        &caveats.fs_read,
        workspace.path().to_str().unwrap(),
        &root,
        root.to_str().unwrap(),
    ));
    std::fs::remove_dir(&root).unwrap();
    std::os::unix::fs::symlink(directory.path(), &root).unwrap();
    let args = serde_json::json!({});
    let opts = find_opts_from_args(&args);
    let (hits, _) = find_walk(&root, workspace.path(), &opts, None, |_| {}).unwrap();
    assert!(hits.iter().any(|hit| hit.contains("private-frame-record")));
    let output = dispatch(
        &harness,
        workspace.path(),
        &caveats,
        "find",
        serde_json::json!({"path":"."}),
        None,
    )
    .await;
    assert!(output.contains("Error: frame isolation:"), "{output}");
}

/// Native grep walks and reopens paths exactly as find does, so smart
/// sessions refuse it for the same reason until the walker retains directory
/// capability (#2677 review). Linux/macOS only, like the find test: elsewhere
/// the durable smart harness refuses every filesystem tool up front.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
#[serial_test::serial]
async fn smart_grep_refuses_the_unbound_recursive_walker() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    let workspace = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let (harness, _) = harness(directory.path());
    let caveats = crate::confined_exec::workspace_confined_caveats(workspace.path());
    let output = dispatch(
        &harness,
        workspace.path(),
        &caveats,
        "grep",
        serde_json::json!({"pattern":"x","path":"."}),
        None,
    )
    .await;
    assert!(
        output.contains("Error: frame isolation: native grep"),
        "{output}"
    );
}

impl super::super::git_tool::GitTool for UnconfinedDelegate {
    fn dispatch(
        &self,
        _: &str,
        _: &serde_json::Value,
        _: &crate::git_caveats::GitCaveats,
        _: &Caveats,
    ) -> Result<String, String> {
        Ok(std::fs::read_to_string(&self.0).unwrap())
    }
}

#[async_trait::async_trait]
impl super::super::crew_tool::CrewRunner for UnconfinedDelegate {
    async fn dispatch(
        &self,
        _: &str,
        _: &serde_json::Value,
        _: &Caveats,
    ) -> Result<String, String> {
        Ok(std::fs::read_to_string(&self.0).unwrap())
    }
}

/// Grounds delegate refusals against a real private file. The injected
/// delegate models native Git's unrestricted add and crew's std::fs access.
#[tokio::test]
#[serial_test::serial]
async fn smart_delegates_cannot_read_private_payloads() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    let workspace = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let (harness, _) = harness(directory.path());
    let marker = directory.path().join("marker");
    std::fs::write(&marker, "private generated material").unwrap();
    let delegate = UnconfinedDelegate(marker.clone());
    let caveats = crate::confined_exec::workspace_confined_caveats(workspace.path());
    for (name, args) in [
        ("git", serde_json::json!({"op":"add","paths":[marker]})),
        ("crew", serde_json::json!({"task":"read private frame"})),
    ] {
        let batch = harness.fixture_tool_batch(name, args.clone());
        let invocation = batch.start(0, None).unwrap();
        let mut display = super::super::display::ToolDisplay::new(Vec::new(), false, 80, 20, false);
        let output = execute_tool_with_display_cancellable(
            &mut display,
            name,
            &args,
            workspace.path().to_str().unwrap(),
            false,
            20,
            &caveats,
            &mut NoMcp,
            ToolCollaborators {
                invocation: Some(&invocation),
                git_tool: Some(&delegate),
                crew_runner: Some(&delegate),
                ..Default::default()
            },
            false,
            PromptDisposition::Act,
            None,
        )
        .await
        .unwrap()
        .unwrap();
        assert!(
            !output.contains("private generated material"),
            "{name}: {output}"
        );
        assert!(
            output.contains("scoped fs_read") || output.contains("frame isolation"),
            "{name}: {output}"
        );
    }
}

/// Grounds launch-authority refusal at the tool entry point, including
/// embedders that create a Session directly instead of using frontend config.
#[tokio::test]
#[serial_test::serial]
async fn smart_tools_refuse_unconfined_launch_authority() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let workspace = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let (harness, _) = harness(directory.path());
    std::fs::write(workspace.path().join("inside.txt"), "allowed content").unwrap();
    let caveats = crate::confined_exec::workspace_confined_caveats(workspace.path());
    for (yolo, full) in [("1", "0"), ("0", "1")] {
        let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", yolo);
        let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", full);
        let output = dispatch(
            &harness,
            workspace.path(),
            &caveats,
            "read_file",
            serde_json::json!({"path":"inside.txt"}),
            None,
        )
        .await;
        assert!(output.contains("frame isolation"), "{output}");
        assert!(!output.contains("allowed content"), "{output}");
    }
}

/// #2636 finding 2 (FIX-FIRST): FramePermissionGate must forward consume_pending_once to
/// its inner gate. The default no-op silently drops the call, leaving the inner gate's
/// once-grant alive for a later unrelated operation.
/// Before the fix: ConsumeSpy.consumed remains false → assertion red.
#[test]
fn frame_permission_gate_forwards_consume_pending_once() {
    use crate::agentic::smart_harness::FramePermissionGate;

    use std::cell::Cell;
    use std::rc::Rc;

    let consumed = Rc::new(Cell::new(false));

    struct ConsumeSpy(Rc<Cell<bool>>);
    impl PermissionGate for ConsumeSpy {
        fn ask(&mut self, _: &[PermissionRequest]) -> PermissionDecision {
            PermissionDecision::Deny
        }
        fn ask_question(&mut self, _: &str) -> HumanQuestionOutcome {
            HumanQuestionOutcome::Unavailable
        }
        fn consume_pending_once(&mut self, _kind: DenialKind, _target: &str) {
            self.0.set(true);
        }
    }

    let directory = tempfile::tempdir().unwrap();
    let workspace = tempfile::tempdir().unwrap();
    let (h, _) = harness(directory.path());
    let mut spy = ConsumeSpy(consumed.clone());
    {
        let mut gate = FramePermissionGate {
            harness: &h,
            workspace: workspace.path(),
            inner: &mut spy,
            refusal: None,
        };
        gate.consume_pending_once(DenialKind::FsWrite, "/ws/out.txt");
    }
    assert!(
        consumed.get(),
        "#2636 finding 2: FramePermissionGate must forward consume_pending_once to inner gate"
    );
}

/// A native positive control prevents a macOS run from passing only because
/// every dispatch was refused before any file operation.
#[cfg(target_os = "macos")]
#[tokio::test]
#[serial_test::serial]
async fn macos_smart_runtime_admits_confined_seatbelt() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    assert!(
        agent_bridle::seatbelt_is_supported(),
        "native suite requires Seatbelt"
    );
    crate::agentic::smart_harness::validate_isolation_runtime().unwrap();
}

/// The shrink guard is a read too: a symlink into private storage must neither
/// leak its line count nor let edit_file return a private content preview.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
#[serial_test::serial]
async fn private_frame_cannot_leak_through_write_shrink_or_edit_preview() {
    let _env = super::disable_ocap_tests::env_lock().await;
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    let workspace = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let (harness, _) = harness(directory.path());
    let marker = directory.path().join("marker");
    let private = "private generated material\n".repeat(100);
    std::fs::write(&marker, &private).unwrap();
    std::os::unix::fs::symlink(&marker, workspace.path().join("link")).unwrap();
    let caveats = crate::confined_exec::workspace_confined_caveats(workspace.path());
    for (name, args) in [
        (
            "write_file",
            serde_json::json!({"path":"link","content":"changed"}),
        ),
        (
            "edit_file",
            serde_json::json!({"path":"link","old_string":"absent","new_string":"changed"}),
        ),
    ] {
        let output = dispatch(&harness, workspace.path(), &caveats, name, args, None).await;
        assert!(
            output.contains("denied") || output.contains("frame isolation"),
            "{output}"
        );
        assert!(!output.contains("100"), "shrink oracle: {output}");
        assert!(
            !output.contains("private generated material"),
            "preview leak: {output}"
        );
        assert_eq!(std::fs::read_to_string(&marker).unwrap(), private);
    }
}

/// Ground worktree support in real Git administrative files and confined file
/// edits. An external worktree is usable only with its own explicit grant;
/// its parent directory and private frame remain outside that grant.
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
#[serial_test::serial]
async fn smart_shell_worktrees_support_scoped_creation_editing_and_staging() {
    use std::os::unix::fs::PermissionsExt as _;
    let _env = super::disable_ocap_tests::env_lock().await;
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    let _engine = super::disable_ocap_tests::EnvVar::set("NEWT_SHELL_ENGINE", "host");
    let _env_grant = super::disable_ocap_tests::EnvVar::set(
        "NEWT_SHELL_ENV_PASSTHROUGH",
        "GIT_CONFIG_GLOBAL:GIT_CONFIG_SYSTEM",
    );
    let _global = super::disable_ocap_tests::EnvVar::set("GIT_CONFIG_GLOBAL", "/dev/null");
    let _system = super::disable_ocap_tests::EnvVar::set("GIT_CONFIG_SYSTEM", "/dev/null");
    let workspace = tempfile::tempdir().unwrap();
    let private = tempfile::tempdir().unwrap();
    let external_parent = tempfile::tempdir().unwrap();
    let external = external_parent.path().join("task-worktree");
    std::fs::create_dir(&external).unwrap();
    std::fs::set_permissions(&external, std::fs::Permissions::from_mode(0o700)).unwrap();
    let sibling = external_parent.path().join("ungranted");
    std::fs::write(&sibling, "outside authority").unwrap();
    let (harness, _) = harness(private.path());
    let git_fixture = |args: &[&str]| {
        let output = crate::git_hardening::hardened_git(workspace.path(), args)
            .unwrap()
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "{}",
            String::from_utf8_lossy(&output.stderr)
        );
    };
    git_fixture(&["init", "-q"]);
    std::fs::write(workspace.path().join("task.txt"), "baseline\n").unwrap();
    std::fs::write(workspace.path().join(".gitignore"), ".worktrees/\n").unwrap();
    git_fixture(&["add", "task.txt", ".gitignore"]);
    git_fixture(&[
        "-c",
        "user.name=Fixture",
        "-c",
        "user.email=fixture@example.invalid",
        "commit",
        "-qm",
        "fixture baseline",
    ]);
    let mut caveats = crate::confined_exec::workspace_confined_caveats(workspace.path());
    caveats.net = crate::caveats::Scope::All;
    let session = crate::worktree_adoption::WorktreeSession::default();
    for (index, destination) in [workspace.path().join(".worktrees/task"), external.clone()]
        .into_iter()
        .enumerate()
    {
        if index == 1 {
            // The external directory alone is delegated, never its parent.
            caveats.fs_read = crate::caveats::Scope::only([
                workspace.path().to_string_lossy().into_owned(),
                external.to_string_lossy().into_owned(),
            ]);
            caveats.fs_write = caveats.fs_read.clone();
        }
        let create = dispatch_with_worktree_session(&harness, workspace.path(), &caveats, "run_command",
            serde_json::json!({"command":format!("git worktree add -b fixture-{index} '{}'", destination.display())}), None, Some(&session)).await;
        if index == 0 {
            // #2813/#2759: nested creation must use the same admission as a
            // live session; the old fixture silently bypassed that boundary.
            assert!(create.contains("choose a sibling destination"), "{create}");
            assert!(!destination.join("task.txt").exists());
            continue;
        }
        assert!(
            session.snapshot().is_some(),
            "creation was not adopted: {create}"
        );
        assert!(destination.join("task.txt").exists(), "{create}");
        let edited = dispatch_with_worktree_session(&harness, &destination, &caveats, "edit_file",
            serde_json::json!({"path":destination.join("task.txt"), "old_string":"baseline", "new_string":"worktree change"}), None, Some(&session)).await;
        assert_eq!(
            std::fs::read_to_string(destination.join("task.txt")).unwrap(),
            "worktree change\n",
            "{edited}"
        );
        let staged = dispatch_with_worktree_session(&harness, &destination, &caveats, "run_command",
            serde_json::json!({"command":"git add task.txt && git status --short", "cwd":destination}), None, Some(&session)).await;
        assert!(staged.contains("M  task.txt"), "{staged}");
        assert_eq!(
            std::fs::read_to_string(workspace.path().join("task.txt")).unwrap(),
            "baseline\n"
        );
    }
    let denied = dispatch(
        &harness,
        workspace.path(),
        &caveats,
        "read_file",
        serde_json::json!({"path":sibling}),
        None,
    )
    .await;
    assert!(denied.contains("denied"), "{denied}");
    assert!(!denied.contains("outside authority"));
}

/// #2731: forward operation approval only where durable-frame isolation is
/// supported. Windows must refuse before prompting, even for a narrow fence;
/// widening the fence must never expose private frame storage on any platform.
#[test]
fn cold_cache_fetch_frame_gate_preserves_protection() {
    // #2773: ambient dispatch fixtures mutate these process-wide switches.
    // Own the shared lock and establish the confined launch this test proves.
    let _env = crate::process_env::lock();
    let _yolo = super::disable_ocap_tests::EnvVar::set("NEWT_DISABLE_OCAP", "0");
    let _full = super::disable_ocap_tests::EnvVar::set("NEWT_FULL_ACCESS", "0");
    use crate::agentic::smart_harness::FramePermissionGate;
    struct FetchGate(usize);
    impl PermissionGate for FetchGate {
        fn ask(&mut self, _: &[PermissionRequest]) -> PermissionDecision {
            panic!("host path")
        }
        fn ask_question(&mut self, _: &str) -> HumanQuestionOutcome {
            HumanQuestionOutcome::Unavailable
        }
        fn ask_dependency_fetch(
            &mut self,
            prepared: &Caveats,
            _: &PermissionRequest,
        ) -> PermissionDecision {
            self.0 += 1;
            PermissionDecision::Allow(prepared.clone())
        }
    }
    let workspace = tempfile::tempdir().unwrap();
    let directory = tempfile::tempdir().unwrap();
    let (h, _) = harness(directory.path());
    let mut inner = FetchGate(0);
    let request = PermissionRequest {
        tool: "lifecycle".into(),
        kind: DenialKind::Net,
        target: "one locked fetch".into(),
        reason: "unrestricted fetch egress".into(),
        harness_bound: true,
    };
    let mut prepared = crate::confined_exec::workspace_confined_caveats(workspace.path());
    prepared.net = crate::Scope::All;
    {
        let mut gate = FramePermissionGate {
            harness: &h,
            workspace: workspace.path(),
            inner: &mut inner,
            refusal: None,
        };
        let decision = gate.ask_dependency_fetch(&prepared, &request);
        #[cfg(any(target_os = "linux", target_os = "macos"))]
        assert!(
            matches!(decision, PermissionDecision::Allow(_)),
            "unexpected frame refusal: {:?}",
            gate.refusal
        );
        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
        {
            assert!(matches!(decision, PermissionDecision::Deny));
            assert!(gate.refusal.as_deref().is_some_and(|reason| reason.contains(
                "durable smart harness requires object-bound filesystem tools and a supported kernel sandbox"
            )));
        }
        prepared.fs_read = crate::Scope::All;
        assert!(matches!(
            gate.ask_dependency_fetch(&prepared, &request),
            PermissionDecision::Deny
        ));
        assert!(gate.refusal.is_some());
    }
    assert_eq!(
        inner.0,
        usize::from(cfg!(any(target_os = "linux", target_os = "macos")))
    );
}