edgecrab-tools 0.11.0

Tool registry, ToolHandler trait, and 50+ tool implementations
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
//! # read_file — Read file contents with optional line ranges
//!
//! WHY line ranges: LLMs have limited context. Reading entire large files
//! wastes tokens. Line ranges let the agent focus on relevant sections,
//! matching established paginated read workflows.
//!
//! WHY line numbers: Adds column-1 line numbers (`  42|content`) by default,
//! matching the legacy line-numbered read format.
//! Line numbers let the LLM reference specific locations in follow-up
//! `patch` calls without guessing offsets.

use async_trait::async_trait;
use serde::Deserialize;
use serde_json::json;

use edgecrab_types::{ToolError, ToolSchema};

use crate::artifact_spill::{SpillConfig, SpillContext, SpillOutcome, SpillSequence, maybe_spill};
use crate::budget_config::is_artifact_spill_path;
use crate::path_utils::jail_read_path;
use crate::read_tracker;
use crate::registry::{ToolContext, ToolHandler};

pub struct ReadFileTool;

#[derive(Deserialize)]
struct Args {
    #[serde(alias = "file_path")]
    path: String,
    #[serde(default)]
    line_start: Option<usize>,
    #[serde(default)]
    line_end: Option<usize>,
    /// Legacy pagination start line (1-indexed, inclusive).
    #[serde(default)]
    offset: Option<usize>,
    /// Legacy pagination line count.
    #[serde(default)]
    limit: Option<usize>,
    /// Add `  N|` line-number prefix to every output line.
    /// Default true — keeps line-addressable output for follow-up edits.
    #[serde(default = "default_line_numbers")]
    line_numbers: bool,
}

fn default_line_numbers() -> bool {
    true
}

/// Extension / path-based media redirect before any UTF-8 decode (006).
fn binary_media_redirect_stub(path: &str) -> Option<String> {
    let ext = std::path::Path::new(path)
        .extension()
        .and_then(|e| e.to_str())
        .map(|e| e.to_lowercase())?;
    match ext.as_str() {
        "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tiff" | "tif" | "avif" | "ico" => {
            Some(format!(
                "[IMAGE FILE DETECTED] '{path}' is an image — use vision_analyze instead. \
                 Call vision_analyze with image_source='{path}' to inspect its contents."
            ))
        }
        "pptx" | "ppt" | "docx" | "doc" | "xlsx" | "xls" | "odt" | "odp" | "pdf" | "zip"
        | "jar" | "whl" | "gz" | "tgz" | "bz2" | "7z" | "rar" | "wasm" | "so" | "dylib" | "dll"
        | "exe" | "bin" => {
            let mime = mime_for_office_ext(&ext);
            Some(
                serde_json::json!({
                    "ok": false,
                    "binary": true,
                    "path": path,
                    "mime": mime,
                    "suggested_tools": suggested_tools_for_mime(mime),
                    "note": "Binary/office artifact — do not read as UTF-8 text. \
                             Verify via filesystem metadata (ls/stat) or export to PDF/JPG + vision_analyze."
                })
                .to_string(),
            )
        }
        _ => None,
    }
}

fn mime_for_office_ext(ext: &str) -> &'static str {
    match ext {
        "pptx" | "ppt" => {
            "application/vnd.openxmlformats-officedocument.presentationml.presentation"
        }
        "docx" | "doc" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "xlsx" | "xls" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "pdf" => "application/pdf",
        "zip" | "jar" | "whl" => "application/zip",
        "gz" | "tgz" => "application/gzip",
        _ => "application/octet-stream",
    }
}

fn suggested_tools_for_mime(mime: &str) -> Vec<&'static str> {
    if mime.starts_with("image/") {
        vec!["vision_analyze"]
    } else if mime.contains("presentation") || mime == "application/pdf" {
        vec!["terminal", "vision_analyze"]
    } else {
        vec!["terminal"]
    }
}

/// Magic-byte media router when extension is missing/misleading.
fn binary_stub_from_magic(path: &str, bytes: &[u8]) -> Option<String> {
    if bytes.len() < 4 {
        return None;
    }
    // ZIP-based Office (PK..)
    if bytes[0] == 0x50
        && bytes[1] == 0x4B
        && (bytes[2] == 0x03 || bytes[2] == 0x05 || bytes[2] == 0x07)
    {
        let mime = "application/zip";
        return Some(
            serde_json::json!({
                "ok": false,
                "binary": true,
                "path": path,
                "mime": mime,
                "magic": "PK",
                "bytes": bytes.len(),
                "suggested_tools": ["terminal", "vision_analyze"],
                "note": "ZIP/Office binary detected by magic bytes — not UTF-8 text."
            })
            .to_string(),
        );
    }
    // PDF
    if bytes.starts_with(b"%PDF") {
        return Some(
            serde_json::json!({
                "ok": false,
                "binary": true,
                "path": path,
                "mime": "application/pdf",
                "magic": "%PDF",
                "bytes": bytes.len(),
                "suggested_tools": ["terminal", "vision_analyze"],
                "note": "PDF binary — verify via metadata or exported page images + vision_analyze."
            })
            .to_string(),
        );
    }
    // PNG
    if bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {
        return Some(format!(
            "[IMAGE FILE DETECTED] '{path}' is an image — use vision_analyze instead. \
             Call vision_analyze with image_source='{path}' to inspect its contents."
        ));
    }
    // JPEG
    if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) {
        return Some(format!(
            "[IMAGE FILE DETECTED] '{path}' is an image — use vision_analyze instead. \
             Call vision_analyze with image_source='{path}' to inspect its contents."
        ));
    }
    None
}

fn normalize_line_range(args: &Args) -> Result<(Option<usize>, Option<usize>), ToolError> {
    if args.line_start.is_some() || args.line_end.is_some() {
        let (start, end) = (args.line_start, args.line_end);
        if let (Some(s), Some(e)) = (start, end) {
            if s == 0 || e == 0 {
                return Err(ToolError::InvalidArgs {
                    tool: "read_file".into(),
                    message: "line_start and line_end must be >= 1".into(),
                });
            }
            if s > e {
                return Err(ToolError::InvalidArgs {
                    tool: "read_file".into(),
                    message: format!(
                        "line_start ({s}) must be <= line_end ({e}); swap them or omit line_end"
                    ),
                });
            }
        } else if let Some(s) = start
            && s == 0
        {
            return Err(ToolError::InvalidArgs {
                tool: "read_file".into(),
                message: "line_start must be >= 1".into(),
            });
        } else if let Some(e) = end
            && e == 0
        {
            return Err(ToolError::InvalidArgs {
                tool: "read_file".into(),
                message: "line_end must be >= 1".into(),
            });
        }
        return Ok((start, end));
    }

    let Some(offset) = args.offset.or_else(|| args.limit.map(|_| 1)) else {
        return Ok((None, None));
    };

    if offset == 0 {
        return Err(ToolError::InvalidArgs {
            tool: "read_file".into(),
            message: "offset must be >= 1".into(),
        });
    }

    if let Some(limit) = args.limit {
        if limit == 0 {
            return Err(ToolError::InvalidArgs {
                tool: "read_file".into(),
                message: "limit must be >= 1".into(),
            });
        }
        let end = offset.saturating_add(limit.saturating_sub(1));
        Ok((Some(offset), Some(end)))
    } else {
        Ok((Some(offset), None))
    }
}

/// Add `  N|` line-number prefixes to `content`, starting at `first_line`.
///
/// Format mirrors the legacy numbered-read output:
/// ```text
///     1| line one content
///    42| def foo():
/// ```
/// Long lines are NOT truncated here — the LLM needs the full content for `patch`.
fn add_line_numbers(content: &str, first_line: usize) -> String {
    // Determine width needed (e.g. 3 chars for files ≤ 999 lines)
    let total = first_line + content.lines().count().saturating_sub(1);
    let width = total.to_string().len().max(4);

    content
        .lines()
        .enumerate()
        .map(|(i, line)| format!("{:>width$}| {line}", first_line + i, width = width))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Suggest similar file names when the requested file is not found.
///
/// WHY: LLMs frequently typo or guess file names. Providing nearby candidates
/// (difflib-style, shared 50%+ chars) avoids a wasted round-trip.
/// Mirrors the legacy similar-file suggestion behavior.
fn suggest_similar_files(path: &str, cwd: &std::path::Path) -> Vec<String> {
    let dir = std::path::Path::new(path)
        .parent()
        .map(|p| {
            if p.components().count() == 0 {
                cwd.to_path_buf()
            } else {
                cwd.join(p)
            }
        })
        .unwrap_or_else(|| cwd.to_path_buf());
    let basename = std::path::Path::new(path)
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or(path)
        .to_lowercase();

    let Ok(entries) = std::fs::read_dir(&dir) else {
        return Vec::new();
    };

    let mut candidates: Vec<String> = entries
        .flatten()
        .filter_map(|e| {
            let fname = e.file_name();
            let name = fname.to_str()?;
            let name_lower = name.to_lowercase();
            // Shared character-set overlap ≥ 50% by unique char count.
            let b_chars: std::collections::HashSet<char> = basename.chars().collect();
            let n_chars: std::collections::HashSet<char> = name_lower.chars().collect();
            let common = b_chars.intersection(&n_chars).count();
            if common * 2 >= basename.len().min(name_lower.len()) {
                Some(e.path().display().to_string())
            } else {
                None
            }
        })
        .take(5)
        .collect();

    candidates.sort();
    candidates
}

#[async_trait]
impl ToolHandler for ReadFileTool {
    fn name(&self) -> &'static str {
        "read_file"
    }

    fn toolset(&self) -> &'static str {
        "file"
    }

    fn parallel_safe(&self) -> bool {
        true
    }

    fn emoji(&self) -> &'static str {
        "📄"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: "read_file".into(),
            description: "Read the contents of a file. Optionally specify line range. \
                          Supports either EdgeCrab line_start/line_end or legacy offset/limit pagination. \
                          Returns content with line numbers by default (set line_numbers=false to disable)."
                .into(),
            parameters: json!({
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "File path relative to working directory"
                    },
                    "line_start": {
                        "type": "integer",
                        "description": "Start line (1-indexed, inclusive)"
                    },
                    "line_end": {
                        "type": "integer",
                        "description": "End line (1-indexed, inclusive)"
                    },
                    "offset": {
                        "type": "integer",
                        "description": "Legacy start line (1-indexed, inclusive). Use with limit."
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Legacy line count to return. Use with offset."
                    },
                    "line_numbers": {
                        "type": "boolean",
                        "description": "Prefix each line with its line number (default: true)"
                    }
                },
                "required": ["path"]
            }),
            strict: None,
        }
    }

    async fn execute(
        &self,
        args: serde_json::Value,
        ctx: &ToolContext,
    ) -> Result<String, ToolError> {
        let args: Args = serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs {
            tool: "read_file".into(),
            message: e.to_string(),
        })?;

        // Media router: never UTF-8-decode images/office/zip binaries (006 / Claude Code).
        let (line_start, line_end) = normalize_line_range(&args)?;

        if let Some(stub) = binary_media_redirect_stub(&args.path) {
            return Ok(stub);
        }

        let path_policy = ctx.config.file_path_policy(&ctx.cwd);

        // Resolve and jail path using the shared path helper (SRP — security in one place)
        let resolved = match jail_read_path(&args.path, &path_policy) {
            Ok(p) => p,
            Err(e) => {
                // File not found → suggest similar file names, matching prior behavior.
                if matches!(&e, ToolError::NotFound(_)) {
                    let suggestions = suggest_similar_files(&args.path, &ctx.cwd);
                    if !suggestions.is_empty() {
                        return Err(ToolError::NotFound(format!(
                            "{e}\nSimilar files found:\n{}",
                            suggestions.join("\n")
                        )));
                    }
                }
                return Err(e);
            }
        };

        // Size check
        let metadata = tokio::fs::metadata(&resolved)
            .await
            .map_err(|e| ToolError::Other(format!("Cannot stat '{}': {}", args.path, e)))?;

        if metadata.len() as usize > ctx.config.max_file_read_bytes {
            return Err(ToolError::Other(format!(
                "File too large ({} bytes, max {}). Use line_start/line_end or offset/limit to read a section.",
                metadata.len(),
                ctx.config.max_file_read_bytes
            )));
        }

        // Consecutive re-read loop detection runs FIRST — before dedup — so that
        // the counter always increments on every attempted read, ensuring warn/block
        // thresholds fire even when dedup would short-circuit the actual file I/O.
        let key = read_tracker::read_key(&resolved.to_string_lossy(), line_start, line_end);
        let count = read_tracker::check_and_update(&ctx.session_id, key);

        if count >= 4 {
            return Err(ToolError::Other(format!(
                "BLOCKED: You have read '{}' (lines {:?}{:?}) {} times in a row. \
                 The content has NOT changed. You already have this information. \
                 Stop re-reading and proceed with your task.",
                args.path, line_start, line_end, count
            )));
        }

        // FP13: mtime-based read dedup — skip re-read if file unchanged since last read.
        // Only applies when below the warning threshold (count < 3): at count == 3 we
        // must return the actual content alongside the warning so the user can verify.
        // Cast to u64 for the DedupKey (line numbers are small; no overflow risk here).
        let dedup_start = line_start.map(|v| v as u64);
        let dedup_end = line_end.map(|v| v as u64);
        if count < 3
            && let Some(stub) =
                read_tracker::check_read_dedup(&ctx.session_id, &resolved, dedup_start, dedup_end)
        {
            return Ok(stub);
        }

        let raw = tokio::fs::read(&resolved)
            .await
            .map_err(|e| ToolError::Other(format!("Cannot read '{}': {}", args.path, e)))?;

        if let Some(stub) = binary_stub_from_magic(&args.path, &raw) {
            return Ok(stub);
        }

        let content = match String::from_utf8(raw) {
            Ok(s) => s,
            Err(_) => {
                return Ok(serde_json::json!({
                    "ok": false,
                    "binary": true,
                    "path": args.path,
                    "mime": "application/octet-stream",
                    "bytes": metadata.len(),
                    "suggested_tools": ["terminal"],
                    "note": "File is not valid UTF-8 — do not decode as text."
                })
                .to_string());
            }
        };

        // Apply line range filter.
        // `first_line` tracks the 1-based line number of the first output line
        // so that add_line_numbers() produces correct absolute numbers even for
        // partial reads (e.g. line_start=100 → output starts at "  100|").
        let (output, first_line) = match (line_start, line_end) {
            (Some(start), Some(end)) => {
                let lines: Vec<&str> = content.lines().collect();
                let start_idx = start.saturating_sub(1); // 1-indexed to 0-indexed
                let end_idx = end.min(lines.len());
                if start_idx >= lines.len() {
                    return Ok(format!("(empty — file has {} lines)", lines.len()));
                }
                if start_idx >= end_idx {
                    return Ok(format!(
                        "(empty — invalid range {start}{end}; file has {} lines)",
                        lines.len()
                    ));
                }
                (lines[start_idx..end_idx].join("\n"), start)
            }
            (Some(start), None) => {
                let lines: Vec<&str> = content.lines().collect();
                let start_idx = start.saturating_sub(1);
                if start_idx >= lines.len() {
                    return Ok(format!("(empty — file has {} lines)", lines.len()));
                }
                (lines[start_idx..].join("\n"), start)
            }
            _ => (content, 1usize),
        };

        // Apply line-number prefixes when requested (default: true).
        let output = if args.line_numbers && !output.is_empty() {
            add_line_numbers(&output, first_line)
        } else {
            output
        };

        // Record snapshot for freshness guards (patch/write stale-read detection).
        let _ = read_tracker::record_file_snapshot(&ctx.session_id, &resolved);

        // FP13: Record dedup entry so next identical read can short-circuit.
        read_tracker::record_read_dedup(&ctx.session_id, &resolved, dedup_start, dedup_end);

        if count >= 3 {
            let warning = format!(
                "[WARNING: You have read this exact region {} times consecutively. \
                 The content has not changed since your last read. \
                 If you are stuck in a loop, stop reading and proceed.]\n",
                count
            );
            return Ok(format!("{warning}{output}"));
        }

        read_file_maybe_spill_large(&args.path, &output, ctx)
    }
}

fn read_file_maybe_spill_large(
    path: &str,
    output: &str,
    ctx: &ToolContext,
) -> Result<String, ToolError> {
    if is_artifact_spill_path(path) {
        return Ok(output.to_string());
    }
    let spill_config = SpillConfig::from(&ctx.config);
    if !spill_config.enabled || output.len() <= spill_config.threshold {
        return Ok(output.to_string());
    }
    let spill_ctx = SpillContext {
        source_path: Some(path.to_string()),
    };
    let seq = SpillSequence::new();
    match maybe_spill(
        "read_file",
        ctx.current_tool_call_id.as_deref().unwrap_or("read"),
        output.to_string(),
        &ctx.session_id,
        &ctx.cwd,
        &spill_config,
        &seq,
        Some(&spill_ctx),
    ) {
        SpillOutcome::Spilled { stub, .. } => Ok(stub),
        SpillOutcome::Inline(s) => Ok(s),
    }
}

// Compile-time registration
inventory::submit!(&ReadFileTool as &dyn ToolHandler);

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn ctx_in(dir: &std::path::Path) -> ToolContext {
        let mut ctx = ToolContext::test_context();
        ctx.cwd = dir.to_path_buf();
        ctx
    }

    #[tokio::test]
    async fn read_file_basic() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("test.txt"), "line1\nline2\nline3\n").expect("write");

        let ctx = ctx_in(dir.path());
        let result = ReadFileTool
            .execute(json!({"path": "test.txt"}), &ctx)
            .await
            .expect("read");

        assert!(result.contains("line1"));
        assert!(result.contains("line3"));
    }

    #[tokio::test]
    async fn read_file_rejects_inverted_line_range() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("test.txt"), "a\nb\nc\n").expect("write");
        let ctx = ctx_in(dir.path());
        let err = ReadFileTool
            .execute(
                json!({"path": "test.txt", "line_start": 3, "line_end": 1}),
                &ctx,
            )
            .await
            .expect_err("inverted range");
        let ToolError::InvalidArgs { message, .. } = err else {
            panic!("expected InvalidArgs, got {err:?}");
        };
        assert!(message.contains("line_start"));
    }

    #[tokio::test]
    async fn read_file_line_range() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("test.txt"), "a\nb\nc\nd\ne\n").expect("write");

        let ctx = ctx_in(dir.path());
        // Disable line numbers for an exact content equality check
        let result = ReadFileTool
            .execute(
                json!({"path": "test.txt", "line_start": 2, "line_end": 4, "line_numbers": false}),
                &ctx,
            )
            .await
            .expect("read");

        assert_eq!(result, "b\nc\nd");
    }

    #[tokio::test]
    async fn read_file_supports_offset_limit_pagination() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("paged.txt"), "a\nb\nc\nd\ne\n").expect("write");

        let ctx = ctx_in(dir.path());
        let result = ReadFileTool
            .execute(
                json!({"path": "paged.txt", "offset": 2, "limit": 3, "line_numbers": false}),
                &ctx,
            )
            .await
            .expect("read");

        assert_eq!(result, "b\nc\nd");
    }

    #[tokio::test]
    async fn read_file_rejects_zero_limit() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("paged.txt"), "a\nb\n").expect("write");

        let ctx = ctx_in(dir.path());
        let result = ReadFileTool
            .execute(json!({"path": "paged.txt", "offset": 1, "limit": 0}), &ctx)
            .await;

        assert!(result.is_err());
        let error = result.expect_err("expected invalid args").to_string();
        assert!(error.contains("limit must be >= 1"), "got: {error}");
    }

    #[tokio::test]
    async fn read_file_line_numbers_are_on_by_default() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("nums.txt"), "first\nsecond\nthird\n").expect("write");

        let ctx = ctx_in(dir.path());
        let result = ReadFileTool
            .execute(json!({"path": "nums.txt"}), &ctx)
            .await
            .expect("read");

        // Default output should contain `1|` prefix
        assert!(
            result.contains("1|"),
            "expected line number prefix, got: {result}"
        );
        assert!(result.contains("first"), "expected content");
    }

    #[tokio::test]
    async fn read_file_line_range_numbers_are_absolute() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("abs.txt"), "l1\nl2\nl3\nl4\nl5\n").expect("write");

        let ctx = ctx_in(dir.path());
        // Read starting at line 3 — the prefix should say "3|" not "1|"
        let result = ReadFileTool
            .execute(
                json!({"path": "abs.txt", "line_start": 3, "line_end": 5}),
                &ctx,
            )
            .await
            .expect("read");

        assert!(
            result.contains("3|"),
            "expected absolute line number 3, got: {result}"
        );
        assert!(
            result.contains("l3"),
            "expected line content l3, got: {result}"
        );
    }

    #[tokio::test]
    async fn read_file_path_traversal_blocked() {
        let dir = TempDir::new().expect("tmpdir");
        let ctx = ctx_in(dir.path());

        let result = ReadFileTool
            .execute(json!({"path": "../../../etc/passwd"}), &ctx)
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn read_file_missing_file() {
        let dir = TempDir::new().expect("tmpdir");
        let ctx = ctx_in(dir.path());

        let result = ReadFileTool
            .execute(json!({"path": "nonexistent.txt"}), &ctx)
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn read_file_pptx_returns_binary_stub_not_utf8_error() {
        let dir = TempDir::new().expect("tmpdir");
        // Minimal ZIP/PK magic (Office Open XML container).
        std::fs::write(dir.path().join("deck.pptx"), b"PK\x03\x04fake-office").expect("write");
        let ctx = ctx_in(dir.path());
        let result = ReadFileTool
            .execute(json!({"path": "deck.pptx"}), &ctx)
            .await
            .expect("binary stub ok");
        assert!(result.contains("binary"), "got: {result}");
        assert!(
            result.contains("mime") || result.contains("suggested_tools"),
            "got: {result}"
        );
        assert!(
            !result.contains("stream did not contain valid UTF-8"),
            "must not surface UTF-8 decode panic: {result}"
        );
    }

    #[tokio::test]
    async fn read_file_image_redirects_to_vision_analyze() {
        let dir = TempDir::new().expect("tmpdir");
        // Write a fake PNG (doesn't need valid bytes — redirect happens before read)
        std::fs::write(dir.path().join("screenshot.png"), b"\x89PNG\r\n").expect("write");
        let ctx = ctx_in(dir.path());

        let result = ReadFileTool
            .execute(json!({"path": "screenshot.png"}), &ctx)
            .await
            .expect("should return redirect message, not error");

        assert!(
            result.contains("vision_analyze"),
            "expected redirect to vision_analyze, got: {result}"
        );
        assert!(
            result.contains("screenshot.png"),
            "expected path in message"
        );
    }

    #[tokio::test]
    async fn read_file_image_redirect_covers_common_extensions() {
        let dir = TempDir::new().expect("tmpdir");
        let ctx = ctx_in(dir.path());

        for ext in ["jpg", "jpeg", "gif", "webp", "bmp", "tiff", "avif", "ico"] {
            let fname = format!("img.{ext}");
            std::fs::write(dir.path().join(&fname), b"fake").expect("write");
            let result = ReadFileTool
                .execute(json!({"path": fname}), &ctx)
                .await
                .expect("redirect expected");
            assert!(
                result.contains("vision_analyze"),
                "ext={ext} should redirect"
            );
        }
    }

    #[tokio::test]
    async fn read_file_warns_on_third_consecutive_read() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("loop.txt"), "some content").expect("write");

        // Each test needs a unique session_id to avoid cross-test interference
        let mut ctx = ctx_in(dir.path());
        ctx.session_id = format!("test-warn-{}", uuid::Uuid::new_v4());

        let args = json!({"path": "loop.txt"});

        // Reads 1 and 2 — normal result, no warning
        let r1 = ReadFileTool.execute(args.clone(), &ctx).await.expect("r1");
        assert!(!r1.contains("WARNING"), "read 1 should not warn");
        let r2 = ReadFileTool.execute(args.clone(), &ctx).await.expect("r2");
        assert!(!r2.contains("WARNING"), "read 2 should not warn");

        // Read 3 — warning prepended
        let r3 = ReadFileTool.execute(args.clone(), &ctx).await.expect("r3");
        assert!(
            r3.contains("WARNING"),
            "read 3 should contain warning, got: {r3}"
        );
        assert!(
            r3.contains("some content"),
            "content still present with warning"
        );
    }

    #[tokio::test]
    async fn read_file_blocks_on_fourth_consecutive_read() {
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("blocked.txt"), "content").expect("write");

        let mut ctx = ctx_in(dir.path());
        ctx.session_id = format!("test-block-{}", uuid::Uuid::new_v4());

        let args = json!({"path": "blocked.txt"});

        // Reads 1-3 allowed
        for _ in 0..3 {
            let _ = ReadFileTool.execute(args.clone(), &ctx).await;
        }

        // Read 4 must return an error
        let r4 = ReadFileTool.execute(args.clone(), &ctx).await;
        assert!(r4.is_err(), "read 4 should be BLOCKED");
        let msg = r4.unwrap_err().to_string();
        assert!(
            msg.contains("BLOCKED"),
            "error should say BLOCKED, got: {msg}"
        );
    }

    #[tokio::test]
    async fn read_file_other_tool_resets_counter() {
        // Simulate: read 3x → warning; then "other tool" fires → counter resets;
        // next read should be count=1 again (no warning).
        let dir = TempDir::new().expect("tmpdir");
        std::fs::write(dir.path().join("reset.txt"), "data").expect("write");

        let mut ctx = ctx_in(dir.path());
        ctx.session_id = format!("test-reset-{}", uuid::Uuid::new_v4());

        let args = json!({"path": "reset.txt"});

        // 3 reads (third triggers warning)
        for _ in 0..3 {
            let _ = ReadFileTool.execute(args.clone(), &ctx).await;
        }
        // Simulate another tool calling notify (e.g., write_file)
        crate::read_tracker::notify_other_tool_call(&ctx.session_id);

        // Next read should be count=1, no warning
        let r = ReadFileTool
            .execute(args.clone(), &ctx)
            .await
            .expect("after reset");
        assert!(
            !r.contains("WARNING"),
            "after reset read should not warn, got: {r}"
        );
    }

    #[tokio::test]
    async fn read_file_allows_absolute_path_in_configured_allowed_root() {
        let dir = TempDir::new().expect("workspace");
        let extra = TempDir::new().expect("extra");
        let extra_file = extra.path().join("shared.txt");
        std::fs::write(&extra_file, "shared").expect("write");

        let mut ctx = ctx_in(dir.path());
        ctx.config.file_allowed_roots = vec![extra.path().to_path_buf()];

        let result = ReadFileTool
            .execute(
                json!({"path": extra_file.to_string_lossy(), "line_numbers": false}),
                &ctx,
            )
            .await
            .expect("read");

        assert_eq!(result, "shared");
    }

    #[tokio::test]
    async fn read_file_maps_absolute_tmp_into_edgecrab_temp_root() {
        let dir = TempDir::new().expect("workspace");
        let edgecrab_home = TempDir::new().expect("edgecrab_home");
        let mapped = edgecrab_home.path().join("tmp/files/summary.md");
        std::fs::create_dir_all(mapped.parent().expect("tmp parent")).expect("create tmp parent");
        std::fs::write(&mapped, "tmp contents").expect("write mapped tmp");

        let mut ctx = ctx_in(dir.path());
        ctx.config.edgecrab_home = edgecrab_home.path().to_path_buf();

        let result = ReadFileTool
            .execute(
                json!({"path": "/tmp/summary.md", "line_numbers": false}),
                &ctx,
            )
            .await
            .expect("read virtual tmp");

        assert_eq!(result, "tmp contents");
    }

    #[tokio::test]
    async fn ha23_large_read_spills_with_inline_preview() {
        let dir = TempDir::new().expect("tmpdir");
        let lines: Vec<String> = (1..=150).map(|i| format!("content line {i}")).collect();
        std::fs::write(dir.path().join("big.txt"), lines.join("\n")).expect("write");

        let mut ctx = ctx_in(dir.path());
        ctx.config.result_spill = true;
        ctx.config.result_spill_threshold = 500;
        ctx.config.result_spill_preview_lines = 20;

        let result = ReadFileTool
            .execute(json!({"path": "big.txt", "line_numbers": false}), &ctx)
            .await
            .expect("read");

        assert!(result.contains("[tool_result_spill]"));
        assert!(result.contains("BEGIN PREVIEW"));
        assert!(result.contains("next: read_file"));
        assert!(result.contains("big.txt"));
    }
}