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
//! Swarm coordinator: orchestrates parallel agent execution.
//!
//! Phases:
//!   1. analyze_and_split — use coordinator LLM to decompose task
//!   2. execute_parallel  — spawn independent agent loops (work-stealing queue)
//!   3. detect_and_resolve_conflicts — check SharedKnowledge for overlapping edits
//!   4. verify_merge      — run `cargo check` to validate integration
//!   5. merge_results     — build coherent summary

use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

use crate::agent::context::ConversationContext;
use crate::agent::r#loop::AgentEvent;
use crate::agent::subagent::SubagentResult;
use crate::agent::swarm::config::CollaborationConfig;
use crate::agent::swarm::conflict;
use crate::agent::swarm::knowledge::{
    CheckpointTask, ExecutionCheckpoint, SharedKnowledge, clear_checkpoint, load_checkpoint,
    save_checkpoint,
};
use crate::api::models::Message;
use crate::api::provider::OpenAiCompatibleProvider;
use crate::config::Config;

mod analysis;
mod execution;
mod merge;
mod plan_review;
mod run_strategy;
mod scheduler;

pub use scheduler::{SwarmTask, VerificationResult};
use scheduler::{
    TaskScheduler, enforce_file_disjoint, is_trivially_sequential, parse_task_json, truncate,
};

#[cfg(test)]
mod tests;

/// Heartbeat interval during work-stealing execution (ms).
pub(super) const HEARTBEAT_INTERVAL_MS: u64 = 5_000;
/// Checkpoint is considered stale after this duration (ms) — triggers recovery.
const CHECKPOINT_STALE_TIMEOUT_MS: u64 = 120_000; // 2 minutes

/// Orchestrates parallel agent execution for flock mode.
pub struct SwarmCoordinator {
    pub(super) config: Config,
    pub(super) hive_config: CollaborationConfig,
    pub(super) client: OpenAiCompatibleProvider,
    pub(super) knowledge: SharedKnowledge,
    pub(super) working_dir: String,
    pub(super) lsp_manager: crate::lsp::manager::LspManager,
    /// All registered agent definitions — passed into the split prompt so the
    /// coordinator LLM can assign tasks to specific agents by name/description.
    pub(super) available_agents: Vec<crate::config::AgentDef>,
    /// Shared session-level approval cache (set by the TUI before spawning).
    pub(super) session_approvals: Option<crate::agent::approval::SessionApprovals>,
    /// Sender half of the approval request channel (set by the TUI before spawning).
    pub(super) approval_req_tx:
        Option<tokio::sync::mpsc::UnboundedSender<crate::agent::approval::ApprovalRequest>>,
    /// Shared approval mode (set by the TUI before spawning).
    pub(super) approve_mode: Option<crate::agent::approval::SharedApproveMode>,
    /// When set, the coordinator biases agent selection toward this agent name.
    /// This preserves the user's Tab-selected agent in parallel/swarm mode.
    pub(super) preferred_agent: Option<String>,
    /// Agents explicitly requested via @mention in addition to the primary (Tab) agent.
    /// The coordinator must assign at least one subtask to each of these agents.
    pub(super) additional_agents: Vec<String>,
    /// Shared resources built once (lazily) and distributed to all workers.
    /// Uses `OnceCell` so `ensure_shared_resources` only needs `&self`.
    pub(super) shared_resources: tokio::sync::OnceCell<SharedWorkerResources>,
}

/// Pre-built resources shared across all swarm workers.
///
/// Built lazily on first dispatch via `OnceCell`, then cloned into each worker.
pub(super) struct SharedWorkerResources {
    pub(super) tool_index: std::sync::Arc<crate::tools::tool_index::ToolIndex>,
    pub(super) skill_registry: std::sync::Arc<crate::skills::SkillRegistry>,
    pub(super) mcp: std::sync::Arc<crate::mcp::manager::McpManager>,
}

impl SwarmCoordinator {
    pub fn new(
        config: Config,
        hive_config: CollaborationConfig,
        client: OpenAiCompatibleProvider,
        working_dir: String,
        lsp_manager: crate::lsp::manager::LspManager,
        available_agents: Vec<crate::config::AgentDef>,
    ) -> Self {
        Self {
            config,
            hive_config,
            client,
            knowledge: SharedKnowledge::new(),
            working_dir,
            lsp_manager,
            available_agents,
            preferred_agent: None,
            additional_agents: Vec::new(),
            session_approvals: None,
            approval_req_tx: None,
            approve_mode: None,
            shared_resources: tokio::sync::OnceCell::new(),
        }
    }

    /// Set the user's preferred agent — preserves Tab selection in swarm/parallel mode.
    pub fn with_preferred_agent(mut self, agent_name: impl Into<String>) -> Self {
        self.preferred_agent = Some(agent_name.into());
        self
    }

    /// Set additional agents explicitly requested via @mention.
    ///
    /// The coordinator will ensure each of these agents is assigned at least
    /// one subtask, mirroring the validation logic for `preferred_agent`.
    pub fn with_additional_agents(mut self, agents: Vec<String>) -> Self {
        // Filter to only agents that actually exist in the roster
        self.additional_agents = agents
            .into_iter()
            .filter(|name| self.available_agents.iter().any(|a| &a.name == name))
            .collect();
        self
    }

    /// Inject pre-built shared resources (MCP, skills, tool index) so workers
    /// don't block on lazy initialization. Call this when the App already has
    /// cached MCP/skills from startup.
    pub fn with_shared_resources(
        self,
        mcp: std::sync::Arc<crate::mcp::manager::McpManager>,
        skills: std::sync::Arc<crate::skills::SkillRegistry>,
        tool_index: std::sync::Arc<crate::tools::tool_index::ToolIndex>,
    ) -> Self {
        let _ = self.shared_resources.set(SharedWorkerResources {
            tool_index,
            skill_registry: skills,
            mcp,
        });
        self
    }

    /// Get a clone of the shared knowledge handle for external controllers (TUI).
    pub fn shared_knowledge(&self) -> SharedKnowledge {
        self.knowledge.clone()
    }

    /// Attach the TUI-level approval gate components so hive agents share the
    /// same session cache and request channel as the main agent.
    pub fn with_approval(
        mut self,
        approve_mode: crate::agent::approval::SharedApproveMode,
        approval_req_tx: tokio::sync::mpsc::UnboundedSender<
            crate::agent::approval::ApprovalRequest,
        >,
        session_approvals: crate::agent::approval::SessionApprovals,
    ) -> Self {
        self.approve_mode = Some(approve_mode);
        self.approval_req_tx = Some(approval_req_tx);
        self.session_approvals = Some(session_approvals);
        self
    }

    /// Build an approval gate for a hive sub-agent.
    ///
    /// Falls back to yolo if the coordinator was not given approval components.
    pub(super) fn make_approval_gate(&self) -> crate::agent::approval::ApprovalGate {
        match (
            &self.approve_mode,
            &self.approval_req_tx,
            &self.session_approvals,
        ) {
            (Some(mode), Some(tx), Some(sa)) => {
                crate::agent::approval::ApprovalGate::new_with_session(
                    mode.clone(),
                    tx.clone(),
                    sa.clone(),
                )
            }
            _ => crate::agent::approval::ApprovalGate::yolo(),
        }
    }

    /// Human-readable mode label for status messages (e.g. "Flock", "Hive", "Fork").
    pub(super) fn mode_label(&self) -> String {
        let raw = self.hive_config.mode.label();
        let mut s = raw.to_string();
        if let Some(c) = s.get_mut(0..1) {
            c.make_ascii_uppercase();
        }
        s
    }

    /// Determine the display label for single-agent fallback.
    /// Returns the user's preferred agent name, or the short model name as a neutral fallback.
    pub(super) fn single_agent_label(&self) -> String {
        // Honor the user's explicitly selected agent first.
        if let Some(ref name) = self.preferred_agent {
            return name.clone();
        }
        // Coordinator LLM should always populate agent_name; this is a last-resort
        // fallback so the UI never shows a raw model name.
        "assistant".to_string()
    }

    /// Build a client using the lightest available agent's model.
    /// Used for cheap utility calls (e.g. query translation) that don't need a powerful model.
    /// Falls back to `self.client` if no light-tier agent is configured.
    pub(super) fn client_for_light_tier(&self) -> OpenAiCompatibleProvider {
        let light_agent = self
            .available_agents
            .iter()
            .find(|a| a.tier.as_deref() == Some("light") && !a.model.is_empty());
        if let Some(agent) = light_agent {
            if let Ok(file) = crate::config::load_config_file() {
                for entry in &file.providers {
                    if entry.all_models().contains(&agent.model.as_str()) && !entry.is_cli() {
                        let api_key = entry
                            .api_key_enc
                            .as_deref()
                            .and_then(|enc| crate::config::decrypt_key(enc).ok())
                            .unwrap_or_else(|| self.client.api_key().to_string());
                        if let Ok(client) = OpenAiCompatibleProvider::from_entry(
                            entry,
                            &api_key,
                            &agent.model,
                            std::collections::HashMap::new(),
                        ) {
                            return client;
                        }
                    }
                }
            }
            let mut c = self.client.clone();
            c.model = agent.model.clone();
            return c;
        }
        self.client.clone()
    }

    #[allow(dead_code)]
    /// Translate a non-English query to English.
    /// Uses the light-tier model to minimize cost. Returns `None` on failure.
    pub(super) async fn translate_query_to_english(&self, query: &str) -> Option<String> {
        use crate::api::models::{ChatRequest, Message};
        let client = self.client_for_light_tier();
        let req = ChatRequest {
            model: client.model.clone(),
            messages: vec![
                Message {
                    role: "system".to_string(),
                    content: Some(crate::api::content::Content::text(
                        "You are a translator. Output only the English translation of the given \
                         text, nothing else.",
                    )),
                    reasoning_content: None,
                    tool_calls: None,
                    tool_call_id: None,
                },
                Message {
                    role: "user".to_string(),
                    content: Some(crate::api::content::Content::text(format!(
                        "Translate the following task description to English. \
                         Reply with only the translation, no explanation:\n\n{query}"
                    ))),
                    reasoning_content: None,
                    tool_calls: None,
                    tool_call_id: None,
                },
            ],
            tools: None,
            tool_choice: None,
            max_tokens: 200,
            stream: false,
            temperature: Some(0.0),
            thinking_budget_tokens: None,
            reasoning_effort: None,
        };
        match client.chat(&req).await {
            Ok(resp) => {
                let text = resp
                    .choices
                    .into_iter()
                    .next()
                    .and_then(|c| c.message.content)
                    .map(|c| c.text_content())
                    .unwrap_or_default();
                let text = text.trim().to_string();
                if text.is_empty() { None } else { Some(text) }
            }
            Err(e) => {
                tracing::debug!(error = %e, "Query translation failed; falling back to full roster");
                None
            }
        }
    }

    /// Build a client with the preferred agent's model applied (if set).
    /// Returns a clone of `self.client` with `model` overridden when the preferred
    /// agent exists in the roster and declares a non-empty model.
    pub(super) fn client_for_preferred_agent(&self) -> OpenAiCompatibleProvider {
        if let Some(ref name) = self.preferred_agent
            && let Some(agent) = self.available_agents.iter().find(|a| &a.name == name)
            && !agent.model.is_empty()
        {
            // Log the resolved capabilities for this agent+model combination.
            let model = &agent.model;
            tracing::debug!(
                agent = %name,
                model = %model,
                max_output_tokens = self.config.resolve_max_output_tokens(model, Some(agent)),
                supports_tools   = self.config.resolve_supports_tools(model, Some(agent)),
                supports_reasoning = self.config.resolve_supports_reasoning(model, Some(agent)),
                context_window   = self.config.resolve_context_window(model, Some(agent)),
                max_iterations   = self.config.resolve_max_iterations(model, Some(agent)),
                iteration_delay_ms = self.config.resolve_iteration_delay_ms(model, Some(agent)),
                "Swarm: resolved capabilities for preferred agent"
            );
            // When the agent's model belongs to a different provider, construct a
            // fresh client so the correct base URL and credentials are used.
            if let Ok(file) = crate::config::load_config_file() {
                for entry in &file.providers {
                    if entry.all_models().contains(&agent.model.as_str()) && !entry.is_cli() {
                        let api_key = entry
                            .api_key_enc
                            .as_deref()
                            .and_then(|enc| crate::config::decrypt_key(enc).ok())
                            .unwrap_or_else(|| self.client.api_key().to_string());
                        if let Ok(client) = OpenAiCompatibleProvider::from_entry(
                            entry,
                            &api_key,
                            &agent.model,
                            std::collections::HashMap::new(),
                        ) {
                            return client;
                        }
                    }
                }
            }
            let mut c = self.client.clone();
            c.model = agent.model.clone();
            return c;
        }
        self.client.clone()
    }

    /// Build a `Config` clone with CLI passthrough fields aligned to the
    /// preferred agent's provider. When the preferred agent's model belongs to
    /// a CLI provider entry, set `config.cli`/`config.cli_args` so the agent
    /// loop takes the CLI fast-path; otherwise clear them so HTTP is used.
    /// Without this, delegating to a preferred agent inherits the *active*
    /// app provider's CLI state, which causes e.g. an HTTP provider to be
    /// invoked with a CLI-only model (or vice versa).
    pub(super) fn config_for_preferred_agent(&self) -> Config {
        let mut cfg = self.config.clone();
        let Some(ref name) = self.preferred_agent else {
            return cfg;
        };
        let Some(agent) = self.available_agents.iter().find(|a| &a.name == name) else {
            return cfg;
        };
        if agent.model.is_empty() {
            return cfg;
        }
        let Ok(file) = crate::config::load_config_file() else {
            return cfg;
        };
        for entry in &file.providers {
            if entry.all_models().contains(&agent.model.as_str()) {
                if entry.is_cli() {
                    cfg.cli = entry.cli.clone();
                    cfg.cli_args = entry.cli_args.clone();
                } else {
                    cfg.cli = None;
                    cfg.cli_args = Vec::new();
                }
                break;
            }
        }
        cfg
    }

    /// Apply the preferred agent's system prompt to the conversation context.
    /// Used when delegating directly to a named agent without a coordinator LLM call.
    pub(super) fn apply_preferred_agent_prompt(
        &self,
        mut context: ConversationContext,
        agent_name: &str,
    ) -> ConversationContext {
        if let Some(agent) = self
            .available_agents
            .iter()
            .find(|a| a.name.eq_ignore_ascii_case(agent_name))
            && !agent.system_prompt.is_empty()
        {
            context.update_system_prompt(agent.system_prompt.clone());
        }
        context
    }

    /// Build shared resources (ToolIndex, SkillRegistry, MCP) once for all workers.
    ///
    /// Uses `OnceCell` so this only needs `&self` — safe to call from `run()`.
    /// First call builds everything; subsequent calls return the cached instance.
    pub(super) async fn ensure_shared_resources(&self) -> &SharedWorkerResources {
        self.shared_resources
            .get_or_init(|| async {
                // Skill registry
                let skill_registry = std::sync::Arc::new(crate::skills::SkillRegistry::discover(
                    std::path::Path::new(&self.working_dir),
                ));

                // MCP connections
                let mcp = std::sync::Arc::new(
                    crate::mcp::manager::McpManager::connect_all(&self.working_dir).await,
                );

                // Full ToolIndex: MCP tools + skills + agents
                let mut tool_index = crate::tools::tool_index::ToolIndex::new();
                tool_index.index_mcp_tools(&mcp);
                tool_index.index_skills(&skill_registry);
                tool_index.index_agents(&self.available_agents);

                SharedWorkerResources {
                    tool_index: std::sync::Arc::new(tool_index),
                    skill_registry,
                    mcp,
                }
            })
            .await
    }

    /// Build a `SharedResources` bundle for a worker.
    pub(super) fn worker_resources(
        &self,
        shared: &SharedWorkerResources,
    ) -> crate::agent::subagent::SharedResources {
        crate::agent::subagent::SharedResources {
            mcp_manager: Some(shared.mcp.clone()),
            tool_index: Some(shared.tool_index.clone()),
            skill_registry: Some(shared.skill_registry.clone()),
            shared_knowledge: Some(self.knowledge.clone()),
            hook_runtime: None,
        }
    }

    /// Project-scoped data directory under `collet_home/projects/<hash>/`.
    pub(super) fn project_data_dir(&self) -> std::path::PathBuf {
        crate::config::project_data_dir_with(&self.working_dir, self.config.collet_home.to_str())
    }

    /// Path to the execution checkpoint file.
    pub(super) fn checkpoint_path(&self) -> std::path::PathBuf {
        self.project_data_dir().join("checkpoint.json")
    }

    /// Recovery-aware entry point: checks for an incomplete checkpoint and
    /// resumes from it if found, otherwise starts fresh via `run()`.
    ///
    /// This is the recommended entry point instead of calling `run()` directly.
    pub async fn run_or_recover(
        &self,
        context: ConversationContext,
        user_msg: String,
        event_tx: mpsc::UnboundedSender<AgentEvent>,
        cancel: CancellationToken,
    ) {
        let cp_path = self.checkpoint_path();

        // Check for incomplete checkpoint
        if cp_path.exists() {
            match load_checkpoint(&cp_path) {
                Ok(checkpoint)
                    if checkpoint.is_incomplete()
                        && checkpoint.is_stale(CHECKPOINT_STALE_TIMEOUT_MS) =>
                {
                    tracing::info!(
                        "Found stale checkpoint with {}/{} tasks complete — resuming",
                        checkpoint.completed_task_ids.len(),
                        checkpoint.tasks.len(),
                    );

                    let _ = event_tx.send(AgentEvent::PhaseChange {
                        label: format!(
                            "{} — recovering from checkpoint ({}/{} tasks done)...",
                            self.mode_label(),
                            checkpoint.completed_task_ids.len(),
                            checkpoint.tasks.len(),
                        ),
                    });

                    self.resume_from_checkpoint(context, checkpoint, event_tx, cancel)
                        .await;
                    return;
                }
                Ok(checkpoint) if checkpoint.finished => {
                    // Previous execution completed successfully — clean up
                    let _ = clear_checkpoint(&cp_path);
                }
                Ok(_) => {
                    // Checkpoint exists but isn't stale — another coordinator may be running
                    tracing::debug!("Active checkpoint found, starting fresh");
                    let _ = clear_checkpoint(&cp_path);
                }
                Err(e) => {
                    tracing::debug!("Could not read checkpoint: {e}");
                    let _ = clear_checkpoint(&cp_path);
                }
            }
        }

        // No recovery needed — run fresh
        self.run(context, user_msg, event_tx, cancel).await;
    }

    /// Resume execution from a checkpoint, only running remaining tasks.
    pub(super) async fn resume_from_checkpoint(
        &self,
        context: ConversationContext,
        mut checkpoint: ExecutionCheckpoint,
        event_tx: mpsc::UnboundedSender<AgentEvent>,
        cancel: CancellationToken,
    ) {
        let system_prompt = context.system_prompt().to_string();

        // Restore knowledge base
        let kb_path = self.project_data_dir().join("knowledge.json");
        if kb_path.exists() {
            let _ = self.knowledge.load_from_file(&kb_path).await;
        }

        // Rebuild remaining tasks from checkpoint
        let remaining_ids = checkpoint.remaining_task_ids();
        let remaining_tasks: Vec<SwarmTask> = checkpoint
            .tasks
            .iter()
            .filter(|t| remaining_ids.contains(&t.id))
            .map(|t| SwarmTask {
                id: t.id.clone(),
                prompt: t.prompt.clone(),
                role: t.role.clone(),
                agent_name: t.agent_name.clone(),
                dependencies: t.dependencies.clone(),
                target_files: t.target_files.clone(),
            })
            .collect();

        if remaining_tasks.is_empty() {
            checkpoint.mark_finished();
            let _ = save_checkpoint(&checkpoint, &self.checkpoint_path());
            let _ = clear_checkpoint(&self.checkpoint_path());
            let _ = event_tx.send(AgentEvent::Done {
                context,
                stop_reason: None,
            });
            return;
        }

        let _ = event_tx.send(AgentEvent::PhaseChange {
            label: format!(
                "{} — resuming {} remaining tasks...",
                self.mode_label(),
                remaining_tasks.len()
            ),
        });

        // Hive/Flock: release the user immediately for resumed tasks too.
        if self.hive_config.mode.has_consensus() {
            let _ = event_tx.send(AgentEvent::SwarmWorkersDispatched);
        }

        // Execute remaining tasks (reuse work-stealing logic)
        let results = self
            .execute_with_work_stealing_checkpointed(
                remaining_tasks,
                &system_prompt,
                &event_tx,
                &cancel,
                &mut checkpoint,
            )
            .await;

        // Merge all results (recovered + newly completed)
        let mut all_results: Vec<SubagentResult> = checkpoint
            .completed_results
            .iter()
            .map(|cr| SubagentResult {
                id: cr.id.clone(),
                success: cr.success,
                response: cr.response.clone(),
                modified_files: cr.modified_files.clone(),
                tool_calls: cr.tool_calls,
                input_tokens: cr.input_tokens,
                output_tokens: cr.output_tokens,
                continuation_hint: None,
            })
            .collect();
        all_results.extend(results);

        // Phase 3-5: conflicts, verification, merge (same as run())
        let mut conflicts = conflict::detect_conflicts(&self.knowledge).await;
        self.resolve_conflicts(&mut conflicts, &event_tx).await;
        let verification = self.verify_merge(&event_tx).await;
        let merged = self.merge_results(&all_results, &conflicts, verification.as_ref());

        // Log knowledge base diagnostics for observability.
        let files_read = self.knowledge.all_files_read().await;
        let facts_about_results = self.knowledge.query_facts("result:").await;
        let recent_announcements = self.knowledge.announcements_since(0).await;
        tracing::debug!(
            files_read = files_read.len(),
            result_facts = facts_about_results.len(),
            announcements = recent_announcements.len(),
            "Knowledge base stats at swarm completion"
        );

        // Mark checkpoint finished and clean up
        checkpoint.mark_finished();
        let _ = save_checkpoint(&checkpoint, &self.checkpoint_path());
        let _ = clear_checkpoint(&self.checkpoint_path());

        // Persist knowledge
        if let Some(parent) = kb_path.parent() {
            let _ = tokio::fs::create_dir_all(parent).await;
        }
        let _ = self.knowledge.save_to_file(&kb_path).await;

        let total_tool_calls: u32 = all_results.iter().map(|r| r.tool_calls).sum();
        let mut merged_context = context;
        merged_context.push(Message {
            role: "assistant".to_string(),
            content: Some(crate::api::Content::text(merged.clone())),
            reasoning_content: None,
            tool_calls: None,
            tool_call_id: None,
        });

        let _ = event_tx.send(AgentEvent::SwarmDone {
            context: merged_context,
            merged_response: merged,
            agent_count: all_results.len(),
            total_tool_calls,
            conflicts_resolved: conflicts.len(),
        });
    }

    /// Main entry point: analyze task, split, execute, verify, merge.
    ///
    /// Branches into one of three strategies based on configuration:
    /// 1. CLI passthrough (provider is a CLI agent)
    /// 2. Plan-review-execute (Fork mode + `plan_review_execute` strategy)
    /// 3. Auto-split (default — coordinator LLM decomposes the task)
    ///
    /// Trivially-sequential requests bypass coordinator analysis when a
    /// preferred agent is set.
    pub async fn run(
        &self,
        context: ConversationContext,
        user_msg: String,
        event_tx: mpsc::UnboundedSender<AgentEvent>,
        cancel: CancellationToken,
    ) {
        let system_prompt = context.system_prompt().to_string();

        // Try to restore previous knowledge if available
        let kb_path = self.project_data_dir().join("knowledge.json");
        if kb_path.exists() {
            if let Err(e) = self.knowledge.load_from_file(&kb_path).await {
                tracing::debug!("Could not restore knowledge: {e}");
            } else {
                tracing::info!("Restored knowledge from {}", kb_path.display());
            }
        }

        // ── Static parallelization gate: CLI providers ──
        if self.config.cli.is_some() {
            self.try_cli_passthrough(context, user_msg, event_tx, cancel)
                .await;
            return;
        }

        // ── Static parallelization gate: non-parallel modes ──
        // When the collaboration mode is None (the default) or max_agents
        // is clamped to ≤1, the auto-split coordinator LLM call is pure
        // overhead — its result is always "single subtask". Skipping it
        // halves LLM calls per turn and removes the most common 429 source
        // when the upstream provider is overloaded.
        if !self.hive_config.mode.is_parallel() || self.hive_config.max_agents <= 1 {
            let agent_label = self.single_agent_label();
            let _ = event_tx.send(AgentEvent::SwarmResolvedToSingle {
                agent_label: agent_label.clone(),
            });
            let _ = event_tx.send(AgentEvent::PhaseChange {
                label: format!(
                    "{} — single-agent mode, skipping coordinator analysis...",
                    self.mode_label()
                ),
            });
            let context = self.apply_preferred_agent_prompt(context, &agent_label);
            self.delegate_single_agent(context, user_msg, event_tx, cancel)
                .await;
            return;
        }

        // ── Trivial sequential shortcut (only with a preferred agent) ──
        let (context, user_msg, event_tx, cancel) = match self
            .try_trivially_sequential(context, user_msg, event_tx, cancel)
            .await
        {
            Ok(()) => return,
            Err(rest) => rest,
        };
        // arbor: no early return — fall through to coordinator LLM analysis so it
        // can pick the right specialist agent even for simple tasks.

        // ── Strategy dispatch ──
        use crate::agent::swarm::config::SwarmStrategy;

        // Guard: warn when plan_review_execute is set for non-Fork modes.
        if self.hive_config.strategy == SwarmStrategy::PlanReviewExecute
            && self.hive_config.mode != crate::agent::swarm::config::CollaborationMode::Fork
        {
            tracing::warn!(
                "strategy 'plan_review_execute' is only valid for Fork mode (coordinator assigns roles). \
                 In Hive/Flock, workers self-select roles — falling back to auto_split. \
                 Set collaboration.mode = \"fork\" to enable plan-review.",
            );
            let _ = event_tx.send(AgentEvent::PhaseChange {
                label: format!(
                    "{} — ⚠ strategy 'plan_review_execute' is Fork-only; \
                     falling back to auto_split (workers self-select roles in Hive/Flock)",
                    self.mode_label()
                ),
            });
        }

        if self.hive_config.strategy == SwarmStrategy::PlanReviewExecute
            && self.hive_config.mode == crate::agent::swarm::config::CollaborationMode::Fork
        {
            self.run_plan_review_execute_strategy(
                context,
                user_msg,
                system_prompt,
                kb_path,
                event_tx,
                cancel,
            )
            .await;
            return;
        }

        self.run_auto_split_strategy(context, user_msg, system_prompt, kb_path, event_tx, cancel)
            .await;
    }
}