collet 0.1.1

Relentless agentic coding orchestrator with zero-drop agent loops
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
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
//! Strategy branches extracted from `SwarmCoordinator::run`.
//!
//! The top-level `run` method in `mod.rs` is now a thin dispatcher that
//! decides which strategy applies (CLI passthrough, trivial-sequential
//! shortcut, plan-review-execute, or auto-split) and forwards to the
//! corresponding helper here.

use std::path::Path;

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

use super::{
    CheckpointTask, ExecutionCheckpoint, SwarmCoordinator, clear_checkpoint, conflict,
    save_checkpoint, scheduler::truncate,
};
use crate::agent::context::ConversationContext;
use crate::agent::r#loop::AgentEvent;
use crate::api::Content;
use crate::api::models::Message;

impl SwarmCoordinator {
    /// Delegate the entire turn to a single standard agent loop with the
    /// coordinator's standard parameter set. Used by every "fall back to a
    /// single agent" branch in `run`.
    pub(super) async fn delegate_single_agent(
        &self,
        context: ConversationContext,
        user_msg: String,
        event_tx: mpsc::UnboundedSender<AgentEvent>,
        cancel: CancellationToken,
    ) {
        crate::agent::r#loop::run_with_mode(crate::agent::r#loop::AgentParams {
            client: self.client_for_preferred_agent(),
            config: self.config_for_preferred_agent(),
            context,
            user_msg,
            working_dir: self.working_dir.clone(),
            event_tx,
            cancel,
            lsp_manager: self.lsp_manager.clone(),
            trust_level: crate::trust::TrustLevel::Full,
            approval_gate: self.make_approval_gate(),
            images: Vec::new(),
        })
        .await;
    }

    /// CLI provider passthrough — when the active provider is a CLI agent,
    /// the coordinator's HTTP-based analysis can't run. Delegate the whole
    /// turn to a single agent loop instead. Returns `true` when the request
    /// was handled (caller should return early).
    pub(super) async fn try_cli_passthrough(
        &self,
        context: ConversationContext,
        user_msg: String,
        event_tx: mpsc::UnboundedSender<AgentEvent>,
        cancel: CancellationToken,
    ) -> bool {
        if self.config.cli.is_none() {
            return false;
        }
        let _ = event_tx.send(AgentEvent::SwarmResolvedToSingle {
            agent_label: self.single_agent_label(),
        });
        let _ = event_tx.send(AgentEvent::PhaseChange {
            label: format!(
                "{} — CLI provider detected, running as single agent...",
                self.mode_label()
            ),
        });
        self.delegate_single_agent(context, user_msg, event_tx, cancel)
            .await;
        true
    }

    /// Trivially-sequential shortcut — short, single-file, sequential-keyword
    /// requests skip coordinator analysis and run directly on the preferred
    /// agent (when set). Returns `true` when the request was handled.
    pub(super) async fn try_trivially_sequential(
        &self,
        context: ConversationContext,
        user_msg: String,
        event_tx: mpsc::UnboundedSender<AgentEvent>,
        cancel: CancellationToken,
    ) -> Result<
        (),
        (
            ConversationContext,
            String,
            mpsc::UnboundedSender<AgentEvent>,
            CancellationToken,
        ),
    > {
        if !super::is_trivially_sequential(&user_msg) {
            return Err((context, user_msg, event_tx, cancel));
        }
        let Some(name) = self.preferred_agent.clone() else {
            return Err((context, user_msg, event_tx, cancel));
        };
        let _ = event_tx.send(AgentEvent::SwarmResolvedToSingle {
            agent_label: name.clone(),
        });
        let _ = event_tx.send(AgentEvent::PhaseChange {
            label: format!("{} — delegating to {} agent...", self.mode_label(), name),
        });
        let context = self.apply_preferred_agent_prompt(context, &name);
        self.delegate_single_agent(context, user_msg, event_tx, cancel)
            .await;
        Ok(())
    }

    /// Post-execute pipeline shared by both strategy branches: conflict
    /// resolution → verification → merge → checkpoint cleanup → knowledge
    /// persistence → `SwarmDone`.
    #[allow(clippy::too_many_arguments)]
    pub(super) async fn finalize_swarm_results(
        &self,
        context: ConversationContext,
        results: Vec<crate::agent::subagent::SubagentResult>,
        mut checkpoint: ExecutionCheckpoint,
        kb_path: &Path,
        event_tx: &mpsc::UnboundedSender<AgentEvent>,
    ) {
        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;
        if let Some(ref vr) = verification
            && !vr.passed
        {
            let _ = event_tx.send(AgentEvent::PhaseChange {
                label: format!(
                    "{} — ⚠ verification failed: {}",
                    self.mode_label(),
                    truncate(&vr.output, 200)
                ),
            });
        }

        let merged = self.merge_results(&results, &conflicts, verification.as_ref());
        let total_tool_calls: u32 = results.iter().map(|r| r.tool_calls).sum();

        checkpoint.mark_finished();
        let _ = clear_checkpoint(&self.checkpoint_path());

        if let Some(parent) = kb_path.parent() {
            let _ = tokio::fs::create_dir_all(parent).await;
        }
        if let Err(e) = self.knowledge.save_to_file(kb_path).await {
            tracing::debug!("Could not persist knowledge: {e}");
        }

        let mut merged_context = context;
        merged_context.push(Message {
            role: "assistant".to_string(),
            content: Some(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: results.len(),
            total_tool_calls,
            conflicts_resolved: conflicts.len(),
        });
    }

    /// Helper: notify TUI that each task has started, used by both strategies.
    pub(super) fn announce_tasks(
        &self,
        tasks: &[super::SwarmTask],
        event_tx: &mpsc::UnboundedSender<AgentEvent>,
    ) {
        for task in tasks {
            let _ = event_tx.send(AgentEvent::SwarmAgentStarted {
                agent_id: task.id.clone(),
                agent_name: task.role.clone(),
                task_preview: truncate(&task.prompt, 80),
            });
        }
    }

    /// Helper: build a checkpoint from the planned tasks.
    pub(super) fn build_checkpoint(
        user_msg: &str,
        tasks: &[super::SwarmTask],
    ) -> ExecutionCheckpoint {
        ExecutionCheckpoint::new(
            user_msg.to_string(),
            tasks
                .iter()
                .map(|t| CheckpointTask {
                    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(),
        )
    }

    /// Helper: send per-agent done events after execution.
    pub(super) fn send_per_agent_done(
        &self,
        results: &[crate::agent::subagent::SubagentResult],
        event_tx: &mpsc::UnboundedSender<AgentEvent>,
    ) {
        for result in results {
            let _ = event_tx.send(AgentEvent::SwarmAgentDone {
                agent_id: result.id.clone(),
                agent_name: result.id.clone(),
                success: result.success,
                modified_files: result.modified_files.clone(),
                tool_calls: result.tool_calls,
                input_tokens: result.input_tokens,
                output_tokens: result.output_tokens,
                response: result.response.clone(),
            });
        }
    }

    /// Plan-review-execute strategy: planner → reviewers → workers execute
    /// the approved plan. Only valid for Fork mode.
    pub(super) async fn run_plan_review_execute_strategy(
        &self,
        context: ConversationContext,
        user_msg: String,
        system_prompt: String,
        kb_path: std::path::PathBuf,
        event_tx: mpsc::UnboundedSender<AgentEvent>,
        cancel: CancellationToken,
    ) {
        let tier_label = "FORK";
        let _ = event_tx.send(AgentEvent::SwarmModeSwitch {
            label: tier_label.to_string(),
        });
        let _ = event_tx.send(AgentEvent::PhaseChange {
            label: format!(
                "{} — plan-review-execute: planning phase…",
                self.mode_label()
            ),
        });

        let approved_plan = self
            .run_plan_review(&user_msg, &system_prompt, &event_tx, &cancel)
            .await;

        let Some(plan) = approved_plan else {
            let _ = event_tx.send(AgentEvent::Done {
                context,
                stop_reason: None,
            });
            return;
        };

        if cancel.is_cancelled() {
            let _ = event_tx.send(AgentEvent::Done {
                context,
                stop_reason: None,
            });
            return;
        }

        // ── Execute phase ──
        let exec_label = if self.hive_config.mode.has_realtime() {
            "FLOCK"
        } else {
            "FORK"
        };
        let _ = event_tx.send(AgentEvent::SwarmModeSwitch {
            label: exec_label.to_string(),
        });
        let _ = event_tx.send(AgentEvent::PhaseChange {
            label: format!("{} — executing approved plan…", self.mode_label()),
        });

        let execution_msg = format!(
            "Execute the following approved implementation plan. \
             Follow it exactly, implementing all steps:\n\n{plan}\n\n\
             Original task context: {user_msg}"
        );

        let split_tasks = match self.analyze_and_split(&execution_msg, &system_prompt).await {
            Ok(mut t) => {
                t.truncate(self.hive_config.max_agents);
                t
            }
            Err(e) => {
                tracing::warn!(
                    "PlanReviewExecute: task split failed ({e}), falling back to single agent"
                );
                self.delegate_single_agent(context, execution_msg, event_tx, cancel)
                    .await;
                return;
            }
        };

        if split_tasks.len() <= 1 {
            self.delegate_single_agent(context, execution_msg, event_tx, cancel)
                .await;
            return;
        }

        self.announce_tasks(&split_tasks, &event_tx);

        let mut checkpoint = Self::build_checkpoint(&user_msg, &split_tasks);

        // Small task sets with no existing checkpoint use the lightweight
        // (non-checkpointed) work-stealing scheduler directly.
        let results = if split_tasks.len() <= 2 && !self.checkpoint_path().exists() {
            self.execute_with_work_stealing(split_tasks, &system_prompt, &event_tx, &cancel)
                .await
        } else {
            let _ = save_checkpoint(&checkpoint, &self.checkpoint_path());
            self.execute_with_work_stealing_checkpointed(
                split_tasks,
                &system_prompt,
                &event_tx,
                &cancel,
                &mut checkpoint,
            )
            .await
        };

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

        self.send_per_agent_done(&results, &event_tx);
        self.finalize_swarm_results(context, results, checkpoint, &kb_path, &event_tx)
            .await;
    }

    /// Auto-split strategy: coordinator LLM decomposes the task and a
    /// work-stealing scheduler runs the resulting subtasks in parallel.
    pub(super) async fn run_auto_split_strategy(
        &self,
        context: ConversationContext,
        user_msg: String,
        system_prompt: String,
        kb_path: std::path::PathBuf,
        event_tx: mpsc::UnboundedSender<AgentEvent>,
        cancel: CancellationToken,
    ) {
        let _ = event_tx.send(AgentEvent::PhaseChange {
            label: format!(
                "{} — analyzing task and splitting work...",
                self.mode_label()
            ),
        });

        // ── Phase 1: Analyze and split ──
        let tasks = match self.resolve_split(&user_msg, &system_prompt).await {
            SplitOutcome::Multi(tasks) => tasks,
            SplitOutcome::Single { agent_label } => {
                let _ = event_tx.send(AgentEvent::SwarmResolvedToSingle {
                    agent_label: agent_label.clone(),
                });
                let _ = event_tx.send(AgentEvent::PhaseChange {
                    label: format!(
                        "{} — single subtask, running as standard agent...",
                        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;
            }
            SplitOutcome::Failed(e) => {
                // Both the primary and fallback coordinator LLM calls failed
                // (commonly: upstream 429/overload). Don't strand the user —
                // fall back to a single-agent loop with the preferred agent
                // so the request still gets executed.
                tracing::warn!(
                    "swarm analysis failed ({e}); falling back to single-agent execution"
                );
                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!(
                        "{} — coordinator unavailable ({e}); running as single agent…",
                        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;
            }
        };

        if cancel.is_cancelled() {
            let _ = event_tx.send(AgentEvent::Done {
                context,
                stop_reason: None,
            });
            return;
        }

        let mut checkpoint = Self::build_checkpoint(&user_msg, &tasks);
        let _ = save_checkpoint(&checkpoint, &self.checkpoint_path());

        self.announce_tasks(&tasks, &event_tx);

        // ── Phase 2: Execute ──
        let active_label = if self.hive_config.mode.has_realtime() {
            "FLOCK"
        } else {
            "FORK"
        };
        let _ = event_tx.send(AgentEvent::SwarmModeSwitch {
            label: active_label.to_string(),
        });
        let _ = event_tx.send(AgentEvent::PhaseChange {
            label: format!(
                "{} — executing {} subtasks...",
                self.mode_label(),
                tasks.len()
            ),
        });

        // Hive/Flock: release the user immediately after dispatching workers.
        if self.hive_config.mode.has_consensus() {
            let _ = event_tx.send(AgentEvent::SwarmWorkersDispatched);
        }

        let results = self
            .execute_with_work_stealing_checkpointed(
                tasks,
                &system_prompt,
                &event_tx,
                &cancel,
                &mut checkpoint,
            )
            .await;

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

        self.send_per_agent_done(&results, &event_tx);
        self.finalize_swarm_results(context, results, checkpoint, &kb_path, &event_tx)
            .await;
    }

    /// Run analyze_and_split with one fallback retry, classifying the result
    /// into multi-task / single-task / failed outcomes.
    async fn resolve_split(&self, user_msg: &str, system_prompt: &str) -> SplitOutcome {
        match self.analyze_and_split(user_msg, system_prompt).await {
            Ok(mut tasks) if tasks.len() > 1 => {
                tasks.truncate(self.hive_config.max_agents);
                SplitOutcome::Multi(tasks)
            }
            Ok(mut tasks) => {
                let agent_label = tasks
                    .first_mut()
                    .and_then(|t| t.agent_name.take())
                    .unwrap_or_else(|| self.single_agent_label());
                SplitOutcome::Single { agent_label }
            }
            Err(e) => {
                tracing::warn!("analyze_and_split failed: {e}, attempting fallback...");
                match self
                    .analyze_and_split_fallback(user_msg, system_prompt)
                    .await
                {
                    Ok(mut tasks) if tasks.len() > 1 => {
                        tasks.truncate(self.hive_config.max_agents);
                        SplitOutcome::Multi(tasks)
                    }
                    Ok(mut tasks) => {
                        let agent_label = tasks
                            .first_mut()
                            .and_then(|t| t.agent_name.take())
                            .unwrap_or_else(|| self.single_agent_label());
                        SplitOutcome::Single { agent_label }
                    }
                    Err(_) => SplitOutcome::Failed(e.to_string()),
                }
            }
        }
    }
}

/// Outcome of the analyze-and-split phase, with fallback retry handled.
pub(super) enum SplitOutcome {
    /// Multiple subtasks — run via work-stealing scheduler.
    Multi(Vec<super::SwarmTask>),
    /// Single subtask — fall back to a standard agent loop with the chosen agent.
    Single { agent_label: String },
    /// Both attempts failed — emit an error and bail out.
    Failed(String),
}