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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
use crate::agent::mentions;
use crate::agent::prompt;
use crate::config::AgentDef;
use crate::repo_map::RepoMap;

use super::App;

/// Compute the maximum scroll offset for a popup's content.
pub(super) fn popup_max_scroll(popup: &crate::tui::state::PopupState, term_height: u16) -> u16 {
    use crate::tui::state::PopupKind;
    let content_lines = match &popup.kind {
        PopupKind::Info => popup.content.lines().count(),
        PopupKind::Select { items, .. } => items.len() + 2,
        PopupKind::TableSelect { items, .. } => items.len(),
        PopupKind::Config { items, .. } => items.len(),
        PopupKind::SessionResume { items, .. } => items.len(),
        PopupKind::QueueConfirm { pending, .. } => pending.len() + 4,
        PopupKind::ContinuationConfirm { .. } => 6,
        PopupKind::ThemeSelect { .. } => crate::tui::theme::Theme::families().len(),
        PopupKind::ModeApproval { .. } => 8,
        PopupKind::McpToggle { items, .. } => items.len(),
        PopupKind::PiiWarning { findings, .. } => findings.len() + 5,
        PopupKind::OptimizeSuggestion { items, .. } => items.len() * 4 + 6,
        PopupKind::LspInstall { .. } => 8,
        PopupKind::ToolApproval { .. } => 9,
        PopupKind::InitConfirm { .. } => 6,
    } as u16;
    let popup_h = (term_height as f32 * 0.75).max(12.0) as u16;
    let inner_h = popup_h.saturating_sub(2); // borders
    content_lines.saturating_sub(inner_h)
}

/// Apply ConfigItems to the live Config and persist to disk.
pub(super) fn apply_config_changes(app: &mut App, items: &[crate::tui::state::ConfigItem]) {
    use crate::tui::state::ConfigValue;

    for item in items {
        match item.key.as_str() {
            "model" => {
                if let ConfigValue::Choice { ref value, .. } = item.value {
                    app.config.model = value.clone();
                    app.client.model = value.clone();
                    app.state.model_name = value.clone();
                }
            }
            "theme" => {
                if let ConfigValue::Choice { ref value, .. } = item.value {
                    app.state.set_theme(value);
                    app.config.theme = value.clone();
                    let _ = crate::config::save_ui_theme(value);
                }
            }
            "auto_commit" => {
                if let ConfigValue::Bool(b) = item.value {
                    app.config.auto_commit = b;
                }
            }
            "max_iterations" => {
                if let ConfigValue::Choice { ref value, .. } = item.value
                    && let Ok(n) = value.parse::<u32>()
                {
                    app.config.max_iterations = n;
                }
            }
            "tool_timeout_secs" => {
                if let ConfigValue::Choice { ref value, .. } = item.value
                    && let Ok(n) = value.parse::<u64>()
                {
                    app.config.tool_timeout_secs = n;
                }
            }
            "compaction_threshold" => {
                if let ConfigValue::Choice { ref value, .. } = item.value
                    && let Ok(f) = value.parse::<f32>()
                {
                    app.config.compaction_threshold = f;
                }
            }
            "context_max_tokens" => {
                if let ConfigValue::Choice { ref value, .. } = item.value
                    && let Ok(n) = value.parse::<usize>()
                {
                    app.config.context_max_tokens = n;
                    app.state.context_max_tokens = n;
                }
            }
            "debug_mode" => {
                if let ConfigValue::Bool(b) = item.value {
                    app.config.debug_mode = b;
                    app.state.debug_mode = b;
                    // Activate/deactivate metrics collector
                    if b && app.metrics_collector.is_none() {
                        app.metrics_collector =
                            Some(crate::util::process_metrics::MetricsCollector::new());
                    } else if !b {
                        app.metrics_collector = None;
                    }
                }
            }
            // ── Collaboration ──
            "collab_mode" => {
                if let ConfigValue::Choice { ref value, .. } = item.value {
                    use crate::agent::swarm::config::CollaborationMode;
                    app.config.collaboration.mode = match value.as_str() {
                        "fork" => CollaborationMode::Fork,
                        "hive" => CollaborationMode::Hive,
                        "flock" => CollaborationMode::Flock,
                        _ => CollaborationMode::None,
                    };
                }
            }
            "collab_worktree" => {
                if let ConfigValue::Bool(b) = item.value {
                    app.config.collaboration.worktree = b;
                }
            }
            "collab_max_agents" => {
                if let ConfigValue::Choice { ref value, .. } = item.value
                    && let Ok(n) = value.parse::<usize>()
                {
                    app.config.collaboration.max_agents = n;
                }
            }
            "collab_strategy" => {
                if let ConfigValue::Choice { ref value, .. } = item.value {
                    use crate::agent::swarm::config::SwarmStrategy;
                    app.config.collaboration.strategy = match value.as_str() {
                        "role_based" => SwarmStrategy::RoleBased,
                        "plan_review_execute" => SwarmStrategy::PlanReviewExecute,
                        _ => SwarmStrategy::AutoSplit,
                    };
                }
            }
            "collab_conflict_resolution" => {
                if let ConfigValue::Choice { ref value, .. } = item.value {
                    use crate::agent::swarm::config::ConflictResolution;
                    app.config.collaboration.conflict_resolution = match value.as_str() {
                        "last_writer_wins" => ConflictResolution::LastWriterWins,
                        "user_resolves" => ConflictResolution::UserResolves,
                        _ => ConflictResolution::CoordinatorResolves,
                    };
                }
            }
            _ => {}
        }
    }

    // Persist changes to config file
    if let Err(e) = persist_config(&app.config) {
        app.state.status_msg = format!("Config save error: {e}");
    } else {
        app.state.status_msg = "Configuration saved".to_string();
    }
}

/// Write changed fields back to the TOML config file.
pub(super) fn persist_config(config: &crate::config::Config) -> anyhow::Result<()> {
    use crate::config::{ConfigFile, config_file_path, ensure_config_dir};

    ensure_config_dir()?;
    let path = config_file_path();

    // Read existing file or start fresh
    let mut file_cfg: ConfigFile = if path.exists() {
        let raw = std::fs::read_to_string(&path)?;
        toml::from_str(&raw)?
    } else {
        ConfigFile::default()
    };

    // Patch only the fields we manage
    file_cfg.api.model = Some(config.model.clone());
    file_cfg.ui.theme = Some(config.theme.clone());
    file_cfg.hooks.auto_commit = Some(config.auto_commit);
    file_cfg.agent.max_iterations = Some(config.max_iterations);
    file_cfg.agent.tool_timeout_secs = Some(config.tool_timeout_secs);
    file_cfg.agent.stream_max_retries = Some(config.stream_max_retries);
    file_cfg.agent.iteration_delay_ms = Some(config.iteration_delay_ms);
    file_cfg.context.compaction_threshold = Some(config.compaction_threshold);
    file_cfg.context.max_tokens = Some(config.context_max_tokens);

    // Debug / Collaboration
    file_cfg.ui.debug_mode = Some(config.debug_mode);
    file_cfg.collaboration.mode = Some(config.collaboration.mode.clone());
    file_cfg.collaboration.max_agents = Some(config.collaboration.max_agents);
    file_cfg.collaboration.worktree = Some(config.collaboration.worktree);
    file_cfg.collaboration.strategy = Some(config.collaboration.strategy.clone());
    file_cfg.collaboration.conflict_resolution =
        Some(config.collaboration.conflict_resolution.clone());

    // Persist collet_home only if it differs from the default (~/.collet)
    let default_home = crate::config::collet_home(None);
    if config.collet_home != default_home {
        file_cfg.paths.home = Some(config.collet_home.to_string_lossy().into_owned());
    }

    crate::config::write_config_commented(&path, &file_cfg)?;
    Ok(())
}

/// Build the `/init` analysis prompt that asks the agent to generate AGENTS.md.
///
/// Follows the AGENTS.md standard (Linux Foundation / Agentic AI Foundation, 2026)
/// with 6 core sections: Commands, Project Structure, Code Style, Testing,
/// Git Workflow, Boundaries — plus collet-specific agent role definitions.
/// Whether `/init` should merge into an existing AGENTS.md or replace it.
#[derive(Debug, Clone, Copy)]
pub(super) enum InitMode {
    /// Preserve user-edited sections; update only what has changed.
    Merge,
    /// Discard the existing file and regenerate from scratch.
    Replace,
}

pub(super) fn build_init_prompt(working_dir: &str, mode: InitMode) -> String {
    let agents_md_path = format!("{working_dir}/AGENTS.md");
    let mode_instruction = match mode {
        InitMode::Merge => format!(
            "Read the existing `{agents_md_path}` first. \
             Preserve any user-customized content (custom agent roles, hand-written Boundaries, etc.) \
             and update only sections that have changed based on the current project state."
        ),
        InitMode::Replace => format!(
            "Discard the existing `{agents_md_path}` and regenerate it entirely from scratch."
        ),
    };
    format!(
        r#"Generate `{agents_md_path}` from thorough project analysis.

{mode_instruction}

## Steps
1. Read: README, Cargo.toml/package.json/go.mod/pubspec.yaml, entry points, CI config, tests, lint config
2. If CONTRIBUTING.md or STYLE_GUIDE.md exists → treat as authoritative for Boundaries/Code Style
3. Extract: languages+versions, commands (build/test/lint/format/codegen with flags), directory structure, conventions (naming, error handling, state management, async), git workflow, boundaries
4. Assign agent roles: `code` (always), `architect` (complex projects), `ask` (read-only), plus project-specific if needed
5. Write AGENTS.md using template below — fill ALL sections from analysis

## Template
```markdown
# AGENTS.md
## Commands
- Build: `<exact command>` | Test: `<with flags>` | Test single: `<single file>`
- Lint: `<command>` | Format: `<command>` | Run: `<dev server>`
- Gen/Sync: `<codegen commands or "N/A">`

## Project Structure
- `<dir>/` — <purpose> (list all key directories)

## Code Style
- Language/version, naming, error handling, imports, state/async patterns
### Golden Path
```<lang>
// 5-10 line ideal code snippet from this project
```

## Testing
- Framework | Run all: `<cmd>` | Coverage: `<cmd or "N/A">`
- File naming: `<pattern>` | Mocking: `<strategy or "N/A">`

## Git Workflow
- Branch strategy | Commit format | PR requirements

## Boundaries
- Always: <mandatory actions>
- Ask first: <needs approval>
- Never: <forbidden actions — be specific>
- Never: suppress linter warnings inline — fix the root cause instead
  <LINT_SUPPRESS_RULES: replace with language-specific rule if language detected, otherwise keep this line as-is>

```

## Rules
- Fill from analysis; if unknown → "Not observed". Prioritize existing docs (CONTRIBUTING.md etc.)
- Concise: snippets > prose. Commands: include exact flags. Boundaries: specific, not vague
- For <LINT_SUPPRESS_RULES>: detect project languages from Cargo.toml/package.json/go.mod/pyproject.toml/pubspec.yaml,
  then replace the placeholder with the matching never-rules:
  - Rust     → `Never: Use \`#[allow(...)]\` to suppress warnings — fix the root cause; use \`#[expect(...)]\` only with a tracking issue comment`
  - TypeScript/JavaScript → `Never: Use \`// eslint-disable\` or \`// @ts-ignore\` — fix the type/lint error directly`
  - Python   → `Never: Use \`# noqa\` or \`# type: ignore\` — fix the lint/type error at the source`
  - Go       → `Never: Use \`//nolint:\` directives — address the linter finding instead`
  - Dart/Flutter → `Never: Use \`// ignore:\` or \`// ignore_for_file:\` — resolve the analyzer warning`
  - If a language is not listed, omit the placeholder entirely.
- Report what you created when done."#
    )
}

/// Build system prompt using the type-safe prompt builder.
pub(super) fn build_system_prompt(repo_map: &RepoMap, reasoning: Option<&str>) -> String {
    build_system_prompt_with_agent(repo_map, reasoning, None, None)
}

/// Build system prompt with optional agent behavior from agents/*.md body.
pub(super) fn build_system_prompt_with_agent(
    repo_map: &RepoMap,
    reasoning: Option<&str>,
    agent_behavior: Option<&str>,
    soul_content: Option<&str>,
) -> String {
    prompt::build_prompt_with_agent(
        &repo_map.to_map_string(),
        repo_map.file_count(),
        repo_map.symbol_count(),
        reasoning,
        agent_behavior,
        None, // MCP overview injected later in the agent loop
        soul_content,
    )
}

/// Detect which language servers are available on this machine.
///
/// Checks `which <command>` for each known LSP server and returns the names
/// of those that are installed. Runs synchronously at startup (~2ms total).
pub(super) fn detect_available_lsp(working_dir: &str) -> Vec<String> {
    use crate::lsp::client::{extension_to_language_id, find_server_for_language, known_servers};
    use std::collections::HashSet;

    // Collect language IDs from file extensions present in the project.
    let project_langs: HashSet<String> = walkdir(working_dir)
        .filter_map(|ext| extension_to_language_id(ext.as_str()).map(|id| id.to_string()))
        .collect();

    // cpp shares clangd with c — add "c" if "cpp" is present.
    let mut langs = project_langs.clone();
    if langs.contains("cpp") {
        langs.insert("c".to_string());
    }
    if langs.contains("javascript") {
        langs.insert("typescript".to_string());
    }

    // From those languages, keep only servers that are installed.
    let candidate_commands: Vec<String> = langs
        .iter()
        .filter_map(|lang| find_server_for_language(lang))
        .map(|s| s.command)
        .collect::<std::collections::HashSet<_>>()
        .into_iter()
        .collect();

    // Run `which` checks in parallel for each candidate server.
    use rayon::prelude::*;
    let all_servers: Vec<_> = known_servers()
        .into_iter()
        .filter(|s| candidate_commands.contains(&s.command))
        .collect();
    let mut available: Vec<String> = all_servers
        .into_par_iter()
        .filter(|server| {
            std::process::Command::new("which")
                .arg(&server.command)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status()
                .map(|s| s.success())
                .unwrap_or(false)
        })
        .map(|server| server.command)
        .collect();
    available.dedup();

    tracing::info!(count = available.len(), servers = ?available, "LSP servers detected");
    available
}

/// Detect missing LSP servers for languages present in the project.
///
/// Returns a list of `(language_id, server_command, install_hint)` tuples for
/// languages that have a known server but none installed on `$PATH`.
pub(super) fn detect_missing_lsp(working_dir: &str) -> Vec<(String, String, String)> {
    use crate::lsp::client::{extension_to_language_id, find_missing_server_for_language};
    use std::collections::HashSet;

    let project_langs: HashSet<String> = walkdir(working_dir)
        .filter_map(|ext| extension_to_language_id(ext.as_str()).map(|id| id.to_string()))
        .collect();

    let mut langs = project_langs.clone();
    if langs.contains("cpp") {
        langs.insert("c".to_string());
    }
    if langs.contains("javascript") {
        langs.insert("typescript".to_string());
    }

    let mut missing = Vec::new();
    let mut seen_langs = HashSet::new();
    for lang in &langs {
        if seen_langs.contains(lang) {
            continue;
        }
        if let Some(cfg) = find_missing_server_for_language(lang)
            && let Some(hint) = cfg.install_hint
        {
            missing.push((lang.clone(), cfg.command.clone(), hint.to_string()));
            seen_langs.insert(lang.clone());
        }
    }

    if !missing.is_empty() {
        tracing::info!(count = missing.len(), langs = ?missing.iter().map(|(l,_,_)| l).collect::<Vec<_>>(), "Missing LSP servers detected");
    }
    missing
}

/// Walk `dir` (non-recursively into hidden dirs / target) and collect unique file extensions.
pub(super) fn walkdir(dir: &str) -> impl Iterator<Item = String> {
    let mut exts = std::collections::HashSet::new();
    let root = std::path::Path::new(dir);

    fn collect(path: &std::path::Path, exts: &mut std::collections::HashSet<String>, depth: u8) {
        if depth > 8 {
            return;
        }
        let Ok(entries) = std::fs::read_dir(path) else {
            return;
        };
        for entry in entries.flatten() {
            let p = entry.path();
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            // Skip hidden dirs and common non-source dirs.
            if name_str.starts_with('.')
                || matches!(
                    name_str.as_ref(),
                    "target" | "node_modules" | "vendor" | "dist" | "build"
                )
            {
                continue;
            }
            if p.is_dir() {
                collect(&p, exts, depth + 1);
            } else if let Some(ext) = p.extension().and_then(|e| e.to_str()) {
                exts.insert(ext.to_lowercase());
            }
        }
    }

    collect(root, &mut exts, 0);
    exts.into_iter()
}

/// Return the `@prefix` being typed at the cursor position, or None.
///
/// Scans left from cursor; if we hit `@` (preceded by start/whitespace), return
/// the text between `@` and the cursor. If we hit whitespace first, return None.
pub(super) fn at_prefix_at_cursor(input: &str, cursor: usize) -> Option<String> {
    let before = &input[..cursor.min(input.len())];
    // Walk backwards through characters
    let mut chars: Vec<(usize, char)> = before.char_indices().collect();
    chars.reverse();
    let mut token = String::new();
    for (byte_pos, ch) in chars {
        if ch == '@' {
            // Check the character before '@' is start or whitespace
            let prev_ok = byte_pos == 0
                || input[..byte_pos]
                    .chars()
                    .last()
                    .map(|c| c.is_whitespace())
                    .unwrap_or(true);
            if prev_ok {
                // Return the prefix (characters AFTER '@', reversed back)
                let collected: String = token.chars().rev().collect();
                return Some(collected);
            }
            return None;
        }
        if ch.is_whitespace() {
            return None;
        }
        token.push(ch);
    }
    None
}

/// Return the byte position of `@` that starts the mention at cursor.
pub(super) fn at_start_pos(input: &str, cursor: usize) -> Option<usize> {
    let before = &input[..cursor.min(input.len())];
    let chars: Vec<(usize, char)> = before.char_indices().collect();
    for i in (0..chars.len()).rev() {
        let (byte_pos, ch) = chars[i];
        if ch == '@' {
            let prev_ok = byte_pos == 0
                || input[..byte_pos]
                    .chars()
                    .last()
                    .map(|c| c.is_whitespace())
                    .unwrap_or(true);
            if prev_ok {
                return Some(byte_pos);
            }
            return None;
        }
        if ch.is_whitespace() {
            return None;
        }
    }
    None
}

/// Extract all `@agent-or-model` mentions from user input.
///
/// Returns `(cleaned_input, mentioned_agents)` where:
/// - `cleaned_input` has all resolved @mention tokens removed
/// - `mentioned_agents` contains all matched AgentDef in order of appearance
///
/// Priority per token:
///   1. Exact agent name match  (e.g., `@architect`)
///   2. Exact model name match  (e.g., `@glm-4-plus`)
///   3. Unique prefix/substring match against agent names then model names
///
/// File mentions (contains `.` or `/`) and names that exist on disk are
/// left for `mentions::extract_mentions` and never treated as agents.
pub(super) fn extract_agent_mention(
    input: &str,
    agents: &[AgentDef],
    working_dir: &str,
) -> (String, Vec<AgentDef>) {
    let mut result_input = input.to_string();
    let mut matched: Vec<AgentDef> = Vec::new();

    // Collect words from original input so we can replace them
    let words: Vec<&str> = input.split_whitespace().collect();
    for word in words {
        if !word.starts_with('@') || word.len() < 2 {
            continue;
        }

        let raw = &word[1..];

        // Skip file mentions (contain . or /)
        if raw.contains('/') || raw.contains('.') {
            continue;
        }

        // Skip if this name exists as a file or directory on disk
        if mentions::exists_on_disk(raw, working_dir) {
            continue;
        }

        let q = raw.to_lowercase();

        // Skip if already matched (dedup by agent name)
        let resolve = |agents: &[AgentDef]| -> Option<AgentDef> {
            // 1. Exact agent name
            if let Some(a) = agents.iter().find(|a| a.name.to_lowercase() == q) {
                return Some(a.clone());
            }
            // 2. Exact model name
            if let Some(a) = agents.iter().find(|a| a.model.to_lowercase() == q) {
                return Some(a.clone());
            }
            // 3. Unique prefix/substring — agent names first, then model names
            let name_hits: Vec<_> = agents
                .iter()
                .filter(|a| a.name.to_lowercase().contains(&q))
                .collect();
            if name_hits.len() == 1 {
                return Some(name_hits[0].clone());
            }
            let model_hits: Vec<_> = agents
                .iter()
                .filter(|a| a.model.to_lowercase().contains(&q))
                .collect();
            if model_hits.len() == 1 {
                return Some(model_hits[0].clone());
            }
            None
        };

        if let Some(agent) = resolve(agents) {
            // Only add if not already in list (avoid duplicates)
            if !matched.iter().any(|a| a.name == agent.name) {
                matched.push(agent);
            }
            // Remove the mention token from input
            result_input = result_input.replacen(word, "", 1);
            // Collapse any extra whitespace that may result
            result_input = result_input
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" ");
        }
    }

    (result_input, matched)
}

/// Truncate a string to a maximum length, adding "..." if truncated.
pub(super) fn truncate(s: &str, max: usize) -> String {
    // Count based on Unicode scalar values (chars), not bytes, to avoid
    // slicing in the middle of a multi-byte UTF-8 character.
    if s.chars().count() <= max {
        return s.to_string();
    }

    let mut end_byte = 0;

    for (count, (idx, ch)) in s.char_indices().enumerate() {
        if count == max {
            break;
        }
        end_byte = idx + ch.len_utf8();
    }

    format!("{}...", &s[..end_byte])
}

/// Return the theme ID for a given family index and dark/light preference.
///
/// If the family has no light variant and `dark_mode` is false, the dark ID
/// is returned as the only option available.
/// Return true when the message looks complex enough to warrant a mode-selection prompt.
///
/// Triggers when auto_suggest is enabled for fork OR hive, AND the message meets
/// at least one complexity criterion:
/// - length > 300 chars (detailed multi-step task)
/// - contains multi-task keywords in Korean or English
pub(super) fn should_suggest_mode(msg: &str, config: &crate::config::Config) -> bool {
    if !config.collaboration.auto_suggest {
        return false;
    }
    let lower = msg.to_lowercase();
    let long_enough = msg.len() > 300;
    let has_keyword = [
        // English
        "implement",
        "refactor",
        "build",
        "migrate",
        "integrate",
        "add feature",
        "create",
        "redesign",
        "rewrite",
        // Korean
        "구현",
        "리팩토링",
        "마이그레이션",
        "통합",
        "개발",
        "만들어",
        "작성해",
        "전체",
        "모두",
        "모든",
        "일괄",
        "일관",
    ]
    .iter()
    .any(|kw| lower.contains(kw));
    long_enough || has_keyword
}

/// Recommendation result for the ModeApproval popup.
pub(super) struct ModeRecommendation {
    /// Index into the popup choices: 0=Fork, 1=Hive, 2=Flock, 3=Single.
    pub(super) index: usize,
    /// Human-readable reason shown in the popup description.
    pub(super) reason: String,
}

/// Analyze the user message and recommend the most appropriate collaboration mode.
///
/// Heuristics (ordered by priority):
///   1. Consensus/review keywords → Hive (agents discuss and reach consensus)
///   2. Multiple independent files/modules mentioned → Fork (parallel split & merge)
///   3. Long complex message with mixed concerns → Flock (real-time coordination)
///   4. Fallback → Fork (safest parallel default)
pub(super) fn recommend_collab_mode(msg: &str) -> ModeRecommendation {
    let lower = msg.to_lowercase();

    // Count distinct file references as a proxy for parallelism potential
    let file_exts = [
        ".rs", ".ts", ".tsx", ".js", ".jsx", ".py", ".go", ".vue", ".svelte",
    ];
    let file_count: usize = file_exts.iter().map(|ext| lower.matches(ext).count()).sum();

    // Count distinct directory/module references
    let dir_seps = msg.matches('/').count();

    // Consensus / review signals → Hive
    let consensus_keywords = [
        "review",
        "합의",
        "검토",
        "리뷰",
        "validate",
        "verify",
        "확인",
        "plan",
        "설계",
        "design",
        "architecture",
        "아키텍처",
        "pros and cons",
        "장단점",
        "trade-off",
        "트레이드오프",
    ];
    let needs_consensus = consensus_keywords.iter().any(|kw| lower.contains(kw));

    // Independent parallel signals → Fork
    let parallel_keywords = [
        "동시에",
        "병렬",
        "parallel",
        "simultaneously",
        "independently",
        "각각",
        "separately",
        "both",
        "모두 동시",
        "and also",
        "그리고 또",
    ];
    let wants_parallel = parallel_keywords.iter().any(|kw| lower.contains(kw));

    // Multi-concern signals → Flock
    let multi_concern_keywords = [
        "frontend and backend",
        "프론트엔드와 백엔드",
        "client and server",
        "클라이언트와 서버",
        "api and ui",
        "test and implement",
        "테스트와 구현",
    ];
    let multi_concern = multi_concern_keywords.iter().any(|kw| lower.contains(kw));

    if needs_consensus {
        ModeRecommendation {
            index: 1, // Hive
            reason: "A task requiring design/review/consensus was detected.\nHive mode is recommended (agents reach consensus before execution).".to_string(),
        }
    } else if multi_concern && (file_count > 2 || msg.len() > 500) {
        ModeRecommendation {
            index: 2, // Flock
            reason: "A complex task spanning multiple domains was detected.\nFlock mode is recommended (real-time coordination between agents).".to_string(),
        }
    } else if file_count > 1 || dir_seps > 2 || wants_parallel {
        ModeRecommendation {
            index: 0, // Fork
            reason: "Independent tasks spanning multiple files/modules were detected.\nFork mode is recommended (parallel split → execute → merge).".to_string(),
        }
    } else if msg.len() > 500 {
        ModeRecommendation {
            index: 0, // Fork
            reason: "A detailed multi-step task was detected.\nFork mode is recommended (parallel split → execute → merge).".to_string(),
        }
    } else {
        ModeRecommendation {
            index: 3, // Single agent
            reason: "A complex task was detected.\nPlease select an execution mode.".to_string(),
        }
    }
}

pub(super) fn resolve_theme_id(family_idx: usize, dark_mode: bool) -> &'static str {
    let families = crate::tui::theme::Theme::families();
    let family = match families.get(family_idx) {
        Some(f) => f,
        None => return "default",
    };
    if dark_mode {
        family.dark_id
    } else {
        family.light_id.unwrap_or(family.dark_id)
    }
}

pub(super) fn mcp_json_path_for_toggle(working_dir: &str) -> std::path::PathBuf {
    // Prefer project config, fallback to user config
    let project = std::path::Path::new(working_dir)
        .join(".collet")
        .join("mcp.json");
    if project.exists() {
        project
    } else {
        crate::config::collet_home(None).join("mcp.json")
    }
}

pub(super) fn build_mcp_toggle_items(
    state: &crate::tui::state::UiState,
    working_dir: &str,
) -> Vec<crate::tui::state::McpToggleItem> {
    use crate::mcp::config::McpStatus;
    use crate::tui::state::McpToggleItem;

    let config_path = mcp_json_path_for_toggle(working_dir);
    let raw = std::fs::read_to_string(&config_path).unwrap_or_default();
    let parsed: serde_json::Value = serde_json::from_str(&raw).unwrap_or_default();
    let servers_obj = parsed
        .get("mcpServers")
        .or_else(|| parsed.get("servers"))
        .and_then(|v| v.as_object())
        .cloned()
        .unwrap_or_default();

    let mut items = Vec::new();
    for (name, cfg) in &servers_obj {
        let disabled = cfg
            .get("disabled")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let sidebar_status = state
            .mcp_servers
            .iter()
            .find(|s| &s.name == name)
            .map(|s| match s.status {
                McpStatus::Available => "available",
                McpStatus::Unavailable => "unavailable",
            })
            .unwrap_or("unknown");

        let tool_count = state
            .mcp_servers
            .iter()
            .find(|s| &s.name == name)
            .map(|_| 0usize) // McpServerUi doesn't have tool_count
            .unwrap_or(0);

        items.push(McpToggleItem {
            name: name.clone(),
            enabled: !disabled,
            tool_count,
            status: sidebar_status.to_string(),
            description: String::new(),
        });
    }
    items
}

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

    fn agents() -> Vec<AgentDef> {
        vec![
            AgentDef {
                name: "code".into(),
                model: "glm-4.5".into(),
                ..AgentDef::default()
            },
            AgentDef {
                name: "flash".into(),
                model: "glm-4.5-air".into(),
                ..AgentDef::default()
            },
            AgentDef {
                name: "pro".into(),
                model: "glm-4.7".into(),
                ..AgentDef::default()
            },
            AgentDef {
                name: "architect".into(),
                model: "glm-4-plus".into(),
                ..AgentDef::default()
            },
            AgentDef {
                name: "ultra".into(),
                model: "glm-5".into(),
                ..AgentDef::default()
            },
        ]
    }

    #[test]
    fn test_agent_mention_exact_name() {
        let (text, agents_found) =
            extract_agent_mention("@architect fix the bug", &agents(), "/nonexistent");
        assert_eq!(agents_found.len(), 1);
        assert_eq!(agents_found[0].name, "architect");
        assert_eq!(agents_found[0].model, "glm-4-plus");
        assert_eq!(text, "fix the bug");
    }

    #[test]
    fn test_agent_mention_exact_model() {
        let (text, agents_found) =
            extract_agent_mention("@glm-5 fix the bug", &agents(), "/nonexistent");
        assert_eq!(agents_found.len(), 1);
        assert_eq!(agents_found[0].name, "ultra");
        assert_eq!(text, "fix the bug");
    }

    #[test]
    fn test_agent_mention_name_prefix_unique() {
        // "arch" uniquely prefixes "architect"
        let (text, agents_found) =
            extract_agent_mention("@arch plan this", &agents(), "/nonexistent");
        assert_eq!(agents_found.len(), 1);
        assert_eq!(agents_found[0].name, "architect");
        assert_eq!(text, "plan this");
    }

    #[test]
    fn test_agent_mention_ambiguous_no_match() {
        let (_, agents_found) = extract_agent_mention("@zzz fix it", &agents(), "/nonexistent");
        assert!(agents_found.is_empty());
    }

    #[test]
    fn test_agent_mention_file_not_matched() {
        let (text, agents_found) =
            extract_agent_mention("fix @src/main.rs please", &agents(), "/nonexistent");
        assert!(agents_found.is_empty());
        assert!(text.contains("@src/main.rs"));
    }

    #[test]
    fn test_agent_mention_no_mention() {
        let (text, agents_found) =
            extract_agent_mention("just a normal message", &agents(), "/nonexistent");
        assert!(agents_found.is_empty());
        assert_eq!(text, "just a normal message");
    }

    #[test]
    fn test_agent_mention_at_end() {
        let (text, agents_found) =
            extract_agent_mention("explain this @ultra", &agents(), "/nonexistent");
        assert_eq!(agents_found.len(), 1);
        assert_eq!(agents_found[0].model, "glm-5");
        assert_eq!(text, "explain this");
    }

    #[test]
    fn test_agent_mention_case_insensitive() {
        let (_, agents_found) =
            extract_agent_mention("@ARCHITECT do it", &agents(), "/nonexistent");
        assert_eq!(agents_found[0].name, "architect");
    }

    #[test]
    fn test_agent_mention_skipped_when_dir_exists() {
        let tmp = std::env::temp_dir().join("collet_agent_dir_test");
        let _ = std::fs::remove_dir_all(&tmp);
        std::fs::create_dir_all(tmp.join("code")).unwrap();

        let wd = tmp.to_str().unwrap();
        // "code" exists on disk as a dir — should NOT match the "code" agent
        let (text, agents_found) = extract_agent_mention("@code fix it", &agents(), wd);
        assert!(
            agents_found.is_empty(),
            "Should skip @code because it's a directory on disk"
        );
        assert!(text.contains("@code"));

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn test_agent_mention_multiple() {
        // @architect and @ultra both mentioned — both should be collected
        let (text, agents_found) = extract_agent_mention(
            "@architect and @ultra review this",
            &agents(),
            "/nonexistent",
        );
        assert_eq!(agents_found.len(), 2);
        assert_eq!(agents_found[0].name, "architect");
        assert_eq!(agents_found[1].name, "ultra");
        assert_eq!(text, "and review this");
    }

    #[test]
    fn test_agent_mention_dedup() {
        // Same agent mentioned twice — should appear only once
        let (_, agents_found) =
            extract_agent_mention("@architect and @architect", &agents(), "/nonexistent");
        assert_eq!(agents_found.len(), 1);
    }
}