codescout 0.15.0

High-performance coding agent toolkit MCP server
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
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
//! `read_file` tool and read helpers.

use anyhow::Result;
use serde_json::{json, Value};

use super::format::format_overflow;
use super::{optional_u64_param, OutputForm, RecoverableError, Tool, ToolContext};
use crate::util::text::extract_lines;

pub struct ReadFile;

#[async_trait::async_trait]
impl Tool for ReadFile {
    fn name(&self) -> &str {
        "read_file"
    }

    fn description(&self) -> &str {
        "Read a file. Large output → @file_* buffer. Format-aware: json_path \
         (JSON), toml_key (TOML/YAML). Use read_markdown for .md. Source files: \
         a line range overlapping a symbol redirects to symbols(include_body=true); \
         pass force=true to bypass."
    }

    fn relevant_guide_topic(&self) -> Option<&str> {
        Some("progressive-disclosure")
    }

    fn input_schema(&self) -> Value {
        json!({
            "type": "object",
            "required": ["path"],
            "properties": {
                "path": { "type": "string", "description": "File path relative to project root" },
                "file_path": { "type": "string", "description": "Alias for path" },
                "start_line": { "type": "integer", "description": "First line (1-indexed). Pair with end_line." },
                "end_line": { "type": "integer", "description": "Last line (1-indexed, inclusive). Pair with start_line." },
                "offset": { "type": "integer", "description": "Native-Read-style alias: 1-indexed start line (= start_line). Ignored when start_line/end_line are set." },
                "limit": { "type": "integer", "description": "Native-Read-style alias: line count from offset (end_line = offset + limit - 1). offset defaults to line 1 if omitted." },
                "json_path": { "type": "string", "description": "JSON subtree by path (e.g. \"$.dependencies\")." },
                "toml_key": { "type": "string", "description": "TOML table or YAML section by key (e.g. \"dependencies\")." },
                "force": { "type": "boolean", "description": "Skip source-symbol hint and read the raw line range." }
            }
        })
    }

    async fn call(&self, input: Value, ctx: &ToolContext) -> Result<Value> {
        // Native-`Read` compatibility: callers habitually pass offset/limit (a 1-indexed
        // start line + a line count, the built-in Read signature). Normalize to
        // start_line/end_line up front — before the buffer fork — so both the buffer and
        // real-file paths honor them through the same line-range logic instead of
        // silently returning the file head.
        let mut input = input;
        normalize_line_nav_aliases(&mut input);

        let raw_path = input["path"]
            .as_str()
            .or_else(|| input["file_path"].as_str())
            .ok_or_else(|| {
                RecoverableError::with_hint(
                    "missing required parameter 'path'",
                    "Provide the file path as: path=\"relative/path/to/file\"",
                )
            })?;
        let path = strip_buffer_ref_quotes(raw_path);

        // Buffer refs bypass the filesystem entirely.
        if path.starts_with("@file_") || path.starts_with("@cmd_") || path.starts_with("@tool_") {
            return read_from_buffer(path, &input, ctx);
        }

        let project_root = ctx
            .agent
            .project_root_for(ctx.workspace_override.as_deref())
            .await;
        let security = ctx
            .agent
            .security_config_for(ctx.workspace_override.as_deref())
            .await;
        let resolved = crate::util::path_security::validate_read_path(
            path,
            project_root.as_deref(),
            &security,
        )?;

        // Gate: redirect .md files to read_markdown
        if resolved.extension().is_some_and(|e| e == "md") {
            return Err(RecoverableError::with_hint(
                "Use read_markdown for markdown files",
                "read_markdown provides heading-based navigation, size-adaptive output, and buffer-ref slicing for .md files.",
            )
            .into());
        }

        let start_line = optional_u64_param(&input, "start_line");
        let end_line = optional_u64_param(&input, "end_line");
        validate_read_nav_params(&input, start_line, end_line)?;
        // start_line alone defaults end_line to a 50-line window (read_with_line_range
        // clamps past-EOF cases, so saturating_add is safe).
        let end_line = match (start_line, end_line) {
            (Some(s), None) => Some(s.saturating_add(49)),
            (_, e) => e,
        };

        let source_tag = compute_source_tag(&resolved, ctx).await;

        if resolved.is_dir() {
            return Err(RecoverableError::with_hint(
                format!("'{}' is a directory, not a file", path),
                "Use tree to browse directory contents, or provide a specific file path",
            )
            .into());
        }

        let text = read_file_text(path, &resolved)?;

        if let Some(jp) = input["json_path"].as_str() {
            return read_json_path_nav(&text, &resolved, jp);
        }
        if let Some(tk) = input["toml_key"].as_str() {
            return read_toml_yaml_key(&text, &resolved, tk);
        }

        let force = input["force"].as_bool().unwrap_or(false);

        if let (Some(start), Some(end)) = (start_line, end_line) {
            return read_with_line_range(
                path,
                &text,
                &resolved,
                start,
                end,
                &source_tag,
                ctx,
                force,
            );
        }
        read_full_file(path, &text, &resolved, &input, &source_tag, ctx)
    }

    fn output_form(&self) -> OutputForm {
        OutputForm::Text
    }

    fn format_compact(&self, result: &Value) -> Option<String> {
        Some(format_read_file(result))
    }
}

/// Strip surrounding quotes from buffer ref paths.
///
/// LLMs often wrap @ref paths in extra quoting — double quotes (`"@tool_abc"`),
/// single quotes (`'@tool_abc'`), or markdown-style backticks (`` `@tool_abc` ``).
/// Stripping any matched pair here lets the ref resolve correctly.
fn strip_buffer_ref_quotes(path: &str) -> &str {
    for q in ['"', '\'', '`'] {
        if let Some(inner) = path.strip_prefix(q).and_then(|s| s.strip_suffix(q)) {
            if inner.starts_with("@file_")
                || inner.starts_with("@cmd_")
                || inner.starts_with("@tool_")
                || inner.starts_with("@ack_")
            {
                return inner;
            }
        }
    }
    path
}

/// Read from an output buffer ref (`@file_*`, `@cmd_*`, `@tool_*`).
///
/// Handles json_path navigation for `@tool_*` refs and line-range slicing.
/// Never re-buffers — returns inline or, for oversized content, paginates
/// via `shown_lines` / `next`.
fn read_from_buffer(path: &str, input: &Value, ctx: &ToolContext) -> Result<Value> {
    let raw = ctx
        .output_buffer
        .get(path)
        .ok_or_else(|| {
            RecoverableError::with_hint(
                format!("buffer reference not found: '{}'", path),
                "Buffer refs expire when the session resets. Re-run the command to get a fresh ref.",
            )
        })?
        .stdout;

    // @tool_* refs contain compact single-line JSON — pretty-print so
    // start_line/end_line navigation and json_path extraction are useful.
    let text: String = if path.starts_with("@tool_") {
        serde_json::from_str::<serde_json::Value>(&raw)
            .ok()
            .and_then(|v| serde_json::to_string_pretty(&v).ok())
            .unwrap_or(raw)
    } else {
        raw
    };

    // json_path navigation is only meaningful for @tool_* (always JSON).
    if path.starts_with("@tool_") {
        if let Some(jp) = input["json_path"].as_str() {
            let (content, type_name, count) =
                crate::tools::file_summary::extract_json_path(&text, jp)?;
            let mut result = if crate::tools::exceeds_inline_limit(&content) {
                let line_count = content.lines().count().max(1);
                let file_id = ctx
                    .output_buffer
                    .store_file(format!("{path}:{jp}"), content);
                json!({
                    "file_id": file_id,
                    "path": jp,
                    "value_type": type_name,
                    "format": "json",
                    "total_lines": line_count,
                    "hint": format!(
                        "Extracted value at {jp} ({line_count} lines). \
                         read_file(\"{file_id}\", start_line=N, end_line=M) to browse, \
                         or run_command(\"grep pattern {file_id}\") to search."
                    ),
                })
            } else {
                json!({
                    "content": content,
                    "path": jp,
                    "value_type": type_name,
                    "format": "json",
                })
            };
            if let Some(c) = count {
                result["count"] = json!(c);
            }
            return Ok(result);
        }
    }

    let total_lines = text.lines().count();
    let start = optional_u64_param(input, "start_line");
    let end = optional_u64_param(input, "end_line");
    // start_line alone defaults end_line to a 50-line window — same as the real-file path.
    let end = match (start, end) {
        (Some(s), None) => Some(s.saturating_add(49)),
        (_, e) => e,
    };

    if let (Some(s), Some(e)) = (start, end) {
        if s == 0 || e < s {
            return Err(RecoverableError::with_hint(
                format!(
                    "invalid line range: start_line={} end_line={} \
                     (start_line must be >= 1 and end_line >= start_line)",
                    s, e
                ),
                "Lines are 1-indexed. Example: start_line=1, end_line=50",
            )
            .into());
        }
        let content = extract_lines(&text, s as usize, e as usize);
        if crate::tools::exceeds_inline_limit(&content) {
            let content_total = content.lines().count();
            let file_id = ctx
                .output_buffer
                .store_file(format!("{}[{}-{}]", path, s, e), content.clone());
            let (chunk, lines_shown, complete) = crate::util::text::extract_lines_to_budget(
                &content,
                1,
                usize::MAX,
                crate::tools::INLINE_BYTE_BUDGET,
            );
            let orig_start = s as usize;
            let orig_end = orig_start + lines_shown.saturating_sub(1);
            let mut result = json!({
                "content": chunk,
                "file_id": file_id,
                "total_lines": content_total,
                "shown_lines": [orig_start, orig_end],
                "complete": complete,
            });
            if !complete {
                let buf_next_start = lines_shown + 1;
                let buf_next_end = (buf_next_start + lines_shown - 1).min(content_total);
                result["next"] = json!(format!(
                    "read_file(\"{file_id}\", start_line={buf_next_start}, end_line={buf_next_end})"
                ));
            }
            return Ok(result);
        }
        return Ok(json!({ "content": content, "total_lines": total_lines }));
    }

    // Full buffer: paginate if over the inline limit. Never re-buffer.
    if crate::tools::exceeds_inline_limit(&text) {
        let (chunk, lines_shown, complete) = crate::util::text::extract_lines_to_budget(
            &text,
            1,
            usize::MAX,
            crate::tools::INLINE_BYTE_BUDGET,
        );
        let mut result = json!({
            "content": chunk,
            "total_lines": total_lines,
            "shown_lines": [1, lines_shown],
            "complete": complete,
        });
        if !complete {
            let next_start = lines_shown + 1;
            let next_end = (next_start + lines_shown - 1).min(total_lines);
            result["next"] = json!(format!(
                "read_file(\"{path}\", start_line={next_start}, end_line={next_end})"
            ));
        }
        return Ok(result);
    }
    Ok(json!({ "content": text, "total_lines": total_lines }))
}

/// Normalize native-`Read`-style `offset`/`limit` into `start_line`/`end_line`.
///
/// Claude Code's built-in `Read` takes `(offset, limit)` as a 1-indexed start line
/// plus a line count, and models reach for that signature out of habit. Mapping it
/// here — before the buffer fork in [`ReadFile::call`] — lets both the buffer and
/// real-file paths serve those calls through the normal line-range logic instead of
/// silently returning the file head (the offset/limit-silently-ignored bug).
///
/// `start_line`/`end_line` are authoritative: if either is present the aliases are
/// left untouched. `offset` maps to `start_line` (1-indexed); `limit` maps to a line
/// count so `end_line = offset + limit - 1`. With only `limit`, `offset` defaults to
/// line 1, preserving the prior "first N lines" behavior.
fn normalize_line_nav_aliases(input: &mut Value) {
    if optional_u64_param(input, "start_line").is_some()
        || optional_u64_param(input, "end_line").is_some()
    {
        return;
    }
    let offset = optional_u64_param(input, "offset");
    let limit = optional_u64_param(input, "limit");
    if offset.is_none() && limit.is_none() {
        return;
    }
    let Some(obj) = input.as_object_mut() else {
        return;
    };
    let start = offset.unwrap_or(1);
    obj.insert("start_line".to_string(), json!(start));
    if let Some(lim) = limit {
        let end = start.saturating_add(lim).saturating_sub(1);
        obj.insert("end_line".to_string(), json!(end));
    }
}

/// Validate navigation parameter combinations for real-file reads.
///
/// `start_line` alone is allowed — the caller defaults `end_line` to a 50-line
/// window. The validation only rejects mutually-exclusive combinations and the
/// (None, Some) shape (end_line without start_line is meaningless).
fn validate_read_nav_params(
    input: &Value,
    start_line: Option<u64>,
    end_line: Option<u64>,
) -> Result<()> {
    if start_line.is_none() && end_line.is_some() {
        return Err(RecoverableError::with_hint(
            "end_line provided without start_line",
            "Pass start_line (end_line defaults to start_line+49), or pass both for an explicit range.",
        )
        .into());
    }
    let json_path = input["json_path"].as_str();
    let toml_key = input["toml_key"].as_str();
    let nav_count = usize::from(json_path.is_some()) + usize::from(toml_key.is_some());
    if nav_count > 1 {
        return Err(RecoverableError::with_hint(
            "only one navigation parameter allowed at a time",
            "Use json_path OR toml_key, not both",
        )
        .into());
    }
    if nav_count > 0 && (start_line.is_some() || end_line.is_some()) {
        return Err(RecoverableError::with_hint(
            "navigation parameters are mutually exclusive with start_line/end_line",
            "Use either json_path/toml_key OR start_line+end_line",
        )
        .into());
    }
    Ok(())
}

/// Resolve the library source tag for a file (`"project"` or `"lib:<name>"`),
/// honoring the per-request workspace pin so a pinned read tags against the
/// pinned project's library registry, not the default's.
async fn compute_source_tag(resolved: &std::path::Path, ctx: &ToolContext) -> String {
    let tag = ctx
        .agent
        .with_project_at(ctx.workspace_override.as_deref(), |p| {
            Ok(p.library_registry
                .is_library_path(resolved)
                .map(|lib| format!("lib:{}", lib.name)))
        })
        .await;
    match tag {
        Ok(Some(t)) => t,
        _ => "project".to_string(),
    }
}

/// Read file contents with user-friendly error messages.
fn read_file_text(path: &str, resolved: &std::path::PathBuf) -> Result<String> {
    std::fs::read_to_string(resolved).map_err(|e| match e.kind() {
        std::io::ErrorKind::NotFound => RecoverableError::with_hint(
            format!("file not found: '{}'", path),
            "Check the path with tree, or use tree with `glob` to locate the file",
        )
        .into(),
        std::io::ErrorKind::InvalidData => RecoverableError::with_hint(
            "file contains non-UTF-8 data (binary file?)",
            "read_file only works with text files. Use tree to check file types.",
        )
        .into(),
        _ => anyhow::anyhow!("failed to read {}: {}", resolved.display(), e),
    })
}

/// Handle `json_path` navigation for JSON files.
fn read_json_path_nav(text: &str, resolved: &std::path::Path, jp: &str) -> Result<Value> {
    let file_type = crate::tools::file_summary::detect_file_type(&resolved.to_string_lossy());
    if !matches!(file_type, crate::tools::file_summary::FileSummaryType::Json) {
        return Err(RecoverableError::with_hint(
            "json_path parameter is only supported for JSON files",
            "For Markdown files use read_markdown, for TOML/YAML use toml_key",
        )
        .into());
    }
    let (content, type_name, count) = crate::tools::file_summary::extract_json_path(text, jp)?;
    let mut result = json!({
        "content": content,
        "path": jp,
        "value_type": type_name,
        "format": "json",
    });
    if let Some(c) = count {
        result["count"] = json!(c);
    }
    Ok(result)
}

/// Handle `toml_key` navigation for TOML and YAML files.
fn read_toml_yaml_key(text: &str, resolved: &std::path::Path, tk: &str) -> Result<Value> {
    let file_type = crate::tools::file_summary::detect_file_type(&resolved.to_string_lossy());
    match file_type {
        crate::tools::file_summary::FileSummaryType::Toml => {
            let result = crate::tools::file_summary::extract_toml_key(text, tk)?;
            Ok(json!({
                "content": result.content,
                "line_range": [result.line_range.0, result.line_range.1],
                "breadcrumb": result.breadcrumb,
                "siblings": result.siblings,
                "format": "toml",
            }))
        }
        crate::tools::file_summary::FileSummaryType::Yaml => {
            let result = crate::tools::file_summary::extract_yaml_key(text, tk)?;
            Ok(json!({
                "content": result.content,
                "line_range": [result.line_range.0, result.line_range.1],
                "breadcrumb": result.breadcrumb,
                "siblings": result.siblings,
                "format": "yaml",
            }))
        }
        _ => Err(RecoverableError::with_hint(
            "toml_key parameter is only supported for TOML and YAML files",
            "For Markdown files use read_markdown, for JSON use json_path",
        )
        .into()),
    }
}

/// Handle an explicit `start_line`+`end_line` range read from a real file.
#[allow(clippy::too_many_arguments)]
fn read_with_line_range(
    path: &str,
    text: &str,
    resolved: &std::path::PathBuf,
    start: u64,
    end: u64,
    source_tag: &str,
    ctx: &ToolContext,
    force: bool,
) -> Result<Value> {
    if start == 0 || end < start {
        return Err(RecoverableError::with_hint(
            format!(
                "invalid line range: start_line={} end_line={} \
                 (start_line must be >= 1 and end_line >= start_line)",
                start, end
            ),
            "Lines are 1-indexed. Example: start_line=1, end_line=50",
        )
        .into());
    }

    if !force
        && crate::tools::file_summary::detect_file_type(path)
            == crate::tools::file_summary::FileSummaryType::Source
    {
        let matches = find_symbols_for_range(text, resolved, start, end);
        if !matches.is_empty() {
            let names: Vec<_> = matches.iter().take(3).map(|s| format!("'{s}'")).collect();
            let mut label = names.join(", ");
            if matches.len() > 3 {
                label.push_str(&format!(" and {} more", matches.len() - 3));
            }
            let first = &matches[0];
            return Err(RecoverableError::with_hint(
                format!("source range overlaps named symbol(s): {label}"),
                format!(
                    "Use symbols(name='{first}', include_body=true) to read the body directly. \
                     Pass force=true to read the raw line range anyway."
                ),
            )
            .into());
        }
    }

    let content = extract_lines(text, start as usize, end as usize);
    let file_total_lines = text.lines().count();

    if content.is_empty() && (start as usize) > file_total_lines {
        return Err(RecoverableError::with_hint(
            format!(
                "line range {}-{} is past end of file ({} lines)",
                start, end, file_total_lines
            ),
            format!(
                "File has {} lines. Use a range within 1..={}.",
                file_total_lines, file_total_lines
            ),
        )
        .into());
    }

    let is_md = path.ends_with(".md") || path.ends_with(".markdown");
    let md_cov = if is_md {
        markdown_coverage(text, resolved, ctx, None, Some(start), Some(end))
    } else {
        None
    };

    // Proactive buffering: oversized extracted ranges are stored as @file_* refs
    // so callers can navigate by line number (BUG-025 class).
    if crate::tools::exceeds_inline_limit(&content) {
        let content_total = content.lines().count();
        let file_id = ctx
            .output_buffer
            .store_file(resolved.to_string_lossy().to_string(), content.clone());
        let (chunk, lines_shown, complete) = crate::util::text::extract_lines_to_budget(
            &content,
            1,
            usize::MAX,
            crate::tools::INLINE_BYTE_BUDGET,
        );
        let orig_start = start as usize;
        let orig_end = orig_start + lines_shown.saturating_sub(1);
        let mut result = json!({
            "content": chunk,
            "file_id": file_id,
            "total_lines": content_total,
            "shown_lines": [orig_start, orig_end],
            "complete": complete,
        });
        if !complete {
            let buf_next_start = lines_shown + 1;
            let buf_next_end = (buf_next_start + lines_shown - 1).min(content_total);
            result["next"] = json!(format!(
                "read_file(\"{file_id}\", start_line={buf_next_start}, end_line={buf_next_end})"
            ));
        }
        if source_tag != "project" {
            result["source"] = json!(source_tag);
        }
        if let Some(c) = md_cov {
            result["coverage"] = c;
        }
        return Ok(result);
    }

    let mut result = json!({ "content": content });
    if source_tag != "project" {
        result["source"] = json!(source_tag);
    }
    if let Some(c) = md_cov {
        result["coverage"] = c;
    }
    Ok(result)
}

/// Handle a full-file read (no range, no navigation param).
///
/// Large files are summarised and buffered. Small files are returned inline,
/// capped at `max_results` lines in exploring mode.
fn read_full_file(
    path: &str,
    text: &str,
    resolved: &std::path::PathBuf,
    input: &Value,
    source_tag: &str,
    ctx: &ToolContext,
) -> Result<Value> {
    use super::output::{OutputGuard, OutputMode, OverflowInfo};

    if crate::tools::exceeds_inline_limit(text) {
        let file_id = ctx
            .output_buffer
            .store_file(resolved.to_string_lossy().to_string(), text.to_string());
        let mut result =
            match crate::tools::file_summary::detect_file_type(&resolved.to_string_lossy()) {
                crate::tools::file_summary::FileSummaryType::Source => {
                    crate::tools::file_summary::summarize_source(&resolved.to_string_lossy(), text)
                }
                crate::tools::file_summary::FileSummaryType::Markdown => {
                    crate::tools::file_summary::summarize_markdown(text)
                }
                crate::tools::file_summary::FileSummaryType::Json => {
                    crate::tools::file_summary::summarize_json(text)
                }
                crate::tools::file_summary::FileSummaryType::Yaml => {
                    crate::tools::file_summary::summarize_yaml(text)
                }
                crate::tools::file_summary::FileSummaryType::Toml => {
                    crate::tools::file_summary::summarize_toml(text)
                }
                crate::tools::file_summary::FileSummaryType::Config => {
                    crate::tools::file_summary::summarize_config(text)
                }
                crate::tools::file_summary::FileSummaryType::Generic => {
                    crate::tools::file_summary::summarize_generic_file(text)
                }
            };
        result["file_id"] = json!(file_id);
        if path.ends_with(".md") || path.ends_with(".markdown") {
            if let Some(c) = markdown_coverage(text, resolved, ctx, None, None, None) {
                result["coverage"] = c;
            }
        }
        return Ok(result);
    }

    let is_md = path.ends_with(".md") || path.ends_with(".markdown");
    let md_cov = if is_md {
        markdown_coverage(text, resolved, ctx, None, None, None)
    } else {
        None
    };

    let guard = OutputGuard::from_input(input);
    let total_lines = text.lines().count();
    let max_lines = guard.max_results;

    if guard.mode == OutputMode::Exploring && total_lines > max_lines {
        let content = extract_lines(text, 1, max_lines);
        let overflow = OverflowInfo {
            shown: max_lines,
            total: total_lines,
            hint: if crate::tools::file_summary::detect_file_type(path)
                == crate::tools::file_summary::FileSummaryType::Source
            {
                format!(
                    "File has {} lines. For source code, prefer symbols(path) \
                     + symbols(query=..., include_body=true) to read specific functions. \
                     Or use start_line/end_line to read a specific line range.",
                    total_lines
                )
            } else {
                format!(
                    "File has {} lines. Use start_line=N, end_line=M to read a specific range.",
                    total_lines
                )
            },
            next_offset: None,
            by_file: None,
            by_file_overflow: 0,
        };
        let mut result = json!({ "content": content, "total_lines": total_lines });
        if source_tag != "project" {
            result["source"] = json!(source_tag);
        }
        result["overflow"] = OutputGuard::overflow_json(&overflow);
        if let Some(c) = md_cov {
            result["coverage"] = c;
        }
        return Ok(result);
    }

    let mut result = json!({ "content": text, "total_lines": total_lines });
    if source_tag != "project" {
        result["source"] = json!(source_tag);
    }
    if crate::tools::file_summary::detect_file_type(&resolved.to_string_lossy())
        == crate::tools::file_summary::FileSummaryType::Source
    {
        result["hint"] = json!(
            "Source file — prefer symbols(path) for overview, \
             symbols(name='...', include_body=true) for specific functions."
        );
    }
    if let Some(c) = md_cov {
        result["coverage"] = c;
    }
    Ok(result)
}

/// Record which markdown headings were covered by a read operation and return
/// an optional `coverage` JSON value to merge into the response when unread
/// sections remain.
///
/// `heading_query` – the heading param if a single-section read was requested.
/// `start_line` / `end_line` – line-range bounds (1-indexed, inclusive) if a
///   range read was requested; both `None` means the whole file was read.
pub(super) fn markdown_coverage(
    text: &str,
    resolved: &std::path::PathBuf,
    ctx: &ToolContext,
    heading_query: Option<&str>,
    start_line: Option<u64>,
    end_line: Option<u64>,
) -> Option<serde_json::Value> {
    let all_headings = crate::tools::file_summary::parse_all_headings(text);
    if all_headings.is_empty() {
        return None;
    }
    let heading_texts: Vec<String> = all_headings.iter().map(|h| h.text.clone()).collect();

    // Determine which headings were "seen" based on the read mode.
    let seen: Vec<String> = if let Some(query) = heading_query {
        // Single heading read — only that section.
        match crate::tools::file_summary::resolve_section_range(text, query) {
            Ok(range) => vec![range.heading_text],
            Err(_) => vec![],
        }
    } else if start_line.is_some() || end_line.is_some() {
        // Line-range read — mark headings whose heading line falls within range.
        let s = start_line.unwrap_or(1) as usize;
        let e = end_line.unwrap_or(usize::MAX as u64) as usize;
        all_headings
            .iter()
            .filter(|h| h.line >= s && h.line <= e)
            .map(|h| h.text.clone())
            .collect()
    } else {
        // Full file read — all headings seen.
        heading_texts.clone()
    };

    if !seen.is_empty() {
        if let Ok(mut cov) = ctx.section_coverage.lock() {
            cov.mark_seen(resolved, &seen);
        }
    }

    // Return a coverage hint only when unread sections remain.
    if let Ok(mut cov) = ctx.section_coverage.lock() {
        if let Some(status) = cov.status(resolved, &heading_texts) {
            if !status.unread.is_empty() {
                return Some(serde_json::json!({
                    "read": status.read_count,
                    "total": status.total_count,
                    "unread": status.unread,
                }));
            }
        }
    }
    None
}

pub(super) fn format_read_file(val: &Value) -> String {
    // Summary modes have a "type" key
    if let Some(file_type) = val["type"].as_str() {
        return format_read_file_summary(val, file_type);
    }

    // Auto-chunked response: shown_lines present means partial read with content.
    // Line numbers are intentionally NOT prefixed — the caller supplied the range,
    // so per-line numbers are redundant noise (and were slice-relative/wrong here
    // before). See docs/issues/2026-05-21-read-file-slice-relative-line-numbers.md.
    if val.get("shown_lines").and_then(|v| v.as_array()).is_some() {
        let total = val["total_lines"].as_u64().unwrap_or(0);
        let complete = val["complete"].as_bool().unwrap_or(true);
        let content = val["content"].as_str().unwrap_or("");
        let lines_shown = content.lines().count();

        let mut out = format!("{total} lines\n\n");
        out.push_str(content);

        if let Some(file_id) = val["file_id"].as_str() {
            out.push_str(&format!("\n\n  Buffer: {file_id}"));
        }
        if !complete {
            out.push_str(&format!("\n  [{lines_shown} of {total} lines shown]"));
            if let Some(next) = val["next"].as_str() {
                out.push_str(&format!("\n  Next: {next}"));
            }
        }
        return out;
    }

    // Old no-content buffered mode (kept for backward compat)
    if val.get("content").is_none() {
        if let Some(file_id) = val["file_id"].as_str() {
            let total = val["total_lines"].as_u64().unwrap_or(0);
            let mut out = format!("{total} lines\n\n  Buffer: {file_id}");
            if let Some(hint) = val["hint"].as_str() {
                out.push_str(&format!("\n  {hint}"));
            }
            return out;
        }
    }

    // Content mode
    let content = match val["content"].as_str() {
        Some(c) => c,
        None => return String::new(),
    };

    let total_lines = val["total_lines"]
        .as_u64()
        .unwrap_or_else(|| content.lines().count() as u64);

    if content.is_empty() {
        let mut out = "0 lines".to_string();
        if let Some(overflow) = val.get("overflow").filter(|o| o.is_object()) {
            out.push('\n');
            out.push_str(&format_overflow(overflow));
        }
        return out;
    }

    // Raw content, no per-line number prefixes (caller-supplied ranges make them
    // redundant; full-file reads can re-derive line numbers trivially).
    let line_word = if total_lines == 1 { "line" } else { "lines" };
    let mut out = format!("{total_lines} {line_word}\n\n");
    out.push_str(content);

    // Overflow
    if let Some(overflow) = val.get("overflow").filter(|o| o.is_object()) {
        out.push('\n');
        out.push_str(&format_overflow(overflow));
    }

    out
}

fn format_read_file_summary(val: &Value, file_type: &str) -> String {
    let line_count = val["line_count"].as_u64().unwrap_or(0);

    let type_label = match file_type {
        "markdown" => " (Markdown)",
        "json" => " (JSON)",
        "yaml" => " (YAML)",
        "toml" => " (TOML)",
        "config" => " (Config)",
        _ => "",
    };
    let mut out = format!("{line_count} lines{type_label}\n");

    match file_type {
        "source" => {
            if let Some(symbols) = val["symbols"].as_array() {
                if !symbols.is_empty() {
                    out.push_str("\n  Symbols:");

                    // Compute alignment widths
                    let max_kind = symbols
                        .iter()
                        .map(|s| s["kind"].as_str().unwrap_or("").len())
                        .max()
                        .unwrap_or(0);
                    let max_name = symbols
                        .iter()
                        .map(|s| s["name"].as_str().unwrap_or("").len())
                        .max()
                        .unwrap_or(0);

                    for sym in symbols {
                        let kind = sym["kind"].as_str().unwrap_or("?");
                        let name = sym["name"].as_str().unwrap_or("?");
                        let line = sym["line"].as_u64().unwrap_or(0);
                        let kind_pad = " ".repeat(max_kind - kind.len());
                        let name_pad = " ".repeat(max_name.saturating_sub(name.len()));
                        out.push_str(&format!(
                            "\n    {kind}{kind_pad}  {name}{name_pad}  L{line}"
                        ));
                    }
                }
            }
        }
        "markdown" => {
            if let Some(headings) = val["headings"].as_array() {
                if !headings.is_empty() {
                    out.push_str("\n  Headings:");
                    for h in headings {
                        let heading = h["heading"].as_str().unwrap_or("?");
                        let line = h["line"].as_u64().unwrap_or(0);
                        let end_line = h["end_line"].as_u64().unwrap_or(0);
                        let level = h["level"].as_u64().unwrap_or(1) as usize;
                        let indent = "  ".repeat(level.saturating_sub(1));
                        out.push_str(&format!("\n    {indent}{heading}  L{line}-{end_line}"));
                    }
                }
            }
        }
        "json" => {
            if let Some(schema) = val.get("schema") {
                let root_type = schema["root_type"].as_str().unwrap_or("?");
                out.push_str(&format!("\n  Root: {root_type}"));
                if let Some(keys) = schema["keys"].as_array() {
                    for k in keys {
                        let path = k["path"].as_str().unwrap_or("?");
                        let typ = k["type"].as_str().unwrap_or("?");
                        let mut desc = format!("\n    {path}: {typ}");
                        if let Some(count) = k["count"].as_u64() {
                            desc.push_str(&format!(" ({count} items)"));
                        }
                        out.push_str(&desc);
                    }
                }
                if let Some(count) = schema["count"].as_u64() {
                    out.push_str(&format!("\n    Count: {count}"));
                    if let Some(elem) = schema["element_type"].as_str() {
                        out.push_str(&format!(" (element type: {elem})"));
                    }
                }
            }
        }
        "toml" => {
            if let Some(sections) = val["sections"].as_array() {
                out.push_str("\n  Sections:");
                for s in sections {
                    let key = s["key"].as_str().unwrap_or("?");
                    let line = s["line"].as_u64().unwrap_or(0);
                    let end = s["end_line"].as_u64().unwrap_or(0);
                    out.push_str(&format!("\n    {key}  L{line}-{end}"));
                }
            }
            if let Some(keys) = val["keys"].as_array() {
                out.push_str("\n  Keys:");
                for k in keys {
                    let key = k["key"].as_str().unwrap_or("?");
                    let line = k["line"].as_u64().unwrap_or(0);
                    out.push_str(&format!("\n    {key}  L{line}"));
                }
            }
        }
        "yaml" => {
            if let Some(sections) = val["sections"].as_array() {
                out.push_str("\n  Sections:");
                for s in sections {
                    let key = s["key"].as_str().unwrap_or("?");
                    let line = s["line"].as_u64().unwrap_or(0);
                    let end = s["end_line"].as_u64().unwrap_or(0);
                    out.push_str(&format!("\n    {key}  L{line}-{end}"));
                }
            }
        }
        // Residual: .xml, .ini, .env, .lock, .cfg (JSON/YAML/TOML have dedicated branches)
        "config" => {
            if let Some(preview) = val["preview"].as_str() {
                out.push_str("\n  Preview:");
                for line in preview.lines() {
                    out.push_str(&format!("\n    {line}"));
                }
            }
        }
        "generic" => {
            if let Some(head) = val["head"].as_str() {
                out.push_str("\n  Head:");
                for line in head.lines() {
                    out.push_str(&format!("\n    {line}"));
                }
            }
            if let Some(tail) = val["tail"].as_str() {
                out.push_str("\n  Tail:");
                for line in tail.lines() {
                    out.push_str(&format!("\n    {line}"));
                }
            }
        }
        _ => {}
    }

    // Buffer reference
    if let Some(file_id) = val["file_id"].as_str() {
        out.push_str(&format!("\n\n  Buffer: {file_id}"));
    }
    if let Some(hint) = val["hint"].as_str() {
        out.push_str(&format!("\n  {hint}"));
    }

    out
}

/// Recursively flatten a symbol tree into a single Vec of references.
fn flatten_symbols<'a>(
    syms: &'a [crate::lsp::SymbolInfo],
    out: &mut Vec<&'a crate::lsp::SymbolInfo>,
) {
    for sym in syms {
        out.push(sym);
        flatten_symbols(&sym.children, out);
    }
}

/// Return the `name_path` of every symbol whose body overlaps (inclusive) the
/// read range: symbol contains range, range contains symbol, or they share a boundary.
///
/// `start` and `end` are 1-indexed (as received from tool input).
/// `SymbolInfo.start_line` / `end_line` are 0-indexed.
/// Returns an empty Vec on parse error (fail open).
fn find_symbols_for_range(
    text: &str,
    resolved: &std::path::Path,
    start: u64,
    end: u64,
) -> Vec<String> {
    let syms = match crate::ast::extract_symbols_from_text(text, resolved) {
        Ok(s) => s,
        Err(_) => return vec![],
    };
    let mut flat = Vec::new();
    flatten_symbols(&syms, &mut flat);

    let s0 = (start.saturating_sub(1)) as u32;
    let e0 = (end.saturating_sub(1)) as u32;

    flat.into_iter()
        .filter(|sym| {
            // symbol body contains read range
            (sym.start_line <= s0 && e0 <= sym.end_line)
            // read range contains symbol body
            || (s0 <= sym.start_line && sym.end_line <= e0)
        })
        .map(|sym| sym.name_path.clone())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::Agent;
    use crate::lsp::LspManager;
    use crate::tools::ToolContext;
    use serde_json::json;

    async fn test_ctx() -> ToolContext {
        ToolContext {
            agent: Agent::new(None).await.unwrap(),
            lsp: LspManager::new_arc(),
            output_buffer: std::sync::Arc::new(crate::tools::output_buffer::OutputBuffer::new(20)),
            progress: None,
            peer: None,
            section_coverage: std::sync::Arc::new(std::sync::Mutex::new(
                crate::tools::section_coverage::SectionCoverage::new(),
            )),
            guide_hints_emitted: std::sync::Arc::new(parking_lot::Mutex::new(Default::default())),
            workspace_override: None,
        }
    }
    /// Phase 3 regression (regime 3): a read tool pinned to workspace A via
    /// `ToolContext.workspace_override` must read A's files even when the
    /// session default is workspace B. Today `read_file` resolves the default
    /// project, so it reads B — this test is RED until Phase 3 wires the
    /// override into path resolution. The single mutation it catches is
    /// "ignore workspace_override," which IS the regime-3 last-writer-wins bug.
    /// Contract: pinned(A) ⇒ reads A, regardless of default B.
    #[tokio::test]
    async fn read_file_honors_workspace_override_pin() {
        use tempfile::tempdir;

        let dir_a = tempdir().unwrap();
        let dir_b = tempdir().unwrap();
        std::fs::create_dir_all(dir_a.path().join(".codescout")).unwrap();
        std::fs::create_dir_all(dir_b.path().join(".codescout")).unwrap();
        std::fs::write(dir_a.path().join("marker.txt"), "ALPHA-CONTENT").unwrap();
        std::fs::write(dir_b.path().join("marker.txt"), "BETA-CONTENT").unwrap();
        let root_a = std::fs::canonicalize(dir_a.path()).unwrap();

        // Default (unpinned) project is B.
        let agent = Agent::new(Some(dir_b.path().to_path_buf())).await.unwrap();
        let mut ctx = test_ctx().await;
        ctx.agent = agent;
        // Pin THIS request to workspace A.
        ctx.workspace_override = Some(root_a);

        let result = ReadFile
            .call(json!({ "path": "marker.txt" }), &ctx)
            .await
            .unwrap();
        let body = result.get("content").and_then(|v| v.as_str()).unwrap_or("");

        assert!(
            body.contains("ALPHA-CONTENT"),
            "pinned read should resolve workspace A (ALPHA), got: {result}"
        );
        assert!(
            !body.contains("BETA-CONTENT"),
            "pinned read must NOT leak the default workspace B (BETA), got: {result}"
        );
    }
    /// Phase 3 regression (regime 3, concurrent form): N tasks share ONE Agent,
    /// each pins a distinct workspace and reads its marker file concurrently on
    /// a multi-thread runtime. Each must read ITS OWN workspace with zero
    /// cross-bleed — proving per-request resolution survives interleaved/parallel
    /// activation, which is exactly the original last-writer-wins-on-the-global-
    /// slot bug. A shared-state regression flips this red.
    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn read_file_concurrent_pins_no_cross_workspace_bleed() {
        use tempfile::tempdir;

        const N: usize = 5;
        let mut dirs = Vec::new();
        let mut roots = Vec::new();
        for i in 0..N {
            let d = tempdir().unwrap();
            std::fs::create_dir_all(d.path().join(".codescout")).unwrap();
            std::fs::write(d.path().join("marker.txt"), format!("WS-{i}")).unwrap();
            roots.push(std::fs::canonicalize(d.path()).unwrap());
            dirs.push(d); // keep tempdirs alive for the duration
        }

        // Default (unpinned) project is workspace 0; tasks pin 0..N concurrently.
        let agent = Agent::new(Some(dirs[0].path().to_path_buf()))
            .await
            .unwrap();

        let mut handles = Vec::new();
        for (i, root_i) in roots.iter().cloned().enumerate() {
            let agent = agent.clone();
            handles.push(tokio::spawn(async move {
                let mut ctx = test_ctx().await;
                ctx.agent = agent;
                ctx.workspace_override = Some(root_i);
                let result = ReadFile
                    .call(json!({ "path": "marker.txt" }), &ctx)
                    .await
                    .unwrap();
                let body = result
                    .get("content")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                (i, body)
            }));
        }

        for h in handles {
            let (i, body) = h.await.unwrap();
            assert!(
                body.contains(&format!("WS-{i}")),
                "task {i} pinned to its own workspace must read WS-{i}, got: {body:?}"
            );
            for j in 0..N {
                if j != i {
                    assert!(
                        !body.contains(&format!("WS-{j}")),
                        "task {i} leaked workspace {j}'s content (regime-3 bleed): {body:?}"
                    );
                }
            }
        }
    }

    #[tokio::test]
    async fn read_file_buffer_midpoint_returns_content() {
        // Probe bug 2026-05-09-read-file-buffer-midpoint-empty.
        // Seed a buffer with 200 plain lines; read midpoint range.
        let lines: Vec<String> = (1..=200).map(|i| format!("line {i}")).collect();
        let content = lines.join("\n");
        let ctx = test_ctx().await;
        let buf_id = ctx.output_buffer.store_tool("cmd", content);

        let tool = ReadFile;
        let result = tool
            .call(
                json!({ "path": buf_id, "start_line": 150, "end_line": 160 }),
                &ctx,
            )
            .await
            .unwrap();

        let body = result.get("content").and_then(|v| v.as_str()).unwrap_or("");
        assert!(
            body.contains("line 150") && body.contains("line 160"),
            "buffer midpoint read should include lines 150-160, got: {body:?} from {result}"
        );
    }

    #[tokio::test]
    async fn read_file_buffer_json_path_array_element_returns_value() {
        // Probe bug 2026-05-09-read-file-json-path-array-elements.
        let content = r#"{"symbols":[{"name":"alpha","body":"fn alpha() {}"},{"name":"beta","body":"fn beta() {}"}],"context":"ok"}"#;
        let ctx = test_ctx().await;
        let buf_id = ctx.output_buffer.store_tool("symbols", content.to_string());

        let tool = ReadFile;
        let result = tool
            .call(
                json!({ "path": buf_id, "json_path": "$.symbols[0].body" }),
                &ctx,
            )
            .await
            .unwrap();

        let body = result.get("content").and_then(|v| v.as_str()).unwrap_or("");
        assert!(
            body.contains("fn alpha"),
            "json_path $.symbols[0].body should return the body string, got: {result}"
        );
    }

    #[tokio::test]
    async fn read_file_call_content_returns_line_numbered_text_not_json() {
        // Regression: small read_file results used to serialize as pretty JSON via
        // the default Tool::call_content path because ReadFile did not declare
        // OutputForm::Text. Now both axes reach format_read_file, so sub-threshold
        // reads come through as raw text. Line-number prefixes were removed
        // (docs/issues/2026-05-21-read-file-slice-relative-line-numbers.md), so the
        // content is shown verbatim with no `N| ` prefixes.
        let content = "alpha\nbeta\ngamma".to_string();
        let ctx = test_ctx().await;
        let buf_id = ctx.output_buffer.store_tool("cmd", content);

        let blocks = ReadFile
            .call_content(
                json!({ "path": buf_id, "start_line": 1, "end_line": 3 }),
                &ctx,
            )
            .await
            .unwrap();

        assert_eq!(blocks.len(), 1, "expected exactly 1 content block");
        let text = blocks[0].as_text().map(|t| t.text.as_str()).unwrap_or("");
        assert!(
            text.contains("alpha\nbeta\ngamma"),
            "expected raw text content, got: {text}"
        );
        assert!(
            !text.contains("1| ") && !text.contains("3| "),
            "line-number prefixes must be dropped, got: {text}"
        );
        assert!(
            !text.trim_start().starts_with('{'),
            "read_file output must be text, not JSON, got: {text}"
        );
    }

    #[tokio::test]
    async fn read_file_buffer_start_line_alone_defaults_50_line_window() {
        // I-6: start_line alone should default end_line to start+49 (50-line window),
        // not be silently ignored (buffer) or rejected (real file).
        let lines: Vec<String> = (1..=200).map(|i| format!("line {i}")).collect();
        let content = lines.join("\n");
        let ctx = test_ctx().await;
        let buf_id = ctx.output_buffer.store_tool("cmd", content);

        let tool = ReadFile;
        let result = tool
            .call(json!({ "path": buf_id, "start_line": 100 }), &ctx)
            .await
            .unwrap();

        let body = result.get("content").and_then(|v| v.as_str()).unwrap_or("");
        assert!(
            body.contains("line 100") && body.contains("line 149"),
            "start_line alone should yield a 50-line window 100..=149, got: {body:?}"
        );
        assert!(
            !body.contains("line 150"),
            "window should stop at start+49 (line 149), got: {body:?}"
        );
        assert!(
            !body.contains("line 99"),
            "window should start at start_line (line 100), got: {body:?}"
        );
    }
    #[test]
    fn normalize_line_nav_aliases_maps_offset_and_limit() {
        let mut input = json!({ "path": "x", "offset": 100, "limit": 50 });
        normalize_line_nav_aliases(&mut input);
        assert_eq!(input["start_line"], json!(100));
        assert_eq!(input["end_line"], json!(149));
    }

    #[test]
    fn normalize_line_nav_aliases_limit_only_defaults_offset_to_one() {
        let mut input = json!({ "path": "x", "limit": 30 });
        normalize_line_nav_aliases(&mut input);
        assert_eq!(input["start_line"], json!(1));
        assert_eq!(input["end_line"], json!(30));
    }

    #[test]
    fn normalize_line_nav_aliases_offset_only_leaves_end_line_unset() {
        let mut input = json!({ "path": "x", "offset": 42 });
        normalize_line_nav_aliases(&mut input);
        assert_eq!(input["start_line"], json!(42));
        assert!(input.get("end_line").is_none());
    }

    #[test]
    fn normalize_line_nav_aliases_explicit_start_line_wins() {
        let mut input = json!({ "path": "x", "start_line": 10, "offset": 100, "limit": 5 });
        normalize_line_nav_aliases(&mut input);
        assert_eq!(input["start_line"], json!(10));
        // The aliases must not overwrite an explicit start_line or inject an end_line.
        assert!(input.get("end_line").is_none());
    }

    #[test]
    fn normalize_line_nav_aliases_noop_without_aliases() {
        let mut input = json!({ "path": "x" });
        normalize_line_nav_aliases(&mut input);
        assert!(input.get("start_line").is_none());
        assert!(input.get("end_line").is_none());
    }

    #[tokio::test]
    async fn read_file_buffer_offset_limit_returns_slice_not_head() {
        // Regression: read_file(@buf, offset=N, limit=M) is native-Read line nav and must
        // return lines N..=N+M-1, NOT silently return the buffer head.
        let lines: Vec<String> = (1..=300).map(|i| format!("line {i}")).collect();
        let content = lines.join("\n");
        let ctx = test_ctx().await;
        let buf_id = ctx.output_buffer.store_tool("cmd", content);

        let tool = ReadFile;
        let result = tool
            .call(json!({ "path": buf_id, "offset": 100, "limit": 50 }), &ctx)
            .await
            .unwrap();

        let body = result.get("content").and_then(|v| v.as_str()).unwrap_or("");
        assert!(
            body.contains("line 100") && body.contains("line 149"),
            "offset=100 limit=50 should yield lines 100..=149, got: {body:?}"
        );
        assert!(
            !body.contains("line 99"),
            "window should start at offset (line 100), not the head, got: {body:?}"
        );
        assert!(
            !body.contains("line 150"),
            "window should stop at offset+limit-1 (line 149), got: {body:?}"
        );
    }

    #[tokio::test]
    async fn read_file_buffer_offset_string_typed_maps_to_range() {
        // MCP clients pass offset/limit as strings ("128"); optional_u64_param coerces them.
        let lines: Vec<String> = (1..=300).map(|i| format!("line {i}")).collect();
        let content = lines.join("\n");
        let ctx = test_ctx().await;
        let buf_id = ctx.output_buffer.store_tool("cmd", content);

        let tool = ReadFile;
        let result = tool
            .call(
                json!({ "path": buf_id, "offset": "200", "limit": "10" }),
                &ctx,
            )
            .await
            .unwrap();

        let body = result.get("content").and_then(|v| v.as_str()).unwrap_or("");
        assert!(
            body.contains("line 200") && body.contains("line 209"),
            "offset=\"200\" limit=\"10\" should yield lines 200..=209, got: {body:?}"
        );
        assert!(
            !body.contains("line 199") && !body.contains("line 210"),
            "string-typed offset/limit must map to the exact window, got: {body:?}"
        );
    }
}