batty-cli 0.11.63

Supervised agent execution for software teams
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
//! Context exhaustion detection, restart, and escalation.

use std::time::Instant;

use anyhow::Result;
use tracing::{info, warn};

use super::super::*;
use super::{CONTEXT_RESTART_COOLDOWN, format_checkpoint_section};
use crate::team::context_management;

impl TeamDaemon {
    pub(in super::super) fn handle_context_exhaustion(&mut self, member_name: &str) -> Result<()> {
        let Some(task) = self.active_task(member_name)? else {
            warn!(member = %member_name, "context exhausted but no active task is recorded");
            self.states
                .insert(member_name.to_string(), MemberState::Idle);
            return Ok(());
        };
        let Some(member) = self
            .config
            .members
            .iter()
            .find(|member| member.name == member_name)
            .cloned()
        else {
            return Ok(());
        };
        let Some(_pane_id) = self.config.pane_map.get(member_name).cloned() else {
            return Ok(());
        };
        let restart_cooldown_key = Self::context_restart_cooldown_key(member_name);
        let restart_on_cooldown = self
            .intervention_cooldowns
            .get(&restart_cooldown_key)
            .is_some_and(|last| last.elapsed() < CONTEXT_RESTART_COOLDOWN);
        let escalation_cooldown_key = Self::context_escalation_cooldown_key(member_name);
        let escalation_on_cooldown = self
            .intervention_cooldowns
            .get(&escalation_cooldown_key)
            .is_some_and(|last| last.elapsed() < CONTEXT_RESTART_COOLDOWN);

        let prior_restarts = self.context_restart_count(task.id)?;
        if prior_restarts >= 1 {
            if escalation_on_cooldown {
                info!(
                    member = %member_name,
                    task_id = task.id,
                    "context exhaustion escalation suppressed by cooldown"
                );
                return Ok(());
            }
            self.escalate_context_exhaustion(&member, &task, prior_restarts + 1)?;
            self.intervention_cooldowns
                .insert(escalation_cooldown_key, Instant::now());
            return Ok(());
        }

        if restart_on_cooldown {
            info!(
                member = %member_name,
                task_id = task.id,
                "context exhaustion restart suppressed by cooldown"
            );
            return Ok(());
        }

        warn!(
            member = %member_name,
            task_id = task.id,
            "context exhausted; restarting agent with task context"
        );
        let work_dir = self.member_work_dir(&member);
        self.stage_restart_resume_context(
            member_name,
            &task,
            &work_dir,
            "context_exhausted",
            prior_restarts + 1,
            None,
        );
        self.restart_member_with_task_context(member_name, "context_exhausted")?;
        self.intervention_cooldowns
            .insert(restart_cooldown_key, Instant::now());
        self.record_agent_restarted(
            member_name,
            task.id.to_string(),
            "context_exhausted",
            prior_restarts + 1,
        );
        Ok(())
    }

    pub(super) fn handle_context_pressure_restart(
        &mut self,
        member_name: &str,
        task_id: Option<u32>,
        output_bytes: u64,
    ) -> Result<bool> {
        let Some(member) = self
            .config
            .members
            .iter()
            .find(|member| member.name == member_name)
            .cloned()
        else {
            return Ok(false);
        };
        let work_dir = self.member_work_dir(&member);
        if context_management::proactive_restart_is_suppressed(
            &work_dir,
            output_bytes,
            CONTEXT_RESTART_COOLDOWN,
        ) {
            info!(
                member = %member_name,
                task_id,
                "context pressure restart suppressed until fresh progress arrives"
            );
            return Ok(false);
        }

        let restart_cooldown_key = Self::context_restart_cooldown_key(member_name);
        let restart_on_cooldown = self
            .intervention_cooldowns
            .get(&restart_cooldown_key)
            .is_some_and(|last| last.elapsed() < CONTEXT_RESTART_COOLDOWN);
        if restart_on_cooldown {
            info!(
                member = %member_name,
                task_id,
                "context pressure restart suppressed by cooldown"
            );
            return Ok(false);
        }

        let Some(task) = self.active_task(member_name)? else {
            warn!(
                member = %member_name,
                "context pressure restart requested but no active task is recorded"
            );
            return Ok(false);
        };
        let restart_count = self.restart_count_for_reason(task.id, "context_pressure")? + 1;
        self.stage_restart_resume_context(
            member_name,
            &task,
            &work_dir,
            "context_pressure",
            restart_count,
            Some(output_bytes),
        );
        self.restart_member_with_task_context(member_name, "context_pressure")?;
        self.intervention_cooldowns
            .insert(restart_cooldown_key, Instant::now());
        if let Some(task_id) = task_id {
            self.record_agent_restarted(
                member_name,
                task_id.to_string(),
                "context_pressure",
                restart_count,
            );
        }
        Ok(true)
    }

    pub(crate) fn restart_member_with_task_context(
        &mut self,
        member_name: &str,
        reason: &str,
    ) -> Result<()> {
        let Some(task) = self.active_task(member_name)? else {
            // #706: managers and architects never claim board tasks, so
            // `active_task` always returns None for them. Before this
            // fallback the stall-retry path (attempt >=3 in
            // `handle_stalled_mid_turn_completion`) silently no-op'd on
            // managers, leaving them in a stall cascade indefinitely.
            // Observed 2026-04-17 11:52 UTC: jordan-pm at 211%
            // context_usage_pct stalled mid-turn attempt=3; restart was
            // requested and immediately dropped with the warn below,
            // so nothing recycled the oversized shim. Task-less
            // `restart_member` (pane respawn + fresh launch identity)
            // is the correct recovery — the engineer-side checkpoint
            // handoff only applies when there's a task to resume.
            info!(
                member = %member_name,
                reason,
                "restart without task context (no active task); falling back to pane respawn + relaunch"
            );
            return self.restart_member(member_name);
        };
        let Some(member) = self
            .config
            .members
            .iter()
            .find(|member| member.name == member_name)
            .cloned()
        else {
            return Ok(());
        };
        let Some(pane_id) = self.config.pane_map.get(member_name).cloned() else {
            return Ok(());
        };

        let work_dir = self.member_work_dir(&member);
        self.preserve_restart_context(member_name, &task, Some(&pane_id), &work_dir, reason);

        tmux::respawn_pane(&pane_id, "bash")?;
        std::thread::sleep(std::time::Duration::from_millis(200));

        let assignment = self.restart_assignment_with_handoff(member_name, &task, &work_dir);
        let launch = self.launch_task_assignment(member_name, &assignment, Some(task.id), false)?;
        let display_reason = reason.replace('_', " ");
        let mut restart_notice = format!(
            "Restarted after {reason}. Continue task #{} from the current worktree state.",
            task.id,
            reason = display_reason
        );
        if let Some(branch) = launch.branch.as_deref() {
            restart_notice.push_str(&format!("\nBranch: {branch}"));
        }
        restart_notice.push_str(&format!("\nWorktree: {}", launch.work_dir.display()));
        if let Some(cp_content) =
            super::super::super::checkpoint::read_checkpoint(&self.config.project_root, member_name)
        {
            restart_notice.push_str(&format_checkpoint_section(&cp_content));
        }
        if let Err(error) = self.queue_message("daemon", member_name, &restart_notice) {
            warn!(member = %member_name, error = %error, "failed to inject restart notice");
        }
        self.record_orchestrator_action(format!(
            "restart: relaunched {} on task #{} after {}",
            member_name, task.id, reason
        ));
        if let Some(branch) = launch.branch.as_deref() {
            info!(member = %member_name, task_id = task.id, branch, reason, "context restart relaunched assignment");
        }
        Ok(())
    }

    fn stage_restart_resume_context(
        &self,
        member_name: &str,
        task: &crate::task::Task,
        work_dir: &std::path::Path,
        reason: &str,
        restart_count: u32,
        output_bytes: Option<u64>,
    ) {
        if let Err(error) = context_management::stage_restart_context(
            work_dir,
            member_name,
            task,
            reason,
            restart_count,
            output_bytes,
        ) {
            warn!(
                member = %member_name,
                task_id = task.id,
                reason,
                error = %error,
                "failed to stage restart resume context"
            );
        }
    }

    pub(super) fn capture_context_handoff_output(&self, pane_id: &str) -> Option<String> {
        let screen_history = self
            .config
            .team_config
            .workflow_policy
            .handoff_screen_history
            .max(1);
        let rows = crate::tmux::pane_dimensions(pane_id)
            .map(|(_, rows)| rows as usize)
            .unwrap_or(50);
        let line_count = rows.saturating_mul(screen_history).min(u32::MAX as usize) as u32;
        crate::tmux::capture_pane_recent(pane_id, line_count).ok()
    }

    fn escalate_context_exhaustion(
        &mut self,
        member: &MemberInstance,
        task: &crate::task::Task,
        restart_count: u32,
    ) -> Result<()> {
        let Some(manager) = member.reports_to.as_deref() else {
            warn!(
                member = %member.name,
                task_id = task.id,
                restart_count,
                "context exhaustion exceeded restart limit with no escalation target"
            );
            return Ok(());
        };

        let body = format!(
            "Task #{task_id} for {member_name} exhausted context {restart_count} times. Batty restarted it once already and will not restart it again automatically.\n\
            Task: {title}\n\
            Next step: decide whether to split the task, redirect the engineer, or intervene directly in the lane.",
            task_id = task.id,
            member_name = member.name,
            title = task.title,
        );
        self.queue_message("daemon", manager, &body)?;
        self.record_orchestrator_action(format!(
            "restart: escalated context exhaustion for {} on task #{} after {} exhaustions",
            member.name, task.id, restart_count
        ));
        self.record_task_escalated(&member.name, task.id.to_string(), Some("context_exhausted"));
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::super::super::*;
    use super::super::test_helpers::test_team_config;
    use crate::team::config::RoleType;
    use crate::team::events::TeamEvent;
    use crate::team::hierarchy::MemberInstance;
    use crate::team::standup::MemberState;
    use crate::team::test_helpers::write_event_log;
    use crate::team::test_support::{
        TestDaemonBuilder, engineer_member, manager_member, setup_fake_claude,
        write_owned_task_file,
    };
    use serial_test::serial;
    use std::collections::HashMap;
    use std::path::Path;
    use std::process::Command;
    use std::time::{Duration, Instant};

    #[test]
    #[serial]
    #[cfg_attr(not(feature = "integration"), ignore)]
    fn agent_restart_relaunches_context_exhausted_member_with_task_context() {
        let session = format!("batty-test-agent-restart-context-{}", std::process::id());
        let _ = crate::tmux::kill_session(&session);

        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".batty").join("team_config")).unwrap();

        let member_name = "eng-ctx-restart";
        let lead_name = "manager-ctx";
        let (fake_bin, fake_log) = setup_fake_claude(&tmp, member_name);
        let inbox_root = inbox::inboxes_root(tmp.path());
        inbox::init_inbox(&inbox_root, lead_name).unwrap();
        inbox::init_inbox(&inbox_root, member_name).unwrap();

        write_owned_task_file(tmp.path(), 42, "test-task", "in-progress", member_name);

        crate::tmux::create_session(&session, "bash", &[], tmp.path().to_str().unwrap()).unwrap();
        crate::tmux::create_window(
            &session,
            "keeper",
            "sleep",
            &["60".to_string()],
            tmp.path().to_str().unwrap(),
        )
        .unwrap();
        let pane_id = crate::tmux::pane_id(&session).unwrap();
        Command::new("tmux")
            .args(["set-option", "-p", "-t", &pane_id, "remain-on-exit", "on"])
            .output()
            .unwrap();

        let member = MemberInstance {
            name: member_name.to_string(),
            role_name: "engineer".to_string(),
            role_type: RoleType::Engineer,
            agent: Some("claude".to_string()),
            prompt: None,
            reports_to: Some(lead_name.to_string()),
            use_worktrees: false,
            ..Default::default()
        };
        let mut daemon = TeamDaemon::new(DaemonConfig {
            project_root: tmp.path().to_path_buf(),
            team_config: test_team_config("ctx-restart"),
            session: session.clone(),
            members: vec![member],
            pane_map: HashMap::from([(member_name.to_string(), pane_id.clone())]),
        })
        .unwrap();
        daemon.active_tasks.insert(member_name.to_string(), 42);

        daemon.handle_context_exhaustion(member_name).unwrap();

        let log = (0..100)
            .find_map(|_| {
                let content = match std::fs::read_to_string(&fake_log) {
                    Ok(content) => content,
                    Err(_) => {
                        std::thread::sleep(Duration::from_millis(100));
                        return None;
                    }
                };
                if content.contains("--append-system-prompt") {
                    Some(content)
                } else {
                    std::thread::sleep(Duration::from_millis(100));
                    None
                }
            })
            .unwrap_or_else(|| {
                panic!(
                    "fake claude log was not written by restarted member at {}",
                    fake_log.display()
                )
            });
        assert!(log.contains("--append-system-prompt"));

        let events = crate::team::events::read_events(
            &tmp.path()
                .join(".batty")
                .join("team_config")
                .join("events.jsonl"),
        )
        .unwrap();
        assert!(events.iter().any(|event| event.event == "agent_restarted"
            && event.task.as_deref() == Some("42")
            && event.reason.as_deref() == Some("context_exhausted")));

        let restart_msg =
            inbox::pending_messages(&inbox::inboxes_root(tmp.path()), member_name).unwrap();
        assert!(
            restart_msg
                .iter()
                .any(|msg| msg.body.contains("context exhaustion")),
            "restart notice should be sent to the restarted member"
        );

        crate::tmux::kill_session(&session).unwrap();
        let _ = std::fs::remove_dir_all(&fake_bin);
    }

    #[test]
    #[serial]
    #[cfg_attr(not(feature = "integration"), ignore)]
    fn context_exhaustion_relaunch_corrects_mismatched_cwd() {
        let session = format!("batty-test-ctx-cwd-correct-{}", std::process::id());
        let _ = crate::tmux::kill_session(&session);

        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".batty").join("team_config")).unwrap();
        let wrong_dir = tmp.path().join("wrong");
        std::fs::create_dir_all(&wrong_dir).unwrap();

        let member_name = "eng-ctx-cwd";
        let lead_name = "manager-ctx-cwd";
        let (fake_bin, _fake_log) = setup_fake_claude(&tmp, member_name);
        let inbox_root = inbox::inboxes_root(tmp.path());
        inbox::init_inbox(&inbox_root, lead_name).unwrap();
        inbox::init_inbox(&inbox_root, member_name).unwrap();

        write_owned_task_file(tmp.path(), 42, "test-task", "in-progress", member_name);

        crate::tmux::create_session(&session, "bash", &[], wrong_dir.to_string_lossy().as_ref())
            .unwrap();
        crate::tmux::create_window(
            &session,
            "keeper",
            "sleep",
            &["60".to_string()],
            wrong_dir.to_string_lossy().as_ref(),
        )
        .unwrap();
        let pane_id = crate::tmux::pane_id(&session).unwrap();
        Command::new("tmux")
            .args(["set-option", "-p", "-t", &pane_id, "remain-on-exit", "on"])
            .output()
            .unwrap();

        let member = MemberInstance {
            name: member_name.to_string(),
            role_name: "engineer".to_string(),
            role_type: RoleType::Engineer,
            agent: Some("claude".to_string()),
            prompt: None,
            reports_to: Some(lead_name.to_string()),
            use_worktrees: false,
            ..Default::default()
        };
        let mut daemon = TeamDaemon::new(DaemonConfig {
            project_root: tmp.path().to_path_buf(),
            team_config: test_team_config("ctx-cwd"),
            session: session.clone(),
            members: vec![member],
            pane_map: HashMap::from([(member_name.to_string(), pane_id.clone())]),
        })
        .unwrap();
        daemon.active_tasks.insert(member_name.to_string(), 42);

        daemon.handle_context_exhaustion(member_name).unwrap();

        let expected = normalized_assignment_dir(tmp.path());
        let cwd_ok = (0..30).any(|_| {
            std::thread::sleep(Duration::from_millis(200));
            crate::tmux::pane_current_path(&pane_id)
                .map(|p| normalized_assignment_dir(Path::new(&p)) == expected)
                .unwrap_or(false)
        });
        assert!(
            cwd_ok,
            "context restart should correct pane cwd to project root"
        );

        crate::tmux::kill_session(&session).unwrap();
        let _ = std::fs::remove_dir_all(&fake_bin);
    }

    #[test]
    #[serial]
    #[cfg_attr(not(feature = "integration"), ignore)]
    fn agent_restart_second_exhaustion_escalates_instead_of_restarting() {
        let session = format!("batty-test-agent-restart-escalate-{}", std::process::id());
        let _ = crate::tmux::kill_session(&session);

        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".batty").join("team_config")).unwrap();

        let member_name = "eng-ctx-escalate";
        let lead_name = "manager-ctx-escalate";
        let (_fake_bin, _fake_log) = setup_fake_claude(&tmp, member_name);
        let inbox_root = inbox::inboxes_root(tmp.path());
        inbox::init_inbox(&inbox_root, lead_name).unwrap();
        inbox::init_inbox(&inbox_root, member_name).unwrap();

        write_owned_task_file(tmp.path(), 42, "test-task", "in-progress", member_name);

        // Write a prior restart event so this counts as the second exhaustion.
        write_event_log(
            tmp.path(),
            &[TeamEvent::agent_restarted(
                member_name,
                "42",
                "context_exhausted",
                1,
            )],
        );

        crate::tmux::create_session(&session, "bash", &[], tmp.path().to_str().unwrap()).unwrap();
        let pane_id = crate::tmux::pane_id(&session).unwrap();

        let member = MemberInstance {
            name: member_name.to_string(),
            role_name: "engineer".to_string(),
            role_type: RoleType::Engineer,
            agent: Some("claude".to_string()),
            prompt: None,
            reports_to: Some(lead_name.to_string()),
            use_worktrees: false,
            ..Default::default()
        };
        let mut daemon = TeamDaemon::new(DaemonConfig {
            project_root: tmp.path().to_path_buf(),
            team_config: test_team_config("ctx-escalate"),
            session: session.clone(),
            members: vec![
                MemberInstance {
                    name: lead_name.to_string(),
                    role_name: "manager".to_string(),
                    role_type: RoleType::Manager,
                    agent: None,
                    prompt: None,
                    reports_to: None,
                    use_worktrees: false,
                    ..Default::default()
                },
                member,
            ],
            pane_map: HashMap::from([(member_name.to_string(), pane_id)]),
        })
        .unwrap();
        daemon.active_tasks.insert(member_name.to_string(), 42);

        daemon.handle_context_exhaustion(member_name).unwrap();

        let manager_messages =
            inbox::pending_messages(&inbox::inboxes_root(tmp.path()), lead_name).unwrap();
        assert!(
            manager_messages
                .iter()
                .any(|msg| msg.body.contains("exhausted context")),
            "escalation message should be sent to manager"
        );

        let events = crate::team::events::read_events(
            &tmp.path()
                .join(".batty")
                .join("team_config")
                .join("events.jsonl"),
        )
        .unwrap();
        assert!(
            events
                .iter()
                .any(|event| event.event == "task_escalated"
                    && event.task.as_deref() == Some("42")),
            "task_escalated event should be emitted"
        );

        crate::tmux::kill_session(&session).unwrap();
    }

    #[test]
    #[serial]
    #[cfg_attr(not(feature = "integration"), ignore)]
    fn agent_restart_respects_cooldown_before_first_restart() {
        let session = format!("batty-test-agent-cooldown-{}", std::process::id());
        let _ = crate::tmux::kill_session(&session);

        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".batty").join("team_config")).unwrap();

        let member_name = "eng-ctx-cooldown";
        let lead_name = "manager-ctx-cooldown";
        let (_fake_bin, _fake_log) = setup_fake_claude(&tmp, member_name);
        let inbox_root = inbox::inboxes_root(tmp.path());
        inbox::init_inbox(&inbox_root, lead_name).unwrap();
        inbox::init_inbox(&inbox_root, member_name).unwrap();

        write_owned_task_file(tmp.path(), 42, "test-task", "in-progress", member_name);

        crate::tmux::create_session(&session, "bash", &[], tmp.path().to_str().unwrap()).unwrap();
        let pane_id = crate::tmux::pane_id(&session).unwrap();

        let member = MemberInstance {
            name: member_name.to_string(),
            role_name: "engineer".to_string(),
            role_type: RoleType::Engineer,
            agent: Some("claude".to_string()),
            prompt: None,
            reports_to: Some(lead_name.to_string()),
            use_worktrees: false,
            ..Default::default()
        };
        let mut daemon = TeamDaemon::new(DaemonConfig {
            project_root: tmp.path().to_path_buf(),
            team_config: test_team_config("ctx-cooldown"),
            session: session.clone(),
            members: vec![member],
            pane_map: HashMap::from([(member_name.to_string(), pane_id)]),
        })
        .unwrap();
        daemon.active_tasks.insert(member_name.to_string(), 42);

        // Set the cooldown so restart is suppressed.
        daemon.intervention_cooldowns.insert(
            TeamDaemon::context_restart_cooldown_key(member_name),
            Instant::now(),
        );

        daemon.handle_context_exhaustion(member_name).unwrap();

        // No restart notice should be sent.
        let member_msgs =
            inbox::pending_messages(&inbox::inboxes_root(tmp.path()), member_name).unwrap();
        assert!(
            member_msgs.is_empty(),
            "cooldown should suppress the restart"
        );

        crate::tmux::kill_session(&session).unwrap();
    }

    #[test]
    fn handle_context_exhaustion_no_task_sets_idle() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".batty").join("team_config")).unwrap();

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![engineer_member("eng-1", Some("manager"), false)])
            .build();
        daemon
            .states
            .insert("eng-1".to_string(), MemberState::Working);
        // No active task set — active_tasks is empty.

        daemon.handle_context_exhaustion("eng-1").unwrap();

        assert_eq!(daemon.states.get("eng-1"), Some(&MemberState::Idle));
    }

    #[test]
    fn handle_context_exhaustion_unknown_member_is_noop() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".batty").join("team_config")).unwrap();

        let mut daemon = TestDaemonBuilder::new(tmp.path()).build();
        // Calling with a member that doesn't exist should not panic.
        let result = daemon.handle_context_exhaustion("nonexistent");
        assert!(result.is_ok());
    }

    #[test]
    fn handle_context_exhaustion_escalation_cooldown_suppresses() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(tmp.path().join(".batty").join("team_config")).unwrap();

        let member_name = "eng-1";
        let lead_name = "manager";
        let inbox_root = inbox::inboxes_root(tmp.path());
        inbox::init_inbox(&inbox_root, lead_name).unwrap();
        inbox::init_inbox(&inbox_root, member_name).unwrap();

        write_owned_task_file(tmp.path(), 42, "test-task", "in-progress", member_name);
        // Write a prior restart event so we'd normally escalate.
        write_event_log(
            tmp.path(),
            &[TeamEvent::agent_restarted(
                member_name,
                "42",
                "context_exhausted",
                1,
            )],
        );

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![
                manager_member(lead_name, Some("architect")),
                engineer_member(member_name, Some(lead_name), false),
            ])
            .build();
        daemon.active_tasks.insert(member_name.to_string(), 42);
        // Set the escalation cooldown so it suppresses the escalation.
        daemon.intervention_cooldowns.insert(
            TeamDaemon::context_escalation_cooldown_key(member_name),
            Instant::now(),
        );

        daemon.handle_context_exhaustion(member_name).unwrap();

        // No message should have been sent to the manager.
        let pending = inbox::pending_messages(&inbox_root, lead_name).unwrap();
        assert!(
            pending.is_empty(),
            "escalation should be suppressed by cooldown"
        );
    }

    #[test]
    fn handle_context_pressure_restart_cooldown_suppresses_repeat_restart() {
        let tmp = tempfile::tempdir().unwrap();
        let member_name = "eng-1";
        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![engineer_member(member_name, Some("manager"), false)])
            .build();
        daemon.intervention_cooldowns.insert(
            TeamDaemon::context_restart_cooldown_key(member_name),
            Instant::now(),
        );

        let restarted = daemon
            .handle_context_pressure_restart(member_name, Some(42), 0)
            .unwrap();

        assert!(!restarted, "cooldown should suppress the proactive restart");
    }

    #[test]
    fn restart_member_with_task_context_falls_back_to_pane_respawn_for_manager_without_task() {
        // #706: pre-fix, `restart_member_with_task_context` warned and
        // bailed when `active_task` returned None — which is always true
        // for managers/architects. That left jordan-pm stuck in a
        // stall-mid-turn loop at 211% context with no recovery path.
        // After the fix the function falls back to `restart_member`
        // (pane respawn + relaunch). In this test env there is no pane
        // registered for the member, so `restart_member` itself bails at
        // its own no-pane guard — we just need to confirm the outer
        // function returns Ok(()) without panic (i.e. took the fallback
        // branch rather than choking on a missing pane from a path that
        // assumed a task existed).
        let tmp = tempfile::tempdir().unwrap();
        let member_name = "manager-1";
        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![manager_member(member_name, None)])
            .build();

        let result = daemon.restart_member_with_task_context(member_name, "stalled mid-turn");
        assert!(
            result.is_ok(),
            "restart fallback should not error when the member has no active task"
        );
        assert!(
            !daemon.active_tasks.contains_key(member_name),
            "manager should remain task-less after the fallback restart"
        );
    }

    #[test]
    fn handle_context_pressure_restart_suppresses_without_fresh_progress() {
        let tmp = tempfile::tempdir().unwrap();
        let member_name = "eng-1";
        let task = crate::task::Task {
            id: 42,
            title: "resume".to_string(),
            status: "in-progress".to_string(),
            priority: "high".to_string(),
            assignee: None,
            claimed_by: Some(member_name.to_string()),
            claimed_at: None,
            claim_ttl_secs: None,
            claim_expires_at: None,
            last_progress_at: None,
            claim_warning_sent_at: None,
            claim_extensions: None,
            last_output_bytes: None,
            blocked: None,
            tags: Vec::new(),
            depends_on: Vec::new(),
            review_owner: None,
            blocked_on: None,
            worktree_path: None,
            branch: None,
            commit: None,
            artifacts: Vec::new(),
            next_action: None,
            scheduled_for: None,
            cron_schedule: None,
            cron_last_run: None,
            completed: None,
            description: "resume".to_string(),
            batty_config: None,
            source_path: tmp.path().join("task-42.md"),
        };
        crate::team::context_management::stage_restart_context(
            tmp.path(),
            member_name,
            &task,
            "context_pressure",
            1,
            Some(0),
        )
        .unwrap();
        crate::team::context_management::consume_restart_context(tmp.path()).unwrap();

        let mut daemon = TestDaemonBuilder::new(tmp.path())
            .members(vec![engineer_member(member_name, Some("manager"), false)])
            .build();

        let restarted = daemon
            .handle_context_pressure_restart(member_name, Some(42), 0)
            .unwrap();

        assert!(
            !restarted,
            "no-progress proactive restarts should be suppressed"
        );
    }
}