srcwalk 0.2.1

Tree-sitter indexed lookups — smart code reading for AI agents
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
pub mod imports;
pub mod outline;

use std::fmt::Write as _;
use std::fs;
use std::path::Path;

use memmap2::Mmap;

use crate::cache::OutlineCache;
use crate::error::SrcwalkError;
use crate::format;
use crate::lang::detect_file_type;
use crate::lang::outline::get_outline_entries as lang_get_outline_entries;
use crate::types::{estimate_tokens, FileType, OutlineEntry, ViewMode};

pub(crate) const TOKEN_THRESHOLD: u64 = 6_000;
const FILE_SIZE_CAP: u64 = 500_000; // 500KB

/// Sections exceeding this token count are degraded to an outline of the range.
/// Override with `SRCWALK_SECTION_SOFT_LIMIT` env var.
fn section_token_limit() -> u64 {
    std::env::var("SRCWALK_SECTION_SOFT_LIMIT")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(5_000)
}

/// Max file size for `full=true` reads. Files above this threshold get a
/// warning header + outline instead of raw content, preventing multi-megabyte
/// responses that cause MCP client timeouts.
/// Override with `SRCWALK_FULL_SIZE_CAP` env var (bytes). Default: 2MB.
fn full_read_size_cap() -> u64 {
    std::env::var("SRCWALK_FULL_SIZE_CAP")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(2_000_000)
}

/// Main entry point for read mode. Routes through the decision tree.
pub fn read_file(
    path: &Path,
    section: Option<&str>,
    full: bool,
    cache: &OutlineCache,
) -> Result<String, SrcwalkError> {
    let meta = match fs::metadata(path) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(SrcwalkError::NotFound {
                path: path.to_path_buf(),
                suggestion: suggest_similar(path),
            });
        }
        Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
            return Err(SrcwalkError::PermissionDenied {
                path: path.to_path_buf(),
            });
        }
        Err(e) => {
            return Err(SrcwalkError::IoError {
                path: path.to_path_buf(),
                source: e,
            });
        }
    };

    // Directory → list contents
    if meta.is_dir() {
        return list_directory(path);
    }

    let byte_len = meta.len();

    // Empty check before mmap — mmap on 0-byte file may fail on some platforms
    if byte_len == 0 {
        return Ok(format::file_header(path, 0, 0, ViewMode::Empty));
    }

    // Section param → return those lines verbatim, any size
    if let Some(range) = section {
        return read_section(path, range, cache);
    }

    // Binary detection
    let file = fs::File::open(path).map_err(|e| SrcwalkError::IoError {
        path: path.to_path_buf(),
        source: e,
    })?;
    let mmap = unsafe { Mmap::map(&file) }.map_err(|e| SrcwalkError::IoError {
        path: path.to_path_buf(),
        source: e,
    })?;
    let buf = &mmap[..];

    if crate::lang::detection::is_binary(buf) {
        let mime = mime_from_ext(path);
        return Ok(format::binary_header(path, byte_len, mime));
    }

    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");

    // Generated
    if crate::lang::detection::is_generated_by_name(name)
        || crate::lang::detection::is_generated_by_content(buf)
    {
        let line_count = memchr::memchr_iter(b'\n', buf).count() as u32 + 1;
        return Ok(format::file_header(
            path,
            byte_len,
            line_count,
            ViewMode::Generated,
        ));
    }

    let tokens = estimate_tokens(byte_len);
    let content = String::from_utf8_lossy(buf);
    let line_count = memchr::memchr_iter(b'\n', buf).count() as u32 + 1;

    // Guard: full=true on very large files. Return first-N numbered lines +
    // outline + section continue hint instead of dead-ending. This lets the
    // agent see head content immediately and paginate via `section`.
    let cap = full_read_size_cap();
    if full && byte_len > cap {
        const PROGRESSIVE_LINES: u32 = 200;
        let file_type = detect_file_type(path);
        let mtime = meta.modified().unwrap_or(std::time::SystemTime::UNIX_EPOCH);
        #[allow(clippy::cast_precision_loss)] // cap and file sizes fit in f64 mantissa for display
        let cap_mb = cap as f64 / 1_000_000.0;
        #[allow(clippy::cast_precision_loss)]
        let file_mb = byte_len as f64 / 1_000_000.0;

        // Take the first PROGRESSIVE_LINES via memchr — avoids allocating the full content split.
        let head_end = memchr::memchr_iter(b'\n', buf)
            .nth(PROGRESSIVE_LINES as usize - 1)
            .map_or(buf.len(), |p| p + 1);
        let head = String::from_utf8_lossy(&buf[..head_end]);
        let numbered_head = format::number_lines(&head, 1);

        let outline = cache.get_or_compute(path, mtime, || {
            outline::generate(path, file_type, &content, buf, true)
        });

        let header = format::file_header(path, byte_len, line_count, ViewMode::Full);
        let shown = PROGRESSIVE_LINES.min(line_count);
        let next_start = shown + 1;
        return Ok(format!(
            "{header}\n\n> **full=true capped**: file is {file_mb:.1}MB (cap: {cap_mb:.1}MB). \
             Showing first {shown} of {line_count} lines.\n\n\
             {numbered_head}\n\n## Outline\n\n{outline}\n\n> Tip: full output was capped. Continue with --section {next_start}-<end>, or set SRCWALK_FULL_SIZE_CAP={byte_len} to override."
        ));
    }

    // Full mode or small file → return full content (skip smart view)
    if full || tokens <= TOKEN_THRESHOLD {
        let header = format::file_header(path, byte_len, line_count, ViewMode::Full);
        let numbered = format::number_lines(&content, 1);
        return Ok(format!("{header}\n\n{numbered}"));
    }

    // Large file → smart view by file type
    let file_type = detect_file_type(path);
    let mtime = meta.modified().unwrap_or(std::time::SystemTime::UNIX_EPOCH);

    let capped = byte_len > FILE_SIZE_CAP;

    let outline = cache.get_or_compute(path, mtime, || {
        outline::generate(path, file_type, &content, buf, capped)
    });

    let mode = match file_type {
        FileType::StructuredData => ViewMode::Keys,
        _ => ViewMode::Outline,
    };
    let header = format::file_header(path, byte_len, line_count, mode);
    Ok(format!(
        "{header}\n\n{outline}\n\n> Tip: drill into a symbol with --section <name> or a line range"
    ))
}

/// Would this file produce an outline (rather than full content) in default read mode?
/// Used by the MCP layer to decide whether to append related-file hints.
pub fn would_outline(path: &Path) -> bool {
    std::fs::metadata(path).is_ok_and(|m| !m.is_dir() && estimate_tokens(m.len()) > TOKEN_THRESHOLD)
}

/// Wrapper around `read_file` that, for `--full` requests with `--budget`,
/// degrades gracefully instead of letting the post-hoc `budget::apply`
/// truncate body bytes mid-function and leave a misleading `[full]` header.
///
/// Cascade (when `full=true` and rendered output exceeds `budget`):
///   1. full file        → if fits, return as-is.
///   2. outline           → labelled `[outline (full requested, over budget)]` + note.
///   3. signatures only   → labelled `[signatures (...)]` + note (outline still overflows).
///   4. header + advice   → file too large at any granularity for this budget.
///
/// For `section`, non-`full`, or no-budget paths, behaves identically to `read_file`
/// (caller still applies the top-level budget cap if needed).
pub fn read_file_with_budget(
    path: &Path,
    section: Option<&str>,
    full: bool,
    budget: Option<u64>,
    cache: &OutlineCache,
) -> Result<String, SrcwalkError> {
    // Fast path: not a full-file budgeted request → defer to read_file.
    let Some(b) = budget else {
        return read_file(path, section, full, cache);
    };
    if !full || section.is_some() {
        return read_file(path, section, full, cache);
    }

    let full_out = read_file(path, section, full, cache)?;
    if estimate_tokens(full_out.len() as u64) <= b {
        return Ok(full_out);
    }

    // Step 2: outline cascade.
    let outline_out = render_outline_view(path, cache, ViewMode::OutlineCascade)?;
    let with_note = append_cascade_note(&outline_out, "full body", full_out.len(), b);
    if estimate_tokens(with_note.len() as u64) <= b {
        return Ok(with_note);
    }

    // Step 3: signatures only.
    let sig_out = render_signatures_view(path, cache)?;
    let sig_with_note = append_cascade_note(&sig_out, "outline", outline_out.len(), b);
    if estimate_tokens(sig_with_note.len() as u64) <= b {
        return Ok(sig_with_note);
    }

    // Step 4: terminal — header + advice only.
    let meta = std::fs::metadata(path).map_err(|e| SrcwalkError::IoError {
        path: path.to_path_buf(),
        source: e,
    })?;
    let line_count =
        std::fs::read(path).map_or(0, |buf| memchr::memchr_iter(b'\n', &buf).count() as u32 + 1);
    let header = format::file_header(path, meta.len(), line_count, ViewMode::Signatures);
    Ok(format!(
        "{header}\n\n> File too large for budget {b} tokens at any granularity. \
         Drill: `--section <fn-name>` or raise `--budget`."
    ))
}

fn render_outline_view(
    path: &Path,
    cache: &OutlineCache,
    mode: ViewMode,
) -> Result<String, SrcwalkError> {
    let meta = std::fs::metadata(path).map_err(|e| SrcwalkError::IoError {
        path: path.to_path_buf(),
        source: e,
    })?;
    let buf = std::fs::read(path).map_err(|e| SrcwalkError::IoError {
        path: path.to_path_buf(),
        source: e,
    })?;
    let content = String::from_utf8_lossy(&buf);
    let line_count = memchr::memchr_iter(b'\n', &buf).count() as u32 + 1;
    let file_type = detect_file_type(path);
    let mtime = meta.modified().unwrap_or(std::time::SystemTime::UNIX_EPOCH);
    let outline = cache.get_or_compute(path, mtime, || {
        outline::generate(path, file_type, &content, &buf, true)
    });
    let header = format::file_header(path, meta.len(), line_count, mode);
    Ok(format!("{header}\n\n{outline}"))
}

/// Signatures-only view: keep top-level outline lines (no nested children body).
/// Heuristic: drop indented continuation lines from the outline, preserving
/// only the first non-indented entry per block.
fn render_signatures_view(path: &Path, cache: &OutlineCache) -> Result<String, SrcwalkError> {
    let outline_full = render_outline_view(path, cache, ViewMode::Signatures)?;
    let mut lines = outline_full.lines();
    let header = lines.next().unwrap_or("");
    let mut kept: Vec<&str> = vec![header];
    for line in lines {
        // Keep blank separators and lines starting at column 0 or with one level of indent.
        if line.is_empty() {
            kept.push(line);
            continue;
        }
        let indent = line.chars().take_while(|c| *c == ' ').count();
        if indent <= 2 {
            kept.push(line);
        }
    }
    Ok(kept.join("\n"))
}

fn append_cascade_note(body: &str, prev_kind: &str, prev_bytes: usize, budget: u64) -> String {
    let prev_tokens = estimate_tokens(prev_bytes as u64);
    format!(
        "{body}\n\n> Note: {prev_kind} ({prev_tokens} tokens) exceeded budget ({budget}). \
         Drill: `--section <fn-name>` for specific symbol, or raise `--budget`."
    )
}

/// Resolve a heading address to a line range in a markdown file.
/// Returns `(start_line, end_line)` as 1-indexed inclusive range.
/// Returns `None` if heading not found.
fn resolve_heading(buf: &[u8], heading: &str) -> Option<(usize, usize)> {
    let heading_trimmed = heading.trim_end();
    let heading_level = heading_trimmed.chars().take_while(|&c| c == '#').count();

    if heading_level == 0 {
        return None;
    }

    // Build line offsets
    let mut line_offsets: Vec<usize> = vec![0];
    for pos in memchr::memchr_iter(b'\n', buf) {
        line_offsets.push(pos + 1);
    }
    // Exclude phantom empty line after trailing newline (match outline's count)
    let total_lines = if buf.last() == Some(&b'\n') {
        line_offsets.len() - 1
    } else {
        line_offsets.len()
    };

    let mut in_code_block = false;
    let mut found_line: Option<usize> = None;

    // Scan for the target heading
    for (line_idx, &offset) in line_offsets.iter().enumerate() {
        let line_end = if line_idx + 1 < line_offsets.len() {
            line_offsets[line_idx + 1] - 1 // exclude newline
        } else {
            buf.len()
        };

        if let Ok(line_str) = std::str::from_utf8(&buf[offset..line_end]) {
            let trimmed = line_str.trim_end();

            // Track code blocks
            if trimmed.starts_with("```") {
                in_code_block = !in_code_block;
                continue;
            }

            // Skip headings inside code blocks
            if in_code_block {
                continue;
            }

            // Check if this line matches the heading (exact or with anchor/attribute/ATX-close suffix)
            // Accept: "## Foo", "## Foo {#anchor}", "## Foo {:.class}", "## Foo ##", "## Foo\t"
            let matches = trimmed == heading_trimmed
                || (trimmed.starts_with(heading_trimmed)
                    && trimmed[heading_trimmed.len()..]
                        .chars()
                        .next()
                        .is_none_or(|c| matches!(c, ' ' | '\t' | '{' | '#')));
            if matches {
                found_line = Some(line_idx + 1); // 1-indexed
                break;
            }
        }
    }

    let start_line = found_line?;

    // Find the next heading of same or higher level
    in_code_block = false;
    let start_idx = start_line - 1; // convert back to 0-indexed for iteration

    for (line_idx, &offset) in line_offsets.iter().enumerate().skip(start_idx + 1) {
        let line_end = if line_idx + 1 < line_offsets.len() {
            line_offsets[line_idx + 1] - 1
        } else {
            buf.len()
        };

        if let Ok(line_str) = std::str::from_utf8(&buf[offset..line_end]) {
            let trimmed = line_str.trim_end();

            if trimmed.starts_with("```") {
                in_code_block = !in_code_block;
                continue;
            }

            if in_code_block {
                continue;
            }

            // Check if this is a heading
            if trimmed.starts_with('#') {
                let level = trimmed.chars().take_while(|&c| c == '#').count();
                if level <= heading_level {
                    // 0-based line_idx of next heading = 1-indexed line before it
                    return Some((start_line, line_idx));
                }
            }
        }
    }

    // No next heading found — section goes to end of file
    Some((start_line, total_lines))
}

/// Collect up to `top_n` headings whose text is closest (by edit distance)
/// to the queried heading. Returns headings as they appear in the file
/// (e.g. "## Foo Bar"), excluding ones inside fenced code blocks.
fn suggest_headings(buf: &[u8], query: &str, top_n: usize) -> Vec<String> {
    let q = query.trim_end();
    let q_text = q.trim_start_matches('#').trim();
    if q_text.is_empty() {
        return Vec::new();
    }

    let mut in_code_block = false;
    let mut scored: Vec<(usize, String)> = Vec::new();
    for line in buf.split(|&b| b == b'\n') {
        let Ok(s) = std::str::from_utf8(line) else {
            continue;
        };
        let trimmed = s.trim_end();
        if trimmed.starts_with("```") {
            in_code_block = !in_code_block;
            continue;
        }
        if in_code_block || !trimmed.starts_with('#') {
            continue;
        }
        let h_text = trimmed.trim_start_matches('#').trim();
        if h_text.is_empty() {
            continue;
        }
        // Strip kramdown attr / ATX-close trailing markers from comparison text.
        let h_clean = h_text
            .split('{')
            .next()
            .unwrap_or(h_text)
            .trim_end_matches('#')
            .trim();
        let dist = edit_distance(&q_text.to_ascii_lowercase(), &h_clean.to_ascii_lowercase());
        scored.push((dist, trimmed.to_string()));
    }

    scored.sort_by_key(|(d, _)| *d);
    scored.into_iter().take(top_n).map(|(_, h)| h).collect()
}

/// Read a specific line range from a file.
/// Uses memchr to find the Nth newline offset and slice the mmap buffer directly
/// instead of collecting all lines into a Vec.
fn read_section(path: &Path, range: &str, _cache: &OutlineCache) -> Result<String, SrcwalkError> {
    let file = fs::File::open(path).map_err(|e| SrcwalkError::IoError {
        path: path.to_path_buf(),
        source: e,
    })?;
    let mmap = unsafe { Mmap::map(&file) }.map_err(|e| SrcwalkError::IoError {
        path: path.to_path_buf(),
        source: e,
    })?;
    let buf = &mmap[..];

    // Resolve section address: line range, focused line, heading, or symbol name
    let mut focus_line = None;
    let (start, end) = if range.starts_with('#') {
        // Markdown heading
        resolve_heading(buf, range).ok_or_else(|| {
            let suggestions = suggest_headings(buf, range, 5);
            let reason = if suggestions.is_empty() {
                "heading not found in file".to_string()
            } else {
                format!(
                    "heading not found in file. Closest matches:\n  {}",
                    suggestions.join("\n  ")
                )
            };
            SrcwalkError::InvalidQuery {
                query: range.to_string(),
                reason,
            }
        })?
    } else if let Some((start, end, focus)) = parse_range(range) {
        // Line range like "45-89" or focused line like "45"
        focus_line = focus;
        (start, end)
    } else if let Some(r) = resolve_symbol(buf, path, range) {
        // Symbol name like "isCustomization" or "handleRequest"
        r
    } else {
        // Check for comma-separated multi-symbol request
        if range.contains(',') {
            return read_multi_symbol_section(path, buf, range);
        }
        let suggestions = suggest_symbols(buf, path, range, 3);
        let reason = if suggestions.is_empty() {
            "not a valid line number (e.g. \"45\"), line range (e.g. \"45-89\"), heading (e.g. \"## Foo\"), or symbol name in this file"
                .to_string()
        } else {
            format!("symbol not found. Closest:\n  {}", suggestions.join("\n  "))
        };
        return Err(SrcwalkError::InvalidQuery {
            query: range.to_string(),
            reason,
        });
    };

    // Find line offsets using memchr — no full-file Vec<&str> allocation
    let mut line_offsets: Vec<usize> = vec![0];
    for pos in memchr::memchr_iter(b'\n', buf) {
        line_offsets.push(pos + 1);
    }
    let total = line_offsets.len();

    let s = (start.saturating_sub(1)).min(total);
    let e = end.min(total);

    if s >= e {
        return Err(SrcwalkError::InvalidQuery {
            query: range.to_string(),
            reason: format!("range out of bounds (file has {total} lines)"),
        });
    }

    let start_byte = line_offsets[s];
    let end_byte = if e < line_offsets.len() {
        line_offsets[e]
    } else {
        buf.len()
    };

    let selected = String::from_utf8_lossy(&buf[start_byte..end_byte]);
    let byte_len = selected.len() as u64;
    let line_count = (e - s) as u32;
    let tok_est = estimate_tokens(byte_len);
    let limit = section_token_limit();

    if tok_est > limit {
        // Degrade: render outline entries within the section range
        let file_type = detect_file_type(path);
        let content = String::from_utf8_lossy(buf);
        let header = format::file_header(path, byte_len, line_count, ViewMode::SectionOutline);

        let start32 = start as u32;
        let end32 = end as u32;

        if let crate::types::FileType::Code(lang) = file_type {
            let entries = lang_get_outline_entries(&content, lang);
            let filtered = filter_entries_in_range(&entries, start32, end32);
            if !filtered.is_empty() {
                let body = format_section_outline(&filtered);
                return Ok(format!(
                    "{header}\n\n{body}\n\n\
                     > Section spans ~{tok_est} tokens (limit {limit}). Showing outline of {start}-{end}.\n\
                     > Drill: `--section <fn-name>` for a specific symbol."
                ));
            }
        }

        // Fallback: no structured outline available — return header + advice only
        return Ok(format!(
            "{header}\n\n\
             > Section spans ~{tok_est} tokens (limit {limit}).\n\
             > Drill: `--section <fn-name>` for a specific symbol, or use a narrower line range."
        ));
    }

    let header = format::file_header(path, byte_len, line_count, ViewMode::Section);
    let formatted = if let Some(focus) = focus_line {
        format_focused_lines(&selected, start as u32, focus)
    } else {
        format::number_lines(&selected, start as u32)
    };
    Ok(format!("{header}\n\n{formatted}"))
}

fn format_focused_lines(content: &str, start: u32, focus_line: usize) -> String {
    let lines: Vec<&str> = content.lines().collect();
    let last = (start as usize + lines.len()).max(1);
    let width = (last.ilog10() + 1).max(4) as usize;
    let mut out = String::with_capacity(content.len() + lines.len() * (width + 5));
    for (i, line) in lines.iter().enumerate() {
        let num = start as usize + i;
        let prefix = if num == focus_line { "" } else { "  " };
        let _ = writeln!(out, "{prefix}{num:>width$} │ {line}");
    }
    out
}

/// Resolve multiple comma-separated symbol names and return their bodies concatenated.
fn read_multi_symbol_section(path: &Path, buf: &[u8], range: &str) -> Result<String, SrcwalkError> {
    let symbols: Vec<&str> = range
        .split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .collect();
    if symbols.is_empty() {
        return Err(SrcwalkError::InvalidQuery {
            query: range.to_string(),
            reason: "empty symbol list".to_string(),
        });
    }

    let mut blocks: Vec<(usize, usize, String)> = Vec::new(); // (start, end, name)
    let mut errors: Vec<String> = Vec::new();

    for sym in &symbols {
        if let Some((start, end)) = resolve_symbol(buf, path, sym) {
            blocks.push((start, end, sym.to_string()));
        } else {
            let suggestions = suggest_symbols(buf, path, sym, 3);
            if suggestions.is_empty() {
                errors.push(format!("{sym}: not found"));
            } else {
                errors.push(format!(
                    "{sym}: not found. Closest:\n    {}",
                    suggestions.join("\n    ")
                ));
            }
        }
    }

    if !errors.is_empty() && blocks.is_empty() {
        // All symbols missed — hard error
        return Err(SrcwalkError::InvalidQuery {
            query: range.to_string(),
            reason: format!("symbols not found:\n  {}", errors.join("\n  ")),
        });
    }

    // Sort blocks by start line for natural reading order
    blocks.sort_by_key(|(start, _, _)| *start);

    // Build line offsets
    let mut line_offsets: Vec<usize> = vec![0];
    for pos in memchr::memchr_iter(b'\n', buf) {
        line_offsets.push(pos + 1);
    }
    let total = line_offsets.len();

    let mut parts: Vec<String> = Vec::new();
    let mut total_bytes: u64 = 0;
    let mut total_lines: u32 = 0;

    for (start, end, _name) in &blocks {
        let s = (start.saturating_sub(1)).min(total);
        let e = (*end).min(total);
        if s >= e {
            continue;
        }
        let start_byte = line_offsets[s];
        let end_byte = if e < line_offsets.len() {
            line_offsets[e]
        } else {
            buf.len()
        };
        let selected = String::from_utf8_lossy(&buf[start_byte..end_byte]);
        total_bytes += selected.len() as u64;
        total_lines += (e - s) as u32;
        parts.push(format::number_lines(&selected, *start as u32));
    }

    let tok_est = estimate_tokens(total_bytes);
    let limit = section_token_limit();

    if tok_est > limit {
        // Over budget — show outline-style summary instead
        let header = format::file_header(path, total_bytes, total_lines, ViewMode::SectionOutline);
        let names: Vec<&str> = blocks.iter().map(|(_, _, n)| n.as_str()).collect();
        return Ok(format!(
            "{header}\n\n\
             > {count} symbols ({names}) span ~{tok_est} tokens (limit {limit}).\n\
             > Drill: `--section <fn-name>` for one at a time.",
            count = blocks.len(),
            names = names.join(", "),
        ));
    }

    let sym_count = blocks.len();
    let header = format::file_header(path, total_bytes, total_lines, ViewMode::Section);
    let header = header.replace("[section]", &format!("[{sym_count} symbols, section]"));
    let body = parts.join("\n\n");

    if errors.is_empty() {
        Ok(format!("{header}\n\n{body}"))
    } else {
        let missing = errors.join("\n  ");
        Ok(format!(
            "{header}\n\n{body}\n\n> Missing symbols:\n>   {missing}"
        ))
    }
}

/// Filter outline entries (and children) to those overlapping [`range_start`, `range_end`].
fn filter_entries_in_range(
    entries: &[OutlineEntry],
    range_start: u32,
    range_end: u32,
) -> Vec<&OutlineEntry> {
    let mut out = Vec::new();
    for e in entries {
        // For container entries (class/struct) that span beyond the range,
        // skip the parent — we'll include matching children directly.
        if !e.children.is_empty() && (e.start_line < range_start || e.end_line > range_end) {
            // Recurse into children
            for c in &e.children {
                if c.start_line <= range_end && c.end_line >= range_start {
                    out.push(c);
                }
            }
        } else if e.start_line <= range_end && e.end_line >= range_start {
            out.push(e);
        }
    }
    out
}

/// Format filtered outline entries for section degrade output.
fn format_section_outline(entries: &[&OutlineEntry]) -> String {
    let mut lines = Vec::new();
    for e in entries {
        let range = if e.start_line == e.end_line {
            format!("[{}]", e.start_line)
        } else {
            format!("[{}-{}]", e.start_line, e.end_line)
        };
        let sig = e.signature.as_deref().unwrap_or(&e.name);
        lines.push(format!("  {range:>14}    {sig}"));
        // Show children in range
        for c in &e.children {
            let cr = if c.start_line == c.end_line {
                format!("[{}]", c.start_line)
            } else {
                format!("[{}-{}]", c.start_line, c.end_line)
            };
            let csig = c.signature.as_deref().unwrap_or(&c.name);
            lines.push(format!("    {cr:>12}    {csig}"));
        }
    }
    lines.join("\n")
}

/// Parse "45-89" or focused line "45". 1-indexed.
fn parse_range(s: &str) -> Option<(usize, usize, Option<usize>)> {
    if !s.contains('-') {
        let line: usize = s.trim().parse().ok()?;
        if line == 0 {
            return None;
        }
        return Some((line.saturating_sub(2).max(1), line + 2, Some(line)));
    }

    let (a, b) = s.split_once('-')?;
    let start: usize = a.trim().parse().ok()?;
    let end: usize = b.trim().parse().ok()?;
    if start == 0 || end < start {
        return None;
    }
    Some((start, end, None))
}

/// Resolve a symbol name to its line range using AST outline.
/// Returns (`start_line`, `end_line`) if found.
fn resolve_symbol(buf: &[u8], path: &Path, symbol: &str) -> Option<(usize, usize)> {
    let content = std::str::from_utf8(buf).ok()?;
    let FileType::Code(lang) = detect_file_type(path) else {
        return None;
    };
    let entries = lang_get_outline_entries(content, lang);
    find_symbol_in_entries(&entries, symbol)
}

/// Collect symbol names from outline entries (recursively) with their line ranges,
/// then rank by prefix match + edit distance, returning top `top_n` suggestions.
fn suggest_symbols(buf: &[u8], path: &Path, query: &str, top_n: usize) -> Vec<String> {
    let Ok(content) = std::str::from_utf8(buf) else {
        return Vec::new();
    };
    let FileType::Code(lang) = detect_file_type(path) else {
        return Vec::new();
    };
    let entries = lang_get_outline_entries(content, lang);
    let mut flat: Vec<(&str, usize, usize)> = Vec::new();
    collect_symbol_names(&entries, &mut flat);

    let q = query.to_ascii_lowercase();
    let mut scored: Vec<(usize, &str, usize, usize)> = flat
        .iter()
        .map(|&(name, start, end)| {
            let nl = name.to_ascii_lowercase();
            // Prefix match gets a big bonus (distance 0 override)
            let dist = if nl.starts_with(&q) {
                0
            } else {
                edit_distance(&q, &nl)
            };
            (dist, name, start, end)
        })
        .collect();
    scored.sort_by_key(|(d, _, _, _)| *d);
    scored
        .into_iter()
        .take(top_n)
        .map(|(_, name, start, end)| format!("{name} [{start}-{end}]"))
        .collect()
}

/// Flatten outline entries into (name, `start_line`, `end_line`) tuples.
fn collect_symbol_names<'a>(entries: &'a [OutlineEntry], out: &mut Vec<(&'a str, usize, usize)>) {
    for entry in entries {
        out.push((
            &entry.name,
            entry.start_line as usize,
            entry.end_line as usize,
        ));
        collect_symbol_names(&entry.children, out);
    }
}

/// Recursively search for a symbol in outline entries.
fn find_symbol_in_entries(entries: &[OutlineEntry], symbol: &str) -> Option<(usize, usize)> {
    for entry in entries {
        if entry.name == symbol {
            return Some((entry.start_line as usize, entry.end_line as usize));
        }
        // Search children (methods inside class, etc.)
        if let Some(range) = find_symbol_in_entries(&entry.children, symbol) {
            return Some(range);
        }
    }
    None
}

/// List directory contents — treat as glob on dir/*.
fn list_directory(path: &Path) -> Result<String, SrcwalkError> {
    let mut entries: Vec<String> = Vec::new();
    let read_dir = fs::read_dir(path).map_err(|e| SrcwalkError::IoError {
        path: path.to_path_buf(),
        source: e,
    })?;

    let mut items: Vec<_> = read_dir.filter_map(std::result::Result::ok).collect();
    items.sort_by_key(std::fs::DirEntry::file_name);

    for entry in &items {
        let ft = entry.file_type().ok();
        let name = entry.file_name();
        let name = name.to_string_lossy();
        let meta = entry.metadata().ok();

        let suffix = match ft {
            Some(t) if t.is_dir() => "/".to_string(),
            Some(t) if t.is_symlink() => "".to_string(),
            _ => match meta {
                Some(m) => {
                    let tokens = estimate_tokens(m.len());
                    format!("  ({tokens} tokens)")
                }
                None => String::new(),
            },
        };
        entries.push(format!("  {name}{suffix}"));
    }

    let header = format!("# {} ({} items)", path.display(), items.len());
    Ok(format!("{header}\n\n{}", entries.join("\n")))
}

/// Public entry point for did-you-mean on path-like fallthrough queries.
/// Resolves the query relative to scope and checks the parent directory.
pub fn suggest_similar_file(scope: &Path, query: &str) -> Option<String> {
    let resolved = scope.join(query);
    suggest_similar(&resolved)
}

/// Suggest a similar file name from the parent directory (edit distance).
fn suggest_similar(path: &Path) -> Option<String> {
    let parent = path.parent()?;
    let name = path.file_name()?.to_str()?;
    let entries = fs::read_dir(parent).ok()?;

    let mut best: Option<(usize, String)> = None;
    for entry in entries.flatten() {
        let candidate = entry.file_name();
        let candidate = candidate.to_string_lossy();
        let dist = edit_distance(name, &candidate);
        if dist <= 3 {
            match &best {
                Some((d, _)) if dist < *d => best = Some((dist, candidate.into_owned())),
                None => best = Some((dist, candidate.into_owned())),
                _ => {}
            }
        }
    }
    best.map(|(_, name)| name)
}

/// Simple Levenshtein distance — only used on short file names.
pub(crate) fn edit_distance(a: &str, b: &str) -> usize {
    let a = a.as_bytes();
    let b = b.as_bytes();
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    let mut curr = vec![0; b.len() + 1];

    for (i, &ca) in a.iter().enumerate() {
        curr[0] = i + 1;
        for (j, &cb) in b.iter().enumerate() {
            let cost = usize::from(ca != cb);
            curr[j + 1] = (prev[j] + cost).min(prev[j + 1] + 1).min(curr[j] + 1);
        }
        std::mem::swap(&mut prev, &mut curr);
    }
    prev[b.len()]
}

/// Guess MIME type from extension for binary file headers.
fn mime_from_ext(path: &Path) -> &'static str {
    match path.extension().and_then(|e| e.to_str()) {
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("svg") => "image/svg+xml",
        Some("webp") => "image/webp",
        Some("ico") => "image/x-icon",
        Some("pdf") => "application/pdf",
        Some("zip") => "application/zip",
        Some("gz" | "tgz") => "application/gzip",
        Some("tar") => "application/x-tar",
        Some("wasm") => "application/wasm",
        Some("woff" | "woff2") => "font/woff2",
        Some("ttf" | "otf") => "font/ttf",
        Some("mp3") => "audio/mpeg",
        Some("mp4") => "video/mp4",
        _ => "application/octet-stream",
    }
}

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

    #[test]
    fn heading_found() {
        let input = b"# Title\nSome content\n## Section\nSection content\n";
        let result = resolve_heading(input, "## Section");

        assert_eq!(result, Some((3, 4)));
    }

    #[test]
    fn heading_not_found() {
        let input = b"# Title\nContent\n";
        let result = resolve_heading(input, "## Missing");

        assert_eq!(result, None);
    }

    #[test]
    fn heading_in_code_block() {
        let input = b"# Real\n```\n## Fake\n```\n";
        let result = resolve_heading(input, "## Fake");

        // Heading inside code block should be skipped
        assert_eq!(result, None);
    }

    #[test]
    fn duplicate_headings() {
        let input = b"## First\ntext\n## First\ntext\n";
        let result = resolve_heading(input, "## First");

        // Should return the first occurrence
        assert_eq!(result, Some((1, 2)));
    }

    #[test]
    fn last_heading_to_eof() {
        let input = b"# Start\ntext\n## End\nfinal line\n";
        let result = resolve_heading(input, "## End");

        // Last heading should extend to total_lines (4)
        assert_eq!(result, Some((3, 4)));
    }

    #[test]
    fn nested_sections() {
        let input = b"## A\ncontent\n### B\nmore\n## C\ntext\n";
        let result = resolve_heading(input, "## A");

        // ## A should include ### B, ending when ## C starts (line 5)
        // So range is [1, 4]
        assert_eq!(result, Some((1, 4)));
    }

    #[test]
    fn no_hashes() {
        let input = b"# Heading\ntext\n";

        // Empty string
        assert_eq!(resolve_heading(input, ""), None);

        // String without hashes
        assert_eq!(resolve_heading(input, "hello"), None);
    }

    #[test]
    fn full_true_size_cap_returns_outline() {
        use std::io::Write;

        // Create a temp file larger than our small cap (100 bytes)
        let path = std::env::temp_dir().join("srcwalk_test_large.rs");
        let mut f = std::fs::File::create(&path).unwrap();
        // Write enough to exceed the cap — 200 bytes of Rust code
        for i in 0..20 {
            writeln!(f, "pub fn func_{i}() {{ println!(\"hello\"); }}").unwrap();
        }
        drop(f);

        // Set a tiny cap so the guard triggers
        std::env::set_var("SRCWALK_FULL_SIZE_CAP", "100");

        let cache = OutlineCache::new();
        let result = read_file(&path, None, true, &cache).unwrap();

        // Should contain the progressive-read warning, not the full file content
        assert!(
            result.contains("full=true capped"),
            "expected size cap warning, got: {result}"
        );
        assert!(
            result.contains("func_0"),
            "expected head/outline content in output"
        );

        std::env::remove_var("SRCWALK_FULL_SIZE_CAP");
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn budget_cascade_full_to_outline() {
        // Build a file large enough that --full would emit ~5k tokens.
        let mut body = String::from("<?php\nclass Big {\n");
        for i in 0..120 {
            body.push_str(&format!(
                "    public function method_{i}() {{\n        $x = {i}; // padding line {i}\n        return $x * 2;\n    }}\n"
            ));
        }
        body.push_str("}\n");
        let path = std::env::temp_dir().join("srcwalk_p11_cascade.php");
        std::fs::write(&path, body.as_bytes()).unwrap();

        let cache = OutlineCache::new();
        let out = read_file_with_budget(&path, None, true, Some(800), &cache).unwrap();

        // Budget honored.
        let tokens = estimate_tokens(out.len() as u64);
        assert!(tokens <= 800, "cascade overshot budget: {tokens} tokens");
        // Header relabelled, not [full].
        assert!(
            out.contains("[outline (full requested, over budget)]") || out.contains("[signatures"),
            "expected cascade header label, got: {}",
            &out[..out.len().min(200)]
        );
        // Cascade note present.
        assert!(out.contains("exceeded budget"), "missing cascade note");

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

    #[test]
    fn budget_cascade_passthrough_when_fits() {
        // Tiny file fits in budget → unchanged behavior (full content).
        let path = std::env::temp_dir().join("srcwalk_p11_tiny.php");
        std::fs::write(&path, b"<?php\nclass Tiny { public function f() {} }\n").unwrap();

        let cache = OutlineCache::new();
        let out = read_file_with_budget(&path, None, true, Some(2000), &cache).unwrap();

        assert!(
            out.contains("[full]"),
            "expected [full] label, got header in: {out}"
        );
        assert!(
            !out.contains("exceeded budget"),
            "no cascade note for fitting file"
        );

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

    // --- suggest_symbols tests ---

    #[test]
    fn suggest_symbols_prefix_match() {
        let code = b"fn collect_ranges() {}\nfn collect_names() {}\nfn parse_input() {}\n";
        let path = std::env::temp_dir().join("srcwalk_suggest_prefix.rs");
        std::fs::write(&path, code).unwrap();

        let suggestions = suggest_symbols(code, &path, "collect", 3);
        assert!(
            suggestions.len() >= 2,
            "expected at least 2 prefix matches: {suggestions:?}"
        );
        // Prefix matches should come first (distance 0)
        assert!(
            suggestions[0].starts_with("collect_"),
            "first should be prefix match: {}",
            suggestions[0]
        );
        assert!(
            suggestions[1].starts_with("collect_"),
            "second should be prefix match: {}",
            suggestions[1]
        );

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

    #[test]
    fn suggest_symbols_edit_distance_fallback() {
        let code = b"fn tag_comment_matches() {}\nfn find_symbol() {}\n";
        let path = std::env::temp_dir().join("srcwalk_suggest_edit.rs");
        std::fs::write(&path, code).unwrap();

        let suggestions = suggest_symbols(code, &path, "tag_comment", 3);
        assert!(!suggestions.is_empty(), "should have suggestions");
        assert!(
            suggestions[0].contains("tag_comment_matches"),
            "closest should be tag_comment_matches: {}",
            suggestions[0]
        );

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

    #[test]
    fn suggest_symbols_includes_line_ranges() {
        let code = b"fn alpha() {}\nfn beta() {}\n";
        let path = std::env::temp_dir().join("srcwalk_suggest_ranges.rs");
        std::fs::write(&path, code).unwrap();

        let suggestions = suggest_symbols(code, &path, "alph", 3);
        assert!(!suggestions.is_empty());
        // Format should be "name [start-end]"
        assert!(
            suggestions[0].contains('[') && suggestions[0].contains(']'),
            "should include line range: {}",
            suggestions[0]
        );

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

    #[test]
    fn suggest_symbols_empty_for_non_code() {
        let md = b"# Heading\nSome text\n";
        let path = std::env::temp_dir().join("srcwalk_suggest_md.md");
        std::fs::write(&path, md).unwrap();

        let suggestions = suggest_symbols(md, &path, "foo", 3);
        assert!(
            suggestions.is_empty(),
            "non-code file should return empty suggestions"
        );

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

    // --- symbol suggest on miss integration ---

    #[test]
    fn section_symbol_miss_shows_suggestions() {
        let code = "fn resolve_heading() {}\nfn resolve_symbol() {}\nfn resolve_range() {}\n";
        let path = std::env::temp_dir().join("srcwalk_section_miss.rs");
        std::fs::write(&path, code).unwrap();

        let cache = OutlineCache::new();
        let err = read_section(&path, "resolve_sym", &cache).unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("symbol not found. Closest:"),
            "should show suggestions: {msg}"
        );
        assert!(
            msg.contains("resolve_symbol"),
            "should suggest resolve_symbol: {msg}"
        );

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

    // --- multi-symbol section tests ---

    #[test]
    fn multi_symbol_section_returns_all_bodies() {
        let code = "fn aaa() {\n    1\n}\nfn bbb() {\n    2\n}\nfn ccc() {\n    3\n}\n";
        let path = std::env::temp_dir().join("srcwalk_multi_sym.rs");
        std::fs::write(&path, code).unwrap();

        let cache = OutlineCache::new();
        let out = read_section(&path, "aaa,ccc", &cache).unwrap();
        assert!(
            out.contains("2 symbols, section"),
            "header should show symbol count: {out}"
        );
        assert!(out.contains("aaa()"), "should contain aaa body");
        assert!(out.contains("ccc()"), "should contain ccc body");
        assert!(!out.contains("bbb()"), "should NOT contain bbb body");

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

    #[test]
    fn multi_symbol_section_sorted_by_line_order() {
        let code = "fn first() {\n    1\n}\nfn second() {\n    2\n}\n";
        let path = std::env::temp_dir().join("srcwalk_multi_order.rs");
        std::fs::write(&path, code).unwrap();

        let cache = OutlineCache::new();
        // Request in reverse order
        let out = read_section(&path, "second,first", &cache).unwrap();
        let pos_first = out.find("first()").unwrap();
        let pos_second = out.find("second()").unwrap();
        assert!(
            pos_first < pos_second,
            "should be sorted by line order, not request order"
        );

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

    #[test]
    fn multi_symbol_section_partial_miss_returns_found() {
        let code = "fn real_fn() {}\nfn other_fn() {}\n";
        let path = std::env::temp_dir().join("srcwalk_multi_miss.rs");
        std::fs::write(&path, code).unwrap();

        let cache = OutlineCache::new();
        let out = read_section(&path, "real_fn,nope_fn", &cache).unwrap();
        assert!(
            out.contains("real_fn()"),
            "should contain found symbol: {out}"
        );
        assert!(
            out.contains("Missing symbols"),
            "should note missing: {out}"
        );
        assert!(out.contains("nope_fn"), "should name missing symbol: {out}");

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

    #[test]
    fn multi_symbol_section_all_miss_errors() {
        let code = "fn real_fn() {}\n";
        let path = std::env::temp_dir().join("srcwalk_multi_all_miss.rs");
        std::fs::write(&path, code).unwrap();

        let cache = OutlineCache::new();
        let err = read_section(&path, "zzz_fake,yyy_fake", &cache).unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("symbols not found"),
            "all-miss should error: {msg}"
        );

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