collet 0.1.0

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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use super::App;

use crate::tui::state::{AcCandidate, AcKind, MentionAc};

use super::utils::{at_prefix_at_cursor, at_start_pos};

/// Cached filesystem listing for `@`-mention autocomplete.
/// Avoids re-scanning the filesystem on every keystroke (4-level recursive walk).
struct FsCache {
    entries: Vec<(String, bool)>,
    created_at: std::time::Instant,
    working_dir: String,
}

/// How long the cached filesystem listing remains valid.
const FS_CACHE_TTL: std::time::Duration = std::time::Duration::from_millis(2000);

thread_local! {
    static FS_CACHE: std::cell::RefCell<Option<FsCache>> = const { std::cell::RefCell::new(None) };
}

/// Cached skill registry to avoid re-scanning on every keystroke.
struct SkillCache {
    skills: Vec<(String, String)>, // (name, description)
    created_at: std::time::Instant,
    working_dir: String,
}

const SKILL_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(5);

thread_local! {
    static SKILL_CACHE: std::cell::RefCell<Option<SkillCache>> = const { std::cell::RefCell::new(None) };
}

/// Fuzzy subsequence match. Returns a score if every char in `query` appears
/// in order within `target` (case-insensitive). Higher = better match.
///
/// Bonuses:
/// - Word/segment start (after `-`, `_`, `/`, space, or position 0): +10
/// - Consecutive match: +5
/// - Exact prefix (all matches are at positions 0..n): +20
fn fuzzy_score(query: &str, target: &str) -> Option<u32> {
    if query.is_empty() {
        return Some(0);
    }
    let q: Vec<char> = query.to_lowercase().chars().collect();
    let t: Vec<char> = target.to_lowercase().chars().collect();

    let mut qi = 0;
    let mut score = 0u32;
    let mut prev_match: Option<usize> = None;

    for (ti, &tc) in t.iter().enumerate() {
        if qi >= q.len() {
            break;
        }
        if tc == q[qi] {
            score += 1;
            let at_word_start = ti == 0 || matches!(t[ti - 1], '-' | '_' | '/' | ' ' | '.');
            if at_word_start {
                score += 10;
            }
            if let Some(prev) = prev_match
                && ti == prev + 1
            {
                score += 5;
            }
            prev_match = Some(ti);
            qi += 1;
        }
    }

    if qi == q.len() { Some(score) } else { None }
}

impl App {
    /// Recompute autocomplete candidates based on the `@prefix` at the cursor.
    pub(super) fn update_mention_ac(&mut self) {
        let prefix = match at_prefix_at_cursor(&self.state.input, self.state.cursor) {
            Some(p) => p,
            None => {
                self.state.mention_ac = None;
                return;
            }
        };

        let q = prefix.to_lowercase();
        let mut candidates: Vec<AcCandidate> = Vec::new();

        // Agent name matches — fuzzy, sorted by score descending
        let mut agent_scored: Vec<(u32, AcCandidate)> = self
            .config
            .agents
            .iter()
            .filter_map(|a| {
                fuzzy_score(&q, &a.name.to_lowercase()).map(|score| {
                    (
                        score,
                        AcCandidate {
                            label: format!("{} ({})", a.name, a.model),
                            kind: AcKind::Agent,
                        },
                    )
                })
            })
            .collect();
        agent_scored.sort_by(|a, b| b.0.cmp(&a.0));
        candidates.extend(agent_scored.into_iter().map(|(_, c)| c));

        // Filesystem candidates with fuzzy matching.
        //
        // Two modes:
        //   - Slash in prefix (e.g. "@src/ma"): search only inside that subdir, 1-level deep.
        //   - No slash (e.g. "@main"):           recursively collect up to 4 levels, fuzzy-rank.
        if let Some(slash_pos) = prefix.rfind('/') {
            // User is navigating a specific subdir — fuzzy match within that dir only.
            let subdir = &prefix[..slash_pos];
            // Guard: skip filesystem completion for paths that escape the working directory
            // (e.g. @../../.env). A ParentDir component (`..`) in any position is sufficient
            // to break out of the working dir tree.
            let has_traversal = std::path::Path::new(subdir)
                .components()
                .any(|c| matches!(c, std::path::Component::ParentDir));
            if !has_traversal {
                let file_q = prefix[slash_pos + 1..].to_lowercase();
                let dir_prefix = format!("{}/", subdir);
                let search_dir = format!("{}/{}", self.working_dir, subdir);

                // Secondary guard: canonicalize both paths and verify containment to
                // catch symlink-based escapes that bypass the ParentDir component check.
                // Falls back to `true` if either path doesn't exist yet (partial input).
                let within_working_dir = std::path::Path::new(&self.working_dir)
                    .canonicalize()
                    .and_then(|wd_canon| {
                        std::path::Path::new(&search_dir)
                            .canonicalize()
                            .map(|sd_canon| sd_canon.starts_with(wd_canon))
                    })
                    .unwrap_or(true);
                if !within_working_dir {
                    // skip — resolved path escapes working dir
                } else if let Ok(rd) = std::fs::read_dir(&search_dir) {
                    let mut scored: Vec<(u32, AcCandidate)> = rd
                        .filter_map(|e| e.ok())
                        .filter_map(|e| {
                            let name = e.file_name().to_string_lossy().to_string();
                            if name.starts_with('.') {
                                return None;
                            }
                            let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false);
                            let score = if file_q.is_empty() {
                                Some(0u32)
                            } else {
                                fuzzy_score(&file_q, &name.to_lowercase())
                            }?;
                            let label = if is_dir {
                                format!("{}{}/", dir_prefix, name)
                            } else {
                                format!("{}{}", dir_prefix, name)
                            };
                            Some((
                                score,
                                AcCandidate {
                                    label,
                                    kind: if is_dir { AcKind::Dir } else { AcKind::File },
                                },
                            ))
                        })
                        .collect();
                    scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.label.cmp(&b.1.label)));
                    candidates.extend(scored.into_iter().map(|(_, c)| c));
                }
            } // end if !has_traversal
        } else {
            // No slash — use cached filesystem listing (refreshed every 2s).
            let all_paths: Vec<(String, bool)> = FS_CACHE.with(|cell| {
                let mut cache = cell.borrow_mut();
                let valid = cache.as_ref().is_some_and(|c| {
                    c.working_dir == self.working_dir && c.created_at.elapsed() < FS_CACHE_TTL
                });
                if valid {
                    return cache.as_ref().unwrap().entries.clone();
                }
                let mut entries: Vec<(String, bool)> = Vec::new();
                collect_fs_recursive(
                    std::path::Path::new(&self.working_dir),
                    "",
                    0,
                    4,
                    &mut entries,
                );
                let result = entries.clone();
                *cache = Some(FsCache {
                    entries,
                    created_at: std::time::Instant::now(),
                    working_dir: self.working_dir.clone(),
                });
                result
            });

            let mut scored: Vec<(u32, AcCandidate)> = all_paths
                .into_iter()
                .filter_map(|(rel, is_dir)| {
                    let score = if q.is_empty() {
                        // Only show top-level entries when prefix is empty
                        if rel.contains('/') {
                            return None;
                        }
                        Some(0u32)
                    } else {
                        fuzzy_score(&q, &rel.to_lowercase())
                    }?;
                    let label = if is_dir {
                        format!("{}/", rel)
                    } else {
                        rel.clone()
                    };
                    Some((
                        score,
                        AcCandidate {
                            label,
                            kind: if is_dir { AcKind::Dir } else { AcKind::File },
                        },
                    ))
                })
                .collect();
            scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.label.cmp(&b.1.label)));
            candidates.extend(scored.into_iter().map(|(_, c)| c));
        }

        // Cap at 10 candidates
        candidates.truncate(10);

        if candidates.is_empty() {
            self.state.mention_ac = None;
        } else {
            let selected = self
                .state
                .mention_ac
                .as_ref()
                .map(|ac| ac.selected.min(candidates.len().saturating_sub(1)))
                .unwrap_or(0);
            self.state.mention_ac = Some(MentionAc {
                prefix,
                candidates,
                selected,
            });
        }
    }

    pub(super) fn update_command_ac(&mut self) {
        let trimmed = self.state.input.trim_start().to_string();
        if !trimmed.starts_with('/') || trimmed.contains(' ') {
            self.state.command_ac = None;
            // Clear hint once user starts typing args
            if trimmed.contains(' ') {
                self.state.input_hint = None;
            }
            return;
        }
        // Also clear hint when input changes (e.g. backspace removed the space)
        self.state.input_hint = None;
        let prefix = trimmed[1..].to_lowercase();

        // Collect built-in commands with fuzzy scores.
        let mut scored: Vec<(u32, AcCandidate)> = crate::commands::command_list()
            .iter()
            .filter_map(|(cmd, desc)| {
                fuzzy_score(&prefix, &cmd[1..]).map(|score| {
                    (
                        score,
                        AcCandidate {
                            label: format!("{}{}", cmd, desc),
                            kind: AcKind::Command,
                        },
                    )
                })
            })
            .collect();

        // Collect skills with fuzzy scores (cached to avoid re-scanning filesystem per keystroke).
        let skills = SKILL_CACHE.with(|cell| {
            let mut cache = cell.borrow_mut();
            let valid = cache.as_ref().is_some_and(|c| {
                c.working_dir == self.working_dir && c.created_at.elapsed() < SKILL_CACHE_TTL
            });
            if !valid {
                let registry =
                    crate::skills::SkillRegistry::discover(std::path::Path::new(&self.working_dir));
                let entries: Vec<(String, String)> = registry
                    .all()
                    .iter()
                    .map(|s| (s.name.clone(), s.description.clone()))
                    .collect();
                *cache = Some(SkillCache {
                    skills: entries,
                    created_at: std::time::Instant::now(),
                    working_dir: self.working_dir.clone(),
                });
            }
            cache.as_ref().unwrap().skills.clone()
        });
        for (name, description) in &skills {
            if let Some(score) = fuzzy_score(&prefix, name) {
                scored.push((
                    score,
                    AcCandidate {
                        label: format!("/{}{}", name, description),
                        kind: AcKind::Skill,
                    },
                ));
            }
        }

        // Sort by score descending (best match first).
        scored.sort_by(|a, b| b.0.cmp(&a.0));
        let candidates: Vec<AcCandidate> = scored.into_iter().map(|(_, c)| c).collect();

        if candidates.is_empty() {
            self.state.command_ac = None;
        } else {
            let selected = self
                .state
                .command_ac
                .as_ref()
                .map(|ac| ac.selected.min(candidates.len().saturating_sub(1)))
                .unwrap_or(0);
            self.state.command_ac = Some(MentionAc {
                prefix: trimmed[1..].to_string(),
                candidates,
                selected,
            });
        }
    }

    pub(super) fn mention_ac_next(&mut self) {
        if let Some(ref mut ac) = self.state.mention_ac {
            ac.selected = (ac.selected + 1) % ac.candidates.len();
        }
    }

    pub(super) fn mention_ac_prev(&mut self) {
        if let Some(ref mut ac) = self.state.mention_ac {
            let n = ac.candidates.len();
            ac.selected = (ac.selected + n - 1) % n;
        }
    }

    pub(super) fn command_ac_next(&mut self) {
        if let Some(ref mut ac) = self.state.command_ac {
            ac.selected = (ac.selected + 1) % ac.candidates.len();
        }
    }

    pub(super) fn command_ac_prev(&mut self) {
        if let Some(ref mut ac) = self.state.command_ac {
            let n = ac.candidates.len();
            ac.selected = (ac.selected + n - 1) % n;
        }
    }

    /// Complete command autocomplete (Enter behavior): replace command prefix, no hint injection.
    pub(super) fn command_ac_complete(&mut self) {
        let cmd = match &self.state.command_ac {
            Some(ac) => match ac.selected_candidate() {
                Some(c) => c.label.split_whitespace().next().unwrap_or("").to_string(),
                None => return,
            },
            None => return,
        };
        let existing = self.state.input.trim_start().to_string();
        let args_part = existing.find(' ').map(|i| &existing[i..]).unwrap_or("");
        let new_input = format!("{cmd}{args_part}");
        self.state.cursor = if args_part.is_empty() {
            self.state.input = cmd.clone();
            cmd.len()
        } else {
            self.state.input = new_input.clone();
            new_input.len()
        };
        self.state.input_hint = None;
        self.state.command_ac = None;
    }

    /// Tab-complete: complete command + inject subcommand hint if available.
    pub(super) fn command_ac_expand(&mut self) {
        let cmd = match &self.state.command_ac {
            Some(ac) => match ac.selected_candidate() {
                Some(c) => c.label.split_whitespace().next().unwrap_or("").to_string(),
                None => return,
            },
            None => return,
        };
        let existing = self.state.input.trim_start().to_string();
        let args_part = existing.find(' ').map(|i| &existing[i..]).unwrap_or("");

        if args_part.is_empty() {
            if let Some(hint) = crate::commands::subcommand_hint(&cmd) {
                // Inject "cmd " with trailing space + show hint
                let with_space = format!("{cmd} ");
                self.state.cursor = with_space.len();
                self.state.input = with_space;
                self.state.input_hint = Some(hint.to_string());
            } else {
                // No subcommands — just complete the command name
                self.state.input = cmd.clone();
                self.state.cursor = cmd.len();
                self.state.input_hint = None;
            }
        } else {
            let new_input = format!("{cmd}{args_part}");
            self.state.cursor = new_input.len();
            self.state.input = new_input;
            self.state.input_hint = None;
        }
        self.state.command_ac = None;
    }

    /// Complete the currently selected autocomplete candidate into the input.
    pub(super) fn mention_ac_complete(&mut self) {
        let (_prefix, label, is_dir) = match &self.state.mention_ac {
            Some(ac) => match ac.selected_candidate() {
                Some(c) => {
                    let raw = c.label.split_whitespace().next().unwrap_or("");
                    let is_dir = c.kind == AcKind::Dir;
                    // Keep trailing slash for dirs so the user can keep navigating;
                    // strip it for files/agents so the word is cleanly terminated.
                    let label = if is_dir {
                        raw.to_string()
                    } else {
                        raw.trim_end_matches('/').to_string()
                    };
                    (ac.prefix.clone(), label, is_dir)
                }
                None => return,
            },
            None => return,
        };

        // Replace @<prefix> at cursor with @<completion>.
        // For directories keep no trailing space so the user can continue typing;
        // for everything else append a space to separate from the next word.
        let cursor = self.state.cursor;
        let input = self.state.input.clone();

        if let Some(at_pos) = at_start_pos(&input, cursor) {
            let completion = if is_dir {
                format!("@{label}")
            } else {
                format!("@{label} ")
            };
            let new_input = format!("{}{}{}", &input[..at_pos], completion, &input[cursor..]);
            let new_cursor = at_pos + completion.len();
            self.state.input = new_input;
            self.state.cursor = new_cursor;
        }

        self.state.mention_ac = None;
    }
}

/// Recursively collect filesystem entries under `dir` up to `max_depth` levels.
///
/// Skips hidden entries (`.*`), `node_modules`, and `target`.
/// Each entry is stored as a relative path string (e.g. `"src/main.rs"`) plus a bool
/// indicating whether it is a directory.
fn collect_fs_recursive(
    dir: &std::path::Path,
    prefix: &str,
    depth: usize,
    max_depth: usize,
    out: &mut Vec<(String, bool)>,
) {
    if depth > max_depth {
        return;
    }
    let Ok(rd) = std::fs::read_dir(dir) else {
        return;
    };
    let mut entries: Vec<_> = rd.filter_map(|e| e.ok()).collect();
    entries.sort_by_key(|e| e.file_name());
    for entry in entries {
        let name = entry.file_name().to_string_lossy().to_string();
        if name.starts_with('.') || name == "node_modules" || name == "target" {
            continue;
        }
        let rel = if prefix.is_empty() {
            name.clone()
        } else {
            format!("{}/{}", prefix, name)
        };
        let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
        out.push((rel.clone(), is_dir));
        if is_dir {
            collect_fs_recursive(&entry.path(), &rel, depth + 1, max_depth, out);
        }
    }
}