blyte-agent 0.91.1

The blyte agent loop: tools, context, persistent shell sessions, search and the command sandbox.
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
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
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
//! Tool behaviour, concentrating on the ways a tool can quietly do the wrong thing.

use blyte_agent::fs::LocalFs;
use blyte_agent::shell::LocalShell;
use blyte_agent::tools::{distil, execute, specs, OUTPUT_LINE_BUDGET};
use serde_json::json;

fn ws() -> tempfile::TempDir {
    tempfile::tempdir().unwrap()
}

#[test]
fn no_tool_offers_a_background_mode() {
    // 47.6% of all input tokens in EXP-081 went to turns that only waited for a background
    // task (FINDINGS 13.29). The fix is that there is nothing to background and nothing to
    // poll -- asserted here so it cannot be reintroduced for convenience.
    // Checked against tool NAMES and PARAMETER names, not raw text: the bash description
    // legitimately contains the word "poll" while telling the model there is nothing to poll,
    // and a substring match on prose flagged it.
    let specs = specs();
    for t in &specs {
        assert!(
            !t.name.starts_with("job_"),
            "job control tool present: {}",
            t.name
        );
        let props = t.parameters.get("properties").and_then(|p| p.as_object());
        for key in props.into_iter().flatten().map(|(k, _)| k.as_str()) {
            assert!(
                !matches!(key, "run_in_background" | "background" | "async" | "detach"),
                "tool `{}` offers a background parameter `{key}`",
                t.name
            );
        }
    }
    assert!(
        specs.iter().any(|t| t.name == "bash"),
        "bash must exist to be constrained"
    );
}

#[test]
fn bash_blocks_until_the_command_finishes() {
    let d = ws();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "bash",
        &json!({"command": "sleep 1; echo done"}),
    );
    assert!(
        r.content.contains("done"),
        "must return the output, not a job handle: {r:?}"
    );
    assert!(!r.is_error);
}

#[test]
fn bash_always_states_the_exit_code() {
    // A non-zero exit with quiet output otherwise reads as success.
    let d = ws();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "bash",
        &json!({"command": "exit 3"}),
    );
    assert!(r.content.starts_with("exit 3"), "got {:?}", r.content);
    assert!(r.is_error, "a failing command must be marked an error");
}

#[test]
fn a_path_escaping_the_workspace_is_refused() {
    // The previous harness relied on a prompt rule: "confine all inspections to the workspace".
    // Invariant IV exists because agents ignore rules like that under pressure.
    let d = ws();
    for bad in ["../../../etc/passwd", "/etc/passwd"] {
        let r = execute(
            d.path(),
            &LocalShell,
            &LocalFs,
            "read",
            &json!({"path": bad}),
        );
        assert!(
            r.is_error && r.content.contains("escapes the workspace"),
            "{bad} must be refused, got {r:?}"
        );
    }
}

#[test]
fn a_new_file_outside_the_workspace_is_refused_even_though_it_does_not_exist_yet() {
    // Canonicalising only existing paths would wave through exactly the dangerous case.
    let d = ws();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "write",
        &json!({"path": "../escaped.txt", "content": "x"}),
    );
    assert!(r.is_error, "writing outside the workspace must fail: {r:?}");
}

#[test]
fn edit_refuses_an_ambiguous_match_instead_of_guessing() {
    // Replacing the first of several matches silently edits the wrong place, and the agent
    // has no way to tell that it did.
    let d = ws();
    std::fs::write(d.path().join("a.rs"), "let x = 1;\nlet x = 1;\n").unwrap();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "edit",
        &json!({"path": "a.rs", "old": "let x = 1;", "new": "let x = 2;"}),
    );
    assert!(
        r.is_error && r.content.contains("appears 2 times"),
        "got {r:?}"
    );
    assert_eq!(
        std::fs::read_to_string(d.path().join("a.rs")).unwrap(),
        "let x = 1;\nlet x = 1;\n",
        "a refused edit must not modify the file"
    );
}

#[test]
fn edit_says_to_read_first_when_the_target_is_absent() {
    let d = ws();
    std::fs::write(d.path().join("a.rs"), "fn main() {}\n").unwrap();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "edit",
        &json!({"path": "a.rs", "old": "nope", "new": "x"}),
    );
    assert!(
        r.is_error && r.content.contains("Read it first"),
        "got {r:?}"
    );
}

#[test]
fn read_numbers_lines_so_edits_can_be_precise() {
    let d = ws();
    std::fs::write(d.path().join("a.rs"), "one\ntwo\nthree\n").unwrap();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "read",
        &json!({"path": "a.rs", "start_line": 2, "end_line": 3}),
    );
    assert!(r.content.contains("2\ttwo"), "got {:?}", r.content);
    assert!(!r.content.contains("one"), "range must be respected");
}

#[test]
fn distil_keeps_the_tail_because_test_runners_summarise_at_the_end() {
    // Head-only truncation would hide the answer and keep the noise -- the opposite of useful
    // for the 25,105-line `go test` output this exists for (FINDINGS 13.26).
    let text: String = (1..=5000).map(|i| format!("line {i}\n")).collect();
    let out = distil(&text, OUTPUT_LINE_BUDGET);
    assert!(out.contains("line 1"), "head kept");
    assert!(
        out.contains("line 5000"),
        "TAIL kept -- the summary lives here"
    );
    assert!(
        out.contains("elided by blyte"),
        "elision must be stated, not silent"
    );
    assert!(out.lines().count() < OUTPUT_LINE_BUDGET + 10);
}

#[test]
fn distil_leaves_short_output_untouched() {
    assert_eq!(distil("a\nb\nc", OUTPUT_LINE_BUDGET), "a\nb\nc");
}

// ---- discovery tools -------------------------------------------------------------------

fn seeded() -> tempfile::TempDir {
    let d = ws();
    std::fs::create_dir_all(d.path().join("src/deep")).unwrap();
    std::fs::create_dir_all(d.path().join("node_modules/junk")).unwrap();
    std::fs::write(
        d.path().join("src/main.rs"),
        "fn main() { parse_array(); }\n",
    )
    .unwrap();
    std::fs::write(
        d.path().join("src/deep/array.rs"),
        "fn parse_array() {}\n// multicolumn\n",
    )
    .unwrap();
    std::fs::write(
        d.path().join("src/notes.md"),
        "parse_array is the entry point\n",
    )
    .unwrap();
    std::fs::write(
        d.path().join("node_modules/junk/array.rs"),
        "fn parse_array() {}\n",
    )
    .unwrap();
    d
}

#[test]
fn glob_finds_files_recursively() {
    let d = seeded();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "glob",
        &json!({"pattern": "src/**/*.rs"}),
    );
    assert!(!r.is_error, "{r:?}");
    assert!(r.content.contains("src/main.rs"), "got {}", r.content);
    assert!(
        r.content.contains("src/deep/array.rs"),
        "** must recurse: {}",
        r.content
    );
}

#[test]
fn glob_reports_no_match_rather_than_returning_empty() {
    // An empty string reads to a model as a tool that broke, and it retries. Saying so plainly
    // is the difference between one call and three.
    let d = seeded();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "glob",
        &json!({"pattern": "*.nope"}),
    );
    assert!(!r.is_error);
    assert!(r.content.contains("no files match"), "got {}", r.content);
}

#[test]
fn grep_returns_path_line_and_text() {
    let d = seeded();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "grep",
        &json!({"pattern": "parse_array"}),
    );
    assert!(!r.is_error, "{r:?}");
    assert!(
        r.content.contains("src/main.rs:1:"),
        "must carry path:line: {}",
        r.content
    );
}

#[test]
fn grep_honours_gitignore_so_node_modules_does_not_drown_the_result() {
    // The single reason a repo-wide search is usable. Requires ripgrep; skipped without it
    // rather than asserted falsely, since the grep fallback has no such behaviour.
    let d = seeded();
    let have_rg = std::process::Command::new("rg")
        .arg("--version")
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);
    if !have_rg {
        return;
    }
    std::fs::write(d.path().join(".gitignore"), "node_modules/\n").unwrap();
    std::process::Command::new("git")
        .args(["init", "-q"])
        .current_dir(d.path())
        .output()
        .unwrap();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "grep",
        &json!({"pattern": "parse_array"}),
    );
    assert!(
        !r.content.contains("node_modules"),
        "ignored paths must stay out: {}",
        r.content
    );
}

#[test]
fn grep_can_be_restricted_by_glob() {
    let d = seeded();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "grep",
        &json!({"pattern": "parse_array", "glob": "*.md"}),
    );
    assert!(r.content.contains("notes.md"), "got {}", r.content);
    assert!(
        !r.content.contains("main.rs"),
        "glob must restrict: {}",
        r.content
    );
}

#[test]
fn grep_says_when_it_capped_rather_than_implying_completeness() {
    let d = ws();
    let many: String = (0..500).map(|i| format!("needle {i}\n")).collect();
    std::fs::write(d.path().join("big.txt"), many).unwrap();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "grep",
        &json!({"pattern": "needle"}),
    );
    assert!(
        r.content.contains("capped at"),
        "a truncated search must not read as complete: {}",
        &r.content[r.content.len().saturating_sub(200)..]
    );
}

#[test]
fn grep_patterns_with_shell_metacharacters_are_passed_verbatim() {
    // `$`, quotes and spaces in a regex must reach the tool, not the shell.
    let d = ws();
    std::fs::write(d.path().join("a.rs"), "let x = \"a b\";\nprice $5\n").unwrap();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "grep",
        &json!({"pattern": r"price \$5"}),
    );
    assert!(r.content.contains("a.rs:2:"), "got {}", r.content);
}

#[test]
fn grep_outside_the_workspace_is_refused() {
    let d = ws();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "grep",
        &json!({"pattern": "x", "path": "../.."}),
    );
    assert!(
        r.is_error && r.content.contains("escapes the workspace"),
        "{r:?}"
    );
}

#[test]
fn the_environment_probe_finds_the_tools_that_are_actually_here() {
    let d = ws();
    let bins = blyte_agent::tools::available_binaries(&LocalShell, d.path()).unwrap();
    assert!(
        bins.iter().any(|b| b == "git"),
        "git is present on any dev machine: {bins:?}"
    );
    assert!(!bins.iter().any(|b| b == "definitely-not-a-real-binary"));
}

// ---- the execution seam ----------------------------------------------------------------

/// A shell that records what it was asked to run and answers from a script.
#[derive(Default)]
struct FakeShell {
    seen: std::sync::Mutex<Vec<String>>,
}

impl blyte_agent::shell::Shell for FakeShell {
    fn exec(
        &self,
        command: &str,
        _cwd: &std::path::Path,
        _t: std::time::Duration,
    ) -> Result<blyte_agent::shell::Output, String> {
        self.seen.lock().unwrap().push(command.to_string());
        Ok(blyte_agent::shell::Output {
            stdout: "ran elsewhere\n".into(),
            stderr: String::new(),
            exit_code: 0,
        })
    }
    fn describe(&self) -> String {
        "a fake".into()
    }
}

#[test]
fn bash_goes_through_the_seam_not_the_host() {
    // The whole point of the seam: a container or remote deployment composes the executor and
    // the model's tool surface does not change. If `bash` reached the host directly, a
    // containerised run would edit the wrong filesystem -- which is what happened before.
    let d = ws();
    let fake = FakeShell::default();
    let r = execute(
        d.path(),
        &fake,
        &LocalFs,
        "bash",
        &json!({"command": "npm test"}),
    );
    assert!(
        r.content.contains("ran elsewhere"),
        "output must come from the seam: {r:?}"
    );
    assert_eq!(
        fake.seen.lock().unwrap().as_slice(),
        &["npm test".to_string()]
    );
}

/// Host files presented as a remote filesystem, as a container's are.
struct NotLocal;
impl blyte_agent::fs::Fs for NotLocal {
    fn read(&self, p: &std::path::Path) -> Result<String, String> {
        LocalFs.read(p)
    }
    fn write(&self, p: &std::path::Path, c: &str) -> Result<(), String> {
        LocalFs.write(p, c)
    }
    fn canonicalize(&self, p: &std::path::Path) -> Result<std::path::PathBuf, String> {
        LocalFs.canonicalize(p)
    }
}

#[test]
fn search_tools_also_go_through_the_seam() {
    // A container's files are not local (`Fs::is_local` is false), so glob, like grep, must go
    // through its executor. A local workspace is searched in-process instead (test_native_glob).
    let d = ws();
    let fake = FakeShell::default();
    execute(
        d.path(),
        &fake,
        &NotLocal,
        "glob",
        &json!({"pattern": "**/*.rs"}),
    );
    // A container's files are not local (`Fs::is_local` is false), so grep must go through its
    // executor. A local workspace is searched in-process instead (test_native_grep).
    execute(
        d.path(),
        &fake,
        &NotLocal,
        "grep",
        &json!({"pattern": "needle"}),
    );
    let seen = fake.seen.lock().unwrap();
    assert!(
        seen.len() >= 2,
        "both searches must reach the executor: {seen:?}"
    );
    // glob lists a container's repository with git ls-files (or falls back to a shell glob).
    assert!(seen
        .iter()
        .any(|c| c.contains("ls-files") || c.contains("*.rs")));
    assert!(seen.iter().any(|c| c.contains("needle")));
}

#[test]
fn the_probe_reports_what_the_execution_environment_has_not_the_host() {
    // A container deployment must not advertise the host's toolchain. The fake answers
    // every probe affirmatively, so every candidate comes back -- proving the list is built
    // from the seam's reply rather than from the host.
    let d = ws();
    let fake = FakeShell::default();
    let bins = blyte_agent::tools::available_binaries(&fake, d.path()).unwrap();
    assert!(
        bins.contains(&"ran elsewhere".to_string()) || !bins.is_empty(),
        "probe must be answered by the executor, got {bins:?}"
    );
    assert!(fake
        .seen
        .lock()
        .unwrap()
        .iter()
        .any(|c| c.contains("command -v")));
}

#[test]
fn the_environment_is_probed_in_one_round_trip() {
    // A remote shell pays a round trip per call; sixteen before the first turn is a poor start.
    let d = ws();
    let fake = FakeShell::default();
    blyte_agent::tools::available_binaries(&fake, d.path()).unwrap();
    assert_eq!(
        fake.seen.lock().unwrap().len(),
        1,
        "the whole probe must be one command, not one per binary"
    );
}

#[test]
fn posix_guaranteed_utilities_are_not_advertised() {
    // Listing sed/awk/find in every prompt is noise: they are present everywhere, so the model
    // has no decision to make from knowing it.
    use blyte_agent::tools::{ACCELERATORS, TOOLCHAINS};
    for noise in ["sed", "awk", "find", "xargs", "grep"] {
        assert!(
            !ACCELERATORS.contains(&noise) && !TOOLCHAINS.contains(&noise),
            "{noise} is POSIX-guaranteed and should not be advertised"
        );
    }
    assert!(
        ACCELERATORS.contains(&"rg"),
        "rg changes search strategy, so it is worth stating"
    );
}

// ---- the filesystem seam ---------------------------------------------------------------

/// An in-memory filesystem. If a tool touches the host instead, these tests fail.
#[derive(Default)]
struct FakeFs {
    files: std::sync::Mutex<std::collections::HashMap<String, String>>,
}

impl blyte_agent::fs::Fs for FakeFs {
    fn read(&self, path: &std::path::Path) -> Result<String, String> {
        self.files
            .lock()
            .unwrap()
            .get(&path.to_string_lossy().to_string())
            .cloned()
            .ok_or_else(|| format!("no such file: {}", path.display()))
    }
    fn write(&self, path: &std::path::Path, content: &str) -> Result<(), String> {
        self.files
            .lock()
            .unwrap()
            .insert(path.to_string_lossy().to_string(), content.to_string());
        Ok(())
    }
    fn canonicalize(&self, path: &std::path::Path) -> Result<std::path::PathBuf, String> {
        // No symlinks in the fake; lexical resolution is enough to exercise the escape check.
        Ok(path.to_path_buf())
    }
}

#[test]
fn write_lands_on_the_seam_not_the_host_disk() {
    // The defect this seam exists to prevent: the model edits one filesystem while its
    // verification runs against another. If `write` reached std::fs, the host would have the
    // file and the fake would not.
    let d = ws();
    let fake = FakeFs::default();
    let r = execute(
        d.path(),
        &LocalShell,
        &fake,
        "write",
        &json!({"path": "src/new.rs", "content": "fn x() {}"}),
    );
    assert!(!r.is_error, "{r:?}");
    assert!(
        !d.path().join("src/new.rs").exists(),
        "must NOT have touched the host disk"
    );
    assert_eq!(
        fake.files.lock().unwrap().values().next().unwrap(),
        "fn x() {}"
    );
}

#[test]
fn read_comes_from_the_seam() {
    let d = ws();
    let fake = FakeFs::default();
    let p = d
        .path()
        .join("only-in-the-seam.rs")
        .to_string_lossy()
        .to_string();
    fake.files
        .lock()
        .unwrap()
        .insert(p, "fn seam() {}\n".into());
    let r = execute(
        d.path(),
        &LocalShell,
        &fake,
        "read",
        &json!({"path": "only-in-the-seam.rs"}),
    );
    assert!(
        r.content.contains("fn seam()"),
        "read must consult the seam: {r:?}"
    );
}

#[test]
fn edit_reads_and_writes_through_the_same_seam() {
    // A half-routed edit -- reading the container and writing the host, or vice versa -- would
    // silently discard the change or corrupt the wrong file.
    let d = ws();
    let fake = FakeFs::default();
    let p = d.path().join("a.rs").to_string_lossy().to_string();
    fake.files
        .lock()
        .unwrap()
        .insert(p.clone(), "let x = 1;\n".into());
    let r = execute(
        d.path(),
        &LocalShell,
        &fake,
        "edit",
        &json!({"path": "a.rs", "old": "let x = 1;", "new": "let x = 2;"}),
    );
    assert!(!r.is_error, "{r:?}");
    assert_eq!(fake.files.lock().unwrap()[&p], "let x = 2;\n");
    assert!(
        !d.path().join("a.rs").exists(),
        "the host must be untouched"
    );
}

#[test]
fn the_escape_check_is_evaluated_against_the_seam() {
    // Canonicalising on the host's disk says nothing about where a path leads inside a
    // container, so the check has to ask the filesystem the write will actually land on.
    let d = ws();
    let fake = FakeFs::default();
    let r = execute(
        d.path(),
        &LocalShell,
        &fake,
        "write",
        &json!({"path": "../../escaped.rs", "content": "x"}),
    );
    assert!(
        r.is_error && r.content.contains("escapes the workspace"),
        "{r:?}"
    );
    assert!(
        fake.files.lock().unwrap().is_empty(),
        "a refused write must write nothing anywhere"
    );
}

#[test]
fn shell_and_fs_are_independently_composable() {
    // The combination that motivated splitting them: commands run in a container while files
    // are bind-mounted on the host. Both must be selectable without the tools noticing.
    let d = ws();
    let fake_shell = FakeShell::default();
    std::fs::write(d.path().join("host.rs"), "on the host\n").unwrap();
    let r = execute(
        d.path(),
        &fake_shell,
        &LocalFs,
        "read",
        &json!({"path": "host.rs"}),
    );
    assert!(
        r.content.contains("on the host"),
        "local fs with a remote shell must work: {r:?}"
    );
    let c = execute(
        d.path(),
        &fake_shell,
        &LocalFs,
        "bash",
        &json!({"command": "true"}),
    );
    assert!(
        c.content.contains("ran elsewhere"),
        "and the shell still goes elsewhere: {c:?}"
    );
}

#[test]
fn traversal_is_refused_even_when_canonicalize_does_not_normalise() {
    // Regression for a real hole. `Path::starts_with` compares components, so
    // `/ws/../../escaped.rs` lexically starts with `/ws`. Before lexical normalisation the
    // entire escape guarantee rested on the Fs implementation's canonicalize resolving `..`,
    // which is true of std::fs and `readlink -f` but is a property of those implementations
    // rather than of the check. FakeFs canonicalises lexically -- as a weak or partially
    // failing implementation would -- and the traversal got through.
    let d = ws();
    let fake = FakeFs::default();
    for escape in [
        "../../escaped.rs",
        "sub/../../../escaped.rs",
        "./../escaped.rs",
    ] {
        let r = execute(
            d.path(),
            &LocalShell,
            &fake,
            "write",
            &json!({"path": escape, "content": "x"}),
        );
        assert!(r.is_error, "{escape} must be refused, got {r:?}");
    }
    assert!(
        fake.files.lock().unwrap().is_empty(),
        "no refused write may land"
    );
}

#[test]
fn legitimate_dot_segments_inside_the_workspace_still_work() {
    // Normalisation must not become a blanket ban on `..`: `src/a/../b.rs` is an ordinary path
    // that stays inside, and refusing it would make the tool surprising.
    let d = ws();
    std::fs::create_dir_all(d.path().join("src/a")).unwrap();
    std::fs::write(d.path().join("src/b.rs"), "inside\n").unwrap();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "read",
        &json!({"path": "src/a/../b.rs"}),
    );
    assert!(!r.is_error && r.content.contains("inside"), "{r:?}");
}

static DISPATCH_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

struct ResetDispatch;
impl Drop for ResetDispatch {
    fn drop(&mut self) {
        blyte_agent::tools::set_dispatch_cmd(None);
    }
}

#[test]
fn dispatch_tool_runs_stub_command_and_echoes_json() {
    let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetDispatch;
    blyte_agent::tools::set_dispatch_cmd(Some("cat".into()));

    let tool_specs = specs();
    assert!(tool_specs.iter().any(|t| t.name == "dispatch"));

    let d = ws();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "dispatch",
        &json!({"task": "implement feature X", "gate": "cargo test", "max_seconds": 60}),
    );
    assert!(!r.is_error, "expected success, got {r:?}");
    let v: serde_json::Value =
        serde_json::from_str(&r.content).expect("stdout should be valid json");
    assert_eq!(v["task"], "implement feature X");
    assert_eq!(v["gate"], "cargo test");
    assert_eq!(v["max_seconds"], 60);
}

#[test]
fn dispatch_tool_failing_command_gives_error_result() {
    let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetDispatch;
    blyte_agent::tools::set_dispatch_cmd(Some(
        "sh -c 'echo failed to execute task >&2; exit 1'".into(),
    ));

    let d = ws();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "dispatch",
        &json!({"task": "fail", "gate": "false"}),
    );
    assert!(r.is_error, "expected error, got {r:?}");
    assert!(
        r.content.contains("failed to execute task"),
        "content was: {:?}",
        r.content
    );
}

#[test]
fn dispatch_tool_sets_dispatch_parent_env() {
    let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetDispatch;
    std::env::set_var("BLYTE_SESSION", "test-orch-session-123");
    blyte_agent::tools::set_dispatch_cmd(Some("sh -c 'echo parent=$BLYTE_DISPATCH_PARENT'".into()));

    let d = ws();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "dispatch",
        &json!({"task": "test", "gate": "true"}),
    );
    assert!(!r.is_error, "expected success, got {r:?}");
    assert!(
        r.content.contains("parent=test-orch-session-123"),
        "content was: {:?}",
        r.content
    );
}

#[test]
fn dispatch_tool_stdin_write_failure_returns_error_outcome() {
    let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetDispatch;
    blyte_agent::tools::set_dispatch_cmd(Some("exec <&-; exit 0".into()));

    let d = ws();
    let large_task = "x".repeat(512 * 1024);
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "dispatch",
        &json!({"task": large_task, "gate": "true"}),
    );
    assert!(
        r.is_error,
        "expected error on stdin write failure, got {r:?}"
    );
    assert!(
        r.content.contains("stdin") && r.content.contains("write"),
        "expected error message naming stdin write failure, got: {:?}",
        r.content
    );
}

#[test]
fn dispatch_tool_reports_the_command_failure_when_it_exits_before_reading() {
    let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetDispatch;
    blyte_agent::tools::set_dispatch_cmd(Some(
        "exec <&-; echo failed to execute task >&2; exit 1".into(),
    ));

    let d = ws();
    let large_task = "x".repeat(512 * 1024);
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "dispatch",
        &json!({"task": large_task, "gate": "false"}),
    );
    assert!(r.is_error, "expected error, got {r:?}");
    assert!(
        r.content.contains("failed to execute task"),
        "expected command stderr in content, got: {:?}",
        r.content
    );
    assert!(
        r.content.contains("failed to write arguments to stdin"),
        "expected stdin write error in content, got: {:?}",
        r.content
    );
}

#[cfg(unix)]
#[test]
fn dispatch_tool_reports_signal_termination_without_fabricating_exit_code() {
    let _lock = DISPATCH_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetDispatch;
    blyte_agent::tools::set_dispatch_cmd(Some("cat >/dev/null; kill -9 $$".into()));

    let d = ws();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "dispatch",
        &json!({"task": "killed", "gate": "false"}),
    );
    assert!(r.is_error, "expected error, got {r:?}");
    assert!(
        r.content.contains("without exit code") && r.content.contains("signal"),
        "expected signal termination without exit code, got: {:?}",
        r.content
    );
    assert!(
        !r.content.contains("exit 1"),
        "must not fabricate exit 1 for a signal-killed process, got: {:?}",
        r.content
    );
}

static PEER_TOOLS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

struct ResetPeerTools;
impl Drop for ResetPeerTools {
    fn drop(&mut self) {
        blyte_agent::tools::set_peer_tools(None);
    }
}

struct FakePeerTools {
    surfaces_result: Result<String, String>,
    tell_result: Result<String, String>,
    tell_calls: std::sync::Mutex<Vec<(String, String)>>,
}

impl FakePeerTools {
    fn ok(surfaces_text: &str, tell_text: &str) -> std::sync::Arc<Self> {
        std::sync::Arc::new(Self {
            surfaces_result: Ok(surfaces_text.to_string()),
            tell_result: Ok(tell_text.to_string()),
            tell_calls: std::sync::Mutex::new(Vec::new()),
        })
    }

    fn tell_err(err_text: &str) -> std::sync::Arc<Self> {
        std::sync::Arc::new(Self {
            surfaces_result: Ok(String::new()),
            tell_result: Err(err_text.to_string()),
            tell_calls: std::sync::Mutex::new(Vec::new()),
        })
    }
}

impl blyte_agent::tools::PeerTools for FakePeerTools {
    fn surfaces(&self) -> Result<String, String> {
        self.surfaces_result.clone()
    }

    fn tell(&self, name: &str, message: &str) -> Result<String, String> {
        self.tell_calls
            .lock()
            .unwrap()
            .push((name.to_string(), message.to_string()));
        self.tell_result.clone()
    }
}

#[test]
fn peer_tools_are_listed_only_when_registered() {
    let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetPeerTools;
    blyte_agent::tools::set_peer_tools(None);

    let before = specs();
    assert!(!before.iter().any(|t| t.name == "surfaces"));
    assert!(!before.iter().any(|t| t.name == "tell"));

    blyte_agent::tools::set_peer_tools(Some(FakePeerTools::ok("ok", "delivered")));
    let during = specs();
    let surfaces_spec = during.iter().find(|t| t.name == "surfaces").unwrap();
    assert_eq!(
        surfaces_spec.description,
        "List the surfaces running on this machine: name, repository, branch and what each is doing."
    );
    assert_eq!(
        surfaces_spec.parameters["properties"]
            .as_object()
            .unwrap()
            .len(),
        0
    );
    let tell_spec = during.iter().find(|t| t.name == "tell").unwrap();
    assert_eq!(
        tell_spec.description,
        "Send a message to another running surface by name. Its model reads it between turns as a message from this surface, not from its user. Returns delivered or held."
    );
    let tell_props = tell_spec.parameters["properties"].as_object().unwrap();
    assert_eq!(tell_props["name"]["type"], "string");
    assert_eq!(tell_props["message"]["type"], "string");
    assert_eq!(tell_spec.parameters["required"], json!(["name", "message"]));

    blyte_agent::tools::set_peer_tools(None);
    let after = specs();
    assert!(!after.iter().any(|t| t.name == "surfaces"));
    assert!(!after.iter().any(|t| t.name == "tell"));
}

#[test]
fn surfaces_tool_returns_the_registered_text() {
    let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetPeerTools;
    let fake = FakePeerTools::ok("api-2  repo/api  main  idle", "delivered");
    blyte_agent::tools::set_peer_tools(Some(fake));

    let d = ws();
    let r = execute(d.path(), &LocalShell, &LocalFs, "surfaces", &json!({}));
    assert!(!r.is_error, "expected ok, got {r:?}");
    assert_eq!(r.content, "api-2  repo/api  main  idle");
}

#[test]
fn tell_tool_passes_name_and_message() {
    let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetPeerTools;
    let fake = FakePeerTools::ok("", "delivered");
    blyte_agent::tools::set_peer_tools(Some(fake.clone()));

    let d = ws();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "tell",
        &json!({"name": "api-2", "message": "please rebase"}),
    );
    assert!(!r.is_error, "expected ok, got {r:?}");
    assert_eq!(r.content, "delivered");
    assert_eq!(
        fake.tell_calls.lock().unwrap().as_slice(),
        &[("api-2".to_string(), "please rebase".to_string())]
    );
}

#[test]
fn tell_tool_reports_the_error_text() {
    let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetPeerTools;
    let fake = FakePeerTools::tell_err("no running surface named ghost");
    blyte_agent::tools::set_peer_tools(Some(fake));

    let d = ws();
    let r = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "tell",
        &json!({"name": "ghost", "message": "hello"}),
    );
    assert!(r.is_error, "expected error, got {r:?}");
    assert_eq!(r.content, "no running surface named ghost");
}

#[test]
fn tell_tool_refuses_blank_arguments() {
    let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetPeerTools;
    let fake = FakePeerTools::ok("", "delivered");
    blyte_agent::tools::set_peer_tools(Some(fake.clone()));

    let d = ws();
    for bad in [
        json!({}),
        json!({"name": "api-2"}),
        json!({"message": "hello"}),
        json!({"name": "", "message": "hello"}),
        json!({"name": "   ", "message": "hello"}),
        json!({"name": "api-2", "message": ""}),
        json!({"name": "api-2", "message": " \t\n "}),
        json!({"name": 123, "message": "hello"}),
        json!({"name": "api-2", "message": true}),
    ] {
        let r = execute(d.path(), &LocalShell, &LocalFs, "tell", &bad);
        assert!(r.is_error, "expected error for {bad}, got {r:?}");
        assert_eq!(
            r.content, "tell needs a name and a message",
            "unexpected error for {bad}"
        );
    }
    assert!(
        fake.tell_calls.lock().unwrap().is_empty(),
        "stand-in must not be called for invalid arguments"
    );
}

#[test]
fn peer_tools_unregistered_say_so() {
    let _lock = PEER_TOOLS_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let _guard = ResetPeerTools;
    blyte_agent::tools::set_peer_tools(None);

    let d = ws();
    let s = execute(d.path(), &LocalShell, &LocalFs, "surfaces", &json!({}));
    assert!(s.is_error, "expected error, got {s:?}");
    assert_eq!(s.content, "the surfaces tool is not available here");

    let t = execute(
        d.path(),
        &LocalShell,
        &LocalFs,
        "tell",
        &json!({"name": "api-2", "message": "hello"}),
    );
    assert!(t.is_error, "expected error, got {t:?}");
    assert_eq!(t.content, "the tell tool is not available here");
}