symforge 11.20.1

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
//! Shared source-read rendering. Presentation may normalize displayed line endings;
//! the index and native exact-byte pages retain the original source bytes.
use super::source::{canonical_truncation_notice, token_truncation_footer};
use crate::live_index::{FileContentView, IndexedFile, LiveIndex, search};
/// Return raw file content, optionally sliced by 1-indexed line range.
///
/// Not-found: "File not found: {path}"
pub fn file_content(
    index: &LiveIndex,
    path: &str,
    start_line: Option<u32>,
    end_line: Option<u32>,
) -> String {
    let options = search::FileContentOptions::for_explicit_path_read(path, start_line, end_line);
    match index.capture_shared_file_for_scope(&options.path_scope) {
        Some(file) => {
            file_content_from_indexed_file_with_context(file.as_ref(), options.content_context)
        }
        None => not_found_file(path),
    }
}

pub fn file_content_from_indexed_file(
    file: &IndexedFile,
    start_line: Option<u32>,
    end_line: Option<u32>,
) -> String {
    file_content_from_indexed_file_with_context(
        file,
        search::ContentContext::line_range(start_line, end_line),
    )
}

pub fn file_content_from_indexed_file_with_context(
    file: &IndexedFile,
    context: search::ContentContext,
) -> String {
    if let Some(around_symbol) = context.around_symbol.as_deref() {
        return render_numbered_around_symbol_excerpt(
            file,
            around_symbol,
            context.symbol_line,
            context.context_lines.unwrap_or(0),
            context.max_lines,
        );
    }

    render_file_content_bytes(&file.relative_path, &file.content, context)
}

/// Compatibility renderer for `FileContentView`.
///
/// Main hot-path readers should prefer `file_content_from_indexed_file()`.
pub fn file_content_view(
    view: &FileContentView,
    start_line: Option<u32>,
    end_line: Option<u32>,
) -> String {
    render_file_content_bytes(
        &view.relative_path,
        &view.content,
        search::ContentContext::line_range(start_line, end_line),
    )
}

const DEFAULT_AROUND_LINE_CONTEXT_LINES: u32 = 2;

pub(crate) fn render_file_content_bytes(
    path: &str,
    content: &[u8],
    context: search::ContentContext,
) -> String {
    let content = String::from_utf8_lossy(content);
    let lines: Vec<&str> = content.lines().collect();
    let line_count = lines.len() as u32;

    if let Some(chunk_index) = context.chunk_index {
        let Some(max_lines) = context.max_lines else {
            return format!("{path} [error: chunked read requires max_lines parameter]");
        };
        return render_numbered_chunk_excerpt(path, &lines, chunk_index, max_lines);
    }
    if let Some(around_match) = context.around_match.as_deref() {
        return render_numbered_around_match_excerpt(
            path,
            &lines,
            around_match,
            context.match_occurrence.unwrap_or(1),
            context
                .context_lines
                .unwrap_or(DEFAULT_AROUND_LINE_CONTEXT_LINES),
        );
    }

    // Validate explicit line range against file length.
    if let Some(start) = context.start_line
        && start > line_count
    {
        return format!(
            "{path} [error: requested range (lines {start}-{}) exceeds file length ({line_count} lines)]",
            context.end_line.unwrap_or(start),
        );
    }

    if let Some(around_line) = context.around_line {
        if around_line > line_count {
            return format!(
                "{path} [error: around_line={around_line} exceeds file length ({line_count} lines)]",
            );
        }
        return render_numbered_around_line_excerpt(
            &lines,
            around_line,
            context
                .context_lines
                .unwrap_or(DEFAULT_AROUND_LINE_CONTEXT_LINES),
        );
    }

    if !context.show_line_numbers && !context.header {
        return match (context.start_line, context.end_line) {
            (None, None) => content.into_owned(),
            (start, end) => render_raw_line_slice(&lines, start, end),
        };
    }

    render_ordinary_read(
        path,
        &lines,
        context.start_line,
        context.end_line,
        context.show_line_numbers,
        context.header,
    )
}

fn render_raw_line_slice(lines: &[&str], start_line: Option<u32>, end_line: Option<u32>) -> String {
    slice_lines(lines, start_line, end_line)
        .into_iter()
        .map(|(_, line)| line)
        .collect::<Vec<_>>()
        .join("\n")
}

fn render_ordinary_read(
    path: &str,
    lines: &[&str],
    start_line: Option<u32>,
    end_line: Option<u32>,
    show_line_numbers: bool,
    header: bool,
) -> String {
    let selected = slice_lines(lines, start_line, end_line);
    let body = if show_line_numbers {
        selected
            .iter()
            .map(|(line_number, line)| format!("{line_number}: {line}"))
            .collect::<Vec<_>>()
            .join("\n")
    } else {
        selected
            .iter()
            .map(|(_, line)| *line)
            .collect::<Vec<_>>()
            .join("\n")
    };

    // FR-027: a numbered range that passes the end of the file says where the file ends.
    let body = match end_line {
        Some(end) if show_line_numbers && end as usize > lines.len() => {
            let note = format!("[range passes the end: file ends at line {}]", lines.len());
            if body.is_empty() {
                note
            } else {
                format!("{body}\n{note}")
            }
        }
        _ => body,
    };

    if !header {
        return body;
    }

    let header_line = if start_line.is_some() || end_line.is_some() {
        render_ordinary_read_header(path, &selected)
    } else {
        path.to_string()
    };

    if body.is_empty() {
        header_line
    } else {
        format!("{header_line}\n{body}")
    }
}

fn slice_lines<'a>(
    lines: &'a [&'a str],
    start_line: Option<u32>,
    end_line: Option<u32>,
) -> Vec<(u32, &'a str)> {
    let start_idx = start_line
        .map(|start| start.saturating_sub(1) as usize)
        .unwrap_or(0);
    let end_idx = end_line.map(|end| end as usize).unwrap_or(usize::MAX);

    lines
        .iter()
        .enumerate()
        .filter_map(|(idx, line)| {
            if idx >= start_idx && idx < end_idx {
                Some((idx as u32 + 1, *line))
            } else {
                None
            }
        })
        .collect()
}

fn render_ordinary_read_header(path: &str, selected: &[(u32, &str)]) -> String {
    match (selected.first(), selected.last()) {
        (Some((first, _)), Some((last, _))) => format!("{path} [lines {first}-{last}]"),
        _ => format!("{path} [lines empty]"),
    }
}

fn render_numbered_chunk_excerpt(
    path: &str,
    lines: &[&str],
    chunk_index: u32,
    max_lines: u32,
) -> String {
    let chunk_size = max_lines as usize;

    if chunk_index == 0 || chunk_size == 0 {
        return out_of_range_file_chunk(path, chunk_index, 0);
    }

    let total_chunks = lines.len().div_ceil(chunk_size);
    if total_chunks == 0 {
        return out_of_range_file_chunk(path, chunk_index, 0);
    }

    let chunk_number = chunk_index as usize;
    if chunk_number > total_chunks {
        return out_of_range_file_chunk(path, chunk_index, total_chunks);
    }

    let start_idx = (chunk_number - 1) * chunk_size;
    let end_idx = (start_idx + chunk_size).min(lines.len());
    let start_line = start_idx + 1;
    let end_line = end_idx;

    let body = lines[start_idx..end_idx]
        .iter()
        .enumerate()
        .map(|(offset, line)| format!("{}: {line}", start_line + offset))
        .collect::<Vec<_>>()
        .join("\n");

    format!(
        "{} [chunk {}/{}, lines {}-{}]\n{}",
        path, chunk_index, total_chunks, start_line, end_line, body
    )
}

fn render_numbered_around_symbol_excerpt(
    file: &IndexedFile,
    around_symbol: &str,
    symbol_line: Option<u32>,
    context_lines: u32,
    max_lines: Option<u32>,
) -> String {
    let content = String::from_utf8_lossy(&file.content);
    let lines: Vec<&str> = content.lines().collect();

    match resolve_around_symbol_range(file, around_symbol, symbol_line) {
        Ok((sym_start, sym_end)) => render_numbered_symbol_range_excerpt(
            &lines,
            sym_start,
            sym_end,
            context_lines,
            max_lines,
        ),
        Err(AroundSymbolResolutionError::NotFound) => {
            render_not_found_symbol(&file.relative_path, &file.symbols, around_symbol)
        }
        Err(AroundSymbolResolutionError::SelectorNotFound(symbol_line)) => {
            format!(
                "Symbol not found in {}: {} at line {}",
                file.relative_path, around_symbol, symbol_line
            )
        }
        Err(AroundSymbolResolutionError::Ambiguous(candidate_lines)) => {
            let candidate_lines = candidate_lines
                .iter()
                .map(u32::to_string)
                .collect::<Vec<_>>()
                .join(", ");
            format!(
                "Ambiguous symbol selector for {around_symbol} in {}; pass `symbol_line` to disambiguate. Candidates: {candidate_lines}",
                file.relative_path
            )
        }
    }
}

/// Render a numbered excerpt covering the full symbol range `sym_start..=sym_end`
/// (1-indexed inclusive), extended by `context_lines` on each side.
/// When `max_lines` is set and the total exceeds it, truncate with a hint.
fn render_numbered_symbol_range_excerpt(
    lines: &[&str],
    sym_start: u32,
    sym_end: u32,
    context_lines: u32,
    max_lines: Option<u32>,
) -> String {
    if lines.is_empty() {
        return String::new();
    }

    let total = lines.len();
    let start = (sym_start as usize)
        .saturating_sub(context_lines as usize)
        .max(1);
    let end = ((sym_end as usize).saturating_add(context_lines as usize)).min(total);

    if start > end || start > total {
        return String::new();
    }

    let full_range_len = end - start + 1;

    if let Some(ml) = max_lines {
        let ml = ml as usize;
        if ml > 0 && full_range_len > ml {
            let truncated_end = start + ml - 1;
            let mut result: Vec<String> = (start..=truncated_end)
                .map(|n| format!("{n}: {}", lines[n - 1]))
                .collect();
            let detail = format!(
                "Range is {full_range_len} lines (symbol {} + {context_lines} ctx/side), showing first {ml}.",
                sym_end.saturating_sub(sym_start) + 1
            );
            result.push(canonical_truncation_notice(
                ml as u64,
                "lines",
                Some(detail.as_str()),
            ));
            return result.join("\n");
        }
    }

    (start..=end)
        .map(|n| format!("{n}: {}", lines[n - 1]))
        .collect::<Vec<_>>()
        .join("\n")
}

#[derive(Debug, PartialEq, Eq)]
pub(crate) enum AroundSymbolResolutionError {
    NotFound,
    SelectorNotFound(u32),
    Ambiguous(Vec<u32>),
}

/// Why a content selection selects nothing from a file that exists.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ContentSelectionMiss {
    /// The selector names something the file does not hold (an
    /// `around_symbol`, `around_match`, or `match_occurrence` miss).
    NotFound,
    /// An `around_symbol` selector matches more than one symbol.
    Ambiguous,
    /// The request cannot select from this file (a line past its end, a chunk
    /// out of range, a chunk read without `max_lines`).
    Invalid,
}

/// The typed outcome of applying `context` to an existing file, decided in the
/// order the renderers apply it. MCP and the embedded host both read their
/// outcome from here, never from the rendered text. `file` is the indexed
/// record when there is one; an unindexed file has no symbols to select.
pub(crate) fn content_selection(
    file: Option<&IndexedFile>,
    content: &[u8],
    context: &search::ContentContext,
) -> Result<(), ContentSelectionMiss> {
    if let Some(name) = context.around_symbol.as_deref() {
        let Some(file) = file else {
            return Err(ContentSelectionMiss::NotFound);
        };
        return match resolve_around_symbol_range(file, name, context.symbol_line) {
            Ok(_) => Ok(()),
            Err(AroundSymbolResolutionError::Ambiguous(_)) => Err(ContentSelectionMiss::Ambiguous),
            Err(_) => Err(ContentSelectionMiss::NotFound),
        };
    }
    let text = String::from_utf8_lossy(content);
    let lines: Vec<&str> = text.lines().collect();
    let count = lines.len() as u32;
    if let Some(chunk) = context.chunk_index {
        let max_lines = context.max_lines.ok_or(ContentSelectionMiss::Invalid)?;
        if max_lines == 0 || chunk == 0 || chunk > count.div_ceil(max_lines) {
            return Err(ContentSelectionMiss::Invalid);
        }
        return Ok(());
    }
    if let Some(query) = context.around_match.as_deref() {
        let matches = find_case_insensitive_match_lines(&lines, query);
        let occurrence = context.match_occurrence.unwrap_or(1).saturating_sub(1) as usize;
        return if matches.get(occurrence).is_some() {
            Ok(())
        } else {
            Err(ContentSelectionMiss::NotFound)
        };
    }
    if context.start_line.is_some_and(|line| line > count)
        || context.around_line.is_some_and(|line| line > count)
    {
        return Err(ContentSelectionMiss::Invalid);
    }
    Ok(())
}

/// Resolve an `around_symbol` selector to the symbol's full 1-indexed line range
/// `(start_line, end_line)`.  Both bounds are inclusive.
pub(crate) fn resolve_around_symbol_range(
    file: &IndexedFile,
    around_symbol: &str,
    symbol_line: Option<u32>,
) -> Result<(u32, u32), AroundSymbolResolutionError> {
    let matching_symbols: Vec<&crate::domain::SymbolRecord> = file
        .symbols
        .iter()
        .filter(|symbol| symbol.name == around_symbol)
        .collect();

    if matching_symbols.is_empty() {
        return Err(AroundSymbolResolutionError::NotFound);
    }

    if let Some(symbol_line) = symbol_line {
        // symbol_line is 1-based (from search_symbols output); line_range is 0-based.
        let exact_matches: Vec<&crate::domain::SymbolRecord> = matching_symbols
            .iter()
            .copied()
            .filter(|symbol| symbol.line_range.0 + 1 == symbol_line)
            .collect();

        return match exact_matches.as_slice() {
            [symbol] => Ok((
                symbol.line_range.0.saturating_add(1),
                symbol.line_range.1.saturating_add(1),
            )),
            [] => Err(AroundSymbolResolutionError::SelectorNotFound(symbol_line)),
            _ => Err(AroundSymbolResolutionError::Ambiguous(
                dedup_symbol_candidate_lines(&exact_matches),
            )),
        };
    }

    match matching_symbols.as_slice() {
        [symbol] => Ok((
            symbol.line_range.0.saturating_add(1),
            symbol.line_range.1.saturating_add(1),
        )),
        _ => Err(AroundSymbolResolutionError::Ambiguous(
            dedup_symbol_candidate_lines(&matching_symbols),
        )),
    }
}

fn dedup_symbol_candidate_lines(symbols: &[&crate::domain::SymbolRecord]) -> Vec<u32> {
    let mut candidate_lines: Vec<u32> = symbols.iter().map(|symbol| symbol.line_range.0).collect();
    candidate_lines.sort_unstable();
    candidate_lines.dedup();
    candidate_lines
}

fn render_numbered_around_match_excerpt(
    path: &str,
    lines: &[&str],
    around_match: &str,
    match_occurrence: u32,
    context_lines: u32,
) -> String {
    let candidate_lines = find_case_insensitive_match_lines(lines, around_match);
    if candidate_lines.is_empty() {
        return not_found_file_match(path, around_match);
    }

    let occurrence_index = match_occurrence.saturating_sub(1) as usize;
    let Some(&around_line) = candidate_lines.get(occurrence_index) else {
        let available_lines = candidate_lines
            .iter()
            .map(u32::to_string)
            .collect::<Vec<_>>()
            .join(", ");
        return format!(
            "Match occurrence {match_occurrence} for '{around_match}' not found in {}; {} match(es) available at lines {available_lines}",
            path,
            candidate_lines.len()
        );
    };

    render_numbered_around_line_excerpt(lines, around_line, context_lines)
}

pub(crate) fn find_case_insensitive_match_lines(lines: &[&str], around_match: &str) -> Vec<u32> {
    let needle = around_match.to_lowercase();

    lines
        .iter()
        .enumerate()
        .filter_map(|(index, line)| {
            line.to_lowercase()
                .contains(&needle)
                .then_some((index + 1) as u32)
        })
        .collect()
}

fn render_numbered_around_line_excerpt(
    lines: &[&str],
    around_line: u32,
    context_lines: u32,
) -> String {
    if lines.is_empty() {
        return String::new();
    }

    let anchor = around_line.max(1) as usize;
    let context = context_lines as usize;
    let start = anchor.saturating_sub(context).max(1);
    let end = anchor.saturating_add(context).min(lines.len());

    if start > end || start > lines.len() {
        return String::new();
    }

    (start..=end)
        .map(|line_number| format!("{line_number}: {}", lines[line_number - 1]))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Hard byte cap for `get_file_content` output. Anchored to the Claude Code
/// token-optimizer hook trip point (~25K tokens). ASCII source ≈ 3–4 chars/token
/// → 60 KB ≈ 15–20K tokens (well under trip). Exposed as a const for easy tuning.
pub const GET_FILE_CONTENT_MAX_BYTES: usize = 60_000;

/// Apply the hard byte cap to `get_file_content` output.
/// Returns `output` unchanged when `output.len() <= GET_FILE_CONTENT_MAX_BYTES`.
/// Otherwise truncates at the last `\n` boundary under the cap and appends a
/// footer suggesting narrower read modes. Idempotent.
/// Append an honest NUL-byte warning to already-rendered `get_file_content`
/// output when `content` contains literal NUL (`0x00`) bytes.
///
/// Central rendering-boundary guard. NUL is valid UTF-8, so it passes
/// `String::from_utf8_lossy` untouched and then renders invisibly (terminals
/// show nothing or a space). An agent that copies the rendered text for an edit
/// gets bytes that do NOT match the file. The warning is appended AFTER the byte
/// cap so truncation can never drop it. `content` is the exact byte slice whose
/// rendering `output` represents (the full file for whole-file reads), so the
/// reported count/offsets describe what was actually scanned.
pub fn append_nul_byte_warning(output: String, content: &[u8]) -> String {
    let scan = crate::domain::index::scan_nul_bytes(content);
    match crate::domain::index::nul_byte_warning_line(&scan) {
        Some(warning) if output.is_empty() => warning,
        Some(warning) => format!("{output}\n{warning}"),
        None => output,
    }
}

/// `get_file_content`'s last steps for a rendered body, served or refused, on both lanes:
/// the hard byte cap with its continuation, the NUL-byte warning for `content`, then an
/// explicit `max_tokens`. Returns the text before the token budget, the budgeted text,
/// and whether the budget cut it.
pub fn finish_file_content(
    body: String,
    path: &str,
    first_line: u32,
    numbered: bool,
    content: &[u8],
    max_tokens: Option<u64>,
) -> (String, String, bool) {
    let capped = cap_file_content_output_for(body, path, first_line, numbered);
    let warned = append_nul_byte_warning(capped, content);
    let (budgeted, cut) = super::source::enforce_token_budget_flagged(
        warned.clone(),
        max_tokens.filter(|limit| *limit > 0),
    );
    (warned, budgeted, cut)
}

/// An `around_symbol` read of a file the index did not parse: it has no symbols.
pub fn unindexed_symbol_not_found(path: &str, name: &str) -> String {
    format!("Symbol not found in {path}: {name}")
}

pub fn cap_file_content_output(output: String) -> String {
    cap_file_content_output_for(output, "", 1, false)
}

/// [`cap_file_content_output`] for a known file: the footer states how many lines were
/// left out and gives the literal call that reads the rest (FR-026). `first_line` is the
/// 1-based line the output starts at when it carries no line numbers.
pub fn cap_file_content_output_for(
    output: String,
    path: &str,
    first_line: u32,
    numbered: bool,
) -> String {
    if output.len() <= GET_FILE_CONTENT_MAX_BYTES {
        return output;
    }
    // A leading `── mode: … ──` line is not file content: it is kept and not counted.
    let annotation_len = if output.starts_with("── mode:") {
        output.find('\n').map_or(0, |end| end + 1)
    } else {
        0
    };
    let (annotation, body) = output.split_at(annotation_len);
    let total = body.lines().count() as u32;
    let original_bytes = output.len();
    let original_tokens_est =
        crate::stel::handler::estimate_tokens_from_bytes(original_bytes as u64);
    let cap_tokens_est =
        crate::stel::handler::estimate_tokens_from_bytes(GET_FILE_CONTENT_MAX_BYTES as u64);
    let footer_for = |shown: u32, next_start: u32| {
        let next_call = if path.is_empty() {
            "use chunk_index + max_lines, around_line, around_match, or around_symbol to read a smaller window".to_string()
        } else {
            format!(
                "get_file_content(path={path:?}, start_line={next_start}, end_line={})",
                next_start + shown.saturating_sub(1)
            )
        };
        let detail = format!(
            "Original output is ~{original_tokens_est} tokens ({original_bytes} bytes), exceeding the {GET_FILE_CONTENT_MAX_BYTES}-byte cap; showing {shown} of {total} lines, {} omitted. Next: {next_call}",
            total.saturating_sub(shown)
        );
        token_truncation_footer(cap_tokens_est, Some(detail.as_str()))
    };
    // The footer is appended after the cut, so its longest form (every count at its
    // widest) is reserved first and the result stays within the cap.
    let reserve = footer_for(total, first_line.saturating_add(total)).len();
    let mut budget = GET_FILE_CONTENT_MAX_BYTES
        .saturating_sub(reserve)
        .saturating_sub(annotation.len());
    // Cut, build the real footer, and tighten the cut by any overflow until the whole
    // answer fits: the footer's size depends on the cut (counts, next line), so it is
    // measured, not assumed.
    loop {
        while budget > 0 && !body.is_char_boundary(budget) {
            budget -= 1;
        }
        let truncate_at = match body[..budget].rfind('\n') {
            Some(pos) => pos + 1, // keep the newline
            None => budget,       // no newline — truncate at char boundary
        };
        let truncated = &body[..truncate_at];
        let shown = truncated.lines().count() as u32;
        // Only a numbered rendering carries the gutter; raw content lines such as
        // `8080: x` must not be read as one.
        let last_numbered = numbered
            .then(|| {
                truncated
                    .lines()
                    .next_back()
                    .and_then(|line| line.split_once(':'))
                    .and_then(|(n, _)| n.trim().parse::<u32>().ok())
            })
            .flatten();
        let next_start = last_numbered
            .map(|n| n + 1)
            .unwrap_or_else(|| first_line + shown);
        let footer = footer_for(shown, next_start);
        let total_len = annotation.len() + truncated.len() + footer.len();
        if total_len <= GET_FILE_CONTENT_MAX_BYTES || budget == 0 {
            return format!("{annotation}{truncated}{footer}");
        }
        budget = budget
            .saturating_sub(total_len - GET_FILE_CONTENT_MAX_BYTES)
            .min(truncate_at.saturating_sub(1));
    }
}

pub fn not_found_file(path: &str) -> String {
    format!("File not found: {path}")
}

pub fn not_found_file_match(path: &str, query: &str) -> String {
    format!("No matches for '{query}' in {path}")
}

/// Richer "file not found" with suggested similar paths.
/// Call this from tool handlers where the index is available.
pub fn not_found_file_with_suggestions(path: &str, suggestions: &[String]) -> String {
    if suggestions.is_empty() {
        format!("File not found: {path}. Use search_files to find the correct path.")
    } else {
        let top: Vec<&str> = suggestions.iter().take(5).map(|s| s.as_str()).collect();
        format!("File not found: {path}. Did you mean: {}?", top.join(", "))
    }
}

/// Find up to 5 similar file paths for "file not found" suggestions.
/// Extracts the basename from the failed path and searches the index.
pub(crate) fn suggest_similar_files(
    index: &crate::live_index::LiveIndex,
    path: &str,
) -> Vec<String> {
    let basename = std::path::Path::new(path)
        .file_name()
        .and_then(|f| f.to_str())
        .unwrap_or(path);
    // Try basename match first
    let mut suggestions: Vec<String> = index
        .find_files_by_basename(basename)
        .into_iter()
        .take(5)
        .map(|s| s.to_string())
        .collect();
    // If no basename match, try the stem (without extension)
    if suggestions.is_empty() {
        let stem = std::path::Path::new(path)
            .file_stem()
            .and_then(|f| f.to_str())
            .unwrap_or(basename);
        if stem.len() >= 3 {
            let stem_lower = stem.to_ascii_lowercase();
            // `all_files` iterates a hash map: sort before taking five, so the same
            // index suggests the same paths in every process and on both lanes.
            suggestions = index
                .all_files()
                .map(|(p, _)| p.as_str())
                .filter(|p| {
                    let file_stem = std::path::Path::new(p)
                        .file_stem()
                        .and_then(|s| s.to_str())
                        .unwrap_or("");
                    file_stem.to_ascii_lowercase().contains(&stem_lower)
                })
                .map(|s| s.to_string())
                .collect();
            suggestions.sort_unstable();
            suggestions.truncate(5);
        }
    }
    suggestions
}

fn out_of_range_file_chunk(path: &str, chunk_index: u32, total_chunks: usize) -> String {
    format!("Chunk {chunk_index} out of range for {path} ({total_chunks} chunks)")
}

pub fn not_found_symbol(index: &LiveIndex, path: &str, name: &str) -> String {
    match index.capture_shared_file(path) {
        None => not_found_file(path),
        Some(file) => render_not_found_symbol(&file.relative_path, &file.symbols, name),
    }
}

pub(crate) fn render_not_found_symbol(
    relative_path: &str,
    symbols: &[crate::domain::SymbolRecord],
    name: &str,
) -> String {
    let symbol_names: Vec<String> = symbols.iter().map(|s| s.name.clone()).collect();
    not_found_symbol_names(relative_path, &symbol_names, name)
}

fn fuzzy_distance(a: &str, b: &str) -> usize {
    let a_lower = a.to_lowercase();
    let b_lower = b.to_lowercase();

    // Substring match gets highest priority (distance 0).
    if b_lower.contains(&a_lower) || a_lower.contains(&b_lower) {
        return 0;
    }

    // Prefix match gets second priority.
    let prefix_len = a_lower
        .chars()
        .zip(b_lower.chars())
        .take_while(|(x, y)| x == y)
        .count();
    if prefix_len > 0 {
        return a.len().max(b.len()) - prefix_len;
    }

    // Fall back to simple character overlap distance.
    let a_chars: std::collections::HashSet<char> = a_lower.chars().collect();
    let b_chars: std::collections::HashSet<char> = b_lower.chars().collect();
    let intersection = a_chars.intersection(&b_chars).count();
    if intersection == 0 {
        return usize::MAX;
    }
    a.len().max(b.len()) - intersection
}

pub(crate) fn not_found_symbol_names(
    relative_path: &str,
    symbol_names: &[String],
    name: &str,
) -> String {
    if symbol_names.is_empty() {
        return format!(
            "No symbol {name} in {relative_path}. \
             This file has no indexed symbols — it may use top-level statements, \
             expression-bodied code, or a syntax not extracted by the parser. \
             Use get_file_content without around_symbol to read the raw file."
        );
    }

    // Rank by fuzzy distance and take top 5.
    // Filter out very short names (1-2 chars like "i", "d") that are usually
    // loop variables and produce unhelpful suggestions.
    let min_name_len = 2.min(name.len());
    let mut scored: Vec<(&String, usize)> = symbol_names
        .iter()
        .filter(|s| s.len() >= min_name_len)
        .map(|s| (s, fuzzy_distance(name, s)))
        .collect();
    scored.sort_by_key(|(_, d)| *d);

    let close_matches: Vec<&str> = scored
        .iter()
        .take(5)
        .filter(|(_, d)| *d < usize::MAX)
        .map(|(s, _)| s.as_str())
        .collect();

    if close_matches.is_empty() {
        format!(
            "No symbol {name} in {relative_path}. No close matches found. \
             Use get_file_context with sections=['outline'] to see all {} symbols in this file.",
            symbol_names.len()
        )
    } else {
        format!(
            "No symbol {name} in {relative_path}. Close matches: {}. \
             Use get_file_context with sections=['outline'] for the full list ({} symbols).",
            close_matches.join(", "),
            symbol_names.len()
        )
    }
}

pub const COMPETENT_READ_WINDOW_LINES: u32 = 50;

const COMPETENT_READ_AVG_LINE_BYTES: usize = 80;

pub const SMALL_FILE_CHAR_THRESHOLD: usize = 200;

pub fn competent_manual_baseline_chars(raw_chars: usize) -> usize {
    if raw_chars < SMALL_FILE_CHAR_THRESHOLD {
        return raw_chars;
    }
    let window =
        (COMPETENT_READ_WINDOW_LINES as usize).saturating_mul(COMPETENT_READ_AVG_LINE_BYTES);
    raw_chars.min(window)
}

pub fn default_read_max_tokens() -> u64 {
    crate::stel::handler::estimate_tokens_from_bytes(competent_manual_baseline_chars(4000) as u64)
}

/// Retired as an output cap (feature 036 FR-024: no output budget is derived from the
/// input size); kept for the tests that pin its arithmetic.
#[cfg(test)]
pub fn resolve_read_max_tokens(explicit: Option<u64>, raw_chars: usize) -> u64 {
    match explicit {
        Some(t) if t > 0 => t,
        _ => {
            let baseline = competent_manual_baseline_chars(raw_chars);
            crate::stel::handler::estimate_tokens_from_bytes(baseline as u64).max(64)
        }
    }
}

pub fn append_dedup_hint_footer(
    output: String,
    kind: &str,
    age_secs: u64,
    approx_tokens: u32,
) -> String {
    format!(
        "{output}\n\n[session: same {kind} fetched {age_secs}s ago (~{approx_tokens} est tokens); reuse prior unless content changed]"
    )
}

pub fn validate_file_syntax_result(path: &str, file: &IndexedFile) -> String {
    let mut lines = vec![
        format!("Syntax validation: {path}"),
        format!("Language: {}", file.language),
    ];

    match &file.parse_status {
        crate::live_index::ParseStatus::Parsed => {
            lines.push("Status: ok".to_string());
        }
        crate::live_index::ParseStatus::PartialParse { warning } => {
            // SF-003: a TypeScript import-type immediately followed by `[]`
            // (e.g. `import('rxjs').Subscription[]`) is mis-parsed by
            // tree-sitter-typescript 0.23.2 even though it is valid TS. When the
            // partial parse is provably caused only by this grammar limitation,
            // report it as ok with an explanatory note rather than a syntax
            // error.
            if crate::parsing::is_expected_typescript_import_type_array_limitation(
                &file.language,
                &file.content,
                crate::domain::LanguageId::is_tsx_path(&file.relative_path),
            ) {
                lines.push("Status: ok".to_string());
                lines.push(
                    "Note: parser limitation (tree-sitter-typescript 0.23.2 mis-parses an \
                     import-type followed by `[]`; the source is valid TypeScript)"
                        .to_string(),
                );
            } else {
                lines.push("Status: partial".to_string());
                if let Some(diagnostic) = &file.parse_diagnostic {
                    lines.push(format!("Diagnostic: {}", diagnostic.summary()));
                    if let Some((start, end)) = diagnostic.byte_span {
                        lines.push(format!("Byte span: {start}..{end}"));
                    }
                } else {
                    lines.push(format!("Diagnostic: {warning}"));
                }
            }
        }
        crate::live_index::ParseStatus::Failed { error } => {
            lines.push("Status: failed".to_string());
            if let Some(diagnostic) = &file.parse_diagnostic {
                lines.push(format!("Diagnostic: {}", diagnostic.summary()));
                if let Some((start, end)) = diagnostic.byte_span {
                    lines.push(format!("Byte span: {start}..{end}"));
                }
            } else {
                lines.push(format!("Diagnostic: {error}"));
            }
        }
    }

    lines.push(format!("Symbols extracted: {}", file.symbols.len()));
    lines.join("\n")
}

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

    #[test]
    fn raw_content_applies_match_occurrence_and_chunk_selectors() {
        let bytes = b"first needle\r\nmiddle\r\nsecond needle\r\nlast\r\n";
        let mut context = search::ContentContext::line_range(None, None);
        context.around_match = Some("NEEDLE".into());
        context.match_occurrence = Some(2);
        context.context_lines = Some(0);
        assert_eq!(
            render_file_content_bytes("notes.txt", bytes, context),
            "3: second needle"
        );
        let mut context = search::ContentContext::line_range(None, None);
        context.chunk_index = Some(2);
        context.max_lines = Some(2);
        let rendered = render_file_content_bytes("notes.txt", bytes, context);
        assert!(rendered.contains("chunk 2/2, lines 3-4"));
        assert!(rendered.contains("3: second needle"));
        assert!(!rendered.contains("first needle"));
    }
}

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

    /// The footer is reserved before the cut: even with a long path the capped answer
    /// stays within the byte cap, and the annotation line is not counted as content.
    #[test]
    fn capped_output_stays_within_the_cap_and_does_not_count_the_annotation() {
        let path = format!("src/{}/file.rs", "deep".repeat(40));
        let body: String = (1..=4_000)
            .map(|n| format!("{n}: line {n} padding padding\n"))
            .collect();
        let output = format!("── mode: lines (explicit) ──\n{body}");
        let capped = cap_file_content_output_for(output, &path, 1, true);
        assert!(
            capped.len() <= GET_FILE_CONTENT_MAX_BYTES,
            "{}",
            capped.len()
        );
        assert!(capped.starts_with("── mode: lines (explicit) ──\n"));
        assert!(
            capped.contains("of 4000 lines"),
            "annotation counted: {capped}"
        );
        let shown: u32 = capped
            .split("showing ")
            .nth(1)
            .and_then(|rest| rest.split(' ').next())
            .and_then(|n| n.parse().ok())
            .expect("shown count");
        assert!(
            capped.contains(&format!("start_line={}", shown + 1)),
            "next line skips or repeats"
        );
    }

    /// Raw (unnumbered) content lines that look like a gutter must not set the next line.
    #[test]
    fn raw_lines_that_look_numbered_do_not_set_the_next_line() {
        let body: String = (0..4_000)
            .map(|n| format!("8080: raw line {n} padding padding\n"))
            .collect();
        let capped = cap_file_content_output_for(body, "src/raw.txt", 1, false);
        assert!(!capped.contains("start_line=8081"), "{capped}");
    }
}

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

    /// Delta e: numbered gutters far past `first_line + total` (an `around_line` excerpt)
    /// widen the footer; for every path length and line width the whole answer still fits.
    #[test]
    fn capped_answer_fits_the_cap_for_wide_gutters_and_long_paths() {
        for path_len in 0..48 {
            for pad in 0..24 {
                let path = format!("src/{}.rs", "p".repeat(path_len));
                let body: String = (0..8_000)
                    .map(|n| format!("{}: {}\n", 900_000 + n, "x".repeat(pad)))
                    .collect();
                let capped = cap_file_content_output_for(body, &path, 1, true);
                assert!(
                    capped.len() <= GET_FILE_CONTENT_MAX_BYTES,
                    "path_len={path_len} pad={pad}: {} bytes",
                    capped.len()
                );
            }
        }
    }
}