eggsact 1.2.7

Deterministic MCP and in-process utility tools for coding 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
use serde::{Deserialize, Serialize};

const MAX_TEXT_LENGTH: usize = 100_000;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineExtractFinding {
    pub kind: String,
    pub message: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineExtractLine {
    pub text: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineRangeExtractResult {
    pub line_count_total: usize,
    pub start_line: usize,
    pub end_line: usize,
    pub valid_range: bool,
    pub text: String,
    pub lines: Vec<LineExtractLine>,
    pub byte_start: usize,
    pub byte_end: usize,
    pub char_start: usize,
    pub char_end: usize,
    pub newline_style: String,
    pub ends_with_newline: bool,
    pub fingerprint: String,
    pub findings: Vec<LineExtractFinding>,
}

fn detect_newline_style(s: &str) -> &'static str {
    crate::text::primitives::detect_newline_style(s)
}

fn fingerprint(text: &str) -> String {
    use sha2::{Digest, Sha256};

    let mut hasher = Sha256::new();
    hasher.update(text.as_bytes());
    let result = hasher.finalize();
    let hex = format!("{:x}", result);
    hex[..16].to_string()
}

#[derive(Debug, Clone, Copy)]
struct LineSegment<'a> {
    text: &'a str,
    byte_start: usize,
    // End of the visible line content, excluding the line terminator.
    byte_end: usize,
    // Start offset of the next line, including any line terminator bytes.
    byte_after_terminator: usize,
}

fn line_number_to_one_based(line: usize, line_base: usize) -> Result<usize, String> {
    match line_base {
        0 => line
            .checked_add(1)
            .ok_or_else(|| "line number is too large".to_string()),
        1 => Ok(line),
        _ => Err(format!("line_base must be 0 or 1, got {}", line_base)),
    }
}

fn split_line_segments(text: &str) -> Vec<LineSegment<'_>> {
    if text.is_empty() {
        return vec![LineSegment {
            text: "",
            byte_start: 0,
            byte_end: 0,
            byte_after_terminator: 0,
        }];
    }

    let mut segments = Vec::new();
    let mut start = 0usize;
    let mut iter = text.char_indices().peekable();

    while let Some((idx, ch)) = iter.next() {
        match ch {
            '\n' | '\x0b' | '\x0c' | '\x1c' | '\x1d' | '\x1e' | '\u{0085}' | '\u{2028}'
            | '\u{2029}' => {
                segments.push(LineSegment {
                    text: &text[start..idx],
                    byte_start: start,
                    byte_end: idx,
                    byte_after_terminator: idx + ch.len_utf8(),
                });
                start = idx + ch.len_utf8();
            }
            '\r' => {
                let mut end = idx + ch.len_utf8();
                if let Some((next_idx, '\n')) = iter.peek().copied() {
                    iter.next();
                    end = next_idx + '\n'.len_utf8();
                }
                segments.push(LineSegment {
                    text: &text[start..idx],
                    byte_start: start,
                    byte_end: idx,
                    byte_after_terminator: end,
                });
                start = end;
            }
            _ => {}
        }
    }

    if start < text.len()
        || text
            .chars()
            .last()
            .is_some_and(crate::text::primitives::is_line_break)
    {
        segments.push(LineSegment {
            text: &text[start..],
            byte_start: start,
            byte_end: text.len(),
            byte_after_terminator: text.len(),
        });
    }

    segments
}

fn range_text<'a>(
    text: &'a str,
    lines: &[LineSegment<'_>],
    start_idx: usize,
    end_idx: usize,
) -> &'a str {
    if start_idx < end_idx && end_idx > 0 {
        &text[lines[start_idx].byte_start..lines[end_idx - 1].byte_end]
    } else {
        ""
    }
}

fn range_compare_pieces<'a>(
    text: &'a str,
    lines: &[LineSegment<'_>],
    start_idx: usize,
    end_idx: usize,
) -> Vec<&'a str> {
    if start_idx >= end_idx {
        return Vec::new();
    }

    (start_idx..end_idx)
        .map(|i| {
            let end = if i + 1 < end_idx {
                lines[i].byte_after_terminator
            } else {
                lines[i].byte_end
            };
            &text[lines[i].byte_start..end]
        })
        .collect()
}

pub fn line_range_extract(
    text: &str,
    start_line: usize,
    end_line: usize,
    line_base: usize,
    include_line_numbers: bool,
    include_fingerprint: bool,
) -> Result<LineRangeExtractResult, String> {
    // Byte-based to match the MCP budget tier (`max_text_bytes`) and the
    // `_require_str` gate, which reject by byte length.
    let text_length = text.len();
    if text_length > MAX_TEXT_LENGTH {
        return Err(format!(
            "Input length {} exceeds MAX_TEXT_LENGTH {}",
            text_length, MAX_TEXT_LENGTH
        ));
    }

    if start_line > end_line {
        return Err(format!(
            "start_line ({}) must be <= end_line ({})",
            start_line, end_line
        ));
    }

    let mut findings: Vec<LineExtractFinding> = vec![];

    let lines = split_line_segments(text);
    let total_lines = lines.len();

    let start_1based = line_number_to_one_based(start_line, line_base)?;
    let end_1based = line_number_to_one_based(end_line, line_base)?;

    let mut valid_range = true;
    let mut start_1based = start_1based;
    let mut end_1based = end_1based;

    if start_1based < 1 {
        valid_range = false;
        findings.push(LineExtractFinding {
            kind: "out_of_range".to_string(),
            message: format!("start_line {} is before the first line", start_line),
        });
        start_1based = 1;
    }

    if end_1based > total_lines {
        valid_range = false;
        findings.push(LineExtractFinding {
            kind: "out_of_range".to_string(),
            message: format!(
                "end_line {} exceeds total lines ({})",
                end_line, total_lines
            ),
        });
        end_1based = total_lines;
    }

    let mut extracted_lines: Vec<LineExtractLine> = vec![];

    let start_idx = start_1based.saturating_sub(1);
    let end_idx = std::cmp::min(end_1based, lines.len());
    for (i, line) in lines.iter().enumerate().take(end_idx).skip(start_idx) {
        let line_text = line.text.to_string();
        let line_dict = if include_line_numbers {
            LineExtractLine {
                text: line_text,
                line: Some(i + line_base),
            }
        } else {
            LineExtractLine {
                text: line_text,
                line: None,
            }
        };
        extracted_lines.push(line_dict);
    }

    let (byte_start, byte_end) = if start_idx < end_idx && end_idx > 0 {
        (lines[start_idx].byte_start, lines[end_idx - 1].byte_end)
    } else {
        (text.len(), text.len())
    };
    let char_start = text[..byte_start].chars().count();
    let char_end = text[..byte_end].chars().count();

    let newline_style = detect_newline_style(text).to_string();
    let extracted_text = range_text(text, &lines, start_idx, end_idx).to_string();

    let fingerprint = if include_fingerprint {
        fingerprint(&extracted_text)
    } else {
        String::new()
    };

    let ends_with_newline = text.ends_with('\n') || text.ends_with('\r');

    Ok(LineRangeExtractResult {
        line_count_total: total_lines,
        start_line,
        end_line,
        valid_range,
        text: extracted_text,
        lines: extracted_lines,
        byte_start,
        byte_end,
        char_start,
        char_end,
        newline_style,
        ends_with_newline,
        fingerprint,
        findings,
    })
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FirstDifference {
    pub line_offset: usize,
    pub line_number: usize,
    pub left: Option<String>,
    pub right: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineRangeCompareResult {
    pub equal: bool,
    pub left_fingerprint: String,
    pub right_fingerprint: String,
    pub diff_summary: String,
    pub first_difference: Option<FirstDifference>,
}

pub fn line_range_compare(
    left_text: &str,
    right_text: &str,
    start_line: usize,
    end_line: usize,
    line_base: usize,
    comparison_mode: &str,
) -> Result<LineRangeCompareResult, String> {
    // Byte-based to match the MCP budget tier (`max_text_bytes`) and the
    // `_require_str` gate, which reject by byte length.
    let left_length = left_text.len();
    if left_length > MAX_TEXT_LENGTH {
        return Err(format!(
            "left_text length {} exceeds MAX_TEXT_LENGTH {}",
            left_length, MAX_TEXT_LENGTH
        ));
    }
    let right_length = right_text.len();
    if right_length > MAX_TEXT_LENGTH {
        return Err(format!(
            "right_text length {} exceeds MAX_TEXT_LENGTH {}",
            right_length, MAX_TEXT_LENGTH
        ));
    }

    let valid_modes = ["exact", "ignore_trailing_whitespace", "normalize_newlines"];
    if !valid_modes.contains(&comparison_mode) {
        return Err(format!(
            "Invalid comparison_mode: {}. Use one of: {}",
            comparison_mode,
            valid_modes.join(", ")
        ));
    }

    let left_lines = split_line_segments(left_text);
    let right_lines = split_line_segments(right_text);

    let start_1based = line_number_to_one_based(start_line, line_base)?;
    let end_1based = line_number_to_one_based(end_line, line_base)?;

    if start_1based > left_lines.len() || start_1based > right_lines.len() {
        return Err(format!(
            "start_line ({}) exceeds available lines (left: {}, right: {})",
            start_line,
            left_lines.len(),
            right_lines.len()
        ));
    }

    let start_idx = start_1based.saturating_sub(1);
    let left_end_idx = std::cmp::min(end_1based, left_lines.len());
    let right_end_idx = std::cmp::min(end_1based, right_lines.len());
    let left_slice = range_compare_pieces(left_text, &left_lines, start_idx, left_end_idx);
    let right_slice = range_compare_pieces(right_text, &right_lines, start_idx, right_end_idx);

    fn normalize_for_compare(s: &str, mode: &str) -> String {
        match mode {
            "ignore_trailing_whitespace" => s.trim_end().to_string(),
            "normalize_newlines" => crate::text::primitives::normalize_line_endings(s),
            _ => s.to_string(),
        }
    }

    let left_norm: Vec<String> = left_slice
        .iter()
        .map(|l| normalize_for_compare(l, comparison_mode))
        .collect();
    let right_norm: Vec<String> = right_slice
        .iter()
        .map(|r| normalize_for_compare(r, comparison_mode))
        .collect();

    let equal = left_norm == right_norm;

    let left_text_slice = range_text(left_text, &left_lines, start_idx, left_end_idx);
    let right_text_slice = range_text(right_text, &right_lines, start_idx, right_end_idx);
    let left_fp = fingerprint(left_text_slice);
    let right_fp = fingerprint(right_text_slice);

    let mut diff_summary = if equal {
        "equal".to_string()
    } else {
        "different".to_string()
    };
    let mut first_diff: Option<FirstDifference> = None;

    if !equal {
        for (i, (l, r)) in left_norm.iter().zip(right_norm.iter()).enumerate() {
            if l != r {
                first_diff = Some(FirstDifference {
                    line_offset: i,
                    line_number: start_1based + i,
                    left: Some(left_slice[i].to_string()),
                    right: Some(right_slice[i].to_string()),
                });
                diff_summary = format!("differ at line {}", start_1based + i);
                break;
            }
        }
        if first_diff.is_none() && left_norm.len() != right_norm.len() {
            let min_len = std::cmp::min(left_norm.len(), right_norm.len());
            diff_summary = format!(
                "different lengths: {} vs {} lines",
                left_norm.len(),
                right_norm.len()
            );
            if min_len < std::cmp::max(left_norm.len(), right_norm.len()) {
                let idx = min_len;
                first_diff = Some(FirstDifference {
                    line_offset: idx,
                    line_number: start_1based + idx,
                    left: if idx < left_slice.len() {
                        Some(left_slice[idx].to_string())
                    } else {
                        None
                    },
                    right: if idx < right_slice.len() {
                        Some(right_slice[idx].to_string())
                    } else {
                        None
                    },
                });
            }
        }
    }

    Ok(LineRangeCompareResult {
        equal,
        left_fingerprint: left_fp,
        right_fingerprint: right_fp,
        diff_summary,
        first_difference: first_diff,
    })
}