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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use crate::common::Result;
use serde::Deserialize;
use tokio::fs;

#[derive(Debug, Deserialize)]
pub struct FileWriteInput {
    pub path: String,
    pub content: String,
}

#[derive(Debug, Deserialize)]
pub struct FileEditInput {
    pub path: String,
    pub old_string: String,
    pub new_string: String,
    /// When true, replace all occurrences instead of requiring uniqueness.
    #[serde(default)]
    pub replace_all: bool,
}

/// Confidence level of an edit match.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum EditConfidence {
    /// Exact string match (1.0).
    Exact,
    /// Matched after whitespace normalization.
    Normalized,
}

pub fn write_definition() -> serde_json::Value {
    serde_json::json!({
        "type": "function",
        "function": {
            "name": "file_write",
            "description": "Write content to a file, creating it if it doesn't exist.",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Path to the file"
                    },
                    "content": {
                        "type": "string",
                        "description": "Content to write to the file"
                    }
                },
                "required": ["path", "content"]
            }
        }
    })
}

pub fn edit_definition() -> serde_json::Value {
    serde_json::json!({
        "type": "function",
        "function": {
            "name": "file_edit",
            "description": "Perform a surgical edit: replace an exact string in a file with new content.",
            "parameters": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Path to the file"
                    },
                    "old_string": {
                        "type": "string",
                        "description": "The exact string to find and replace"
                    },
                    "new_string": {
                        "type": "string",
                        "description": "The replacement string"
                    },
                    "replace_all": {
                        "type": "boolean",
                        "description": "If true, replace ALL occurrences of old_string. Default: false (requires unique match)."
                    }
                },
                "required": ["path", "old_string", "new_string"]
            }
        }
    })
}

pub async fn execute_write(
    input: FileWriteInput,
    working_dir: &str,
    lsp_manager: Option<&crate::lsp::manager::LspManager>,
) -> Result<String> {
    let path = resolve_path(&input.path, working_dir);

    // Ensure parent directory exists
    if let Some(parent) = std::path::Path::new(&path).parent() {
        fs::create_dir_all(parent).await?;
    }

    let is_new_file = !std::path::Path::new(&path).exists();

    fs::write(&path, &input.content).await?;

    // Register new files with git (intent-to-add) so they appear in diffs
    if is_new_file {
        let _ = tokio::process::Command::new("git")
            .args(["add", "-N", &path])
            .current_dir(working_dir)
            .output()
            .await;
    }

    let mut result = format!(
        "Successfully wrote {} bytes to {}",
        input.content.len(),
        path
    );

    // Notify LSP of file change
    if let Some(lsp) = lsp_manager {
        // Read version counter before sending so we can detect when the server
        // has analysed the new content (any version advance = new diagnostics).
        let version_before = lsp.diag_version(&path).await;

        if let Err(e) = lsp.notify_file_change(&path, &input.content).await {
            tracing::warn!("LSP notification failed for {}: {}", path, e);
        }
        if let Err(e) = lsp.notify_file_save(&path).await {
            tracing::warn!("LSP save notification failed for {}: {}", path, e);
        }

        // Adaptive poll: exit as soon as a publishDiagnostics arrives.
        // Starts at 25 ms and grows to 200 ms (capped), giving quick response
        // for fast LSPs while avoiding excessive polling on slow ones.
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(1_500);
        let mut poll_interval = std::time::Duration::from_millis(25);
        loop {
            tokio::time::sleep(poll_interval).await;
            if lsp.diag_version(&path).await > version_before {
                break;
            }
            if tokio::time::Instant::now() >= deadline {
                break;
            }
            poll_interval = poll_interval
                .mul_f32(1.5)
                .min(std::time::Duration::from_millis(200));
        }

        if let Ok(diagnostics) = lsp.get_diagnostics(&path).await
            && !diagnostics.is_empty()
        {
            result.push_str("\n\n⚠️  LSP Diagnostics:\n");
            for diag in diagnostics.iter().take(10) {
                result.push_str(&format!(
                    "  Line {}: {}\n",
                    diag.range.start.line + 1,
                    diag.message
                ));
            }
        }
    }

    Ok(result)
}

pub async fn execute_edit(
    input: FileEditInput,
    working_dir: &str,
    lsp_manager: Option<&crate::lsp::manager::LspManager>,
) -> Result<String> {
    let path = resolve_path(&input.path, working_dir);

    let content = fs::read_to_string(&path).await?;

    // S1: Adaptive edit strategy — exact match → normalized fallback
    let (new_content, confidence) = apply_edit(&content, &input)?;
    fs::write(&path, &new_content).await?;

    let mut result = match confidence {
        EditConfidence::Exact => format!("Successfully edited {}", path),
        EditConfidence::Normalized => format!(
            "Successfully edited {} (matched after whitespace normalization)",
            path
        ),
    };

    // S9: Post-edit syntax validation via tree-sitter
    if let Some(syntax_err) = validate_syntax(&path, &new_content) {
        result.push_str(&format!("\n\nSYNTAX WARNING: {syntax_err}"));
    }

    // Notify LSP of file change and collect diagnostics
    if let Some(lsp) = lsp_manager {
        let version_before = lsp.diag_version(&path).await;

        if let Err(e) = lsp.notify_file_change(&path, &new_content).await {
            tracing::warn!("LSP notification failed for {}: {}", path, e);
        }
        if let Err(e) = lsp.notify_file_save(&path).await {
            tracing::warn!("LSP save notification failed for {}: {}", path, e);
        }

        let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(1_500);
        let mut poll_interval = std::time::Duration::from_millis(25);
        loop {
            tokio::time::sleep(poll_interval).await;
            if lsp.diag_version(&path).await > version_before {
                break;
            }
            if tokio::time::Instant::now() >= deadline {
                break;
            }
            poll_interval = poll_interval
                .mul_f32(1.5)
                .min(std::time::Duration::from_millis(200));
        }
        if let Ok(diagnostics) = lsp.get_diagnostics(&path).await
            && !diagnostics.is_empty()
        {
            let errors = diagnostics
                .iter()
                .filter(|d| {
                    matches!(
                        d.severity,
                        Some(crate::lsp::protocol::DiagnosticSeverity::Error)
                    )
                })
                .count();
            let warnings = diagnostics.len() - errors;
            result.push_str(&format!(
                "\n\nPOST-EDIT DIAGNOSTICS: {} errors, {} warnings\n",
                errors, warnings
            ));
            for diag in diagnostics.iter().take(10) {
                result.push_str(&format!(
                    "  Line {}: {}\n",
                    diag.range.start.line + 1,
                    diag.message
                ));
            }
            if errors > 0 {
                result.push_str("IMPORTANT: Fix all errors before proceeding to next task.\n");
            }
        }

        // Refresh symbol index for the edited file (used by repo_map).
        if let Some(symbols) = lsp.symbols_for_file(&path).await {
            tracing::trace!(
                path = %path,
                symbol_count = symbols.len(),
                "LSP: symbol index refreshed after edit"
            );
        }
    }

    Ok(result)
}

/// Apply an edit with adaptive matching strategy.
///
/// Strategy:
/// 1. Exact match (original behavior)
/// 2. Whitespace-normalized match (handles indentation mismatches)
fn apply_edit(content: &str, input: &FileEditInput) -> Result<(String, EditConfidence)> {
    let count = content.matches(&input.old_string).count();

    // replace_all mode: replace all occurrences
    if input.replace_all && count > 0 {
        let new_content = content.replace(&input.old_string, &input.new_string);
        return Ok((new_content, EditConfidence::Exact));
    }

    // Exact match — original behavior
    if count == 1 {
        let new_content = content.replacen(&input.old_string, &input.new_string, 1);
        return Ok((new_content, EditConfidence::Exact));
    }

    if count > 1 {
        return Err(crate::common::AgentError::InvalidArgument(format!(
            "old_string found {} times in file - must be unique. \
             Include more surrounding context to disambiguate.",
            count
        )));
    }

    // Phase 2: Whitespace-normalized match
    let normalized_old = normalize_whitespace(&input.old_string);
    let lines: Vec<&str> = content.lines().collect();
    let old_lines: Vec<&str> = input.old_string.lines().collect();
    let old_line_count = old_lines.len();

    if old_line_count > 0 && old_line_count <= lines.len() {
        let mut matches = Vec::new();
        for start in 0..=lines.len().saturating_sub(old_line_count) {
            let window: String = lines[start..start + old_line_count].join("\n");
            if normalize_whitespace(&window) == normalized_old {
                matches.push(start);
            }
        }

        if matches.len() == 1 {
            let start = matches[0];
            let mut new_lines: Vec<&str> = Vec::new();
            new_lines.extend_from_slice(&lines[..start]);
            for line in input.new_string.lines() {
                new_lines.push(line);
            }
            new_lines.extend_from_slice(&lines[start + old_line_count..]);
            let new_content = new_lines.join("\n");
            // Preserve trailing newline
            let new_content = if content.ends_with('\n') && !new_content.ends_with('\n') {
                format!("{new_content}\n")
            } else {
                new_content
            };
            return Ok((new_content, EditConfidence::Normalized));
        }
    }

    // Phase 4: Generate diff hint showing the closest matching region
    let diff_hint = find_closest_match(content, &input.old_string);
    let hint_msg = match diff_hint {
        Some(hint) => format!(
            "old_string not found in file (even after whitespace normalization).\n\
             Closest match found at line {}:\n\
             --- expected (your old_string) ---\n{}\n\
             --- actual (file content) ---\n{}\n\
             Use file_read to verify the current file content before editing.",
            hint.line,
            truncate_for_hint(&input.old_string, 300),
            truncate_for_hint(&hint.actual, 300),
        ),
        None => "old_string not found in file (even after whitespace normalization). \
                 Use file_read to verify the current file content before editing."
            .to_string(),
    };
    Err(crate::common::AgentError::InvalidArgument(hint_msg))
}

/// Result of searching for the closest matching region in a file.
struct ClosestMatch {
    /// 1-based line number where the closest match starts.
    line: usize,
    /// The actual content from the file at that location.
    actual: String,
}

/// Find the region in `content` most similar to `needle` using line-level overlap.
///
/// Slides a window of `needle`'s line count over `content` and picks the window
/// with the highest fraction of matching normalized lines.
fn find_closest_match(content: &str, needle: &str) -> Option<ClosestMatch> {
    let content_lines: Vec<&str> = content.lines().collect();
    let needle_lines: Vec<String> = needle
        .lines()
        .map(|l| l.split_whitespace().collect::<Vec<_>>().join(" "))
        .collect();
    let window = needle_lines.len();

    if window == 0 || window > content_lines.len() {
        return None;
    }

    let mut best_score = 0usize;
    let mut best_start = 0usize;

    for start in 0..=content_lines.len().saturating_sub(window) {
        let score = (0..window)
            .filter(|&i| {
                let actual_norm: String = content_lines[start + i]
                    .split_whitespace()
                    .collect::<Vec<_>>()
                    .join(" ");
                actual_norm == needle_lines[i]
            })
            .count();
        if score > best_score {
            best_score = score;
            best_start = start;
        }
    }

    // Only return if at least 30% of lines match (otherwise it's just noise)
    if best_score * 10 < window * 3 {
        return None;
    }

    let actual = content_lines[best_start..best_start + window].join("\n");
    Some(ClosestMatch {
        line: best_start + 1,
        actual,
    })
}

/// Truncate a string for inclusion in an error hint.
fn truncate_for_hint(s: &str, max_chars: usize) -> String {
    if s.len() <= max_chars {
        s.to_string()
    } else {
        format!("{}...", crate::util::truncate_bytes(s, max_chars))
    }
}

/// Normalize whitespace for fuzzy comparison: collapse runs of spaces/tabs,
/// trim each line, and normalize line endings.
fn normalize_whitespace(s: &str) -> String {
    s.lines()
        .map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Validate syntax of written content using tree-sitter.
/// Returns a description of syntax errors if any are found.
fn validate_syntax(path: &str, content: &str) -> Option<String> {
    let ext = std::path::Path::new(path).extension()?.to_str()?;

    // Only validate languages we have tree-sitter grammars for
    let language = match ext {
        "rs" => tree_sitter_rust::LANGUAGE,
        "py" => tree_sitter_python::LANGUAGE,
        "ts" | "tsx" | "js" | "jsx" => tree_sitter_typescript::LANGUAGE_TYPESCRIPT,
        _ => return None,
    };

    let mut parser = tree_sitter::Parser::new();
    parser.set_language(&language.into()).ok()?;
    let tree = parser.parse(content, None)?;

    if tree.root_node().has_error() {
        // Find the first error node for a useful message
        let root = tree.root_node();
        if let Some(err_node) = find_error_node(root) {
            let start = err_node.start_position();
            Some(format!(
                "Syntax error at line {}, column {} — check the generated code.",
                start.row + 1,
                start.column + 1
            ))
        } else {
            Some("Syntax error detected in generated code.".to_string())
        }
    } else {
        None
    }
}

/// Recursively find the first ERROR node in a tree-sitter tree.
fn find_error_node(node: tree_sitter::Node<'_>) -> Option<tree_sitter::Node<'_>> {
    if node.is_error() || node.is_missing() {
        return Some(node);
    }
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if let Some(err) = find_error_node(child) {
            return Some(err);
        }
    }
    None
}

fn resolve_path(path: &str, working_dir: &str) -> String {
    let candidate = if path.starts_with('/') {
        std::path::PathBuf::from(path)
    } else {
        std::path::Path::new(working_dir).join(path)
    };
    crate::agent::approval::normalize_path_lexical(&candidate)
        .to_string_lossy()
        .into_owned()
}