agent-file-tools 0.50.0

Agent File Tools — tree-sitter powered code analysis 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
//! Low-level line edits produced by lowering PUT/CUT operations.
//!
//! Replacement payloads are tagged so repair layers can distinguish a true
//! replacement group (inserts + matching deletes) from ordinary gap inserts.

use crate::hashline::scan::TerminatorKind;

/// One concrete edit against pre-request line coordinates.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum LineEdit {
    Insert {
        /// 1-based anchor line. For BOF inserts this is 1 with [`InsertPlace::Before`].
        anchor: usize,
        place: InsertPlace,
        text: String,
        mode: InsertMode,
        /// Source operation index inside the section, used to group replacements.
        op_index: usize,
    },
    Delete {
        line: usize,
        op_index: usize,
    },
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum InsertPlace {
    Before,
    After,
    /// Insert before the first line of the file, even when the file is empty.
    Bof,
    /// Append after the last retained line.
    Eof,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum InsertMode {
    Plain,
    Replacement,
}

/// A replacement group: contiguous replacement inserts sharing one op, followed
/// by contiguous deletes for the same op. Mirrors the oracle's lowered form of
/// `PUT N-M:` with a body.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ReplacementGroup {
    pub insert_indices: Vec<usize>,
    pub delete_indices: Vec<usize>,
    pub payload: Vec<String>,
    pub start_line: usize,
    pub end_line: usize,
    pub op_index: usize,
}

/// Detect a replacement group starting at `start` in the edit list.
pub fn find_replacement_group(edits: &[LineEdit], start: usize) -> Option<ReplacementGroup> {
    let LineEdit::Insert {
        anchor,
        place: InsertPlace::Before,
        mode: InsertMode::Replacement,
        op_index,
        ..
    } = edits.get(start)?
    else {
        return None;
    };
    let anchor_line = *anchor;
    let op_index = *op_index;
    let mut insert_indices = Vec::new();
    let mut payload = Vec::new();
    let mut i = start;
    while i < edits.len() {
        match &edits[i] {
            LineEdit::Insert {
                anchor,
                place: InsertPlace::Before,
                text,
                mode: InsertMode::Replacement,
                op_index: edit_op,
            } if *anchor == anchor_line && *edit_op == op_index => {
                insert_indices.push(i);
                payload.push(text.clone());
                i += 1;
            }
            _ => break,
        }
    }
    let mut delete_indices = Vec::new();
    let mut expected = anchor_line;
    while i < edits.len() {
        match &edits[i] {
            LineEdit::Delete {
                line,
                op_index: edit_op,
            } if *line == expected && *edit_op == op_index => {
                delete_indices.push(i);
                expected += 1;
                i += 1;
            }
            _ => break,
        }
    }
    if delete_indices.is_empty() {
        return None;
    }
    Some(ReplacementGroup {
        insert_indices,
        delete_indices,
        payload,
        start_line: anchor_line,
        end_line: expected - 1,
        op_index,
    })
}

/// Coalesce adjacent or overlapping replacement groups that share the same
/// source operation into one contiguous replacement. This is the
/// replacement-coalescing repair layer: agents sometimes emit several
/// single-line PUTs that together replace a contiguous span.
pub fn coalesce_replacement_edits(edits: &[LineEdit]) -> Vec<LineEdit> {
    if edits.is_empty() {
        return Vec::new();
    }

    // Group by op_index while preserving first-seen order.
    let mut op_order: Vec<usize> = Vec::new();
    let mut by_op: std::collections::BTreeMap<usize, Vec<LineEdit>> =
        std::collections::BTreeMap::new();
    for edit in edits {
        let op = match edit {
            LineEdit::Insert { op_index, .. } | LineEdit::Delete { op_index, .. } => *op_index,
        };
        if !by_op.contains_key(&op) {
            op_order.push(op);
        }
        by_op.entry(op).or_default().push(edit.clone());
    }

    let mut out = Vec::with_capacity(edits.len());
    for op in op_order {
        let group = by_op.remove(&op).unwrap_or_default();
        out.extend(coalesce_one_op(group));
    }
    out
}

fn coalesce_one_op(edits: Vec<LineEdit>) -> Vec<LineEdit> {
    let mut deletes: Vec<usize> = edits
        .iter()
        .filter_map(|edit| match edit {
            LineEdit::Delete { line, .. } => Some(*line),
            _ => None,
        })
        .collect();
    let replacements: Vec<String> = edits
        .iter()
        .filter_map(|edit| match edit {
            LineEdit::Insert {
                text,
                mode: InsertMode::Replacement,
                ..
            } => Some(text.clone()),
            _ => None,
        })
        .collect();
    let plain: Vec<LineEdit> = edits
        .iter()
        .filter(|edit| {
            !matches!(
                edit,
                LineEdit::Delete { .. }
                    | LineEdit::Insert {
                        mode: InsertMode::Replacement,
                        ..
                    }
            )
        })
        .cloned()
        .collect();

    if deletes.is_empty() || replacements.is_empty() {
        return edits;
    }

    deletes.sort_unstable();
    deletes.dedup();
    // Only coalesce when deletes form one contiguous span.
    let contiguous = deletes
        .windows(2)
        .all(|pair| pair[1] == pair[0].saturating_add(1));
    if !contiguous {
        return edits;
    }
    let start = deletes[0];
    let end = *deletes.last().unwrap();
    let op_index = match edits.first() {
        Some(LineEdit::Insert { op_index, .. } | LineEdit::Delete { op_index, .. }) => *op_index,
        None => 0,
    };

    let mut coalesced = plain;
    for text in replacements {
        coalesced.push(LineEdit::Insert {
            anchor: start,
            place: InsertPlace::Before,
            text,
            mode: InsertMode::Replacement,
            op_index,
        });
    }
    for line in start..=end {
        coalesced.push(LineEdit::Delete { line, op_index });
    }
    coalesced
}

/// Splice edits into content lines. Coordinates are pre-request (baseline).
pub fn materialize_edits(original_lines: &[String], edits: &[LineEdit]) -> Vec<String> {
    let mut file_lines = original_lines.to_vec();
    let mut bof: Vec<String> = Vec::new();
    let mut eof: Vec<String> = Vec::new();

    // Bucket anchor-targeted edits by line.
    let mut by_line: std::collections::BTreeMap<usize, Vec<&LineEdit>> =
        std::collections::BTreeMap::new();
    for edit in edits {
        match edit {
            LineEdit::Insert {
                place: InsertPlace::Bof,
                text,
                ..
            } => bof.push(text.clone()),
            LineEdit::Insert {
                place: InsertPlace::Eof,
                text,
                ..
            } => eof.push(text.clone()),
            LineEdit::Insert { anchor, .. } => {
                by_line.entry(*anchor).or_default().push(edit);
            }
            LineEdit::Delete { line, .. } => {
                by_line.entry(*line).or_default().push(edit);
            }
        }
    }

    // Apply bottom-up so earlier indices stay valid.
    let lines: Vec<usize> = by_line.keys().copied().collect();
    for line in lines.into_iter().rev() {
        let Some(bucket) = by_line.get(&line) else {
            continue;
        };
        let idx = line.saturating_sub(1);
        if idx > file_lines.len() {
            continue;
        }
        let current = file_lines.get(idx).cloned().unwrap_or_default();
        let mut before = Vec::new();
        let mut after = Vec::new();
        let mut replacement = Vec::new();
        let mut delete_line = false;
        for edit in bucket {
            match edit {
                LineEdit::Insert {
                    place: InsertPlace::Before,
                    text,
                    mode: InsertMode::Replacement,
                    ..
                } => replacement.push(text.clone()),
                LineEdit::Insert {
                    place: InsertPlace::Before,
                    text,
                    ..
                } => before.push(text.clone()),
                LineEdit::Insert {
                    place: InsertPlace::After,
                    text,
                    ..
                } => after.push(text.clone()),
                LineEdit::Delete { .. } => delete_line = true,
                LineEdit::Insert {
                    place: InsertPlace::Bof | InsertPlace::Eof,
                    ..
                } => {}
            }
        }
        if before.is_empty() && replacement.is_empty() && after.is_empty() && !delete_line {
            continue;
        }
        let spliced = if delete_line {
            let mut rows = before;
            rows.extend(replacement);
            rows.extend(after);
            rows
        } else {
            let mut rows = before;
            rows.extend(replacement);
            if idx < file_lines.len() {
                rows.push(current);
            }
            rows.extend(after);
            rows
        };
        if idx < file_lines.len() {
            file_lines.splice(idx..=idx, spliced);
        } else {
            file_lines.extend(spliced);
        }
    }

    if !bof.is_empty() {
        let mut rows = bof;
        rows.append(&mut file_lines);
        file_lines = rows;
    }
    file_lines.extend(eof);
    file_lines
}

/// Rebuild file bytes from logical lines using the baseline terminator policy.
pub fn join_lines(
    lines: &[String],
    default_terminator: TerminatorKind,
    trailing_terminator: bool,
) -> Vec<u8> {
    if lines.is_empty() {
        return Vec::new();
    }
    let mut out = Vec::new();
    for (index, line) in lines.iter().enumerate() {
        out.extend_from_slice(line.as_bytes());
        let is_last = index + 1 == lines.len();
        let term = if is_last && !trailing_terminator {
            TerminatorKind::None
        } else if default_terminator == TerminatorKind::None {
            TerminatorKind::Lf
        } else {
            default_terminator
        };
        match term {
            TerminatorKind::Lf => out.push(b'\n'),
            TerminatorKind::CrLf => out.extend_from_slice(b"\r\n"),
            TerminatorKind::None => {}
        }
    }
    out
}

/// Infer terminator policy from baseline raw records.
pub fn terminator_policy(
    records: &std::collections::BTreeMap<usize, crate::hashline::scan::RawLineRecord>,
) -> (TerminatorKind, bool) {
    let mut lf = 0usize;
    let mut crlf = 0usize;
    let mut trailing = false;
    let last = records.keys().next_back().copied();
    for (&line, record) in records {
        match record.terminator {
            TerminatorKind::Lf => lf += 1,
            TerminatorKind::CrLf => crlf += 1,
            TerminatorKind::None => {}
        }
        if Some(line) == last {
            trailing = record.terminator != TerminatorKind::None;
        }
    }
    let default = if crlf > lf {
        TerminatorKind::CrLf
    } else if lf > 0 || crlf > 0 {
        TerminatorKind::Lf
    } else {
        TerminatorKind::Lf
    };
    (default, trailing || records.is_empty())
}

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

    #[test]
    fn materialize_replaces_a_span() {
        let original = vec!["a".into(), "b".into(), "c".into()];
        let edits = vec![
            LineEdit::Insert {
                anchor: 2,
                place: InsertPlace::Before,
                text: "B".into(),
                mode: InsertMode::Replacement,
                op_index: 0,
            },
            LineEdit::Delete {
                line: 2,
                op_index: 0,
            },
        ];
        assert_eq!(
            materialize_edits(&original, &edits),
            vec!["a".to_string(), "B".into(), "c".into()]
        );
    }

    #[test]
    fn coalesce_merges_contiguous_single_line_replacements() {
        let edits = vec![
            LineEdit::Insert {
                anchor: 1,
                place: InsertPlace::Before,
                text: "A".into(),
                mode: InsertMode::Replacement,
                op_index: 0,
            },
            LineEdit::Delete {
                line: 1,
                op_index: 0,
            },
            LineEdit::Insert {
                anchor: 2,
                place: InsertPlace::Before,
                text: "B".into(),
                mode: InsertMode::Replacement,
                op_index: 0,
            },
            LineEdit::Delete {
                line: 2,
                op_index: 0,
            },
            LineEdit::Insert {
                anchor: 3,
                place: InsertPlace::Before,
                text: "C".into(),
                mode: InsertMode::Replacement,
                op_index: 0,
            },
            LineEdit::Delete {
                line: 3,
                op_index: 0,
            },
        ];
        let coalesced = coalesce_replacement_edits(&edits);
        let group = find_replacement_group(&coalesced, 0).expect("one group");
        assert_eq!(group.start_line, 1);
        assert_eq!(group.end_line, 3);
        assert_eq!(group.payload, vec!["A", "B", "C"]);
    }
}