aidaemon-tools 0.28.0

Ready-made tools for aidaemon agents (files, search, sandboxed shell, web, checklist); implementation crate of the aidaemon SDK, no stability promise (use it through aidaemon-sdk)
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
//! Tests of `read_file` as the daemon assembles it (its policy and wording in
//! `fs::test_support`), on the unconfined local backend.

use crate::OutcomeTool as Tool;
use crate::render_read_file_output_within;
use crate::semantics::{AttachmentProvenance, ReadFileResultMetadata, ReadFileSelectionMetadata};
use crate::{MAX_READ_CHARS, render_read_file_output};
use serde_json::json;

use crate::fs::test_support::ReadFileTool;

mod tests {
    use super::*;
    use crate::testing::ToolCalls as _;
    use std::io::Write;
    use std::path::Path;

    #[test]
    fn test_schema_has_required_fields() {
        let tool = ReadFileTool::new(crate::testing::active_execution_backend());
        let schema = tool.schema();
        assert_eq!(schema["name"], "read_file");
        assert!(!schema["description"].as_str().unwrap().is_empty());
        assert!(schema["parameters"]["properties"]["path"].is_object());
    }

    async fn read_in_tempdir(name: &str, body: &str) -> anyhow::Result<String> {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join(name);
        std::fs::write(&file, body).unwrap();
        let args = json!({"path": file.to_str().unwrap()}).to_string();
        crate::fs::test_support::guarded_call(
            &ReadFileTool::new(crate::testing::active_execution_backend()),
            &args,
        )
        .await
    }

    #[tokio::test]
    async fn read_file_refuses_ssh_private_key() {
        let dir = tempfile::tempdir().unwrap();
        let ssh = dir.path().join(".ssh");
        std::fs::create_dir(&ssh).unwrap();
        let key = ssh.join("id_ed25519");
        std::fs::write(&key, "synthetic-private-key-material\n").unwrap();
        let args = json!({"path": key.to_str().unwrap()}).to_string();
        let out = crate::fs::test_support::guarded_call(
            &ReadFileTool::new(crate::testing::active_execution_backend()),
            &args,
        )
        .await;
        let text = match out {
            Ok(text) => text,
            Err(error) => error.to_string(),
        };
        assert!(text.contains("read_file does not open credential or secret files"));
        assert!(!text.contains("synthetic-private-key-material"));
    }

    #[tokio::test]
    async fn read_file_refuses_dotenv() {
        let text = match read_in_tempdir(".env", "API_TOKEN=synthetic-token\n").await {
            Ok(text) => text,
            Err(error) => error.to_string(),
        };
        assert!(text.contains("read_file does not open credential or secret files"));
        assert!(text.contains("Ask the owner to share what is needed."));
        assert!(!text.contains("synthetic-token"));
    }

    #[tokio::test]
    async fn read_file_allows_env_example() {
        for name in [".env.example", ".env.sample", ".env.template"] {
            let text = read_in_tempdir(name, "API_TOKEN=changeme\n").await.unwrap();
            assert!(text.contains("API_TOKEN=changeme"), "{name}: {text}");
        }
    }

    #[tokio::test]
    async fn read_file_allows_git_head_and_config() {
        let dir = tempfile::tempdir().unwrap();
        let git = dir.path().join(".git");
        std::fs::create_dir(&git).unwrap();
        std::fs::write(git.join("HEAD"), "ref: refs/heads/main\n").unwrap();
        std::fs::write(git.join("config"), "[core]\n\tbare = false\n").unwrap();
        for (name, needle) in [("HEAD", "refs/heads/main"), ("config", "bare = false")] {
            let args = json!({"path": git.join(name).to_str().unwrap()}).to_string();
            let text = ReadFileTool::new(crate::testing::active_execution_backend())
                .call(&args)
                .await
                .unwrap();
            assert!(text.contains(needle), "{name}: {text}");
        }
    }

    #[tokio::test]
    async fn read_file_refuses_the_daemons_own_config() {
        let dir = tempfile::tempdir().unwrap();
        let own = dir.path().join("daemon-config.toml");
        std::fs::write(&own, "token = \"synthetic-secret\"\n").unwrap();
        let paths = crate::path_class::DaemonPaths::new(vec![own.clone()]);
        let args = json!({"path": own.to_str().unwrap()}).to_string();
        let text = crate::fs::test_support::guarded_call_protecting(
            paths,
            &ReadFileTool::new(crate::testing::active_execution_backend()),
            &args,
        )
        .await
        .unwrap_err()
        .to_string();
        assert!(text.contains("does not open credential or secret files"));
        assert!(text.contains("manage_config action 'read'"), "{text}");
        assert!(!text.contains("synthetic-secret"));
        let other = dir.path().join("config.toml");
        std::fs::write(&other, "title = \"ok\"\n").unwrap();
        let args = json!({"path": other.to_str().unwrap()}).to_string();
        assert!(
            ReadFileTool::new(crate::testing::active_execution_backend())
                .call(&args)
                .await
                .unwrap()
                .contains("title")
        );
    }

    #[tokio::test]
    async fn read_file_refuses_env_example_under_a_secret_directory() {
        let dir = tempfile::tempdir().unwrap();
        let ssh = dir.path().join(".ssh");
        std::fs::create_dir(&ssh).unwrap();
        std::fs::write(ssh.join(".env.example"), "synthetic-secret\n").unwrap();
        let args = json!({"path": ssh.join(".env.example").to_str().unwrap()}).to_string();
        let text = crate::fs::test_support::guarded_call(
            &ReadFileTool::new(crate::testing::active_execution_backend()),
            &args,
        )
        .await
        .unwrap_err()
        .to_string();
        assert!(text.contains("does not open credential or secret files"));
        assert!(!text.contains("synthetic-secret"));
    }

    #[tokio::test]
    async fn read_file_allows_regular_source() {
        let text = read_in_tempdir("main.rs", "fn main() {}\n").await.unwrap();
        assert!(text.contains("fn main() {}"));
    }

    #[tokio::test]
    async fn test_read_file_basic() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        write!(f, "line one\nline two\nline three\n").unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();
        let result = ReadFileTool::new(crate::testing::active_execution_backend())
            .call(&args)
            .await
            .unwrap();
        assert!(result.contains("line one"));
        assert!(result.contains("line two"));
        assert!(result.contains("line three"));
        assert!(result.contains("3 lines"));
        assert!(result.contains("bytes"));
        assert!(result.contains("modified"));
    }

    #[tokio::test]
    async fn test_read_file_outcome_includes_complete_typed_metadata() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        write!(f, "line one\nline two\nline three\n").unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();
        let metadata = outcome
            .metadata
            .read_file
            .expect("text reads should expose typed metadata");

        assert_eq!(metadata.display_path, f.path().to_str().unwrap());
        assert_eq!(metadata.returned_start_line, Some(1));
        assert_eq!(metadata.returned_end_line, Some(3));
        assert_eq!(metadata.total_lines, 3);
        assert_eq!(
            metadata.selected_lines,
            vec!["line one", "line two", "line three"]
        );
        assert!(matches!(
            metadata.selection,
            ReadFileSelectionMetadata::Full
        ));
    }

    #[tokio::test]
    async fn test_read_file_range_outcome_metadata_preserves_raw_lines() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        write!(f, "a\nb\nc\nd\ne\n").unwrap();
        let args =
            json!({"path": f.path().to_str().unwrap(), "start_line": 2, "end_line": 4}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();
        let metadata = outcome.metadata.read_file.unwrap();

        assert_eq!(metadata.returned_start_line, Some(2));
        assert_eq!(metadata.returned_end_line, Some(4));
        assert_eq!(metadata.selected_lines, vec!["b", "c", "d"]);
        assert!(matches!(
            metadata.selection,
            ReadFileSelectionMetadata::BoundedRange { .. }
        ));
    }

    #[tokio::test]
    async fn test_empty_file_is_a_typed_full_artifact() {
        let f = tempfile::NamedTempFile::new().unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();
        let metadata = outcome.metadata.read_file.unwrap();

        assert!(matches!(
            metadata.selection,
            ReadFileSelectionMetadata::Full
        ));
        assert_eq!(metadata.total_lines, 0);
        assert_eq!(metadata.returned_start_line, None);
        assert_eq!(metadata.returned_end_line, None);
        assert!(metadata.selected_lines.is_empty());
    }

    #[tokio::test]
    async fn test_binary_file_has_no_typed_read_artifact() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(&[0xFF, 0xD8, 0xFF, 0x00, 0x10, 0x00]).unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();

        assert!(outcome.metadata.read_file.is_none());
    }

    #[tokio::test]
    async fn test_read_file_line_range() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        write!(f, "a\nb\nc\nd\ne\n").unwrap();
        let args =
            json!({"path": f.path().to_str().unwrap(), "start_line": 2, "end_line": 4}).to_string();
        let result = ReadFileTool::new(crate::testing::active_execution_backend())
            .call(&args)
            .await
            .unwrap();
        assert!(result.contains("b"));
        assert!(result.contains("c"));
        assert!(result.contains("d"));
        assert!(result.contains("lines 2-4 of 5"));
        assert!(!result.contains("| a"));
        assert!(!result.contains("| e"));
    }

    /// A call that sends both an explicit range and tail_lines reads the
    /// range: the schema no longer states the exclusion, and rejecting the
    /// pair looped a live run on the same call (2026-11-18).
    #[tokio::test]
    async fn an_explicit_range_wins_over_tail_lines() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        write!(f, "a\nb\nc\n").unwrap();
        let args = json!({
            "path": f.path().to_str().unwrap(),
            "start_line": 1,
            "end_line": 2,
            "tail_lines": 1
        })
        .to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();
        assert!(!outcome.metadata.contract_rejected, "{}", outcome.output);
        assert!(outcome.output.contains("a"));
        assert!(outcome.output.contains("b"));
        assert!(!outcome.output.contains("| c"), "{}", outcome.output);
    }

    #[tokio::test]
    async fn test_read_file_not_found() {
        let args = json!({"path": "/tmp/nonexistent_read_file_test_12345.txt"}).to_string();
        let result = ReadFileTool::new(crate::testing::active_execution_backend())
            .call(&args)
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not found"));
    }

    #[tokio::test]
    async fn test_read_file_jpeg_image_attaches_vision_metadata() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(&[0xFF, 0xD8, 0xFF, 0x00, 0x10, 0x00]).unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();

        assert!(outcome.output.contains("Image file"));
        assert!(outcome.output.contains("image/jpeg"));
        assert!(outcome.output.contains("Attached for vision analysis"));
        assert!(outcome.metadata.read_file.is_none());
        let attachment = outcome
            .metadata
            .attachments
            .first()
            .expect("jpeg image attachment");
        assert_eq!(attachment.mime_type, "image/jpeg");
        assert_eq!(attachment.provenance, AttachmentProvenance::ToolObservation);
        assert_eq!(attachment.source_tool.as_deref(), Some("read_file"));
        assert!(Path::new(&attachment.local_path).exists());
    }

    #[tokio::test]
    async fn test_read_file_png_image_without_null_bytes() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x01, 0x02])
            .unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();

        assert!(outcome.output.contains("Image file"));
        assert!(outcome.output.contains("image/png"));
        assert_eq!(outcome.metadata.attachments.len(), 1);
    }

    /// Line ranges mean nothing for an image or a binary file: any range,
    /// even an invalid one, is ignored and the file is read as it is (live
    /// 2026-11-18: a PNG read with a range was rejected nine times in a row).
    #[tokio::test]
    async fn line_ranges_are_ignored_for_images_and_binary_files() {
        let mut png = tempfile::NamedTempFile::new().unwrap();
        png.write_all(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x01, 0x02])
            .unwrap();
        let mut binary = tempfile::NamedTempFile::new().unwrap();
        binary.write_all(&[0x7F, 0x45, 0x00, 0x00, 0x01]).unwrap();
        let tool = ReadFileTool::new(crate::testing::active_execution_backend());
        for range in [
            json!({"start_line": 5, "end_line": 2, "tail_lines": 3}),
            json!({"start_line": 0}),
            json!({"tail_lines": 10}),
        ] {
            let mut args = range.clone();
            args["path"] = json!(png.path().to_str().unwrap());
            let outcome = tool
                .call_with_status_outcome(&args.to_string(), None)
                .await
                .unwrap();
            assert!(
                outcome.output.contains("image/png"),
                "{range}: {}",
                outcome.output
            );
            assert_eq!(outcome.metadata.attachments.len(), 1, "{range}");

            args["path"] = json!(binary.path().to_str().unwrap());
            let outcome = tool
                .call_with_status_outcome(&args.to_string(), None)
                .await
                .unwrap();
            assert!(
                outcome.output.contains("Binary file"),
                "{range}: {}",
                outcome.output
            );
        }
        // A text file still rejects an invalid range.
        let mut text = tempfile::NamedTempFile::new().unwrap();
        text.write_all(b"one\ntwo\n").unwrap();
        let args = json!({"path": text.path().to_str().unwrap(), "start_line": 0}).to_string();
        let outcome = tool.call_with_status_outcome(&args, None).await.unwrap();
        assert!(outcome.output.contains("1-based"), "{}", outcome.output);
    }

    #[tokio::test]
    async fn test_pdf_file_returns_extraction_hint_not_dead_end() {
        let mut f = tempfile::Builder::new().suffix(".pdf").tempfile().unwrap();
        f.write_all(b"%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\n")
            .unwrap();
        let path = f.path().to_str().unwrap().to_string();
        let args = json!({"path": &path}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();

        assert!(outcome.output.contains("PDF"));
        assert!(
            outcome.output.contains("pdftotext"),
            "must give an exact terminal extraction command, got: {}",
            outcome.output
        );
        assert!(
            outcome.output.contains(&path),
            "extraction command must include the file path"
        );
        assert!(!outcome.output.contains("cannot display contents"));
        assert!(outcome.metadata.read_file.is_none());
    }

    #[tokio::test]
    async fn test_pdf_detected_by_magic_even_without_null_bytes() {
        // A small text-only PDF can pass the NUL-byte binary check; raw PDF
        // syntax must never be dumped as if it were the document text.
        let mut f = tempfile::NamedTempFile::new().unwrap();
        write!(f, "%PDF-1.4\nplain ascii body without nulls\n").unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();

        assert!(outcome.output.contains("pdftotext"));
        assert!(!outcome.output.contains("plain ascii body"));
    }

    #[tokio::test]
    async fn test_docx_file_returns_extraction_hint() {
        let mut f = tempfile::Builder::new().suffix(".docx").tempfile().unwrap();
        f.write_all(b"PK\x03\x04docx-zip-payload").unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();

        assert!(
            outcome.output.contains("Word document"),
            "got: {}",
            outcome.output
        );
        assert!(
            outcome.output.contains("textutil") || outcome.output.contains("pandoc"),
            "must suggest a concrete extraction command, got: {}",
            outcome.output
        );
        assert!(!outcome.output.contains("cannot display contents"));
    }

    #[tokio::test]
    async fn test_generic_binary_stub_suggests_identifying_format() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(&[0x00, 0x01, 0x02, 0x03, 0x04]).unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();

        assert!(outcome.output.contains("cannot display contents"));
        assert!(
            outcome.output.contains("terminal"),
            "binary stub must point to the terminal tool instead of dead-ending, got: {}",
            outcome.output
        );
    }

    #[tokio::test]
    async fn test_read_file_non_image_binary_still_stubbed() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(&[0x00, 0x01, 0x02, 0x03, 0x04]).unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();
        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();

        assert!(outcome.output.contains("Binary file"));
        assert!(outcome.output.contains("cannot display contents"));
        assert!(outcome.metadata.attachments.is_empty());
    }

    #[tokio::test]
    async fn test_read_file_directory() {
        let dir = tempfile::tempdir().unwrap();
        let args = json!({"path": dir.path().to_str().unwrap()}).to_string();
        let result = ReadFileTool::new(crate::testing::active_execution_backend())
            .call(&args)
            .await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("directory"));
    }

    #[tokio::test]
    async fn test_read_file_empty() {
        let f = tempfile::NamedTempFile::new().unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();
        let result = ReadFileTool::new(crate::testing::active_execution_backend())
            .call(&args)
            .await
            .unwrap();
        assert!(result.contains("0 lines"));
        assert!(result.contains("0 bytes"));
    }

    #[tokio::test]
    async fn test_long_lines_truncated_with_marker() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        writeln!(f, "short line").unwrap();
        writeln!(f, "{}", "z".repeat(10_000)).unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();

        assert!(outcome.output.contains("line truncated"));
        assert!(!outcome.output.contains(&"z".repeat(3_000)));
        let metadata = outcome.metadata.read_file.unwrap();
        assert!(
            metadata.selected_lines[1].chars().count() < 2_100,
            "stored line should be capped, got {} chars",
            metadata.selected_lines[1].chars().count()
        );
        assert_eq!(metadata.selected_lines[0], "short line");
    }

    #[tokio::test]
    async fn test_unbounded_range_read_is_capped_with_continuation_hint() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        for i in 1..=25_000 {
            writeln!(f, "line number {} with some padding text", i).unwrap();
        }
        let args = json!({"path": f.path().to_str().unwrap(), "start_line": 1, "end_line": 25_000})
            .to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();
        let metadata = outcome.metadata.read_file.clone().unwrap();

        assert!(metadata.truncated, "capped range read must set truncated");
        assert!(
            metadata.selected_lines.len() < 25_000,
            "returned {} lines, expected capped subset",
            metadata.selected_lines.len()
        );
        assert_eq!(metadata.total_lines, 25_000);
        let end = metadata.returned_end_line.unwrap();
        assert!(
            outcome
                .output
                .contains(&format!("\"start_line\": {}", end + 1)),
            "output must include an exact continuation call; output tail: {}",
            &outcome.output[outcome.output.len().saturating_sub(400)..]
        );
        assert!(outcome.output.contains("NOT returned"));
    }

    #[tokio::test]
    async fn test_full_read_of_large_file_returns_first_page() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        for i in 1..=25_000 {
            writeln!(f, "line number {} with some padding text", i).unwrap();
        }
        assert!(f.as_file().metadata().unwrap().len() > MAX_READ_CHARS as u64);
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .expect("oversized full read should auto-page, not error");
        let metadata = outcome.metadata.read_file.clone().unwrap();

        assert!(metadata.truncated);
        assert_eq!(metadata.returned_start_line, Some(1));
        assert_eq!(metadata.total_lines, 25_000);
        assert!(outcome.output.contains("| line number 1 "));
        assert!(outcome.output.contains("NOT returned"));
        let end = metadata.returned_end_line.unwrap();
        assert!(
            outcome
                .output
                .contains(&format!("\"start_line\": {}", end + 1))
        );
    }

    #[tokio::test]
    async fn test_huge_tail_lines_request_is_bounded() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        write!(f, "a\nb\nc\n").unwrap();
        let args =
            json!({"path": f.path().to_str().unwrap(), "tail_lines": 1_000_000_u64}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();
        let metadata = outcome.metadata.read_file.unwrap();

        assert_eq!(metadata.selected_lines, vec!["a", "b", "c"]);
        assert!(!metadata.truncated);
    }

    #[tokio::test]
    async fn test_small_full_read_has_no_truncation_hint() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        write!(f, "alpha\nbeta\ngamma\n").unwrap();
        let args = json!({"path": f.path().to_str().unwrap()}).to_string();

        let outcome = ReadFileTool::new(crate::testing::active_execution_backend())
            .call_with_status_outcome(&args, None)
            .await
            .unwrap();
        let metadata = outcome.metadata.read_file.unwrap();

        assert!(!metadata.truncated);
        assert!(!outcome.output.contains("NOT returned"));
        assert!(outcome.output.contains("3 lines"));
    }

    fn render_test_metadata(line_count: usize) -> ReadFileResultMetadata {
        ReadFileResultMetadata {
            display_path: "/tmp/example.txt".to_string(),
            canonical_path: "/tmp/example.txt".to_string(),
            selection: ReadFileSelectionMetadata::Full,
            returned_start_line: Some(1),
            returned_end_line: Some(line_count),
            total_lines: line_count,
            file_size: (line_count * 32) as u64,
            modified: Some("2026-06-10T00:00:00+00:00".to_string()),
            selected_lines: (1..=line_count)
                .map(|i| format!("content line {} with some padding", i))
                .collect(),
            truncated: false,
        }
    }

    #[test]
    fn test_render_within_budget_identical_when_it_fits() {
        let metadata = render_test_metadata(5);
        assert_eq!(
            render_read_file_output_within(&metadata, 10_000),
            render_read_file_output(&metadata)
        );
    }

    #[test]
    fn test_render_within_budget_cuts_on_line_boundary_with_hint() {
        let metadata = render_test_metadata(500);
        let out = render_read_file_output_within(&metadata, 2_000);

        assert!(
            out.chars().count() <= 2_400,
            "output should respect budget (+slack), got {} chars",
            out.chars().count()
        );
        assert!(out.contains("NOT returned"));
        assert!(out.contains("\"start_line\": "));
        // Every rendered content line must be complete — cut between lines,
        // never inside one.
        for line in out.lines() {
            if let Some((_, content)) = line.split_once(" | ") {
                assert!(
                    content.ends_with("with some padding"),
                    "line cut mid-content: {line:?}"
                );
            }
        }
        // The hint must point at the first line that was dropped.
        let last_shown = out
            .lines()
            .filter_map(|line| {
                line.split_once(" | ")
                    .and_then(|(n, _)| n.trim().parse::<usize>().ok())
            })
            .max()
            .unwrap();
        assert!(out.contains(&format!("\"start_line\": {}", last_shown + 1)));
    }

    #[test]
    fn test_render_within_budget_tail_keeps_most_recent_lines() {
        let mut metadata = render_test_metadata(500);
        metadata.selection = ReadFileSelectionMetadata::Tail {
            requested_lines: 500,
        };
        let out = render_read_file_output_within(&metadata, 2_000);

        assert!(
            out.contains("| content line 500 "),
            "tail render must keep the final lines"
        );
        assert!(
            !out.contains("| content line 1 "),
            "tail render must drop the oldest lines first"
        );
    }

    #[test]
    fn test_render_within_budget_always_keeps_at_least_one_line() {
        let metadata = render_test_metadata(50);
        let out = render_read_file_output_within(&metadata, 10);
        assert!(out.contains("| content line 1 "));
    }

    #[tokio::test]
    async fn test_read_large_file_with_line_range() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        for i in 1..=25_000 {
            writeln!(f, "line {}", i).unwrap();
        }
        assert!(f.as_file().metadata().unwrap().len() > MAX_READ_CHARS as u64);

        let args =
            json!({"path": f.path().to_str().unwrap(), "start_line": 24998, "end_line": 25000})
                .to_string();
        let result = ReadFileTool::new(crate::testing::active_execution_backend())
            .call(&args)
            .await
            .unwrap();

        assert!(result.contains("lines 24998-25000 of 25000"));
        assert!(result.contains("24998 | line 24998"));
        assert!(result.contains("25000 | line 25000"));
        assert!(!result.contains("24997 | line 24997"));
    }

    #[tokio::test]
    async fn test_read_large_file_with_tail_lines() {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        for i in 1..=25_000 {
            writeln!(f, "line {}", i).unwrap();
        }
        assert!(f.as_file().metadata().unwrap().len() > MAX_READ_CHARS as u64);

        let args = json!({"path": f.path().to_str().unwrap(), "tail_lines": 3}).to_string();
        let result = ReadFileTool::new(crate::testing::active_execution_backend())
            .call(&args)
            .await
            .unwrap();

        assert!(result.contains("last 3 lines of 25000"));
        assert!(result.contains("24998 | line 24998"));
        assert!(result.contains("25000 | line 25000"));
        assert!(!result.contains("24997 | line 24997"));
    }
}