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
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
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

use crate::agent::hooks;
use crate::agent::r#loop::AgentEvent;
use crate::app::utils::detect_available_lsp;
use crate::app::{App, PendingSwarmResult};
use crate::tui::state::{ChatMessage, MessageRole, PendingPlan};

use super::{AGENT_BATCH_LIMIT, AGENT_BATCH_LIMIT_SWARM};

impl App {
    /// Drain and process a batch of agent events starting from `first_event`.
    ///
    /// This includes the batch-drain loop and all `AgentEvent` matching.
    pub(super) async fn handle_agent_event_batch(
        &mut self,
        first_event: AgentEvent,
        event_tx: &mpsc::UnboundedSender<AgentEvent>,
        event_rx: &mut mpsc::UnboundedReceiver<AgentEvent>,
    ) {
        // Update elapsed in agent event path too -- Tick can be starved
        // during heavy streaming because biased select always picks agent_rx first.
        if self.state.agent_busy
            && let Some(since) = self.agent_busy_since
        {
            self.state.elapsed_secs = since.elapsed().as_secs();
        }

        // Batch-drain: process up to AGENT_BATCH_LIMIT queued events
        // in one pass to reduce render-per-token overhead.
        // Swarm mode sends proportionally more events (one stream per agent),
        // so use a larger batch limit to keep up without starving input.
        let batch_limit = if self.state.swarm_status.is_some() {
            AGENT_BATCH_LIMIT_SWARM
        } else {
            AGENT_BATCH_LIMIT
        };
        let mut batch = vec![first_event];
        for _ in 1..batch_limit {
            match event_rx.try_recv() {
                Ok(ev) => batch.push(ev),
                Err(_) => break,
            }
        }
        for agent_event in batch {
            match agent_event {
                AgentEvent::Done {
                    context,
                    stop_reason,
                } => {
                    // Update token budget display from context
                    self.state.context_used_tokens = context.used_tokens();
                    self.state.context_max_tokens = context.max_context_tokens();
                    self.state.compaction_count = context.compaction_count();
                    // Avoid double-clone: take ownership directly; backup
                    // only borrows the same allocation via Arc if needed.
                    self.last_context_backup = None;
                    self.context = Some(context);
                    self.state.handle_done();
                    self.cancel_token = None;

                    // Commit checkpoint for this agent turn
                    self.checkpoint_mgr.commit();
                    self.state.checkpoint_count = self.checkpoint_mgr.count();

                    // S8C: Defer repo map rebuild until next dispatch.
                    // This avoids blocking the UI after agent completes --
                    // the rebuild will happen lazily before the next API call.
                    // (repo_map_dirty flag is preserved for dispatch_agent)

                    // Run post-edit hooks if files were modified
                    if !self.modified_files.is_empty() && self.hooks_config.has_any() {
                        let results = hooks::run_post_edit_hooks(
                            &self.hooks_config,
                            &self.working_dir,
                            &self.modified_files,
                        );
                        if let Some(ref commit) = results.commit
                            && commit.success
                        {
                            let n = self.state.changed_files.len();
                            self.state.changed_files.clear();
                            self.state.status_msg = if n > 0 {
                                format!("{n} file{} committed", if n == 1 { "" } else { "s" })
                            } else {
                                "Committed".to_string()
                            };
                        }
                        if let Some(summary) = hooks::format_results(&results) {
                            self.state.messages.push(ChatMessage::text(
                                MessageRole::System,
                                format!("πŸ“‹ **Post-edit hooks**:\n{summary}"),
                            ));
                        }
                    }
                    self.modified_files.clear();

                    // Persist session after each agent completion
                    self.save_session(false).await;

                    // -- Soul reflection (async, non-blocking) --
                    // Skipped in fast mode to minimize overhead.
                    {
                        use crate::agent::soul;
                        let agent_name = self.state.agent_mode.clone();
                        let agent_def = self.config.agents.iter().find(|a| a.name == agent_name);
                        if !self.fast_mode
                            && soul::is_enabled(&self.config, agent_def)
                            && let Some(ref ctx) = self.context
                        {
                            // Only clone the last few messages for reflection
                            // instead of the entire conversation history.
                            let all = ctx.messages();
                            let start = all.len().saturating_sub(10);
                            let messages = all[start..].to_vec();
                            let collet_home = self.config.collet_home.clone();
                            let agent = agent_name.clone();
                            let client = self.client.clone();
                            let model = self.config.model.clone();
                            let rag_manager = self
                                .config
                                .rag
                                .as_ref()
                                .and_then(crate::rag::RagManager::from_config);
                            let _ =
                                event_tx.send(crate::agent::r#loop::AgentEvent::SoulReflecting {
                                    agent_name: agent.clone(),
                                });
                            tokio::spawn(async move {
                                if let Err(e) = soul::reflect_simple(
                                    &client,
                                    &model,
                                    &collet_home,
                                    &agent,
                                    &messages,
                                    rag_manager,
                                )
                                .await
                                {
                                    tracing::warn!(agent = %agent, "Soul reflection failed: {e}");
                                }
                            });
                        }
                    }

                    // -- Auto-evolution (async, non-blocking) --
                    // Skipped in fast mode to minimize overhead.
                    {
                        use crate::evolution::auto as evo_auto;
                        if !self.fast_mode && evo_auto::is_auto_enabled(&self.config) {
                            let agent_name = self.state.agent_mode.clone();
                            let collet_home = self.config.collet_home.clone();
                            let working_dir = self.working_dir.clone();
                            let client = self.client.clone();
                            let config = self.config.clone();
                            let cancel = CancellationToken::new();
                            tokio::spawn(async move {
                                if let Err(e) = evo_auto::run_auto(
                                    client,
                                    config,
                                    collet_home,
                                    agent_name.clone(),
                                    working_dir,
                                    cancel,
                                )
                                .await
                                {
                                    tracing::warn!(agent = %agent_name, "Auto-evolution failed: {e}");
                                }
                            });
                        }
                    }

                    // -- Benchmark logging --
                    {
                        let s = &self.state;
                        let ctx_pct = if s.context_max_tokens > 0 {
                            (s.context_used_tokens as f64 / s.context_max_tokens as f64 * 100.0)
                                .min(100.0) as u8
                        } else {
                            0
                        };
                        let tools_in_task =
                            s.tool_log.len().saturating_sub(self.task_start_tool_count);
                        let tools_ok = s.tool_log
                            [self.task_start_tool_count.min(s.tool_log.len())..]
                            .iter()
                            .filter(|e| e.success)
                            .count();
                        let entry = crate::bench::BenchEntry {
                            ts: crate::bench::unix_now(),
                            session_id: self.session_id.clone(),
                            project: crate::bench::short_path(&self.working_dir),
                            task: self.current_task.clone(),
                            model: s.model_name.clone(),
                            mode: s.agent_mode.clone(),
                            iter: s.iteration,
                            secs: s.elapsed_secs,
                            tools: tools_in_task as u32,
                            tools_ok: tools_ok as u32,
                            tokens_in: s
                                .token_stats
                                .prompt_tokens
                                .saturating_sub(self.task_start_tokens_in),
                            tokens_out: s
                                .token_stats
                                .completion_tokens
                                .saturating_sub(self.task_start_tokens_out),
                            api_calls: s
                                .token_stats
                                .api_calls
                                .saturating_sub(self.task_start_api_calls),
                            cache_pct: (s.cache_hit_rate * 100.0).min(100.0) as u8,
                            ctx_pct,
                            compactions: s
                                .compaction_count
                                .saturating_sub(self.task_start_compactions)
                                as u32,
                            cancelled: self.was_cancelled,
                            compaction_quality: self
                                .context
                                .as_ref()
                                .and_then(|ctx| ctx.compaction_quality()),
                            tool_latency_avg_ms: s.debug_monitor.tool_latency_avg_ms,
                            tool_latency_max_ms: s.debug_monitor.tool_latency_max_ms,
                            api_latency_avg_ms: s.debug_monitor.api_latency_avg_ms,
                            api_latency_max_ms: s.debug_monitor.api_latency_max_ms,
                            tool_success_rate: s.debug_monitor.tool_success_rate,
                            tokens_per_iteration: s.debug_monitor.tokens_per_iteration,
                            tools_per_iteration: s.debug_monitor.tools_per_iteration,
                            top_tools: s.debug_monitor.top_tools.clone(),
                            continuation_round: self.continuation_count,
                            outcome: match &stop_reason {
                                None => {
                                    if self.was_cancelled {
                                        "cancelled".to_string()
                                    } else {
                                        "success".to_string()
                                    }
                                }
                                Some(r) => match r {
                                    crate::agent::guard::StopReason::TaskTimeout { .. } => {
                                        "timeout".to_string()
                                    }
                                    crate::agent::guard::StopReason::IterationLimit { .. } => {
                                        "iteration_limit".to_string()
                                    }
                                    crate::agent::guard::StopReason::CircuitBreaker { .. } => {
                                        "circuit_breaker".to_string()
                                    }
                                    crate::agent::guard::StopReason::Cancelled => {
                                        "cancelled".to_string()
                                    }
                                },
                            },
                            provider: self.config.base_url.clone(),
                        };
                        let bench_path = crate::config::bench_log_path();
                        let retain = self.config.bench_retain_days;
                        if let Err(e) = crate::bench::append_entry(&bench_path, &entry) {
                            tracing::warn!("bench log write failed: {e}");
                        } else {
                            crate::bench::prune_old_entries(&bench_path, retain);
                        }

                        // -- Telemetry: session_end --
                        crate::telemetry::track(
                            "session_end",
                            serde_json::json!({
                                "model": &entry.model,
                                "mode": &entry.mode,
                                "outcome": &entry.outcome,
                                "iter": entry.iter,
                                "secs": entry.secs,
                                "tools": entry.tools,
                                "tools_ok": entry.tools_ok,
                                "tokens_in": entry.tokens_in,
                                "tokens_out": entry.tokens_out,
                                "ctx_pct": entry.ctx_pct,
                                "compactions": entry.compactions,
                                "cancelled": entry.cancelled,
                            }),
                        );
                    }

                    // Auto-trigger optimizer when ctx usage >= 40% (once per session)
                    if self.config.auto_optimize && !self.optimizer_auto_triggered {
                        let ctx_pct = if self.state.context_max_tokens > 0 {
                            self.state.context_used_tokens as f64
                                / self.state.context_max_tokens as f64
                                * 100.0
                        } else {
                            0.0
                        };
                        if ctx_pct >= 40.0 {
                            self.optimizer_auto_triggered = true;
                            self.try_open_optimize_popup();
                        }
                    }

                    // Re-assert mouse capture: a subprocess may have sent
                    // escape sequences that reset SGR mouse mode.
                    let _ = crossterm::execute!(
                        std::io::stdout(),
                        crossterm::event::EnableMouseCapture,
                    );

                    // Reset Esc pending state when agent finishes
                    self.esc_pending = false;
                    self.esc_pending_at = None;

                    let cancelled = std::mem::replace(&mut self.was_cancelled, false);

                    // -- Auto-continuation logic --
                    // If the agent was stopped by a continuable reason (timeout,
                    // iteration limit) and we haven't exceeded max_continuations,
                    // automatically restart the agent to finish the task.
                    if let Some(ref reason) = stop_reason {
                        if reason.is_continuable()
                            && !cancelled
                            && self.continuation_count < self.config.max_continuations
                        {
                            let mode = self.approve_mode.get();
                            match mode {
                                crate::agent::approval::ApproveMode::Yolo
                                | crate::agent::approval::ApproveMode::Auto => {
                                    self.auto_continue(reason, event_tx.clone());
                                    // Skip normal queue processing -- continuation takes priority
                                    continue;
                                }
                                crate::agent::approval::ApproveMode::Manual => {
                                    // Ask user for confirmation
                                    self.state.popup = Some(crate::tui::state::PopupState {
                                        title: "Task Incomplete".to_string(),
                                        content: format!(
                                            "{}.\n\nContinuation {}/{}.\nContinue working on the task?",
                                            reason,
                                            self.continuation_count + 1,
                                            self.config.max_continuations,
                                        ),
                                        scroll: 0,
                                        kind: crate::tui::state::PopupKind::ContinuationConfirm {
                                            selected: 0,
                                        },
                                        saved_theme: None,
                                        select_prefix: None,
                                        search: String::new(),
                                    });
                                    // Context is already stored in self.context
                                    continue;
                                }
                            }
                        } else if !reason.is_continuable() {
                            // Non-continuable stop (circuit breaker) -- reset counter
                            self.continuation_count = 0;
                        }
                    } else {
                        // Normal completion -- reset continuation counter
                        self.continuation_count = 0;
                    }

                    if cancelled && !self.message_queue.is_empty() {
                        // Agent was cancelled -- ask user what to do with the queue
                        let pending: Vec<String> = self.message_queue.iter().cloned().collect();
                        self.state.popup = Some(crate::tui::state::PopupState {
                            title: "Stopped".to_string(),
                            content: String::new(),
                            scroll: 0,
                            kind: crate::tui::state::PopupKind::QueueConfirm {
                                pending,
                                selected: 0,
                            },
                            saved_theme: None,
                            select_prefix: None,
                            search: String::new(),
                        });
                    } else if !cancelled {
                        // Flush deferred swarm result before processing queued messages
                        if let Some(sr) = self.pending_swarm_result.take() {
                            self.state.messages.push(ChatMessage::text(
                                MessageRole::System,
                                format!(
                                    "[Hive] Completed: {} agents, \
                                 {} tool calls, \
                                 {} conflicts resolved",
                                    sr.agent_count, sr.total_tool_calls, sr.conflicts_resolved
                                ),
                            ));
                            if !sr.merged_response.is_empty() {
                                self.state.messages.push(ChatMessage::text(
                                    MessageRole::Assistant,
                                    sr.merged_response,
                                ));
                            }
                        }
                        // Process next queued message, if any
                        if let Some(next_msg) = self.message_queue.pop_front() {
                            self.state
                                .messages
                                .retain(|m| m.role != MessageRole::Queued);
                            self.state.input = next_msg;
                            self.state.cursor = self.state.input.len();
                            self.submit_message(event_tx.clone());
                        }
                    }
                }
                AgentEvent::PlanReady {
                    plan,
                    context,
                    user_msg,
                } => {
                    // Architect phase done
                    self.state.context_used_tokens = context.used_tokens();
                    self.state.context_max_tokens = context.max_context_tokens();
                    self.last_context_backup = Some(context.clone());
                    self.context = Some(context.clone());

                    let pending = PendingPlan {
                        plan: plan.clone(),
                        user_msg,
                        system_prompt: context.system_prompt().to_string(),
                    };

                    // Always save plan to docs/plan/
                    let save_msg = match self.save_plan_to_file(&pending) {
                        Ok(rel_path) => format!("Plan saved to `{rel_path}`."),
                        Err(e) => e,
                    };

                    // Yolo mode: auto-proceed to code phase
                    if self.approve_mode.get() == crate::agent::approval::ApproveMode::Yolo {
                        self.state.messages.push(ChatMessage::text(
                            MessageRole::System,
                            format!("{save_msg}\n\n⚑ Auto-proceeding to code agent (yolo)..."),
                        ));
                        self.state.pending_plan = Some(pending);
                        self.handle_proceed_plan(event_tx.clone());
                    } else {
                        // Manual/Auto: pause for user review
                        self.state.pending_plan = Some(pending);
                        self.state.handle_done();
                        self.cancel_token = None;

                        self.state.messages.push(ChatMessage::text(
                            MessageRole::System,
                            format!(
                                "**Plan ready.** {save_msg}\n\n\
                             `/proceed`      β€” start code agent now\n\
                             `/save-plan`    β€” save to file and keep reviewing\n\
                             `/cancel-plan`  β€” discard the plan"
                            ),
                        ));
                    }
                }
                AgentEvent::FileModified { path } => {
                    // Snapshot file BEFORE the modification is applied
                    self.checkpoint_mgr.snapshot_file(&path);

                    let full_path = if path.starts_with('/') {
                        std::path::PathBuf::from(&path)
                    } else {
                        std::path::PathBuf::from(&self.working_dir).join(&path)
                    };
                    self.repo_map.invalidate(&full_path);
                    self.repo_map_dirty = true;
                    // Also notify the global project cache for cross-mode sharing.
                    crate::project_cache::global()
                        .notify_file_modified(&full_path.to_string_lossy());
                    // Track for post-edit hooks
                    if !self.modified_files.contains(&path) {
                        self.modified_files.push(path.clone());
                    }
                    tracing::info!("File modified, repo map invalidated: {path}");

                    // Auto-detect new LSP servers when a new language appears.
                    if let Some(ext) = full_path.extension().and_then(|e| e.to_str()) {
                        use crate::lsp::client::extension_to_language_id;
                        if let Some(lang) = extension_to_language_id(ext) {
                            let already_covered = self.state.installed_lsp.iter().any(|cmd| {
                                crate::lsp::client::find_server_for_language(lang)
                                    .is_some_and(|s| s.command == *cmd)
                            });
                            if !already_covered {
                                let refreshed = detect_available_lsp(&self.working_dir);
                                if refreshed != self.state.installed_lsp {
                                    tracing::info!(
                                        before = ?self.state.installed_lsp,
                                        after = ?refreshed,
                                        "LSP servers refreshed after new language detected"
                                    );
                                    self.state.installed_lsp = refreshed;
                                }
                            }
                        }
                    }

                    // Update running LSP status from manager.
                    self.state.running_lsp = self.lsp_manager.get_spawned_names();
                }
                AgentEvent::McpPids { pids } => {
                    self.mcp_pids = pids;
                }
                AgentEvent::ShellOutput {
                    cmd,
                    stdout,
                    stderr,
                    exit_code,
                } => {
                    self.state.agent_busy = false;
                    self.agent_busy_since = None;
                    self.state.status_msg = "Ready".to_string();
                    let mut content = String::new();
                    if !stdout.is_empty() {
                        content.push_str(stdout.trim_end());
                    }
                    if !stderr.is_empty() {
                        if !content.is_empty() {
                            content.push('\n');
                        }
                        content.push_str(stderr.trim_end());
                    }
                    if content.is_empty() {
                        content = format!("(exit {exit_code})");
                    } else if exit_code != 0 {
                        content.push_str(&format!("\n(exit {exit_code})"));
                    }
                    self.state.messages.push(ChatMessage::text(
                        MessageRole::System,
                        format!("```\n{content}\n```"),
                    ));
                    tracing::debug!(cmd = %cmd, exit = exit_code, "shell passthrough done");
                }
                AgentEvent::LspInstalled { language, server } => {
                    // Refresh installed LSP list after a successful install.
                    self.state.installed_lsp = detect_available_lsp(&self.working_dir);
                    self.state.status_msg = format!("LSP ready: {server} ({language})");
                    tracing::info!("LSP installed and detected: {server} ({language})");
                    // Refresh the async PID list so the debug monitor picks up the new process.
                    let lsp = self.lsp_manager.clone();
                    tokio::spawn(async move {
                        let pids = lsp.child_pids().await;
                        tracing::debug!(pids = ?pids, "LSP child PIDs after install");
                    });
                }
                AgentEvent::SwarmWorkersDispatched => {
                    // Hive/Flock workers dispatched -- release the user for interaction.
                    self.state
                        .handle_agent_event(AgentEvent::SwarmWorkersDispatched);
                }
                AgentEvent::SwarmWorkerPaused { ref agent_id } => {
                    // Sync paused flag so coordinator's wait_for_any can detect it.
                    if let Some(ref kb) = self.swarm_knowledge {
                        let kb = kb.clone();
                        let id = agent_id.clone();
                        tokio::spawn(async move {
                            kb.set_worker_paused(&id, true).await;
                        });
                    }
                    self.state
                        .handle_agent_event(AgentEvent::SwarmWorkerPaused {
                            agent_id: agent_id.clone(),
                        });
                }
                AgentEvent::SwarmWorkerResumed { ref agent_id } => {
                    if let Some(ref kb) = self.swarm_knowledge {
                        let kb = kb.clone();
                        let id = agent_id.clone();
                        tokio::spawn(async move {
                            kb.set_worker_paused(&id, false).await;
                        });
                    }
                    self.state
                        .handle_agent_event(AgentEvent::SwarmWorkerResumed {
                            agent_id: agent_id.clone(),
                        });
                }
                AgentEvent::SwarmDone {
                    context,
                    merged_response,
                    agent_count,
                    total_tool_calls,
                    conflicts_resolved,
                } => {
                    // Swarm finished -- release the knowledge handle.
                    self.swarm_knowledge = None;

                    // If the user is busy with another task (started after
                    // SwarmWorkersDispatched released them), defer the report.
                    if self.state.agent_busy {
                        tracing::info!(
                            "SwarmDone arrived while user task is running β€” deferring report"
                        );
                        self.pending_swarm_result = Some(PendingSwarmResult {
                            merged_response,
                            agent_count,
                            total_tool_calls,
                            conflicts_resolved,
                        });
                        // Still persist the context from the swarm run
                        self.last_context_backup = Some(context.clone());
                        self.context = Some(context);
                    } else {
                        self.state.context_used_tokens = context.used_tokens();
                        self.state.context_max_tokens = context.max_context_tokens();
                        self.last_context_backup = Some(context.clone());
                        self.context = Some(context);
                        self.state.handle_done();
                        self.cancel_token = None;

                        self.state.messages.push(ChatMessage::text(
                            MessageRole::System,
                            format!(
                                "[Hive] Completed: {agent_count} agents, \
                             {total_tool_calls} tool calls, \
                             {conflicts_resolved} conflicts resolved"
                            ),
                        ));

                        if !merged_response.is_empty() {
                            self.state
                                .messages
                                .push(ChatMessage::text(MessageRole::Assistant, merged_response));
                        }

                        // Run post-edit hooks
                        if !self.modified_files.is_empty() && self.hooks_config.has_any() {
                            let results = hooks::run_post_edit_hooks(
                                &self.hooks_config,
                                &self.working_dir,
                                &self.modified_files,
                            );
                            if let Some(ref commit) = results.commit
                                && commit.success
                            {
                                let n = self.state.changed_files.len();
                                self.state.changed_files.clear();
                                self.state.status_msg = if n > 0 {
                                    format!("{n} file{} committed", if n == 1 { "" } else { "s" })
                                } else {
                                    "Committed".to_string()
                                };
                            }
                            if let Some(summary) = hooks::format_results(&results) {
                                self.state.messages.push(ChatMessage::text(
                                    MessageRole::System,
                                    format!("Post-edit hooks:\n{summary}"),
                                ));
                            }
                        }
                        self.modified_files.clear();

                        self.save_session(false).await;

                        // -- Global soul reflection (swarm coordinator) --
                        // Skipped in fast mode to minimize overhead.
                        {
                            use crate::agent::soul;
                            if !self.fast_mode
                                && soul::is_enabled(&self.config, None)
                                && let Some(ref ctx) = self.context
                            {
                                let all = ctx.messages();
                                let start = all.len().saturating_sub(10);
                                let messages = all[start..].to_vec();
                                let collet_home = self.config.collet_home.clone();
                                let client = self.client.clone();
                                let model = self.config.model.clone();
                                let rag_manager = self
                                    .config
                                    .rag
                                    .as_ref()
                                    .and_then(crate::rag::RagManager::from_config);
                                let _ = event_tx.send(
                                    crate::agent::r#loop::AgentEvent::SoulReflecting {
                                        agent_name: soul::GLOBAL_SOUL.to_string(),
                                    },
                                );
                                tokio::spawn(async move {
                                    if let Err(e) = soul::reflect_simple(
                                        &client,
                                        &model,
                                        &collet_home,
                                        soul::GLOBAL_SOUL,
                                        &messages,
                                        rag_manager,
                                    )
                                    .await
                                    {
                                        tracing::warn!("Global soul reflection failed: {e}");
                                    }
                                });
                            }
                        }

                        // Reset state
                        self.esc_pending = false;
                        self.esc_pending_at = None;
                        self.was_cancelled = false;

                        // Process next queued message
                        if let Some(next_msg) = self.message_queue.pop_front() {
                            // Remove the queued bubble from the display
                            if let Some(pos) = self
                                .state
                                .messages
                                .iter()
                                .position(|m| m.role == MessageRole::Queued)
                            {
                                self.state.messages.remove(pos);
                            }
                            self.state.input = next_msg;
                            self.state.cursor = self.state.input.len();
                            self.submit_message(event_tx.clone());
                        }
                    }
                }
                AgentEvent::Error(ref msg) => {
                    let outcome = "error";
                    crate::telemetry::track(
                        "session_end",
                        serde_json::json!({
                            "model": &self.state.model_name,
                            "mode": &self.state.agent_mode,
                            "outcome": outcome,
                            "iter": self.state.iteration,
                            "secs": self.state.elapsed_secs,
                            "error": msg,
                        }),
                    );
                    self.state
                        .handle_agent_event(AgentEvent::Error(msg.clone()));
                }
                AgentEvent::GuardStop(ref msg) => {
                    let outcome = "guard_stop";
                    crate::telemetry::track(
                        "session_end",
                        serde_json::json!({
                            "model": &self.state.model_name,
                            "mode": &self.state.agent_mode,
                            "outcome": outcome,
                            "iter": self.state.iteration,
                            "secs": self.state.elapsed_secs,
                            "reason": msg,
                        }),
                    );
                    self.state
                        .handle_agent_event(AgentEvent::GuardStop(msg.clone()));
                }
                AgentEvent::ApprovalRequired {
                    ref tool_name,
                    ref tool_args,
                } => {
                    // In Yolo mode (default), the gate auto-approves via timeout.
                    // Log the event for status display; future Manual/Auto mode
                    // will show a TUI prompt here.
                    tracing::debug!(tool = %tool_name, args_len = tool_args.len(), "Tool approval requested");
                    self.state.status_msg = format!("Approving: {tool_name}");
                }
                AgentEvent::ApprovalDenied { ref tool_name } => {
                    self.state.status_msg = format!("Denied: {tool_name}");
                }
                AgentEvent::Evolution(ref evo_event) => {
                    use crate::evolution::EvolutionEvent;
                    match evo_event {
                        EvolutionEvent::CycleStarted { cycle, max_cycles } => {
                            self.state.status_msg = format!("🧬 Evolution {cycle}/{max_cycles}");
                            self.state.agent_busy = true;
                        }
                        EvolutionEvent::SolveStarted { task_count } => {
                            self.state.status_msg = format!("πŸ”§ Solving {task_count} tasks");
                        }
                        EvolutionEvent::SolveCompleted { score } => {
                            self.state.status_msg = format!("πŸ“Š Batch score: {score:.3}");
                        }
                        EvolutionEvent::EngineStepStarted { engine_name } => {
                            self.state.status_msg = format!("🧠 [{engine_name}] Analyzing...");
                        }
                        EvolutionEvent::EngineStepCompleted { mutated, summary } => {
                            let icon = if *mutated { "βœ…" } else { "⏭" };
                            self.state.status_msg = format!("{icon} {summary}");
                        }
                        EvolutionEvent::CycleCompleted { cycle, score, .. } => {
                            self.state.status_msg = format!("🧬 Cycle {cycle} β€” score: {score:.3}");
                            use crate::tui::state::{ChatMessage, MessageRole};
                            self.state.messages.push(ChatMessage::text(
                                MessageRole::Assistant,
                                format!("Evolution cycle {cycle} complete β€” score: {score:.3}"),
                            ));
                        }
                        EvolutionEvent::Converged { cycle, final_score } => {
                            self.state.status_msg = format!("🎯 Converged at cycle {cycle}");
                            use crate::tui::state::{ChatMessage, MessageRole};
                            self.state.messages.push(ChatMessage::text(
                                MessageRole::Assistant,
                                format!("βœ… Evolution converged at cycle {cycle} β€” final score: {final_score:.3}"),
                            ));
                        }
                        EvolutionEvent::Done(result) => {
                            self.state.agent_busy = false;
                            self.state.status_msg =
                                format!("🧬 Evolution done β€” score: {:.3}", result.final_score);
                            use crate::tui::state::{ChatMessage, MessageRole};
                            self.state.messages.push(ChatMessage::text(
                                MessageRole::Assistant,
                                format!(
                                    "Evolution complete β€” {} cycles, final score: {:.3}{}",
                                    result.cycles_completed,
                                    result.final_score,
                                    if result.converged { " (converged)" } else { "" }
                                ),
                            ));
                        }
                        EvolutionEvent::Error(msg) => {
                            self.state.agent_busy = false;
                            self.state.status_msg = format!("❌ Evolution error: {msg}");
                        }
                    }
                }
                // New observability events β€” handled here to avoid falling through
                // to state.handle_agent_event(), which logs them as BUG errors.
                AgentEvent::ToolBatchProgress { .. } => {
                    // Future: update a tool-batch progress indicator in the status bar.
                }
                AgentEvent::StreamWaiting { .. } => {
                    // Future: show "still working…" in the status bar.
                }
                AgentEvent::CompactionStarted { .. } => {
                    // Reserved β€” not yet emitted.
                }
                AgentEvent::CompactionDone {
                    before_tokens,
                    after_tokens,
                } => {
                    self.state.status_msg =
                        format!("Context compacted: {before_tokens} β†’ {after_tokens} tokens");
                }
                AgentEvent::ToolResultTruncated {
                    tool_name,
                    original_bytes,
                    truncated_bytes,
                } => {
                    tracing::debug!(
                        tool = %tool_name,
                        original = original_bytes,
                        truncated = truncated_bytes,
                        "Tool result truncated"
                    );
                }
                other => {
                    self.state.handle_agent_event(other);
                }
            }
        } // end batch for loop
    }
}