agent-bridle-tool-shell 0.7.2

Capability-confined shell tool for agent-bridle (argv + safe-subset engine).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
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
//! Real-spawn integration tests for the engine's `std::process` path.
//!
//! These exercise the *real* `OsSpawner` with actual processes (and, for
//! redirections, real files), and are kept out of the unit tests (which mock the
//! spawner) per the workspace norm: no real subprocesses/fs in unit tests. They
//! use only universally-present tools (`echo`, `cat`, `sort`, `true`, `false`,
//! and `touch` for the Linux-only Landlock test).
#![cfg(feature = "shell")]

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use agent_bridle_core::{Caveats, Gate, Scope, Tool, ToolContext};
use agent_bridle_tool_shell::ShellTool;

/// Mint a context the only legitimate way — through the gate.
fn ctx(granted: Caveats) -> ToolContext {
    Gate::new(0)
        .authorize(&ShellTool::new(), &granted)
        .expect("authorize")
}

fn exec_only(names: &[&str]) -> Caveats {
    Caveats {
        exec: Scope::only(names.iter().map(|s| (*s).to_string())),
        ..Caveats::top()
    }
}

/// A unique temp path (pid + atomic counter, never a clock) so parallel tests do
/// not collide. The file is created/used by the test and removed at the end.
fn unique_temp(tag: &str) -> PathBuf {
    static N: AtomicU64 = AtomicU64::new(0);
    std::env::temp_dir().join(format!(
        "ab-redir-{}-{}-{}",
        tag,
        std::process::id(),
        N.fetch_add(1, Ordering::Relaxed)
    ))
}

fn shell_path(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

#[tokio::test]
async fn real_echo_runs_and_captures_stdout() {
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"program": "echo", "args": ["hello"]}),
            &ctx(exec_only(&["echo"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["exit_code"], 0);
    assert_eq!(out["stdout"], "hello\n");
    assert!(out.get("denied").is_none());
}

/// #143 regression: the captured-output cap is config-driven (not a hard-coded
/// const). A `ShellTool` built with a tiny `max_output_bytes` truncates a chatty
/// command's stdout at the configured bound and flags it truncated.
#[tokio::test]
async fn real_output_cap_is_config_driven() {
    let limits = agent_bridle_core::LimitsPolicy {
        max_output_bytes: 8,
        ..agent_bridle_core::LimitsPolicy::default()
    };
    let out = ShellTool::with_config(limits)
        .invoke(
            serde_json::json!({"program": "echo", "args": ["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]}),
            &ctx(exec_only(&["echo"])),
        )
        .await
        .expect("invoke");
    let stdout = out["stdout"].as_str().expect("stdout string");
    assert!(
        stdout.len() <= 8,
        "output must be capped at the configured 8 bytes, got {}",
        stdout.len()
    );
    assert_eq!(
        out["stdout_truncated"], true,
        "a source past the configured cap is flagged truncated"
    );
}

#[tokio::test]
async fn real_pipeline_passes_data_between_stages() {
    // echo's stdout becomes cat's stdin; cat echoes it back.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "echo hello | cat"}),
            &ctx(exec_only(&["echo", "cat"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["exit_code"], 0);
    assert_eq!(out["stdout"], "hello\n");
}

#[tokio::test]
async fn real_pipeline_exit_code_is_the_last_stage() {
    // `true | false` → last stage (false) exits 1.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "true | false"}),
            &ctx(exec_only(&["true", "false"])),
        )
        .await
        .expect("invoke");
    assert_eq!(
        out["exit_code"], 1,
        "pipeline exit is the last stage's: {out}"
    );

    // `false | true` → last stage (true) exits 0, even though stage 1 failed.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "false | true"}),
            &ctx(exec_only(&["true", "false"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["exit_code"], 0, "no pipefail: {out}");
}

#[tokio::test]
async fn real_stderr_and_nonzero_exit_are_captured() {
    // `cat` of a nonexistent path writes to stderr and exits non-zero.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"program": "cat", "args": ["/nonexistent/agent-bridle/path"]}),
            &ctx(exec_only(&["cat"])),
        )
        .await
        .expect("invoke");
    assert_ne!(
        out["exit_code"], 0,
        "cat of a missing file must fail: {out}"
    );
    assert!(
        !out["stderr"].as_str().unwrap_or("").is_empty(),
        "stderr must be captured: {out}"
    );
}

#[tokio::test]
async fn real_out_of_scope_program_is_denied_and_never_spawns() {
    // `rm` is not granted: the leash denies it before any real process starts.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"program": "rm", "args": ["-rf", "/tmp/agent-bridle-should-not-exist"]}),
            &ctx(exec_only(&["echo"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["denied"], true);
    assert_eq!(out["denials"][0]["target"], "rm");
    assert!(out.get("exit_code").is_none(), "nothing ran: {out}");
}

#[tokio::test]
async fn real_stdout_redirect_truncates_then_appends_a_file() {
    let path = unique_temp("out");
    let p = shell_path(&path);

    // `> file` writes (truncates).
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!("echo first > {p}")}),
            &ctx(exec_only(&["echo"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["exit_code"], 0, "truncate redirect should run: {out}");
    assert_eq!(std::fs::read_to_string(&path).unwrap(), "first\n");

    // `>> file` appends.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!("echo second >> {p}")}),
            &ctx(exec_only(&["echo"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["exit_code"], 0, "append redirect should run: {out}");
    assert_eq!(std::fs::read_to_string(&path).unwrap(), "first\nsecond\n");

    let _ = std::fs::remove_file(&path);
}

#[tokio::test]
async fn real_stdin_redirect_feeds_a_file() {
    let path = unique_temp("in");
    std::fs::write(&path, "b\na\nc\n").unwrap();
    let p = shell_path(&path);

    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!("cat < {p}")}),
            &ctx(exec_only(&["cat"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["exit_code"], 0);
    assert_eq!(out["stdout"], "b\na\nc\n");

    let _ = std::fs::remove_file(&path);
}

#[tokio::test]
async fn real_pipeline_with_stdout_redirect_on_last_stage() {
    // `echo … | cat > file` — the pipe feeds cat, whose stdout goes to the file;
    // captured stdout is empty because the last stage redirected to a file.
    let path = unique_temp("pipe");
    let p = shell_path(&path);

    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!("echo piped | cat > {p}")}),
            &ctx(exec_only(&["echo", "cat"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["exit_code"], 0);
    assert_eq!(
        out["stdout"], "",
        "last-stage redirect means empty captured stdout: {out}"
    );
    assert_eq!(std::fs::read_to_string(&path).unwrap(), "piped\n");

    let _ = std::fs::remove_file(&path);
}

#[tokio::test]
async fn real_and_chain_runs_then_short_circuits() {
    // `true && echo ran` → echo runs.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "true && echo ran"}),
            &ctx(exec_only(&["true", "echo"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["stdout"], "ran\n");
    assert_eq!(out["exit_code"], 0);

    // `false && echo nope` → echo is skipped; exit is `false`'s.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "false && echo nope"}),
            &ctx(exec_only(&["false", "echo"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["stdout"], "", "echo must be skipped: {out}");
    assert_eq!(out["exit_code"], 1);
}

#[tokio::test]
async fn real_or_fallback_and_semicolon_sequence() {
    // `false || echo fallback` → fallback runs.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "false || echo fallback"}),
            &ctx(exec_only(&["false", "echo"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["stdout"], "fallback\n");

    // `echo a ; echo b` → both run, output concatenated in order.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "echo a ; echo b"}),
            &ctx(exec_only(&["echo"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["stdout"], "a\nb\n");
}

#[tokio::test]
async fn real_glob_expands_against_the_filesystem() {
    // A unique temp dir with a.rs="A", b.rs="B", c.txt="C".
    let dir = unique_temp("glob");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.rs"), "A").unwrap();
    std::fs::write(dir.join("b.rs"), "B").unwrap();
    std::fs::write(dir.join("c.txt"), "C").unwrap();
    let d = dir.to_string_lossy().into_owned();

    // `cat *.rs` (cwd = the temp dir) → expands to `cat a.rs b.rs` (sorted) → "AB".
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "cat *.rs", "cwd": d}),
            &ctx(exec_only(&["cat"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["exit_code"], 0);
    assert_eq!(out["stdout"], "AB", "glob expanded + sorted: {out}");

    // No match → the literal pattern; `cat zzz*` fails (no such file).
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "cat zzz*", "cwd": d}),
            &ctx(exec_only(&["cat"])),
        )
        .await
        .expect("invoke");
    assert_ne!(
        out["exit_code"], 0,
        "unmatched glob → literal, cat fails: {out}"
    );

    let _ = std::fs::remove_dir_all(&dir);
}

#[tokio::test]
async fn real_allowlisted_var_expands_from_the_environment() {
    // `echo $HOME` expands HOME from this process's env (the test reads the same
    // env, so the assertion is deterministic regardless of the host value).
    let expected = format!("{}\n", std::env::var("HOME").unwrap_or_default());
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "echo $HOME"}),
            &ctx(exec_only(&["echo"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["exit_code"], 0);
    assert_eq!(
        out["stdout"], expected,
        "$HOME must expand to the env value: {out}"
    );
}

#[tokio::test]
async fn real_env_map_reaches_the_child() {
    // The env seam (newt #783): a `"env"` map on the dispatch is set on the real
    // child. `env` (coreutils) with no args prints its environment; the var we
    // injected must appear — proof it crossed into the spawned process, not just
    // the recording mock. A unique value so a stray host `FOO` can't false-pass.
    let marker = format!("ab-env-seam-{}", std::process::id());
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({
                "program": "env",
                "env": { "AB_ENV_SEAM_PROOF": marker },
            }),
            &ctx(exec_only(&["env"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["exit_code"], 0, "env must run: {out}");
    let stdout = out["stdout"].as_str().unwrap_or_default();
    assert!(
        stdout.contains(&format!("AB_ENV_SEAM_PROOF={marker}")),
        "the injected env var must reach the child: {out}"
    );
}

#[tokio::test]
async fn real_mixed_and_quoted_variable_words_expand() {
    let home = std::env::var("HOME").unwrap_or_default();

    // Mixed word: `$HOME/sub` → "<home>/sub".
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "echo $HOME/sub"}),
            &ctx(exec_only(&["echo"])),
        )
        .await
        .expect("invoke");
    assert_eq!(out["stdout"], format!("{home}/sub\n"), "mixed word: {out}");

    // Inside double quotes the variable still expands.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "echo \"prefix-$HOME\""}),
            &ctx(exec_only(&["echo"])),
        )
        .await
        .expect("invoke");
    assert_eq!(
        out["stdout"],
        format!("prefix-{home}\n"),
        "quoted var: {out}"
    );
}

#[tokio::test]
async fn real_stderr_redirect_to_file() {
    // `cat <missing> 2> err` — cat's error goes to the file; captured stderr is
    // empty (it was redirected), stdout empty, exit non-zero.
    let path = unique_temp("err");
    let p = shell_path(&path);
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!("cat /nonexistent/agent-bridle 2> {p}")}),
            &ctx(exec_only(&["cat"])),
        )
        .await
        .expect("invoke");
    assert_ne!(out["exit_code"], 0);
    assert_eq!(out["stderr"], "", "stderr went to the file: {out}");
    assert!(
        !std::fs::read_to_string(&path).unwrap().is_empty(),
        "the error must be in the file"
    );
    let _ = std::fs::remove_file(&path);
}

#[tokio::test]
async fn real_2to1_merges_stderr_into_captured_stdout() {
    // `cat <missing> 2>&1` — the error is merged into stdout (captured), so
    // captured stdout is non-empty and captured stderr is empty.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "cat /nonexistent/agent-bridle 2>&1"}),
            &ctx(exec_only(&["cat"])),
        )
        .await
        .expect("invoke");
    assert_ne!(out["exit_code"], 0);
    assert!(
        !out["stdout"].as_str().unwrap_or("").is_empty(),
        "the error must appear on merged stdout: {out}"
    );
    assert_eq!(out["stderr"], "", "stderr was merged into stdout: {out}");
}

#[tokio::test]
async fn real_2to1_before_a_pipe_feeds_stderr_downstream() {
    // `cat <missing> 2>&1 | cat` — stage 0's stderr is merged into its stdout
    // pipe, so stage 1 (cat) receives and re-emits the error to captured stdout.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "cat /nonexistent/agent-bridle 2>&1 | cat"}),
            &ctx(exec_only(&["cat"])),
        )
        .await
        .expect("invoke");
    assert!(
        !out["stdout"].as_str().unwrap_or("").is_empty(),
        "stderr merged into the pipe must reach the downstream stage: {out}"
    );
}

// ── L3 boundary: Landlock actually confines the spawned child (#35) ──────────
//
// This is the regression proof for ADR 0005's claim that L3 is the *boundary*: a
// permitted program's OWN write (not a bridle-performed redirect) is blocked by
// the kernel when it targets a path outside `fs_write` — something L2 cannot see
// once the child has spawned. Linux + `linux-landlock` only; self-skips if the
// kernel lacks Landlock.
#[cfg(all(target_os = "linux", feature = "linux-landlock"))]
#[tokio::test]
async fn real_landlock_confines_a_spawned_childs_own_write() {
    use agent_bridle_core::landlock_is_supported;

    if !landlock_is_supported() {
        eprintln!("skipping: kernel lacks Landlock");
        return;
    }

    let allowed = unique_temp("ll-allowed");
    std::fs::create_dir_all(&allowed).unwrap();
    let forbidden = unique_temp("ll-forbidden");
    std::fs::create_dir_all(&forbidden).unwrap();

    // exec `touch`, but only allow writes under `allowed` (fs_read stays open so
    // the dynamic loader can map libc — the fs_write axis is what we confine).
    let caveats = Caveats {
        exec: Scope::only(["touch".to_string()]),
        fs_write: Scope::only([allowed.to_string_lossy().into_owned()]),
        ..Caveats::top()
    };

    // `touch` itself opens the file for writing — bridle does NOT open it (it is
    // an argument, not a redirect), so only L3 can stop it.
    let inside = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!("touch {}/ok", allowed.to_string_lossy())}),
            &ctx(caveats.clone()),
        )
        .await
        .expect("invoke");
    assert_eq!(
        inside["exit_code"], 0,
        "write within fs_write must succeed: {inside}"
    );
    assert_eq!(
        inside["sandbox_kind"], "landlock",
        "must report kernel enforcement: {inside}"
    );
    assert!(allowed.join("ok").exists(), "the in-scope file must exist");

    let outside = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!("touch {}/escape", forbidden.to_string_lossy())}),
            &ctx(caveats),
        )
        .await
        .expect("invoke");
    assert_ne!(
        outside["exit_code"], 0,
        "the kernel must deny a write outside fs_write scope: {outside}"
    );
    assert!(
        !forbidden.join("escape").exists(),
        "the out-of-scope file must NOT have been created"
    );

    let _ = std::fs::remove_dir_all(&allowed);
    let _ = std::fs::remove_dir_all(&forbidden);
}

// agent-bridle#35/#57 — the "swamp tools die" spike. The proof above confines a
// child bridle spawned directly (`touch`). This one closes the harder hole ADR
// 0001 names: a GRANDCHILD a *permitted* tool forks on its own (`find -exec …`),
// which never re-enters bridle's spawn funnel — exactly what L2 is blind to once
// `find` runs. Both `find` and `touch` are exec-granted (so the grandchild RUNS —
// the #57 Execute axis would otherwise kernel-deny `touch`'s execve); the point
// here is that the kernel `fs_write` ruleset, inherited across find's fork/exec,
// still stops the grandchild's WRITE outside scope. Linux + `linux-landlock`;
// self-skips without Landlock.
#[cfg(all(target_os = "linux", feature = "linux-landlock"))]
#[tokio::test]
async fn real_landlock_confines_a_find_exec_grandchild_write() {
    use agent_bridle_core::landlock_is_supported;
    if !landlock_is_supported() {
        eprintln!("skipping: kernel lacks Landlock");
        return;
    }

    let allowed = unique_temp("ll-fe-allowed");
    std::fs::create_dir_all(&allowed).unwrap();
    // A file for `find` to walk and fire `-exec` on (its content is irrelevant).
    std::fs::write(allowed.join("seed"), b"x").unwrap();
    let forbidden = unique_temp("ll-fe-forbidden");
    std::fs::create_dir_all(&forbidden).unwrap();

    // `find` and `touch` are exec-permitted (so the grandchild runs); writes are
    // confined to `allowed`. The `;` terminating `-exec` is single-quoted so the
    // safe-subset parser treats it as a literal argument to find, not a separator.
    let caveats = Caveats {
        exec: Scope::only(["find".to_string(), "touch".to_string()]),
        fs_write: Scope::only([allowed.to_string_lossy().into_owned()]),
        ..Caveats::top()
    };

    // In scope: the grandchild writes under `allowed` → allowed.
    let inside = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!(
                "find {a} -type f -exec touch {a}/ok ';'",
                a = allowed.to_string_lossy()
            )}),
            &ctx(caveats.clone()),
        )
        .await
        .expect("invoke");
    assert_eq!(inside["sandbox_kind"], "landlock", "{inside}");
    assert!(
        allowed.join("ok").exists(),
        "an in-scope grandchild write must succeed: {inside}"
    );

    // Out of scope: the grandchild's write to `forbidden` is denied by the
    // inherited ruleset — even though `find` was permitted and bridle never saw
    // the `touch` spawn.
    let _ = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!(
                "find {a} -type f -exec touch {f}/escape ';'",
                a = allowed.to_string_lossy(),
                f = forbidden.to_string_lossy()
            )}),
            &ctx(caveats),
        )
        .await
        .expect("invoke");
    assert!(
        !forbidden.join("escape").exists(),
        "the out-of-scope grandchild write must be denied by the kernel"
    );

    let _ = std::fs::remove_dir_all(&allowed);
    let _ = std::fs::remove_dir_all(&forbidden);
}

// agent-bridle#35 — the read-injection spike (`grep -f FILE`, the `grep -f
// /etc/shadow` shape). bridle admits the command because `grep` is permitted and
// it cannot know `-f` means "read this file as control input" (the gap #58's
// command packs would close at L1). Only the kernel `fs_read` ruleset stops grep
// from reading the out-of-scope file. Linux + `linux-landlock`; self-skips.
#[cfg(all(target_os = "linux", feature = "linux-landlock"))]
#[tokio::test]
async fn real_landlock_confines_a_grep_dash_f_read_injection() {
    use agent_bridle_core::landlock_is_supported;
    if !landlock_is_supported() {
        eprintln!("skipping: kernel lacks Landlock");
        return;
    }

    let allowed = unique_temp("ll-ri-allowed");
    std::fs::create_dir_all(&allowed).unwrap();
    std::fs::write(allowed.join("data"), b"hello\n").unwrap();
    let forbidden = unique_temp("ll-ri-forbidden");
    std::fs::create_dir_all(&forbidden).unwrap();
    // The "secret" grep must not be able to read as its -f pattern file.
    std::fs::write(forbidden.join("secret"), b"hello\n").unwrap();

    // `grep` permitted; reads confined to `allowed` (fs_write stays open).
    let caveats = Caveats {
        exec: Scope::only(["grep".to_string()]),
        fs_read: Scope::only([allowed.to_string_lossy().into_owned()]),
        ..Caveats::top()
    };

    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!(
                "grep -f {f}/secret {a}/data",
                f = forbidden.to_string_lossy(),
                a = allowed.to_string_lossy()
            )}),
            &ctx(caveats),
        )
        .await
        .expect("invoke");
    // grep cannot open the out-of-scope pattern file → it errors (non-zero), and
    // no out-of-scope content reaches stdout.
    assert_ne!(
        out["exit_code"], 0,
        "the kernel must deny grep reading the out-of-scope -f file: {out}"
    );
    assert_eq!(
        out["sandbox_kind"], "landlock",
        "must report kernel enforcement: {out}"
    );
    assert_eq!(out["stdout"], "", "no out-of-scope content may leak: {out}");

    let _ = std::fs::remove_dir_all(&allowed);
    let _ = std::fs::remove_dir_all(&forbidden);
}

// The macOS Seatbelt analog of the Landlock proof above: end to end through the
// shell tool, a *permitted* program's OWN write/read of a path outside the
// fs_write/fs_read scope is blocked by the kernel (`sandbox-exec`), and the
// envelope honestly reports `sandbox_kind: seatbelt`. macOS + `macos-seatbelt`
// only; self-skips if `sandbox-exec` is unavailable.
#[cfg(all(target_os = "macos", feature = "macos-seatbelt"))]
#[tokio::test]
async fn real_seatbelt_confines_a_spawned_childs_own_write() {
    use agent_bridle_core::seatbelt_is_supported;

    if !seatbelt_is_supported() {
        eprintln!("skipping: /usr/bin/sandbox-exec unavailable");
        return;
    }

    let allowed = unique_temp("sb-allowed");
    std::fs::create_dir_all(&allowed).unwrap();
    let forbidden = unique_temp("sb-forbidden");
    std::fs::create_dir_all(&forbidden).unwrap();

    // exec `touch`, but only allow writes under `allowed`. `touch` opens the
    // target itself (an argument, not a bridle redirect), so only L3 can stop it.
    let caveats = Caveats {
        exec: Scope::only(["touch".to_string()]),
        fs_write: Scope::only([allowed.to_string_lossy().into_owned()]),
        ..Caveats::top()
    };

    let inside = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!("touch {}/ok", allowed.to_string_lossy())}),
            &ctx(caveats.clone()),
        )
        .await
        .expect("invoke");
    assert_eq!(
        inside["sandbox_kind"], "seatbelt",
        "must report kernel enforcement: {inside}"
    );
    assert_eq!(
        inside["exit_code"], 0,
        "write within fs_write must succeed: {inside}"
    );
    assert!(allowed.join("ok").exists(), "the in-scope file must exist");

    let outside = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!("touch {}/escape", forbidden.to_string_lossy())}),
            &ctx(caveats),
        )
        .await
        .expect("invoke");
    assert_ne!(
        outside["exit_code"], 0,
        "the kernel must deny a write outside fs_write scope: {outside}"
    );
    assert!(
        !forbidden.join("escape").exists(),
        "the out-of-scope file must NOT have been created"
    );

    let _ = std::fs::remove_dir_all(&allowed);
    let _ = std::fs::remove_dir_all(&forbidden);
}

// Every stage of a pipeline is wrapped in its own `sandbox-exec`; the wrapper is
// transparent to the OS pipes, so data still flows stage→stage. Restricting
// `fs_write` engages the Seatbelt wrapper even though neither stage writes.
#[cfg(all(target_os = "macos", feature = "macos-seatbelt"))]
#[tokio::test]
async fn real_seatbelt_wrapped_pipeline_pipes_data_between_stages() {
    use agent_bridle_core::seatbelt_is_supported;

    if !seatbelt_is_supported() {
        eprintln!("skipping: /usr/bin/sandbox-exec unavailable");
        return;
    }
    let scope = unique_temp("sb-pipe");
    std::fs::create_dir_all(&scope).unwrap();
    let caveats = Caveats {
        exec: Scope::only(["echo".to_string(), "cat".to_string()]),
        fs_write: Scope::only([scope.to_string_lossy().into_owned()]),
        ..Caveats::top()
    };
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": "echo wrapped | cat"}),
            &ctx(caveats),
        )
        .await
        .expect("invoke");
    assert_eq!(out["sandbox_kind"], "seatbelt", "{out}");
    assert_eq!(out["exit_code"], 0, "{out}");
    assert_eq!(
        out["stdout"], "wrapped\n",
        "data must flow through both wrapped stages: {out}"
    );
    let _ = std::fs::remove_dir_all(&scope);
}

// Read confinement end to end: a permitted program (`cat`) can read in-scope but
// the kernel denies its read of a file *outside* `fs_read` — the `grep -f
// /etc/shadow`-style exfil, blocked at L3 where L2 cannot see the child's open.
#[cfg(all(target_os = "macos", feature = "macos-seatbelt"))]
#[tokio::test]
async fn real_seatbelt_confines_a_spawned_childs_own_read() {
    use agent_bridle_core::seatbelt_is_supported;

    if !seatbelt_is_supported() {
        eprintln!("skipping: /usr/bin/sandbox-exec unavailable");
        return;
    }

    let allowed = unique_temp("sb-r-allowed");
    std::fs::create_dir_all(&allowed).unwrap();
    let forbidden = unique_temp("sb-r-forbidden");
    std::fs::create_dir_all(&forbidden).unwrap();
    std::fs::write(allowed.join("ok.txt"), b"in-scope\n").unwrap();
    std::fs::write(forbidden.join("secret.txt"), b"top-secret\n").unwrap();

    // Confine reads to `allowed`; `cat`'s own open of an out-of-scope file is what
    // L3 must stop (the path is an argument, not a bridle-checked redirect).
    let caveats = Caveats {
        exec: Scope::only(["cat".to_string()]),
        fs_read: Scope::only([allowed.to_string_lossy().into_owned()]),
        ..Caveats::top()
    };

    let inside = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!("cat {}/ok.txt", allowed.to_string_lossy())}),
            &ctx(caveats.clone()),
        )
        .await
        .expect("invoke");
    assert_eq!(inside["sandbox_kind"], "seatbelt", "{inside}");
    assert_eq!(
        inside["exit_code"], 0,
        "in-scope read must succeed (binary loads + reads): {inside}"
    );
    assert!(
        inside["stdout"]
            .as_str()
            .unwrap_or_default()
            .contains("in-scope"),
        "must read the in-scope file's contents: {inside}"
    );

    let outside = ShellTool::new()
        .invoke(
            serde_json::json!({"cmd": format!("cat {}/secret.txt", forbidden.to_string_lossy())}),
            &ctx(caveats),
        )
        .await
        .expect("invoke");
    assert_ne!(
        outside["exit_code"], 0,
        "the kernel must deny reading a file outside fs_read scope: {outside}"
    );
    assert!(
        !outside["stdout"]
            .as_str()
            .unwrap_or_default()
            .contains("top-secret"),
        "out-of-scope file contents must NOT leak: {outside}"
    );

    let _ = std::fs::remove_dir_all(&allowed);
    let _ = std::fs::remove_dir_all(&forbidden);
}

// The issue #50 "find -exec curl blocked" scenario, end to end: with `net` empty
// (no egress granted), a permitted program's OWN network connection is denied by
// the kernel (`(deny network*)`) — egress L2 cannot see, that Landlock cannot
// gate at all. The envelope honestly reports net=kernel.
#[cfg(all(target_os = "macos", feature = "macos-seatbelt"))]
#[tokio::test]
async fn real_seatbelt_denies_egress_when_net_is_empty() {
    use agent_bridle_core::seatbelt_is_supported;

    if !seatbelt_is_supported() || !std::path::Path::new("/usr/bin/curl").exists() {
        eprintln!("skipping: sandbox-exec or curl unavailable");
        return;
    }

    // Allow exec of curl, deny ALL network (net: none). fs stays open.
    let caveats = Caveats {
        exec: Scope::only(["curl".to_string()]),
        net: Scope::none(),
        ..Caveats::top()
    };
    // Literal IP (no DNS); --max-time bounds it. Under net:none the socket is
    // kernel-denied immediately, so curl exits non-zero without reaching the net.
    let out = ShellTool::new()
        .invoke(
            serde_json::json!({ "cmd": "curl -sS --max-time 5 http://1.1.1.1/" }),
            &ctx(caveats),
        )
        .await
        .expect("invoke");

    assert_eq!(out["sandbox_kind"], "seatbelt", "{out}");
    assert_eq!(
        out["enforcement"]["net"], "kernel",
        "net:none must report kernel-enforced egress denial: {out}"
    );
    // curl exits 7 ("couldn't connect") — the socket was kernel-denied. Asserting
    // exactly 7 (not merely non-zero) keeps this non-vacuous: a timeout (28) or a
    // child that never launched under a broken profile (65) would not be 7.
    assert_eq!(
        out["exit_code"], 7,
        "egress under net:none must be denied at the socket (curl exit 7): {out}"
    );
}