Skip to main content

vtcode_core/tools/handlers/read_file/
mod.rs

1use std::collections::VecDeque;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result};
5use async_trait::async_trait;
6use serde::{Deserialize, Deserializer, Serialize};
7use serde_json::{Value, json};
8use tokio::fs::File;
9use tokio::io::BufReader;
10
11use crate::tools::file_ops::read_bounded_line;
12use crate::tools::file_ops::read_byte_range;
13
14use crate::tools::error_helpers::deserialize_tool_args;
15use crate::tools::traits::Tool;
16use crate::utils::serde_helpers::{deserialize_maybe_quoted, deserialize_opt_maybe_quoted};
17
18mod batch;
19mod lines;
20
21pub use batch::{BatchProgress, BatchReadArgs, BatchReadRequest, BatchReadResult, RangeResult};
22use lines::{condense_collected_lines, format_line, range_result_from_lines, trim_empty_lines};
23
24pub struct ReadFileHandler;
25
26const MAX_LINE_LENGTH: usize = 500;
27const TAB_WIDTH: usize = 4;
28const COMMENT_PREFIXES: &[&str] = &["#", "//", "--"];
29const MIN_BATCH_LIMIT: usize = 200;
30const DEFAULT_MAX_CONCURRENCY: usize = 8;
31const BATCH_CONDENSED_THRESHOLD: usize = 100;
32const DEFAULT_BYTE_CHUNK_SIZE: usize = 8192;
33
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub(crate) struct ReadFileOutcome {
36    pub content: String,
37    pub lines_read: usize,
38    pub has_more: bool,
39    /// True when a physical source line exceeded the bounded reader limit.
40    pub line_truncated: bool,
41    /// True when the requested line count exceeded the absolute cap and was clamped.
42    pub capped_by_limit: bool,
43    /// The line count actually applied after clamping (0 for byte-range reads).
44    pub applied_limit: usize,
45}
46
47/// JSON arguments accepted by the `read_file` tool handler.
48#[derive(Deserialize, Serialize, Clone, Debug)]
49pub struct ReadFileArgs {
50    /// Absolute path to the file that will be read.
51    #[serde(alias = "path", alias = "filepath", alias = "target_path", alias = "file")]
52    pub file_path: String,
53    /// 1-indexed line number to start reading from; defaults to 1.
54    #[serde(default = "defaults::offset", deserialize_with = "deserialize_maybe_quoted")]
55    pub offset: usize,
56    /// Maximum number of lines to return; defaults to the configured `max_read_lines` cap.
57    #[serde(default = "defaults::limit", deserialize_with = "deserialize_maybe_quoted")]
58    pub limit: usize,
59    /// Determines whether the handler reads a simple slice or indentation-aware block.
60    #[serde(default, deserialize_with = "deserialize_read_mode")]
61    pub mode: ReadMode,
62    /// Optional indentation configuration used when `mode` is `Indentation`.
63    #[serde(default, deserialize_with = "deserialize_indentation")]
64    pub indentation: Option<IndentationArgs>,
65    /// Optional token limit for response
66    #[serde(default, deserialize_with = "deserialize_opt_maybe_quoted")]
67    pub max_tokens: Option<usize>,
68    /// Whether to condense long outputs to head/tail.
69    #[serde(default = "defaults::condense", deserialize_with = "deserialize_maybe_quoted")]
70    pub condense: bool,
71    /// Byte offset (0-indexed) to start reading from. When present, enables byte-range read mode.
72    #[serde(default, deserialize_with = "deserialize_opt_maybe_quoted")]
73    pub offset_bytes: Option<u64>,
74    /// Number of bytes to read. Accepts alias `length`. When present with `offset_bytes`, enables byte-range read mode.
75    #[serde(default, alias = "length", deserialize_with = "deserialize_opt_maybe_quoted")]
76    pub page_size_bytes: Option<usize>,
77}
78
79impl ReadFileArgs {
80    /// Effective line request before the absolute cap is applied.
81    pub(crate) fn effective_line_limit(&self) -> usize {
82        if matches!(self.mode, ReadMode::Slice) && self.max_tokens.is_none() {
83            self.limit.max(MIN_BATCH_LIMIT)
84        } else {
85            self.limit
86        }
87    }
88}
89
90/// A range specification for reading.
91#[derive(Deserialize, Serialize, Clone, Debug, Default)]
92pub struct ReadRange {
93    /// 1-indexed line number to start reading from; defaults to 1.
94    #[serde(default = "defaults::offset", deserialize_with = "deserialize_maybe_quoted")]
95    pub offset: usize,
96    /// Maximum number of lines to return; defaults to 500 for batch.
97    #[serde(default = "defaults::batch_limit", deserialize_with = "deserialize_maybe_quoted")]
98    pub limit: usize,
99    /// Read mode: slice or indentation.
100    #[serde(default, deserialize_with = "deserialize_read_mode")]
101    pub mode: ReadMode,
102    /// Indentation options when mode is indentation.
103    #[serde(default, deserialize_with = "deserialize_indentation")]
104    pub indentation: Option<IndentationArgs>,
105}
106
107#[derive(Deserialize, Serialize, Clone, Debug, Default)]
108#[serde(rename_all = "snake_case")]
109pub enum ReadMode {
110    #[default]
111    Slice,
112    Indentation,
113}
114
115/// Additional configuration for indentation-aware reads.
116#[derive(Deserialize, Serialize, Clone, Debug, Default)]
117pub struct IndentationArgs {
118    /// Optional explicit anchor line; defaults to `offset` when omitted.
119    #[serde(default, deserialize_with = "deserialize_opt_maybe_quoted")]
120    pub anchor_line: Option<usize>,
121    /// Maximum indentation depth to collect; `0` means unlimited.
122    #[serde(default = "defaults::max_levels", deserialize_with = "deserialize_maybe_quoted")]
123    pub max_levels: usize,
124    /// Whether to include sibling blocks at the same indentation level.
125    #[serde(default = "defaults::include_siblings")]
126    pub include_siblings: bool,
127    /// Whether to include header lines above the anchor block.
128    #[serde(default = "defaults::include_header")]
129    pub include_header: bool,
130    /// Optional hard cap on returned lines; defaults to the global `limit`.
131    #[serde(default, deserialize_with = "deserialize_opt_maybe_quoted")]
132    pub max_lines: Option<usize>,
133}
134
135fn deserialize_read_mode<'de, D>(deserializer: D) -> Result<ReadMode, D::Error>
136where
137    D: Deserializer<'de>,
138{
139    let value = Value::deserialize(deserializer)?;
140    match value {
141        Value::Null => Ok(ReadMode::Slice),
142        Value::String(raw) => {
143            let trimmed = raw.trim();
144            if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("slice") {
145                Ok(ReadMode::Slice)
146            } else if trimmed.eq_ignore_ascii_case("indentation") {
147                Ok(ReadMode::Indentation)
148            } else {
149                Err(serde::de::Error::custom(format!("invalid read mode: {trimmed}")))
150            }
151        }
152        other => Err(serde::de::Error::custom(format!("invalid read mode type: {other}"))),
153    }
154}
155
156fn deserialize_indentation<'de, D>(deserializer: D) -> Result<Option<IndentationArgs>, D::Error>
157where
158    D: Deserializer<'de>,
159{
160    let value = Value::deserialize(deserializer)?;
161    match value {
162        Value::Null => Ok(None),
163        Value::Bool(true) => Ok(Some(IndentationArgs::default())),
164        Value::Bool(false) => Ok(None),
165        Value::String(raw) => {
166            let trimmed = raw.trim();
167            if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("false") {
168                Ok(None)
169            } else if trimmed.eq_ignore_ascii_case("true") {
170                Ok(Some(IndentationArgs::default()))
171            } else {
172                Err(serde::de::Error::custom(format!("invalid indentation value: {trimmed}")))
173            }
174        }
175        Value::Object(_) => {
176            let args = IndentationArgs::deserialize(value).map_err(serde::de::Error::custom)?;
177            Ok(Some(args))
178        }
179        other => Err(serde::de::Error::custom(format!("invalid indentation type: {other}"))),
180    }
181}
182
183#[derive(Clone, Debug)]
184struct LineRecord {
185    number: usize,
186    raw: String,
187    display: String,
188    indent: usize,
189}
190
191impl LineRecord {
192    fn trimmed(&self) -> &str {
193        self.raw.trim_start()
194    }
195
196    fn is_blank(&self) -> bool {
197        self.trimmed().is_empty()
198    }
199
200    fn is_comment(&self) -> bool {
201        COMMENT_PREFIXES.iter().any(|prefix| self.raw.trim().starts_with(prefix))
202    }
203}
204
205impl ReadFileHandler {
206    /// Execute a batch read of multiple files/ranges in parallel.
207    pub async fn handle_batch(&self, args: BatchReadArgs) -> Result<Value> {
208        batch::execute(self, args).await
209    }
210
211    /// Read a single range from a file.
212    async fn read_range(&self, path: &Path, range: &ReadRange) -> Result<RangeResult> {
213        let offset = range.offset.max(1);
214        let limit = Self::effective_line_limit(range.limit);
215
216        let (collected, line_truncated) = match range.mode {
217            ReadMode::Slice => {
218                let result = slice::read(path, offset, limit).await?;
219                (result.lines, result.line_truncated)
220            }
221            ReadMode::Indentation => {
222                let indentation = range.indentation.clone().unwrap_or_default();
223                let result = indentation::read_block(path, offset, limit, indentation).await?;
224                (result.lines, result.line_truncated)
225            }
226        };
227
228        Ok(range_result_from_lines(offset, collected, line_truncated))
229    }
230
231    /// Clamp a requested line count to the absolute per-call ceiling.
232    ///
233    /// Returns `(applied_limit, capped_by_limit)`. `capped_by_limit` is true
234    /// only when the caller asked for strictly more lines than `absolute_max`
235    /// permits, so a read whose `requested == absolute_max` is *not* flagged as
236    /// clamped (it merely sits at the ceiling). This keeps the pagination chain
237    /// alive on every page that reaches the ceiling without misreporting a
238    /// clamp on the exact-cap follow-up pages.
239    fn clamp_to_absolute_cap(requested: usize, absolute_max: usize) -> (usize, bool) {
240        let capped = requested > absolute_max;
241        (requested.min(absolute_max), capped)
242    }
243
244    fn effective_line_limit(requested: usize) -> usize {
245        let absolute_max = crate::tools::read_limits::absolute_line_cap();
246        Self::clamp_to_absolute_cap(requested.max(1), absolute_max).0
247    }
248
249    pub(crate) async fn handle_detailed(&self, args: ReadFileArgs) -> Result<ReadFileOutcome> {
250        let effective_limit = args.effective_line_limit();
251        let ReadFileArgs {
252            file_path,
253            offset,
254            limit,
255            mode,
256            indentation,
257            max_tokens: _,
258            condense,
259            offset_bytes,
260            page_size_bytes,
261        } = args;
262
263        let path = PathBuf::from(&file_path);
264        anyhow::ensure!(path.is_absolute(), "file_path must be an absolute path");
265
266        // Byte-range read path: when offset_bytes or page_size_bytes is present
267        if offset_bytes.is_some() || page_size_bytes.is_some() {
268            let byte_offset = offset_bytes.unwrap_or(0);
269            let byte_length = page_size_bytes.unwrap_or(DEFAULT_BYTE_CHUNK_SIZE);
270            anyhow::ensure!(byte_length > 0, "page_size_bytes must be greater than 0");
271            return self.read_byte_range(&path, byte_offset, byte_length).await;
272        }
273
274        anyhow::ensure!(offset > 0, "offset must be a 1-indexed line number");
275        anyhow::ensure!(limit > 0, "limit must be greater than zero");
276
277        let absolute_max = crate::tools::read_limits::absolute_line_cap();
278
279        // Absolute hard cap: no single line-based read may return more than
280        // `absolute_max` lines, even when the caller requests a larger `limit`.
281        // Byte-range reads are unaffected (they use `page_size_bytes`).
282        let (applied_limit, capped_by_limit) = Self::clamp_to_absolute_cap(effective_limit, absolute_max);
283
284        let (mut collected, has_more, line_truncated) = match mode {
285            ReadMode::Slice => {
286                let result = slice::read(&path, offset, applied_limit).await?;
287                (result.lines, result.has_more, result.line_truncated)
288            }
289            ReadMode::Indentation => {
290                let indentation = indentation.unwrap_or_default();
291                let result = indentation::read_block(&path, offset, applied_limit, indentation).await?;
292                (result.lines, false, result.line_truncated)
293            }
294        };
295        let lines_read = collected.len();
296
297        if condense {
298            // Skip condensation for paginated reads (caller advanced past
299            // line 1). When the caller passes an explicit offset > 1, they are
300            // following an omit-hint to retrieve a specific slice. Re-condensing
301            // that slice would produce another omit-hint, trapping the agent
302            // in an infinite pagination regress (checkpoint turn_613).
303            if offset <= 1 {
304                condense_collected_lines(&mut collected);
305            }
306        }
307
308        Ok(ReadFileOutcome {
309            content: collected.join("\n"),
310            lines_read,
311            has_more,
312            line_truncated,
313            capped_by_limit,
314            applied_limit,
315        })
316    }
317
318    /// Read a byte range from a file using seek-based access.
319    ///
320    /// Delegates to the shared `read_byte_range` function in `file_ops`.
321    /// Returns content with line numbers prefixed (e.g., "42: content").
322    async fn read_byte_range(
323        &self,
324        file_path: &Path,
325        offset_bytes: u64,
326        page_size_bytes: usize,
327    ) -> Result<ReadFileOutcome> {
328        let result = read_byte_range(file_path, offset_bytes, page_size_bytes, true).await?;
329        Ok(ReadFileOutcome {
330            content: result.content,
331            lines_read: result.lines_read,
332            has_more: result.has_more,
333            line_truncated: false,
334            capped_by_limit: false,
335            applied_limit: 0,
336        })
337    }
338
339    /// Legacy handle method for backward compatibility with file_ops.rs
340    pub async fn handle(&self, args: ReadFileArgs) -> Result<String> {
341        Ok(self.handle_detailed(args).await?.content)
342    }
343}
344
345#[async_trait]
346impl Tool for ReadFileHandler {
347    async fn execute(&self, args: Value) -> Result<Value> {
348        // Try batch mode first (has "reads" field)
349        if args.get("reads").is_some() {
350            let batch_args: BatchReadArgs = deserialize_tool_args(&args, "read_file")?;
351            return self.handle_batch(batch_args).await;
352        }
353
354        // Legacy single-file mode
355        let args: ReadFileArgs = deserialize_tool_args(&args, "read_file")?;
356
357        let file_path = args.file_path.clone();
358        let outcome = self.handle_detailed(args).await?;
359
360        let mut response = json!({
361            "content": outcome.content,
362            "file_path": file_path,
363            "path": file_path,
364            "success": true,
365            "no_spool": true
366        });
367
368        if outcome.has_more {
369            response["has_more"] = json!(true);
370        }
371        if outcome.line_truncated {
372            response["line_truncated"] = json!(true);
373            response["truncated"] = json!(true);
374            response["truncation_reason"] = json!("oversized_line");
375        }
376
377        Ok(response)
378    }
379
380    fn name(&self) -> &str {
381        "read_file"
382    }
383
384    fn description(&self) -> &str {
385        "Read file contents with optional line range, indentation-aware block selection, or batch multiple files"
386    }
387
388    fn parameter_schema(&self) -> Option<Value> {
389        Some(json!({
390            "type": "object",
391            "properties": {
392                "file_path": {
393                    "type": "string",
394                    "description": "Absolute path to the file to read (for single-file mode)"
395                },
396                "offset": {
397                    "type": "integer",
398                    "description": "1-indexed line number to start from (default: 1)",
399                    "default": 1,
400                    "minimum": 1
401                },
402                "limit": {
403                    "type": "integer",
404                    "description": "Maximum lines to return. Requests above the configurable absolute cap (`max_read_lines`) are clamped, and the response carries `next_read_args` to continue reading.",
405                    "default": crate::tools::read_limits::read_limit_lines(),
406                    "minimum": 1
407                },
408                "mode": {
409                    "type": "string",
410                    "enum": ["slice", "indentation"],
411                    "description": "Read mode: slice for simple range, indentation for block",
412                    "default": "slice"
413                },
414                "indentation": {
415                    "description": "Indentation settings when mode=indentation",
416                    "anyOf": [
417                        {"type": "boolean"},
418                        {
419                            "type": "object",
420                            "properties": {
421                                "anchor_line": {
422                                    "type": "integer",
423                                    "description": "Line number to anchor on (defaults to offset)"
424                                },
425                                "max_levels": {
426                                    "type": "integer",
427                                    "description": "Max indentation depth (0=unlimited)",
428                                    "default": 0
429                                },
430                                "include_siblings": {
431                                    "type": "boolean",
432                                    "description": "Include sibling blocks",
433                                    "default": false
434                                },
435                                "include_header": {
436                                    "type": "boolean",
437                                    "description": "Include header lines above anchor",
438                                    "default": true
439                                },
440                                "max_lines": {
441                                    "type": "integer",
442                                    "description": "Hard cap on returned lines"
443                                }
444                            }
445                        }
446                    ]
447                },
448                "max_tokens": {
449                    "type": "integer",
450                    "description": "Optional token limit for response (approximate)"
451                },
452                "condense": {
453                    "type": "boolean",
454                    "description": "Condense long outputs to head/tail (default: true)",
455                    "default": true
456                },
457                "offset_bytes": {
458                    "type": "integer",
459                    "description": "Byte offset (0-indexed) to start reading from. Enables byte-range read mode.",
460                    "minimum": 0
461                },
462                "page_size_bytes": {
463                    "type": "integer",
464                    "description": "Number of bytes to read. Accepts alias `length`. Default: 8192.",
465                    "alias": "length",
466                    "minimum": 1
467                },
468                "reads": {
469                    "type": "array",
470                    "description": "Batch mode: array of file read requests to execute in parallel",
471                    "items": {
472                        "type": "object",
473                        "properties": {
474                            "file_path": {
475                                "type": "string",
476                                "description": "Absolute path to the file"
477                            },
478                            "offset": {
479                                "type": "integer",
480                                "description": "1-indexed start line (default: 1)"
481                            },
482                            "limit": {
483                                "type": "integer",
484                                "description": "Max lines to return (default: 500 for batch)"
485                            },
486                            "ranges": {
487                                "type": "array",
488                                "description": "Multiple ranges from the same file",
489                                "items": {
490                                    "type": "object",
491                                    "properties": {
492                                        "offset": { "type": "integer" },
493                                        "limit": { "type": "integer" },
494                                        "mode": { "type": "string", "enum": ["slice", "indentation"] }
495                                    }
496                                }
497                            }
498                        },
499                        "required": ["file_path"]
500                    }
501                },
502                "max_concurrency": {
503                    "type": "integer",
504                    "description": "Batch mode: max concurrent file reads (default: 8)",
505                    "default": 8
506                }
507            }
508        }))
509    }
510}
511
512mod slice {
513    use super::*;
514
515    #[derive(Clone, Debug, PartialEq, Eq)]
516    pub(super) struct SliceReadResult {
517        pub lines: Vec<String>,
518        pub has_more: bool,
519        pub line_truncated: bool,
520    }
521
522    pub(super) struct SliceReadRanges {
523        pub results: Vec<Option<Result<SliceReadResult>>>,
524        pub error: Option<anyhow::Error>,
525    }
526
527    pub async fn read(path: &Path, offset: usize, limit: usize) -> Result<SliceReadResult> {
528        let file = File::open(path)
529            .await
530            .context(format!("failed to open file: {}", path.display()))?;
531
532        let mut reader = BufReader::new(file);
533        let mut collected = Vec::new();
534        let mut seen = 0usize;
535        let mut buffer = Vec::new();
536        let mut reached_eof = false;
537        let mut line_truncated = false;
538
539        loop {
540            let Some((line, truncated)) = read_formatted_line(&mut reader, &mut buffer).await? else {
541                reached_eof = true;
542                break;
543            };
544
545            seen = seen.saturating_add(1);
546
547            if seen < offset {
548                continue;
549            }
550
551            if collected.len() >= limit {
552                break;
553            }
554
555            collected.push(line);
556            // Only lines actually returned may set this flag: the skipped
557            // prefix and the lookahead line are not part of the result.
558            line_truncated |= truncated;
559        }
560
561        // A successful empty read is necessary to inspect an existing empty
562        // file before its first edit. Higher offsets remain out of bounds.
563        if seen < offset && !(seen == 0 && offset == 1) {
564            anyhow::bail!("offset exceeds file length");
565        }
566
567        Ok(SliceReadResult {
568            lines: collected,
569            has_more: !reached_eof,
570            line_truncated,
571        })
572    }
573
574    pub(super) async fn read_ranges(path: &Path, ranges: &[ReadRange]) -> Result<SliceReadRanges> {
575        let file = File::open(path)
576            .await
577            .context(format!("failed to open file: {}", path.display()))?;
578
579        let normalized_ranges: Vec<(usize, usize)> = ranges
580            .iter()
581            .map(|range| {
582                let offset = range.offset.max(1);
583                let limit = ReadFileHandler::effective_line_limit(range.limit);
584                (offset, offset.saturating_add(limit.saturating_sub(1)))
585            })
586            .collect();
587        let max_line = normalized_ranges.iter().map(|(_, end)| *end).max().unwrap_or(0);
588        let mut collected: Vec<Vec<String>> = normalized_ranges.iter().map(|_| Vec::new()).collect();
589        // Truncation is per range: a long line belongs to exactly the ranges
590        // that returned it, never to sibling ranges in the same batch.
591        let mut truncated_in_range = vec![false; normalized_ranges.len()];
592        let mut reader = BufReader::new(file);
593        let mut buffer = Vec::new();
594        let mut line_number = 0usize;
595        let mut has_lookahead = false;
596        let mut scan_error = None;
597
598        while line_number < max_line {
599            match read_formatted_line(&mut reader, &mut buffer).await {
600                Ok(Some((line, truncated))) => {
601                    line_number += 1;
602                    for (index, (offset, end)) in normalized_ranges.iter().enumerate() {
603                        if (*offset..=*end).contains(&line_number) {
604                            collected[index].push(line.clone());
605                            truncated_in_range[index] |= truncated;
606                        }
607                    }
608                }
609                Ok(None) => break,
610                Err(error) => {
611                    scan_error = Some(error);
612                    break;
613                }
614            }
615        }
616
617        if scan_error.is_none() && line_number == max_line {
618            // The lookahead line decides `has_more` but is never returned, so
619            // its truncation must not leak into any range's result.
620            match read_formatted_line(&mut reader, &mut buffer).await {
621                Ok(Some(_)) => has_lookahead = true,
622                Ok(None) => {}
623                Err(error) => scan_error = Some(error),
624            }
625        }
626
627        let results = normalized_ranges
628            .into_iter()
629            .zip(collected)
630            .zip(truncated_in_range)
631            .map(|(((offset, end), lines), line_truncated)| {
632                if line_number < offset && !(line_number == 0 && offset == 1) {
633                    scan_error
634                        .is_none()
635                        .then_some(Err(anyhow::anyhow!("offset exceeds file length")))
636                } else if scan_error.is_some() && line_number < end {
637                    None
638                } else {
639                    Some(Ok(SliceReadResult {
640                        lines,
641                        has_more: line_number > end || (line_number == end && has_lookahead),
642                        line_truncated,
643                    }))
644                }
645            })
646            .collect();
647
648        Ok(SliceReadRanges { results, error: scan_error })
649    }
650    async fn read_formatted_line(reader: &mut BufReader<File>, buffer: &mut Vec<u8>) -> Result<Option<(String, bool)>> {
651        let Some(truncated) = read_bounded_line(reader, buffer).await.context("failed to read file")? else {
652            return Ok(None);
653        };
654
655        if buffer.last() == Some(&b'\n') {
656            buffer.pop();
657            if buffer.last() == Some(&b'\r') {
658                buffer.pop();
659            }
660        }
661
662        Ok(Some((format_line(buffer), truncated)))
663    }
664}
665
666mod indentation {
667    use super::*;
668
669    pub(super) struct IndentationReadResult {
670        pub lines: Vec<String>,
671        pub line_truncated: bool,
672    }
673
674    pub async fn read_block(
675        path: &Path,
676        offset: usize,
677        limit: usize,
678        options: IndentationArgs,
679    ) -> Result<IndentationReadResult> {
680        let anchor_line = options.anchor_line.unwrap_or(offset);
681        anyhow::ensure!(anchor_line > 0, "anchor_line must be a 1-indexed line number");
682
683        let guard_limit = options.max_lines.unwrap_or(limit);
684        anyhow::ensure!(guard_limit > 0, "max_lines must be greater than zero");
685
686        // Bound the collection to the window the block expansion can ever use:
687        // the anchor plus the downward guard limit. The algorithm expands at
688        // most `final_limit` lines down from the anchor and needs the full
689        // prefix above it, so `anchor + guard_limit` is always sufficient and
690        // prevents an unbounded full-file read of gigantic files.
691        let collect_cap = anchor_line.saturating_add(guard_limit);
692        let (collected, line_truncated) = collect_file_lines(path, collect_cap).await?;
693        anyhow::ensure!(!collected.is_empty() && anchor_line <= collected.len(), "anchor_line exceeds file length");
694
695        let anchor_index = anchor_line - 1;
696        let effective_indents = compute_effective_indents(&collected);
697        let anchor_indent = effective_indents[anchor_index];
698
699        // Compute the min indent
700        let min_indent = if options.max_levels == 0 {
701            0
702        } else {
703            anchor_indent.saturating_sub(options.max_levels * TAB_WIDTH)
704        };
705
706        // Cap requested lines by guard_limit and file length
707        let final_limit = limit.min(guard_limit).min(collected.len());
708
709        if final_limit == 1 {
710            return Ok(IndentationReadResult {
711                lines: vec![format!(
712                    "{}: {}",
713                    collected[anchor_index].number, collected[anchor_index].display
714                )],
715                line_truncated,
716            });
717        }
718
719        // Bidirectional cursors
720        let mut i: isize = anchor_index as isize - 1; // up
721        let mut j: usize = anchor_index + 1; // down
722        let mut i_counter_min_indent = 0;
723        let mut j_counter_min_indent = 0;
724
725        let mut out = VecDeque::with_capacity(limit);
726        out.push_back(&collected[anchor_index]);
727
728        while out.len() < final_limit {
729            let mut progressed = 0;
730
731            // Expand upward
732            if i >= 0 {
733                #[allow(
734                    clippy::cast_sign_loss,
735                    reason = "Intentional compatibility, platform, or test-only suppression."
736                )]
737                let iu = i as usize;
738                if effective_indents[iu] >= min_indent {
739                    out.push_front(&collected[iu]);
740                    progressed += 1;
741                    i -= 1;
742
743                    // Control sibling inclusion
744                    if effective_indents[iu] == min_indent && !options.include_siblings {
745                        let allow_header_comment = options.include_header && collected[iu].is_comment();
746                        let can_take_line = allow_header_comment || i_counter_min_indent == 0;
747
748                        if can_take_line {
749                            i_counter_min_indent += 1;
750                        } else {
751                            out.pop_front();
752                            progressed -= 1;
753                            i = -1;
754                        }
755                    }
756
757                    if out.len() >= final_limit {
758                        break;
759                    }
760                } else {
761                    i = -1;
762                }
763            }
764
765            // Expand downward
766            if j < collected.len() {
767                let ju = j;
768                if effective_indents[ju] >= min_indent {
769                    out.push_back(&collected[ju]);
770                    progressed += 1;
771                    j += 1;
772
773                    // Control sibling inclusion
774                    if effective_indents[ju] == min_indent && !options.include_siblings {
775                        if j_counter_min_indent > 0 {
776                            out.pop_back();
777                            progressed -= 1;
778                            j = collected.len();
779                        }
780                        j_counter_min_indent += 1;
781                    }
782                } else {
783                    j = collected.len();
784                }
785            }
786
787            if progressed == 0 {
788                break;
789            }
790        }
791
792        trim_empty_lines(&mut out);
793
794        Ok(IndentationReadResult {
795            lines: out
796                .into_iter()
797                .map(|record| format!("{}: {}", record.number, record.display))
798                .collect(),
799            line_truncated,
800        })
801    }
802
803    async fn collect_file_lines(path: &Path, max_lines: usize) -> Result<(Vec<LineRecord>, bool)> {
804        let file = File::open(path)
805            .await
806            .context(format!("failed to open file: {}", path.display()))?;
807
808        let mut reader = BufReader::new(file);
809        let mut buffer = Vec::new();
810        let mut lines = Vec::new();
811        let mut number = 0usize;
812        let mut line_truncated = false;
813
814        while lines.len() < max_lines {
815            let Some(truncated) = read_bounded_line(&mut reader, &mut buffer)
816                .await
817                .context("failed to read file")?
818            else {
819                break;
820            };
821            line_truncated |= truncated;
822
823            if buffer.last() == Some(&b'\n') {
824                buffer.pop();
825                if buffer.last() == Some(&b'\r') {
826                    buffer.pop();
827                }
828            }
829
830            number += 1;
831            let raw = String::from_utf8_lossy(&buffer).into_owned();
832            let indent = measure_indent(&raw);
833            let display = format_line(&buffer);
834            lines.push(LineRecord { number, raw, display, indent });
835        }
836
837        Ok((lines, line_truncated))
838    }
839
840    fn compute_effective_indents(records: &[LineRecord]) -> Vec<usize> {
841        let mut effective = Vec::with_capacity(records.len());
842        let mut previous_indent = 0usize;
843        for record in records {
844            if record.is_blank() {
845                effective.push(previous_indent);
846            } else {
847                previous_indent = record.indent;
848                effective.push(previous_indent);
849            }
850        }
851        effective
852    }
853
854    fn measure_indent(line: &str) -> usize {
855        line.chars()
856            .take_while(|c| matches!(c, ' ' | '\t'))
857            .map(|c| if c == '\t' { TAB_WIDTH } else { 1 })
858            .sum()
859    }
860}
861
862mod defaults {
863    pub fn offset() -> usize {
864        1
865    }
866
867    pub fn limit() -> usize {
868        crate::tools::read_limits::read_limit_lines()
869    }
870
871    pub fn batch_limit() -> usize {
872        500
873    }
874
875    pub fn max_concurrency() -> usize {
876        super::DEFAULT_MAX_CONCURRENCY
877    }
878
879    pub fn ui_progress() -> bool {
880        true
881    }
882
883    pub fn max_levels() -> usize {
884        0
885    }
886
887    pub fn include_siblings() -> bool {
888        false
889    }
890
891    pub fn include_header() -> bool {
892        true
893    }
894
895    pub fn condense() -> bool {
896        true
897    }
898}
899
900#[cfg(test)]
901mod tests;