collet 0.1.1

Relentless agentic coding orchestrator with zero-drop agent loops
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
use std::io::Write;
use std::process::{Command, Stdio};

use ansi_to_tui::IntoText;
use ratatui::text::Text;

/// Try to render a unified diff through the `delta` formatter if it is installed.
///
/// Returns `None` if `delta` is not on `$PATH` or the subprocess fails.
/// The caller should fall back to plain rendering in that case.
pub fn try_render_with_delta(content: &str, is_dark: bool, width: u16) -> Option<Text<'static>> {
    let theme_flag = if is_dark { "--dark" } else { "--light" };
    let width_arg = format!("--width={width}");

    let mut child = Command::new("delta")
        .args([
            "--no-gitconfig",
            "--pager=never",
            "--line-numbers",
            "--navigate=never",
            theme_flag,
            &width_arg,
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .ok()?;

    child.stdin.take()?.write_all(content.as_bytes()).ok()?;

    let output = child.wait_with_output().ok()?;

    if !output.status.success() {
        return None;
    }

    output.stdout.into_text().ok()
}

/// The kind of a diff line.
#[derive(Debug, Clone, PartialEq)]
pub enum DiffKind {
    Context,
    Added,
    Removed,
}

/// A single line in a diff view (one side).
#[derive(Debug, Clone)]
pub struct DiffLine {
    pub line_no: Option<usize>,
    pub content: String,
    pub kind: DiffKind,
}

impl DiffLine {
    fn empty(kind: DiffKind) -> Self {
        Self {
            line_no: None,
            content: String::new(),
            kind,
        }
    }

    fn new(line_no: usize, content: &str, kind: DiffKind) -> Self {
        Self {
            line_no: Some(line_no),
            content: content.to_string(),
            kind,
        }
    }
}

/// A hunk of differences with context lines.
#[derive(Debug, Clone)]
pub struct DiffHunk {
    pub old_start: usize,
    pub new_start: usize,
    pub lines: Vec<(DiffLine, DiffLine)>,
}

/// A file-level diff containing path information and hunks.
#[derive(Debug, Clone)]
pub struct FileDiff {
    pub path: String,
    pub old_content: String,
    pub new_content: String,
    pub hunks: Vec<DiffHunk>,
}

impl FileDiff {
    pub fn from_strings(path: &str, old: &str, new: &str) -> Self {
        let hunks = compute_diff(old, new);
        Self {
            path: path.to_string(),
            old_content: old.to_string(),
            new_content: new.to_string(),
            hunks,
        }
    }

    /// Recompute the diff (e.g. after content changes) and return a fresh `FileDiff`.
    pub fn recompute(&self) -> Self {
        Self::from_strings(&self.path, &self.old_content, &self.new_content)
    }
}

/// Edit operation for the LCS-based diff.
#[derive(Debug, Clone, PartialEq)]
enum EditOp {
    Equal,
    Insert,
    Delete,
}

/// Compute a line-by-line diff using LCS (Longest Common Subsequence).
/// Returns hunks with 3 lines of context around each change.
pub fn compute_diff(old: &str, new: &str) -> Vec<DiffHunk> {
    let old_lines: Vec<&str> = if old.is_empty() {
        Vec::new()
    } else {
        old.lines().collect()
    };
    let new_lines: Vec<&str> = if new.is_empty() {
        Vec::new()
    } else {
        new.lines().collect()
    };

    let ops = lcs_diff(&old_lines, &new_lines);

    if ops.iter().all(|op| *op == EditOp::Equal) {
        return Vec::new();
    }

    // Build annotated line pairs from the edit operations.
    // Each entry: (old_line_no, new_line_no, old_text, new_text, changed)
    struct AnnotatedLine {
        old_no: Option<usize>,
        new_no: Option<usize>,
        old_text: String,
        new_text: String,
        changed: bool,
    }

    let mut annotated: Vec<AnnotatedLine> = Vec::new();
    let mut oi = 0usize;
    let mut ni = 0usize;

    for op in &ops {
        match op {
            EditOp::Equal => {
                annotated.push(AnnotatedLine {
                    old_no: Some(oi + 1),
                    new_no: Some(ni + 1),
                    old_text: old_lines[oi].to_string(),
                    new_text: new_lines[ni].to_string(),
                    changed: false,
                });
                oi += 1;
                ni += 1;
            }
            EditOp::Delete => {
                annotated.push(AnnotatedLine {
                    old_no: Some(oi + 1),
                    new_no: None,
                    old_text: old_lines[oi].to_string(),
                    new_text: String::new(),
                    changed: true,
                });
                oi += 1;
            }
            EditOp::Insert => {
                annotated.push(AnnotatedLine {
                    old_no: None,
                    new_no: Some(ni + 1),
                    old_text: String::new(),
                    new_text: new_lines[ni].to_string(),
                    changed: true,
                });
                ni += 1;
            }
        }
    }

    // Group into hunks with CONTEXT_LINES lines of context.
    const CONTEXT_LINES: usize = 3;
    let mut hunks: Vec<DiffHunk> = Vec::new();

    // Find ranges of changed lines, expanded by context.
    let mut change_indices: Vec<usize> = Vec::new();
    for (i, ann) in annotated.iter().enumerate() {
        if ann.changed {
            change_indices.push(i);
        }
    }

    if change_indices.is_empty() {
        return Vec::new();
    }

    // Merge overlapping context ranges.
    let mut ranges: Vec<(usize, usize)> = Vec::new();
    let mut start = change_indices[0].saturating_sub(CONTEXT_LINES);
    let mut end = (change_indices[0] + CONTEXT_LINES).min(annotated.len().saturating_sub(1));

    for &idx in &change_indices[1..] {
        let new_start = idx.saturating_sub(CONTEXT_LINES);
        let new_end = (idx + CONTEXT_LINES).min(annotated.len().saturating_sub(1));
        if new_start <= end + 1 {
            end = new_end;
        } else {
            ranges.push((start, end));
            start = new_start;
            end = new_end;
        }
    }
    ranges.push((start, end));

    // Build hunks from ranges.
    for (range_start, range_end) in ranges {
        let mut lines: Vec<(DiffLine, DiffLine)> = Vec::new();

        // Determine the old_start and new_start for the hunk header.
        let old_start = annotated[range_start].old_no.unwrap_or_else(|| {
            // Walk backwards to find the nearest old line number.
            for i in (0..range_start).rev() {
                if let Some(n) = annotated[i].old_no {
                    return n + 1;
                }
            }
            1
        });
        let new_start = annotated[range_start].new_no.unwrap_or_else(|| {
            for i in (0..range_start).rev() {
                if let Some(n) = annotated[i].new_no {
                    return n + 1;
                }
            }
            1
        });

        for ann in &annotated[range_start..=range_end] {
            if ann.changed {
                if let (Some(old_no), None) = (ann.old_no, ann.new_no) {
                    // Removed line
                    lines.push((
                        DiffLine::new(old_no, &ann.old_text, DiffKind::Removed),
                        DiffLine::empty(DiffKind::Removed),
                    ));
                } else if let (None, Some(new_no)) = (ann.old_no, ann.new_no) {
                    // Added line
                    lines.push((
                        DiffLine::empty(DiffKind::Added),
                        DiffLine::new(new_no, &ann.new_text, DiffKind::Added),
                    ));
                }
            } else if let (Some(old_no), Some(new_no)) = (ann.old_no, ann.new_no) {
                // Context line
                lines.push((
                    DiffLine::new(old_no, &ann.old_text, DiffKind::Context),
                    DiffLine::new(new_no, &ann.new_text, DiffKind::Context),
                ));
            }
        }

        hunks.push(DiffHunk {
            old_start,
            new_start,
            lines,
        });
    }

    hunks
}

/// LCS-based diff producing a sequence of edit operations.
fn lcs_diff<'a>(old: &[&'a str], new: &[&'a str]) -> Vec<EditOp> {
    let m = old.len();
    let n = new.len();

    // Build LCS table.
    let mut table = vec![vec![0u32; n + 1]; m + 1];
    for i in 1..=m {
        for j in 1..=n {
            if old[i - 1] == new[j - 1] {
                table[i][j] = table[i - 1][j - 1] + 1;
            } else {
                table[i][j] = table[i - 1][j].max(table[i][j - 1]);
            }
        }
    }

    // Backtrack to produce edit operations.
    let mut ops = Vec::new();
    let mut i = m;
    let mut j = n;
    while i > 0 || j > 0 {
        if i > 0 && j > 0 && old[i - 1] == new[j - 1] {
            ops.push(EditOp::Equal);
            i -= 1;
            j -= 1;
        } else if j > 0 && (i == 0 || table[i][j - 1] >= table[i - 1][j]) {
            ops.push(EditOp::Insert);
            j -= 1;
        } else {
            ops.push(EditOp::Delete);
            i -= 1;
        }
    }

    ops.reverse();
    ops
}

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

    #[test]
    fn test_compute_diff_identical() {
        let text = "line1\nline2\nline3\n";
        let hunks = compute_diff(text, text);
        assert!(hunks.is_empty(), "identical text should produce no hunks");
    }

    #[test]
    fn test_compute_diff_added_lines() {
        let old = "line1\nline2\n";
        let new = "line1\nline2\nline3\nline4\n";
        let hunks = compute_diff(old, new);
        assert!(!hunks.is_empty(), "should have at least one hunk");
        // The new lines should appear as Added on the right side.
        let has_added = hunks.iter().any(|h| {
            h.lines
                .iter()
                .any(|(_, right)| right.kind == DiffKind::Added)
        });
        assert!(has_added, "should contain added lines");
    }

    #[test]
    fn test_compute_diff_removed_lines() {
        let old = "line1\nline2\nline3\nline4\n";
        let new = "line1\nline2\n";
        let hunks = compute_diff(old, new);
        assert!(!hunks.is_empty(), "should have at least one hunk");
        let has_removed = hunks.iter().any(|h| {
            h.lines
                .iter()
                .any(|(left, _)| left.kind == DiffKind::Removed)
        });
        assert!(has_removed, "should contain removed lines");
    }

    #[test]
    fn test_compute_diff_mixed_changes() {
        let old = "aaa\nbbb\nccc\nddd\n";
        let new = "aaa\nBBB\nccc\neee\n";
        let hunks = compute_diff(old, new);
        assert!(!hunks.is_empty());
        // Should have both removed and added lines.
        let has_removed = hunks.iter().any(|h| {
            h.lines
                .iter()
                .any(|(left, _)| left.kind == DiffKind::Removed)
        });
        let has_added = hunks.iter().any(|h| {
            h.lines
                .iter()
                .any(|(_, right)| right.kind == DiffKind::Added)
        });
        assert!(has_removed, "should have removed lines");
        assert!(has_added, "should have added lines");
    }

    #[test]
    fn test_compute_diff_empty_to_content() {
        let old = "";
        let new = "line1\nline2\nline3\n";
        let hunks = compute_diff(old, new);
        assert!(
            !hunks.is_empty(),
            "adding content to empty should produce hunks"
        );
        let added_count: usize = hunks
            .iter()
            .map(|h| {
                h.lines
                    .iter()
                    .filter(|(_, r)| r.kind == DiffKind::Added)
                    .count()
            })
            .sum();
        assert_eq!(added_count, 3, "should have 3 added lines");
    }

    #[test]
    fn test_file_diff_from_strings() {
        let diff = FileDiff::from_strings("test.rs", "old\n", "new\n");
        assert_eq!(diff.path, "test.rs");
        assert_eq!(diff.old_content, "old\n");
        assert_eq!(diff.new_content, "new\n");
        assert!(!diff.hunks.is_empty(), "should compute hunks");
    }

    #[test]
    fn test_diff_hunk_context_lines() {
        // Build a file with a change surrounded by many context lines.
        let mut old_lines: Vec<String> = Vec::new();
        let mut new_lines: Vec<String> = Vec::new();
        for i in 0..20 {
            old_lines.push(format!("line{i}"));
            new_lines.push(format!("line{i}"));
        }
        // Change line 10.
        old_lines[10] = "OLD_LINE_10".to_string();
        new_lines[10] = "NEW_LINE_10".to_string();

        let old = old_lines.join("\n");
        let new = new_lines.join("\n");
        let hunks = compute_diff(&old, &new);

        assert_eq!(hunks.len(), 1, "should be exactly one hunk");

        let hunk = &hunks[0];
        // Count context lines before the change.
        let context_before: usize = hunk
            .lines
            .iter()
            .take_while(|(left, _)| left.kind == DiffKind::Context)
            .count();
        assert!(
            context_before <= 3,
            "should have at most 3 context lines before the change, got {context_before}"
        );

        // Count context lines after the change.
        let context_after: usize = hunk
            .lines
            .iter()
            .rev()
            .take_while(|(left, _)| left.kind == DiffKind::Context)
            .count();
        assert!(
            context_after <= 3,
            "should have at most 3 context lines after the change, got {context_after}"
        );
    }
}