git-paw 0.7.0

Parallel AI Worktrees — orchestrate multiple AI coding CLI sessions across git worktrees
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
//! Single-tick orchestration for the supervisor auto-approve poll loop.
//!
//! Exposes [`poll_tick`] — given a broker state, a session name, a
//! pane-index resolver, and an [`AutoApproveConfig`], it:
//!
//! 1. Detects stalled agents via [`super::stall::detect_stalled_agents`].
//! 2. Captures each stalled agent's pane via
//!    [`super::permission_prompt::detect_permission_prompt`].
//! 3. For safe-classified prompts, dispatches `BTab Down Enter` via
//!    [`super::approve::auto_approve_pane`].
//! 4. For `Unknown` prompts, forwards a question to the dashboard inbox so
//!    the human can resolve it.
//!
//! The loop driver lives in `main.rs` (background thread spawned by
//! `cmd_supervisor`); this module keeps the per-tick logic pure and
//! testable.

use std::io::{Read, Write};
use std::net::TcpStream;
use std::path::PathBuf;
use std::time::Duration;

use serde::Deserialize;

use crate::broker::BrokerState;
use crate::config::AutoApproveConfig;
use crate::error::PawError;

use super::approve::{ApprovalRequest, KeyDispatcher, auto_approve_pane};
use super::auto_approve::{is_safe_command, is_worktree_file_op};
use super::permission_prompt::{PermissionType, detect_permission_prompt};
use super::stall::detect_stalled_agents;

/// Outcome of processing a single stalled agent during a poll tick.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TickOutcome {
    /// No permission prompt was found in the pane.
    NoPrompt,
    /// Prompt was detected, classified safe, and approved.
    Approved {
        /// Whitelist entry that matched the captured command.
        matched_entry: String,
        /// Permission class of the approved prompt.
        kind: PermissionType,
    },
    /// Prompt was detected but did not match the whitelist; the supervisor
    /// should forward it to the dashboard.
    Forwarded {
        /// Permission class of the forwarded prompt.
        kind: PermissionType,
    },
}

/// Trait providing the pane-index for a given agent ID.
///
/// `cmd_supervisor` knows the mapping from session state; tests substitute
/// a closure-backed implementation.
pub trait PaneResolver {
    /// Returns the tmux pane index for `agent_id`, or `None` if the agent
    /// has no pane (e.g. the supervisor itself).
    fn pane_index_for(&self, agent_id: &str) -> Option<usize>;
}

impl<F> PaneResolver for F
where
    F: Fn(&str) -> Option<usize>,
{
    fn pane_index_for(&self, agent_id: &str) -> Option<usize> {
        self(agent_id)
    }
}

/// Trait providing the worktree root path for a given agent ID.
///
/// Used by the worktree-file-op classifier (bug 3) to resolve a captured
/// file-operation prompt's target against the agent's worktree boundary.
/// `cmd_supervisor` builds the mapping from session state; tests substitute a
/// closure-backed implementation. Returns `None` for agents without a known
/// worktree (e.g. the supervisor itself), which suppresses file-op
/// auto-approval for that agent.
pub trait WorktreeResolver {
    /// Returns the worktree root for `agent_id`, or `None` when unknown.
    fn worktree_root_for(&self, agent_id: &str) -> Option<PathBuf>;
}

impl<F> WorktreeResolver for F
where
    F: Fn(&str) -> Option<PathBuf>,
{
    fn worktree_root_for(&self, agent_id: &str) -> Option<PathBuf> {
        self(agent_id)
    }
}

/// Trait providing the captured pane content for an agent.
///
/// In production this is a thin shim over [`super::permission_prompt::capture_pane`].
/// Tests inject a stub so the captured text is deterministic.
pub trait PaneInspector {
    /// Captures the pane and returns the classification, or `None` when
    /// no approval marker is present.
    fn inspect(&self, session: &str, pane_index: usize) -> Option<PermissionType>;
    /// Returns the raw captured content for whitelist matching, or empty
    /// string when capture fails.
    fn captured_text(&self, session: &str, pane_index: usize) -> String;
}

/// Production [`PaneInspector`] backed by `tmux capture-pane`.
pub struct TmuxPaneInspector;

impl PaneInspector for TmuxPaneInspector {
    fn inspect(&self, session: &str, pane_index: usize) -> Option<PermissionType> {
        detect_permission_prompt(session, pane_index)
    }
    fn captured_text(&self, session: &str, pane_index: usize) -> String {
        super::permission_prompt::capture_pane(session, pane_index).unwrap_or_default()
    }
}

/// Forwarder for unsafe prompts — abstracted so tests can record forwards.
pub trait QuestionForwarder {
    /// Forward a question to the supervisor dashboard inbox.
    ///
    /// Returns the dispatch result; failures are logged but do not abort
    /// the poll tick.
    fn forward_question(&mut self, agent_id: &str, kind: PermissionType, captured: &str);
}

/// Inputs for [`poll_tick`].
///
/// Bundled so the per-tick API is one parameter wide and clippy's
/// `too_many_arguments` lint stays happy.
pub struct PollContext<'a, R, I, D, Q, W>
where
    R: PaneResolver,
    I: PaneInspector,
    D: KeyDispatcher,
    Q: QuestionForwarder,
    W: WorktreeResolver,
{
    /// Broker state used for stall detection by [`poll_tick`].
    ///
    /// Set to `None` when calling [`tick_from_status`] from a process that
    /// does not own the broker state (e.g. the supervisor's background
    /// poll thread, which queries `/status` over HTTP instead).
    pub state: Option<&'a BrokerState>,
    /// tmux session name.
    pub session: &'a str,
    /// Auto-approve config (presets applied by [`poll_tick`]).
    pub config: &'a AutoApproveConfig,
    /// Resolves agent ID to pane index.
    pub resolver: &'a R,
    /// Inspects pane content.
    pub inspector: &'a I,
    /// Sends approval keystrokes.
    pub dispatcher: &'a mut D,
    /// Forwards unsafe prompts to the dashboard.
    pub forwarder: &'a mut Q,
    /// Resolves agent ID to worktree root for the file-op classifier (bug 3).
    pub worktree_resolver: &'a W,
    /// Optional broker URL for audit-log publishing.
    pub broker_url: Option<&'a str>,
}

/// Runs one tick of the auto-approve poll loop and returns the outcome
/// for each stalled agent (in iteration order).
pub fn poll_tick<R, I, D, Q, W>(
    ctx: &mut PollContext<'_, R, I, D, Q, W>,
) -> Vec<(String, TickOutcome)>
where
    R: PaneResolver,
    I: PaneInspector,
    D: KeyDispatcher,
    Q: QuestionForwarder,
    W: WorktreeResolver,
{
    let cfg = ctx.config.resolved();
    if !cfg.enabled {
        return Vec::new();
    }
    let Some(state) = ctx.state else {
        return Vec::new();
    };
    let threshold = Duration::from_secs(cfg.stall_threshold_seconds);
    let stalled = detect_stalled_agents(state, threshold);
    let whitelist = cfg.effective_whitelist();
    drive_outcomes(stalled, ctx, &cfg, &whitelist)
}

/// Subset of an agent record returned by the broker `/status` endpoint that
/// the supervisor poll loop cares about.
#[derive(Debug, Clone, Deserialize)]
pub struct AgentStatusRow {
    /// Agent identifier (slugified branch name).
    pub agent_id: String,
    /// Status label (e.g. `"working"`, `"done"`).
    pub status: String,
    /// Seconds since the agent was last seen.
    pub last_seen_seconds: u64,
}

/// Fetches the broker `/status` endpoint and returns the agent summary.
///
/// Used by `cmd_supervisor`'s background poll thread because the broker
/// state lives in the dashboard process, not in `cmd_supervisor` itself.
/// Errors are surfaced so the caller can decide whether to retry.
pub fn fetch_status_over_http(broker_url: &str) -> Result<Vec<AgentStatusRow>, PawError> {
    let addr = broker_url.strip_prefix("http://").unwrap_or(broker_url);
    let socket_addr = if let Ok(a) = addr.parse() {
        a
    } else {
        use std::net::ToSocketAddrs;
        addr.to_socket_addrs()
            .map_err(|e| PawError::SessionError(format!("invalid broker address {addr}: {e}")))?
            .next()
            .ok_or_else(|| {
                PawError::SessionError(format!("broker address {addr} resolved to no addrs"))
            })?
    };

    let mut stream = TcpStream::connect_timeout(&socket_addr, Duration::from_millis(500))
        .map_err(|e| PawError::SessionError(format!("failed to connect to broker: {e}")))?;
    stream.set_read_timeout(Some(Duration::from_secs(2))).ok();
    stream.set_write_timeout(Some(Duration::from_secs(2))).ok();

    let request = format!("GET /status HTTP/1.1\r\nHost: {addr}\r\nConnection: close\r\n\r\n");
    stream
        .write_all(request.as_bytes())
        .map_err(|e| PawError::SessionError(format!("failed to write status request: {e}")))?;

    let mut response = String::new();
    let _ = stream.read_to_string(&mut response);

    // Find the JSON body (first `{` after the headers).
    let body_start = response
        .find("\r\n\r\n")
        .map(|i| i + 4)
        .ok_or_else(|| PawError::SessionError("malformed broker response".to_string()))?;
    let body = &response[body_start..];

    let parsed: StatusResponse = serde_json::from_str(body)
        .map_err(|e| PawError::SessionError(format!("broker /status parse error: {e}")))?;
    Ok(parsed.agents)
}

#[derive(Deserialize)]
struct StatusResponse {
    agents: Vec<AgentStatusRow>,
}

/// Returns the IDs of agents whose `status` is non-terminal and whose
/// `last_seen_seconds` is at or above `threshold_seconds`.
///
/// HTTP-friendly counterpart to [`super::stall::detect_stalled_agents`]
/// for callers that only have a `/status` snapshot (the supervisor's
/// background poll thread).
#[must_use]
pub fn stalled_from_status(rows: &[AgentStatusRow], threshold_seconds: u64) -> Vec<String> {
    rows.iter()
        .filter(|r| !super::stall::TERMINAL_STATUSES.contains(&r.status.as_str()))
        .filter(|r| r.last_seen_seconds >= threshold_seconds)
        .map(|r| r.agent_id.clone())
        .collect()
}

/// Runs one tick driven by an HTTP `/status` snapshot rather than an
/// in-process [`BrokerState`].
///
/// Mirrors [`poll_tick`] but takes pre-fetched [`AgentStatusRow`] entries
/// so the supervisor's background thread does not need access to the
/// broker's lock.
pub fn tick_from_status<R, I, D, Q, W>(
    rows: &[AgentStatusRow],
    ctx: &mut PollContext<'_, R, I, D, Q, W>,
) -> Vec<(String, TickOutcome)>
where
    R: PaneResolver,
    I: PaneInspector,
    D: KeyDispatcher,
    Q: QuestionForwarder,
    W: WorktreeResolver,
{
    let cfg = ctx.config.resolved();
    if !cfg.enabled {
        return Vec::new();
    }
    let stalled = stalled_from_status(rows, cfg.stall_threshold_seconds);
    let whitelist = cfg.effective_whitelist();
    drive_outcomes(stalled, ctx, &cfg, &whitelist)
}

fn drive_outcomes<R, I, D, Q, W>(
    stalled: Vec<String>,
    ctx: &mut PollContext<'_, R, I, D, Q, W>,
    cfg: &AutoApproveConfig,
    whitelist: &[String],
) -> Vec<(String, TickOutcome)>
where
    R: PaneResolver,
    I: PaneInspector,
    D: KeyDispatcher,
    Q: QuestionForwarder,
    W: WorktreeResolver,
{
    let mut out = Vec::with_capacity(stalled.len());
    for agent_id in stalled {
        let Some(pane_index) = ctx.resolver.pane_index_for(&agent_id) else {
            continue;
        };
        let Some(kind) = ctx.inspector.inspect(ctx.session, pane_index) else {
            out.push((agent_id, TickOutcome::NoPrompt));
            continue;
        };
        let captured = ctx.inspector.captured_text(ctx.session, pane_index);
        // Shell whitelist takes precedence: a `cargo`/`git`/`curl` prompt is
        // approved exactly as in v0.5.0 before the file-op classifier runs.
        if let Some(entry) = first_whitelist_match(&captured, whitelist) {
            let req = ApprovalRequest {
                enabled: cfg.enabled,
                session: ctx.session,
                pane_index,
                agent_id: &agent_id,
                kind,
                matched_entry: Some(entry.as_str()),
                broker_url: ctx.broker_url,
            };
            match auto_approve_pane(ctx.dispatcher, req) {
                Ok(true) => out.push((
                    agent_id,
                    TickOutcome::Approved {
                        matched_entry: entry,
                        kind,
                    },
                )),
                _ => out.push((agent_id, TickOutcome::Forwarded { kind })),
            }
            continue;
        }

        // Bug 3: a Claude write / edit / create prompt whose target resolves
        // inside the agent's own worktree is auto-approved when
        // `approve_worktree_writes` is enabled.
        if let Some(root) = ctx.worktree_resolver.worktree_root_for(&agent_id)
            && is_worktree_file_op(&captured, &root, cfg.approve_worktree_writes())
        {
            let req = ApprovalRequest {
                enabled: cfg.enabled,
                session: ctx.session,
                pane_index,
                agent_id: &agent_id,
                kind: PermissionType::WorktreeFileOp,
                matched_entry: Some("worktree-file-op"),
                broker_url: ctx.broker_url,
            };
            match auto_approve_pane(ctx.dispatcher, req) {
                Ok(true) => out.push((
                    agent_id,
                    TickOutcome::Approved {
                        matched_entry: "worktree-file-op".to_string(),
                        kind: PermissionType::WorktreeFileOp,
                    },
                )),
                _ => out.push((
                    agent_id,
                    TickOutcome::Forwarded {
                        kind: PermissionType::WorktreeFileOp,
                    },
                )),
            }
            continue;
        }

        ctx.forwarder.forward_question(&agent_id, kind, &captured);
        out.push((agent_id, TickOutcome::Forwarded { kind }));
    }
    out
}

fn first_whitelist_match(captured: &str, whitelist: &[String]) -> Option<String> {
    // Walk lines so multi-line pane captures only match the actual command
    // being prompted. Using is_safe_command per-line keeps the prefix-
    // boundary semantics intact.
    for line in captured.lines() {
        for entry in whitelist {
            if is_safe_command(line, std::slice::from_ref(entry)) {
                return Some(entry.clone());
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::broker::messages::{BrokerMessage, StatusPayload};
    use crate::broker::{AgentRecord, BrokerState};
    use crate::config::AutoApproveConfig;
    use std::cell::RefCell;
    use std::time::Instant;

    struct StubInspector {
        kind: Option<PermissionType>,
        captured: String,
    }
    impl PaneInspector for StubInspector {
        fn inspect(&self, _session: &str, _pane_index: usize) -> Option<PermissionType> {
            self.kind
        }
        fn captured_text(&self, _session: &str, _pane_index: usize) -> String {
            self.captured.clone()
        }
    }

    struct RecordingDispatcher {
        events: Vec<(String, usize, String)>,
    }
    impl KeyDispatcher for RecordingDispatcher {
        fn send_key(&mut self, session: &str, pane_index: usize, key: &str) -> std::io::Result<()> {
            self.events
                .push((session.to_string(), pane_index, key.to_string()));
            Ok(())
        }
    }

    #[derive(Default)]
    struct RecordingForwarder {
        forwards: RefCell<Vec<(String, PermissionType, String)>>,
    }
    impl QuestionForwarder for RecordingForwarder {
        fn forward_question(&mut self, agent_id: &str, kind: PermissionType, captured: &str) {
            self.forwards
                .borrow_mut()
                .push((agent_id.to_string(), kind, captured.to_string()));
        }
    }

    fn insert_stalled(state: &BrokerState, id: &str, age_secs: u64) {
        let mut inner = state.write();
        inner.agents.insert(
            id.to_string(),
            AgentRecord {
                agent_id: id.to_string(),
                status: "working".to_string(),
                last_seen: Instant::now()
                    .checked_sub(Duration::from_secs(age_secs))
                    .unwrap_or_else(Instant::now),
                last_message: Some(BrokerMessage::Status {
                    agent_id: id.to_string(),
                    payload: StatusPayload {
                        status: "working".to_string(),
                        modified_files: Vec::new(),
                        message: None,
                        ..Default::default()
                    },
                }),
                last_committed_at: None,
            },
        );
    }

    fn run_tick<R: PaneResolver, I: PaneInspector>(
        state: &BrokerState,
        cfg: &AutoApproveConfig,
        resolver: &R,
        inspector: &I,
    ) -> (
        Vec<(String, TickOutcome)>,
        RecordingDispatcher,
        RecordingForwarder,
    ) {
        // Default: no worktree mapping (file-op classifier inert).
        let no_worktree = |_id: &str| None::<PathBuf>;
        let mut dispatcher = RecordingDispatcher { events: vec![] };
        let mut forwarder = RecordingForwarder::default();
        let out = {
            let mut ctx = PollContext {
                state: Some(state),
                session: "paw-x",
                config: cfg,
                resolver,
                inspector,
                dispatcher: &mut dispatcher,
                forwarder: &mut forwarder,
                worktree_resolver: &no_worktree,
                broker_url: None,
            };
            poll_tick(&mut ctx)
        };
        (out, dispatcher, forwarder)
    }

    #[test]
    fn disabled_config_returns_empty() {
        let state = BrokerState::new(None);
        insert_stalled(&state, "stuck", 600);
        let cfg = AutoApproveConfig {
            enabled: false,
            ..AutoApproveConfig::default()
        };
        let resolver = |_id: &str| Some(1);
        let inspector = StubInspector {
            kind: Some(PermissionType::Cargo),
            captured: "cargo test".into(),
        };
        let (out, dispatcher, _) = run_tick(&state, &cfg, &resolver, &inspector);
        assert!(out.is_empty());
        assert!(dispatcher.events.is_empty());
    }

    #[test]
    fn stalled_safe_agent_is_approved() {
        let state = BrokerState::new(None);
        insert_stalled(&state, "agent-a", 600);
        let cfg = AutoApproveConfig::default();
        let resolver = |id: &str| if id == "agent-a" { Some(2) } else { None };
        let inspector = StubInspector {
            kind: Some(PermissionType::Cargo),
            captured: "cargo test --workspace".into(),
        };
        let (out, dispatcher, forwarder) = run_tick(&state, &cfg, &resolver, &inspector);
        assert_eq!(out.len(), 1);
        let (id, outcome) = &out[0];
        assert_eq!(id, "agent-a");
        match outcome {
            TickOutcome::Approved {
                matched_entry,
                kind,
            } => {
                assert_eq!(matched_entry, "cargo test");
                assert_eq!(*kind, PermissionType::Cargo);
            }
            _ => panic!("expected Approved, got {outcome:?}"),
        }
        // BTab + Down + Enter dispatched in order.
        let keys: Vec<&str> = dispatcher
            .events
            .iter()
            .map(|(_, _, k)| k.as_str())
            .collect();
        assert_eq!(keys, vec!["BTab", "Down", "Enter"]);
        assert!(forwarder.forwards.borrow().is_empty());
    }

    #[test]
    fn stalled_unsafe_agent_is_forwarded_not_approved() {
        let state = BrokerState::new(None);
        insert_stalled(&state, "agent-b", 600);
        let cfg = AutoApproveConfig::default();
        let resolver = |_id: &str| Some(3);
        let inspector = StubInspector {
            kind: Some(PermissionType::Unknown),
            captured: "rm -rf /tmp/foo\nrequires approval".into(),
        };
        let (out, dispatcher, forwarder) = run_tick(&state, &cfg, &resolver, &inspector);
        assert_eq!(out.len(), 1);
        match &out[0].1 {
            TickOutcome::Forwarded { kind } => assert_eq!(*kind, PermissionType::Unknown),
            other => panic!("expected Forwarded, got {other:?}"),
        }
        assert!(
            dispatcher.events.is_empty(),
            "no keystrokes for unsafe prompt"
        );
        let forwards = forwarder.forwards.borrow();
        assert_eq!(forwards.len(), 1);
        assert_eq!(forwards[0].0, "agent-b");
    }

    #[test]
    fn fresh_agent_is_skipped() {
        let state = BrokerState::new(None);
        insert_stalled(&state, "fresh", 0); // age 0 < 30s threshold
        let cfg = AutoApproveConfig::default();
        let resolver = |_id: &str| Some(1);
        let inspector = StubInspector {
            kind: Some(PermissionType::Cargo),
            captured: "cargo test".into(),
        };
        let (out, dispatcher, _) = run_tick(&state, &cfg, &resolver, &inspector);
        assert!(out.is_empty(), "fresh agent must not be polled");
        assert!(dispatcher.events.is_empty());
    }

    #[test]
    fn no_marker_means_no_prompt_outcome() {
        let state = BrokerState::new(None);
        insert_stalled(&state, "agent-c", 600);
        let cfg = AutoApproveConfig::default();
        let resolver = |_id: &str| Some(1);
        let inspector = StubInspector {
            kind: None,
            captured: String::new(),
        };
        let (out, dispatcher, _) = run_tick(&state, &cfg, &resolver, &inspector);
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].1, TickOutcome::NoPrompt);
        assert!(dispatcher.events.is_empty());
    }

    // --- stalled_from_status / tick_from_status ---

    fn row(agent_id: &str, status: &str, last_seen_seconds: u64) -> AgentStatusRow {
        AgentStatusRow {
            agent_id: agent_id.to_string(),
            status: status.to_string(),
            last_seen_seconds,
        }
    }

    #[test]
    fn stalled_from_status_filters_by_threshold() {
        let rows = vec![
            row("fresh", "working", 5),
            row("stale", "working", 60),
            row("ancient", "working", 600),
        ];
        let stalled = stalled_from_status(&rows, 30);
        assert!(stalled.contains(&"stale".to_string()));
        assert!(stalled.contains(&"ancient".to_string()));
        assert!(!stalled.contains(&"fresh".to_string()));
    }

    #[test]
    fn stalled_from_status_skips_terminal() {
        let rows = vec![
            row("a", "done", 600),
            row("b", "verified", 600),
            row("c", "blocked", 600),
            row("d", "committed", 600),
            row("e", "working", 600),
        ];
        let stalled = stalled_from_status(&rows, 30);
        assert_eq!(stalled, vec!["e".to_string()]);
    }

    #[test]
    fn tick_from_status_dispatches_safe_prompt() {
        let rows = vec![row("agent-a", "working", 300)];
        let cfg = AutoApproveConfig::default();
        let resolver = |id: &str| if id == "agent-a" { Some(2) } else { None };
        let inspector = StubInspector {
            kind: Some(PermissionType::Cargo),
            captured: "cargo test --workspace".into(),
        };
        let no_worktree = |_id: &str| None::<PathBuf>;
        let mut dispatcher = RecordingDispatcher { events: vec![] };
        let mut forwarder = RecordingForwarder::default();
        let out = {
            let mut ctx = PollContext {
                state: None,
                session: "paw-x",
                config: &cfg,
                resolver: &resolver,
                inspector: &inspector,
                dispatcher: &mut dispatcher,
                forwarder: &mut forwarder,
                worktree_resolver: &no_worktree,
                broker_url: None,
            };
            tick_from_status(&rows, &mut ctx)
        };
        assert_eq!(out.len(), 1);
        let keys: Vec<&str> = dispatcher
            .events
            .iter()
            .map(|(_, _, k)| k.as_str())
            .collect();
        assert_eq!(keys, vec!["BTab", "Down", "Enter"]);
    }

    // --- Bug 3: worktree file-op approval through the poll loop ---

    fn run_tick_with_worktree<R, I, Wt>(
        state: &BrokerState,
        cfg: &AutoApproveConfig,
        resolver: &R,
        inspector: &I,
        worktree_resolver: &Wt,
    ) -> (
        Vec<(String, TickOutcome)>,
        RecordingDispatcher,
        RecordingForwarder,
    )
    where
        R: PaneResolver,
        I: PaneInspector,
        Wt: WorktreeResolver,
    {
        let mut dispatcher = RecordingDispatcher { events: vec![] };
        let mut forwarder = RecordingForwarder::default();
        let out = {
            let mut ctx = PollContext {
                state: Some(state),
                session: "paw-x",
                config: cfg,
                resolver,
                inspector,
                dispatcher: &mut dispatcher,
                forwarder: &mut forwarder,
                worktree_resolver,
                broker_url: None,
            };
            poll_tick(&mut ctx)
        };
        (out, dispatcher, forwarder)
    }

    #[test]
    fn in_worktree_file_prompt_is_auto_approved() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().to_path_buf();
        let state = BrokerState::new(None);
        insert_stalled(&state, "agent-a", 600);
        let cfg = AutoApproveConfig::default();
        let resolver = |id: &str| if id == "agent-a" { Some(2) } else { None };
        // A file-write prompt classifies as Unknown by command class, then the
        // worktree classifier promotes it to WorktreeFileOp.
        let inspector = StubInspector {
            kind: Some(PermissionType::Unknown),
            captured: "Do you want to allow this write to Containerfile?".into(),
        };
        let worktree = move |id: &str| {
            if id == "agent-a" {
                Some(root.clone())
            } else {
                None
            }
        };
        let (out, dispatcher, forwarder) =
            run_tick_with_worktree(&state, &cfg, &resolver, &inspector, &worktree);
        assert_eq!(out.len(), 1);
        match &out[0].1 {
            TickOutcome::Approved {
                matched_entry,
                kind,
            } => {
                assert_eq!(matched_entry, "worktree-file-op");
                assert_eq!(*kind, PermissionType::WorktreeFileOp);
            }
            other => panic!("expected Approved worktree-file-op, got {other:?}"),
        }
        let keys: Vec<&str> = dispatcher
            .events
            .iter()
            .map(|(_, _, k)| k.as_str())
            .collect();
        assert_eq!(keys, vec!["BTab", "Down", "Enter"]);
        assert!(forwarder.forwards.borrow().is_empty());
    }

    #[test]
    fn out_of_worktree_file_prompt_is_forwarded() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().to_path_buf();
        let state = BrokerState::new(None);
        insert_stalled(&state, "agent-b", 600);
        let cfg = AutoApproveConfig::default();
        let resolver = |_id: &str| Some(3);
        let inspector = StubInspector {
            kind: Some(PermissionType::Unknown),
            captured: "Do you want to allow this write to /etc/hosts?".into(),
        };
        let worktree = move |_id: &str| Some(root.clone());
        let (out, dispatcher, forwarder) =
            run_tick_with_worktree(&state, &cfg, &resolver, &inspector, &worktree);
        assert_eq!(out.len(), 1);
        assert!(matches!(out[0].1, TickOutcome::Forwarded { .. }));
        assert!(
            dispatcher.events.is_empty(),
            "out-of-worktree prompt must not dispatch keystrokes"
        );
        assert_eq!(forwarder.forwards.borrow().len(), 1);
    }

    #[test]
    fn disabled_worktree_writes_forwards_file_prompt() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().to_path_buf();
        let state = BrokerState::new(None);
        insert_stalled(&state, "agent-c", 600);
        let cfg = AutoApproveConfig {
            approve_worktree_writes: Some(false),
            ..AutoApproveConfig::default()
        };
        let resolver = |_id: &str| Some(1);
        let inspector = StubInspector {
            kind: Some(PermissionType::Unknown),
            captured: "Do you want to allow this write to Containerfile?".into(),
        };
        let worktree = move |_id: &str| Some(root.clone());
        let (out, dispatcher, _forwarder) =
            run_tick_with_worktree(&state, &cfg, &resolver, &inspector, &worktree);
        assert_eq!(out.len(), 1);
        assert!(
            matches!(out[0].1, TickOutcome::Forwarded { .. }),
            "approve_worktree_writes=false must forward, got {:?}",
            out[0].1
        );
        assert!(dispatcher.events.is_empty());
    }
}