Skip to main content

agent_doc_tmux/
lib.rs

1//! Shared pure tmux model state for agent-doc.
2//!
3//! This crate owns reusable tmux observations, realtime state, and layout
4//! projection policy. It does not execute `tmux` commands, dispatch turns,
5//! merge document text, or commit document changes.
6
7use lazily::{ThreadSafeContext, ThreadSafeStateMachine};
8use serde::{Deserialize, Serialize};
9use std::{
10    collections::{BTreeSet, HashMap, HashSet},
11    fmt,
12    path::{Path, PathBuf},
13};
14
15pub const TMUX_PANE_GEOMETRY_FORMAT: &str =
16    "#{pane_id} #{pane_left} #{pane_top} #{pane_width} #{pane_height}";
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20pub enum TmuxPaneActivity {
21    Unknown,
22    PromptReady,
23    Busy,
24    OutputActive,
25    Exited,
26    Missing,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[serde(rename_all = "snake_case")]
31pub enum TmuxSupervisorHealth {
32    Unknown,
33    Healthy,
34    Stale,
35    Crashed,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
39pub struct TmuxRealtimeState {
40    pub pane: TmuxPaneActivity,
41    pub supervisor: TmuxSupervisorHealth,
42    pub last_output_watermark: Option<String>,
43}
44
45impl Default for TmuxRealtimeState {
46    fn default() -> Self {
47        Self {
48            pane: TmuxPaneActivity::Unknown,
49            supervisor: TmuxSupervisorHealth::Unknown,
50            last_output_watermark: None,
51        }
52    }
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case", tag = "kind")]
57pub enum TmuxObservation {
58    PaneMissing,
59    PaneExited,
60    PromptReady,
61    Busy,
62    OutputAdvanced { watermark: String },
63    SupervisorHeartbeat,
64    SupervisorStale,
65    SupervisorCrashed,
66}
67
68/// Outcome of reconciling a candidate pane against the document's provably-live
69/// owner pane.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub enum FocusPaneDecision {
72    /// Keep the candidate pane resolved from projection or registry.
73    UseCandidate,
74    /// Focus the pane that currently owns the document instead of the stale
75    /// projection/registry candidate.
76    RepairToLiveOwner(String),
77}
78
79/// Decide whether focus should keep its candidate pane or swap to a provable
80/// live owner pane.
81///
82/// The live owner wins only when it is a different, non-empty pane. When no live
83/// owner is provable, or it matches the candidate, the existing selection is
84/// preserved so the happy path is unchanged.
85pub fn decide_focus_pane(candidate: &str, live_owner: Option<&str>) -> FocusPaneDecision {
86    match live_owner {
87        Some(owner) if !owner.is_empty() && owner != candidate => {
88            FocusPaneDecision::RepairToLiveOwner(owner.to_string())
89        }
90        _ => FocusPaneDecision::UseCandidate,
91    }
92}
93
94/// Determine if the file is in the first column of the editor layout.
95///
96/// When true, a new agent pane should be split before the existing pane. Returns
97/// false when there are fewer than two columns, because there is no meaningful
98/// split-before decision to make.
99pub fn is_first_column(file: &Path, col_args: &[String]) -> bool {
100    if col_args.len() < 2 {
101        return false;
102    }
103    let file_str = file.to_string_lossy();
104    col_args
105        .first()
106        .is_some_and(|first_col| first_col.split(',').any(|f| f.trim() == file_str.as_ref()))
107}
108
109pub fn auto_start_candidate_files(col_args: &[String]) -> Vec<PathBuf> {
110    let mut seen: HashSet<PathBuf> = HashSet::new();
111    let mut out: Vec<PathBuf> = Vec::new();
112    for path in col_args
113        .iter()
114        .flat_map(|arg| arg.split(','))
115        .map(|s| PathBuf::from(s.trim()))
116    {
117        if seen.insert(path.clone()) {
118            out.push(path);
119        }
120    }
121    out
122}
123
124pub fn projected_sync_pane_count(col_args: &[String]) -> usize {
125    col_args
126        .iter()
127        .flat_map(|arg| arg.split(','))
128        .map(str::trim)
129        .filter(|file| !file.is_empty())
130        .map(|file| {
131            let path = PathBuf::from(file);
132            path.canonicalize().unwrap_or(path)
133        })
134        .collect::<HashSet<_>>()
135        .len()
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
139#[serde(rename_all = "snake_case")]
140pub enum PanePosition {
141    Left,
142    Right,
143    Top,
144    Bottom,
145}
146
147impl PanePosition {
148    pub fn parse(input: &str) -> Result<Self, PanePositionError> {
149        match input {
150            "left" => Ok(Self::Left),
151            "right" => Ok(Self::Right),
152            "top" => Ok(Self::Top),
153            "bottom" => Ok(Self::Bottom),
154            _ => Err(PanePositionError::InvalidPosition {
155                position: input.to_string(),
156            }),
157        }
158    }
159
160    pub const fn as_str(self) -> &'static str {
161        match self {
162            Self::Left => "left",
163            Self::Right => "right",
164            Self::Top => "top",
165            Self::Bottom => "bottom",
166        }
167    }
168}
169
170#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
171pub struct TmuxPaneGeometry {
172    pub id: String,
173    pub left: u32,
174    pub top: u32,
175    pub width: u32,
176    pub height: u32,
177}
178
179impl TmuxPaneGeometry {
180    fn right_edge(&self) -> u32 {
181        self.left.saturating_add(self.width)
182    }
183
184    fn bottom_edge(&self) -> u32 {
185        self.top.saturating_add(self.height)
186    }
187}
188
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub enum PanePositionError {
191    NoPanes { scope: String },
192    InvalidPosition { position: String },
193    Unresolved { position: String },
194}
195
196impl fmt::Display for PanePositionError {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        match self {
199            Self::NoPanes { scope } => write!(f, "no panes found in {scope}"),
200            Self::InvalidPosition { position } => write!(
201                f,
202                "invalid position '{position}' - use left, right, top, or bottom"
203            ),
204            Self::Unresolved { position } => {
205                write!(f, "could not resolve pane for position '{position}'")
206            }
207        }
208    }
209}
210
211impl std::error::Error for PanePositionError {}
212
213pub fn parse_tmux_pane_geometry(text: &str) -> Vec<TmuxPaneGeometry> {
214    text.lines()
215        .filter_map(|line| {
216            let mut parts = line.split_whitespace();
217            let id = parts.next()?;
218            let left = parts.next()?.parse().unwrap_or(0);
219            let top = parts.next()?.parse().unwrap_or(0);
220            let width = parts.next()?.parse().unwrap_or(0);
221            let height = parts.next()?.parse().unwrap_or(0);
222            Some(TmuxPaneGeometry {
223                id: id.to_string(),
224                left,
225                top,
226                width,
227                height,
228            })
229        })
230        .collect()
231}
232
233pub fn select_pane_by_position(
234    text: &str,
235    position: &str,
236    scope: &str,
237) -> Result<String, PanePositionError> {
238    let panes = parse_tmux_pane_geometry(text);
239    if panes.is_empty() {
240        return Err(PanePositionError::NoPanes {
241            scope: scope.to_string(),
242        });
243    }
244    if panes.len() == 1 {
245        return Ok(panes[0].id.clone());
246    }
247
248    let position = PanePosition::parse(position)?;
249    let selected = match position {
250        PanePosition::Left => panes.iter().min_by_key(|pane| pane.left),
251        PanePosition::Right => panes.iter().max_by_key(|pane| pane.right_edge()),
252        PanePosition::Top => panes.iter().min_by_key(|pane| pane.top),
253        PanePosition::Bottom => panes.iter().max_by_key(|pane| pane.bottom_edge()),
254    };
255
256    selected
257        .map(|pane| pane.id.clone())
258        .ok_or_else(|| PanePositionError::Unresolved {
259            position: position.as_str().to_string(),
260        })
261}
262
263pub fn parse_session_window_line(line: &str) -> Option<(String, String, String)> {
264    let mut parts = line.splitn(3, ' ');
265    let index = parts.next()?.to_string();
266    let id = parts.next()?.to_string();
267    let name = parts.next()?.to_string();
268    Some((index, id, name))
269}
270
271pub fn parse_session_windows(text: &str) -> Vec<(String, String, String)> {
272    text.lines().filter_map(parse_session_window_line).collect()
273}
274
275/// Foreground program names tmux reports via `#{pane_current_command}` when a
276/// pane has fallen back to a bare interactive shell. Login shells can show a
277/// leading `-`, for example `-zsh`.
278pub fn pane_current_command_is_bare_shell(cmd: &str) -> bool {
279    let name = cmd.trim().trim_start_matches('-');
280    matches!(
281        name,
282        "zsh" | "bash" | "sh" | "fish" | "dash" | "ksh" | "tcsh" | "csh"
283    )
284}
285
286#[derive(Debug, Clone, PartialEq, Eq)]
287pub enum TmuxPaneProcessKind {
288    Agent(String),
289    IdleShell(String),
290    Foreign(String),
291    UnknownTransient,
292}
293
294pub fn pane_current_command_is_agent_process(cmd: &str) -> bool {
295    matches!(cmd, "agent-doc" | "claude" | "codex" | "node")
296}
297
298pub fn pane_process_kind_from_current_command(cmd: &str) -> TmuxPaneProcessKind {
299    if pane_current_command_is_agent_process(cmd) {
300        TmuxPaneProcessKind::Agent(cmd.to_string())
301    } else if pane_current_command_is_bare_shell(cmd) {
302        TmuxPaneProcessKind::IdleShell(cmd.to_string())
303    } else if cmd.is_empty() {
304        TmuxPaneProcessKind::UnknownTransient
305    } else {
306        TmuxPaneProcessKind::Foreign(cmd.to_string())
307    }
308}
309
310pub fn pane_process_kind_from_current_command_samples<'a>(
311    samples: impl IntoIterator<Item = Option<&'a str>>,
312) -> TmuxPaneProcessKind {
313    let mut first_foreign: Option<String> = None;
314    let mut foreign_stable = true;
315
316    for sample in samples {
317        let Some(cmd) = sample else {
318            foreign_stable = false;
319            continue;
320        };
321        match pane_process_kind_from_current_command(cmd) {
322            TmuxPaneProcessKind::Agent(cmd) => return TmuxPaneProcessKind::Agent(cmd),
323            TmuxPaneProcessKind::IdleShell(cmd) => return TmuxPaneProcessKind::IdleShell(cmd),
324            TmuxPaneProcessKind::Foreign(cmd) => match &first_foreign {
325                Some(prev) if prev != &cmd => foreign_stable = false,
326                None => first_foreign = Some(cmd),
327                _ => {}
328            },
329            TmuxPaneProcessKind::UnknownTransient => foreign_stable = false,
330        }
331    }
332
333    match (first_foreign, foreign_stable) {
334        (Some(cmd), true) => TmuxPaneProcessKind::Foreign(cmd),
335        _ => TmuxPaneProcessKind::UnknownTransient,
336    }
337}
338
339#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
340pub enum AssociatedPaneSource {
341    Registered,
342    SessionLog,
343    RegistryRebind,
344    ProcessTree,
345    SupervisorPid,
346}
347
348impl AssociatedPaneSource {
349    fn as_str(&self) -> &'static str {
350        match self {
351            Self::Registered => "registered",
352            Self::SessionLog => "session-log",
353            Self::RegistryRebind => "registry-rebind",
354            Self::ProcessTree => "process-tree",
355            Self::SupervisorPid => "supervisor-pid",
356        }
357    }
358}
359
360#[derive(Debug, Clone, PartialEq, Eq)]
361pub struct AssociatedPaneCandidate {
362    pub pane_id: String,
363    pub pane_pid: String,
364    pub session_name: String,
365    pub window_id: String,
366    pub window_name: String,
367    pub current_command: String,
368    pub sources: BTreeSet<AssociatedPaneSource>,
369}
370
371impl AssociatedPaneCandidate {
372    pub fn is_stash(&self) -> bool {
373        self.window_name == "stash" || self.window_name.starts_with("stash-")
374    }
375
376    pub fn source_summary(&self) -> String {
377        self.sources
378            .iter()
379            .map(AssociatedPaneSource::as_str)
380            .collect::<Vec<_>>()
381            .join(",")
382    }
383}
384
385pub fn associated_pane_candidates_detail<'a>(
386    candidates: impl IntoIterator<Item = &'a AssociatedPaneCandidate>,
387) -> String {
388    candidates
389        .into_iter()
390        .map(|candidate| {
391            format!(
392                "{}:{}:{}:{}",
393                candidate.pane_id,
394                candidate.window_name,
395                candidate.window_id,
396                candidate.source_summary()
397            )
398        })
399        .collect::<Vec<_>>()
400        .join(", ")
401}
402
403fn missing_pane_manual_repair_detail(phase: &str) -> &'static str {
404    match phase {
405        "preflight_started" => "stale preflight state is still open",
406        "response_captured" => "a captured response still needs explicit closeout recovery",
407        "write_applied" => "the write reached disk but the commit boundary is still open",
408        _ => "manual repair is still required",
409    }
410}
411
412pub fn format_missing_pane_manual_repair_reason(
413    file_display: impl fmt::Display,
414    phase: &str,
415) -> String {
416    let file_display = file_display.to_string();
417    let detail = missing_pane_manual_repair_detail(phase);
418    format!(
419        "normal sync will not auto-repair {phase} for {file_display} ({detail}). Run `agent-doc repair {file_display}` or `agent-doc session doctor {file_display} --repair` before syncing again"
420    )
421}
422
423pub fn format_missing_pane_closeout_block_reason(
424    file_display: impl fmt::Display,
425    phase: &str,
426    error_detail: Option<&str>,
427) -> String {
428    let file_display = file_display.to_string();
429    let detail = error_detail.unwrap_or("unknown");
430    format!(
431        "closeout recovery for {phase} failed and needs manual repair ({detail}). Re-run `agent-doc repair {file_display}` before syncing again"
432    )
433}
434
435pub fn format_associated_pane_resolution_error(
436    file_display: impl fmt::Display,
437    candidates: &[AssociatedPaneCandidate],
438    preferred_window: Option<&str>,
439) -> String {
440    let mut lines = vec![format!(
441        "multiple tmux panes are associated with {}; route cannot safely auto-pick one.",
442        file_display
443    )];
444    if let Some(window_id) = preferred_window {
445        lines.push(format!(
446            "Preferred active window: {}. Resolve by inspecting one pane, claiming it explicitly, then killing the redundant panes.",
447            window_id
448        ));
449    } else {
450        lines.push(
451            "Resolve by inspecting one pane, claiming it explicitly, then killing the redundant panes."
452                .to_string(),
453        );
454    }
455    for candidate in candidates {
456        lines.push(format!(
457            "  - {} session={} window={} ({}) cmd={} sources={}",
458            candidate.pane_id,
459            candidate.session_name,
460            candidate.window_id,
461            candidate.window_name,
462            candidate.current_command,
463            candidate.source_summary()
464        ));
465        lines.push(format!(
466            "    view: tmux capture-pane -pt {} | tail -n 80",
467            candidate.pane_id
468        ));
469        lines.push(format!(
470            "    assign: agent-doc claim {} --pane {} --force",
471            file_display, candidate.pane_id
472        ));
473        lines.push(format!("    kill: tmux kill-pane -t {}", candidate.pane_id));
474    }
475    lines.join("\n")
476}
477
478pub fn format_associated_pane_selected_error(
479    file_display: impl fmt::Display,
480    winner: &AssociatedPaneCandidate,
481    redundant: &[AssociatedPaneCandidate],
482) -> String {
483    let mut lines = vec![format!(
484        "route found legacy pane-association evidence for {}, but the normal path will not re-elect ownership from {}.",
485        file_display, winner.pane_id
486    )];
487    lines.push(
488        "Inspect the candidate, claim it explicitly if it is authoritative, or kill it before rerouting."
489            .to_string(),
490    );
491    lines.push(format!(
492        "  - {} session={} window={} ({}) cmd={} sources={}",
493        winner.pane_id,
494        winner.session_name,
495        winner.window_id,
496        winner.window_name,
497        winner.current_command,
498        winner.source_summary()
499    ));
500    lines.push(format!(
501        "    view: tmux capture-pane -pt {} | tail -n 80",
502        winner.pane_id
503    ));
504    lines.push(format!(
505        "    assign: agent-doc claim {} --pane {} --force",
506        file_display, winner.pane_id
507    ));
508    lines.push(format!("    kill: tmux kill-pane -t {}", winner.pane_id));
509    for candidate in redundant {
510        lines.push(format!(
511            "  - redundant {} session={} window={} ({}) cmd={} sources={}",
512            candidate.pane_id,
513            candidate.session_name,
514            candidate.window_id,
515            candidate.window_name,
516            candidate.current_command,
517            candidate.source_summary()
518        ));
519    }
520    lines.join("\n")
521}
522
523pub fn format_associated_pane_fix_error(
524    file_display: impl fmt::Display,
525    candidates: &[AssociatedPaneCandidate],
526    preferred_window: Option<&str>,
527) -> String {
528    let mut lines = vec![format!(
529        "multiple tmux panes are associated with {}; fix will not auto-pick one.",
530        file_display
531    )];
532    if let Some(window_id) = preferred_window {
533        lines.push(format!(
534            "Preferred active window: {}. Inspect one pane, claim it explicitly, then kill the redundant panes.",
535            window_id
536        ));
537    } else {
538        lines.push(
539            "Inspect one pane, claim it explicitly, then kill the redundant panes.".to_string(),
540        );
541    }
542    for candidate in candidates {
543        lines.push(format!(
544            "  - {} session={} window={} ({}) cmd={} sources={}",
545            candidate.pane_id,
546            candidate.session_name,
547            candidate.window_id,
548            candidate.window_name,
549            candidate.current_command,
550            candidate.source_summary()
551        ));
552        lines.push(format!(
553            "    view: tmux capture-pane -pt {} | tail -n 80",
554            candidate.pane_id
555        ));
556        lines.push(format!(
557            "    assign: agent-doc claim {} --pane {} --force",
558            file_display, candidate.pane_id
559        ));
560        lines.push(format!("    kill: tmux kill-pane -t {}", candidate.pane_id));
561    }
562    lines.join("\n")
563}
564
565#[derive(Debug, Clone, PartialEq, Eq)]
566pub enum AssociatedPaneResolution {
567    None,
568    Selected {
569        winner: AssociatedPaneCandidate,
570        redundant: Vec<AssociatedPaneCandidate>,
571    },
572    Ambiguous(Vec<AssociatedPaneCandidate>),
573}
574
575pub fn parse_pane_inventory_line(line: &str) -> Option<AssociatedPaneCandidate> {
576    let mut parts = line.splitn(6, '\t');
577    let pane_id = parts.next()?.trim();
578    let pane_pid = parts.next()?.trim();
579    let window_id = parts.next()?.trim();
580    let window_name = parts.next()?.trim();
581    let session_name = parts.next()?.trim();
582    let current_command = parts.next()?.trim();
583    if pane_id.is_empty() {
584        return None;
585    }
586    Some(AssociatedPaneCandidate {
587        pane_id: pane_id.to_string(),
588        pane_pid: pane_pid.to_string(),
589        session_name: session_name.to_string(),
590        window_id: window_id.to_string(),
591        window_name: window_name.to_string(),
592        current_command: current_command.to_string(),
593        sources: BTreeSet::new(),
594    })
595}
596
597pub fn resolve_associated_panes(
598    mut candidates: Vec<AssociatedPaneCandidate>,
599    preferred_window: Option<&str>,
600) -> AssociatedPaneResolution {
601    if candidates.is_empty() {
602        return AssociatedPaneResolution::None;
603    }
604    candidates.sort_by(|left, right| left.pane_id.cmp(&right.pane_id));
605    if candidates.len() == 1 {
606        return AssociatedPaneResolution::Selected {
607            winner: candidates.remove(0),
608            redundant: Vec::new(),
609        };
610    }
611
612    if let Some(window_id) = preferred_window {
613        let mut preferred_matches = candidates
614            .iter()
615            .filter(|candidate| candidate.window_id == window_id)
616            .cloned()
617            .collect::<Vec<_>>();
618        let non_preferred = candidates
619            .iter()
620            .filter(|candidate| candidate.window_id != window_id)
621            .cloned()
622            .collect::<Vec<_>>();
623        if preferred_matches.len() == 1
624            && non_preferred.iter().all(AssociatedPaneCandidate::is_stash)
625        {
626            let winner = preferred_matches.remove(0);
627            let redundant = candidates
628                .into_iter()
629                .filter(|candidate| candidate.pane_id != winner.pane_id)
630                .collect();
631            return AssociatedPaneResolution::Selected { winner, redundant };
632        }
633    }
634
635    let mut stash_matches = candidates
636        .iter()
637        .filter(|candidate| candidate.is_stash())
638        .cloned()
639        .collect::<Vec<_>>();
640    if stash_matches.len() == 1 && stash_matches.len() == candidates.len() {
641        let winner = stash_matches.remove(0);
642        let redundant = candidates
643            .into_iter()
644            .filter(|candidate| candidate.pane_id != winner.pane_id)
645            .collect();
646        return AssociatedPaneResolution::Selected { winner, redundant };
647    }
648
649    AssociatedPaneResolution::Ambiguous(candidates)
650}
651
652#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
653pub struct TmuxLayoutColumn {
654    pub raw: String,
655    pub agent_doc: Option<String>,
656}
657
658impl TmuxLayoutColumn {
659    pub fn new(raw: impl Into<String>, agent_doc: Option<String>) -> Self {
660        Self {
661            raw: raw.into(),
662            agent_doc,
663        }
664    }
665
666    fn trimmed_raw(&self) -> String {
667        self.raw.trim().to_string()
668    }
669}
670
671pub fn classify_sync_layout_columns<F>(
672    col_args: &[String],
673    mut first_agent_doc_in_col: F,
674) -> Vec<TmuxLayoutColumn>
675where
676    F: FnMut(&str) -> Option<String>,
677{
678    col_args
679        .iter()
680        .map(|col| TmuxLayoutColumn::new(col.clone(), first_agent_doc_in_col(col)))
681        .collect()
682}
683
684fn canonicalize_sync_file(file: &Path) -> Option<PathBuf> {
685    let candidate = if file.is_absolute() {
686        file.to_path_buf()
687    } else {
688        std::env::current_dir().ok()?.join(file)
689    };
690    Some(candidate.canonicalize().unwrap_or(candidate))
691}
692
693pub fn same_sync_file(lhs: &str, rhs: &str) -> bool {
694    let lhs = lhs.trim();
695    let rhs = rhs.trim();
696    if lhs.is_empty() || rhs.is_empty() {
697        return false;
698    }
699    if lhs == rhs {
700        return true;
701    }
702    match (
703        canonicalize_sync_file(Path::new(lhs)),
704        canonicalize_sync_file(Path::new(rhs)),
705    ) {
706        (Some(lhs), Some(rhs)) => lhs == rhs,
707        _ => false,
708    }
709}
710
711pub fn focused_column_index(remembered_layout: &[String], focus: Option<&str>) -> Option<usize> {
712    let focus = focus?.trim();
713    if focus.is_empty() {
714        return None;
715    }
716    remembered_layout.iter().position(|col| {
717        col.split(',')
718            .map(str::trim)
719            .any(|candidate| same_sync_file(candidate, focus))
720    })
721}
722
723#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
724pub struct ColumnMemoryRestoration {
725    pub column_index: usize,
726    pub remembered: String,
727}
728
729#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
730pub struct ColumnMemoryApplication {
731    pub columns: Vec<String>,
732    pub restorations: Vec<ColumnMemoryRestoration>,
733}
734
735pub fn apply_column_memory(
736    columns: &[TmuxLayoutColumn],
737    saved_layout: &[String],
738) -> ColumnMemoryApplication {
739    let visible_docs: HashSet<String> = columns
740        .iter()
741        .filter_map(|col| col.agent_doc.clone())
742        .collect();
743    let mut reserved_docs = visible_docs;
744    let mut restorations = Vec::new();
745    let columns = columns
746        .iter()
747        .enumerate()
748        .map(|(i, col)| {
749            if col.agent_doc.is_some() {
750                col.trimmed_raw()
751            } else if let Some(remembered) = saved_layout.get(i) {
752                let remembered = remembered.trim();
753                if !remembered.is_empty() && !reserved_docs.contains(remembered) {
754                    let remembered = remembered.to_string();
755                    reserved_docs.insert(remembered.clone());
756                    restorations.push(ColumnMemoryRestoration {
757                        column_index: i,
758                        remembered: remembered.clone(),
759                    });
760                    remembered
761                } else {
762                    col.trimmed_raw()
763                }
764            } else {
765                col.trimmed_raw()
766            }
767        })
768        .collect();
769    ColumnMemoryApplication {
770        columns,
771        restorations,
772    }
773}
774
775pub fn build_layout_state(
776    columns: &[TmuxLayoutColumn],
777    saved_layout: &[TmuxLayoutColumn],
778) -> Vec<String> {
779    let current_docs: Vec<Option<String>> =
780        columns.iter().map(|col| col.agent_doc.clone()).collect();
781    let mut current_counts = HashMap::new();
782    for doc in current_docs.iter().flatten() {
783        *current_counts.entry(doc.clone()).or_insert(0usize) += 1;
784    }
785    let mut duplicate_keepers = HashMap::new();
786    for (i, current_doc) in current_docs.iter().enumerate() {
787        let Some(current_doc) = current_doc else {
788            continue;
789        };
790        if current_counts.get(current_doc).copied().unwrap_or_default() <= 1 {
791            duplicate_keepers.entry(current_doc.clone()).or_insert(i);
792            continue;
793        }
794        if saved_layout
795            .get(i)
796            .map(|saved| saved.raw.trim() == current_doc)
797            .unwrap_or(false)
798        {
799            duplicate_keepers.entry(current_doc.clone()).or_insert(i);
800        }
801    }
802    for (i, current_doc) in current_docs.iter().enumerate() {
803        if let Some(current_doc) = current_doc {
804            duplicate_keepers.entry(current_doc.clone()).or_insert(i);
805        }
806    }
807    let mut reserved_docs = HashSet::new();
808    current_docs
809        .iter()
810        .enumerate()
811        .map(|(i, current_doc)| {
812            if let Some(current_doc) = current_doc {
813                let keep_current = duplicate_keepers
814                    .get(current_doc)
815                    .copied()
816                    .is_some_and(|keeper| keeper == i);
817                if keep_current && reserved_docs.insert(current_doc.clone()) {
818                    return current_doc.clone();
819                }
820            }
821            if let Some(remembered) = saved_layout.get(i) {
822                let remembered_raw = remembered.raw.trim();
823                if !remembered_raw.is_empty()
824                    && remembered.agent_doc.is_some()
825                    && reserved_docs.insert(remembered_raw.to_string())
826                {
827                    return remembered_raw.to_string();
828                }
829            }
830            if let Some(current_doc) = current_doc
831                && reserved_docs.insert(current_doc.clone())
832            {
833                return current_doc.clone();
834            }
835            String::new()
836        })
837        .collect()
838}
839
840#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
841#[serde(rename_all = "snake_case")]
842pub enum TmuxFocusOnlyExpansionMode {
843    SafePassive,
844    LiteralProjection,
845}
846
847#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
848#[serde(rename_all = "snake_case", tag = "kind")]
849pub enum TmuxFocusOnlyExpansionEvent {
850    ExactVisibleProjection,
851    Expanded { active_column_index: usize },
852}
853
854#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
855pub struct TmuxFocusOnlyExpansion {
856    pub columns: Vec<String>,
857    pub event: Option<TmuxFocusOnlyExpansionEvent>,
858}
859
860pub fn expand_focus_only_columns_for_editor_switch(
861    columns: &[String],
862    remembered_layout: &[String],
863    active_column_index: Option<usize>,
864    mode: TmuxFocusOnlyExpansionMode,
865) -> TmuxFocusOnlyExpansion {
866    if !matches!(mode, TmuxFocusOnlyExpansionMode::SafePassive)
867        || columns.len() != 1
868        || remembered_layout.len() < 2
869    {
870        return TmuxFocusOnlyExpansion {
871            columns: columns.to_vec(),
872            event: None,
873        };
874    }
875    let Some(active_column_index) =
876        active_column_index.filter(|index| *index < remembered_layout.len())
877    else {
878        return TmuxFocusOnlyExpansion {
879            columns: columns.to_vec(),
880            event: None,
881        };
882    };
883    let focused_column = columns[0].trim();
884    if focused_column.is_empty() {
885        return TmuxFocusOnlyExpansion {
886            columns: columns.to_vec(),
887            event: None,
888        };
889    }
890
891    let mut expanded: Vec<String> = remembered_layout
892        .iter()
893        .map(|col| col.trim().to_string())
894        .collect();
895    expanded[active_column_index] = focused_column.to_string();
896    for (index, col) in expanded.iter_mut().enumerate() {
897        if index != active_column_index && col == focused_column {
898            col.clear();
899        }
900    }
901    TmuxFocusOnlyExpansion {
902        columns: expanded,
903        event: Some(TmuxFocusOnlyExpansionEvent::Expanded {
904            active_column_index,
905        }),
906    }
907}
908
909pub fn apply_focus_only_expansion_policy(
910    columns: &[String],
911    remembered_layout: &[String],
912    active_column_index: Option<usize>,
913    mode: TmuxFocusOnlyExpansionMode,
914    exact_visible_projection: bool,
915) -> TmuxFocusOnlyExpansion {
916    if exact_visible_projection {
917        TmuxFocusOnlyExpansion {
918            columns: columns.to_vec(),
919            event: Some(TmuxFocusOnlyExpansionEvent::ExactVisibleProjection),
920        }
921    } else {
922        expand_focus_only_columns_for_editor_switch(
923            columns,
924            remembered_layout,
925            active_column_index,
926            mode,
927        )
928    }
929}
930
931pub fn repair_layout_skips_rescue_phase(
932    has_target: bool,
933    stash_count: usize,
934    has_exact_stash: bool,
935) -> bool {
936    has_target && (stash_count == 0 || (stash_count == 1 && has_exact_stash))
937}
938
939/// Minimum interval between destructive doctor-repair passes for one tmux
940/// session. Rapid `agent-doc sync` invocations within this window skip the
941/// destructive `repair_layout` window-op sequence while the non-destructive
942/// reconciler still runs.
943pub const DESTRUCTIVE_REPAIR_MIN_INTERVAL_MS: u64 = 1500;
944
945/// Pure throttle decision: `true` means skip the destructive repair this pass.
946///
947/// `last_ms` is the timestamp of the previous destructive repair for this
948/// session, if any. Throttle only when the previous repair is in the past and
949/// strictly within `min_interval_ms` of `now_ms`; a missing or future stamp runs
950/// the repair.
951pub fn destructive_repair_throttled(
952    last_ms: Option<u64>,
953    now_ms: u64,
954    min_interval_ms: u64,
955) -> bool {
956    match last_ms {
957        Some(last) if now_ms >= last => now_ms - last < min_interval_ms,
958        _ => false,
959    }
960}
961
962#[derive(Debug, Clone, Copy, PartialEq, Eq)]
963pub enum PruneCleanupMode {
964    Full,
965    PreserveLiveAgentStashPanes,
966    SkipExpensiveStashCleanup,
967}
968
969/// `#stash-session-ttl-prune`: one stash pane's candidacy for opt-in TTL reaping.
970#[derive(Debug, Clone, PartialEq, Eq)]
971pub struct StashTtlCandidate {
972    pub pane_id: String,
973    /// Seconds since the pane's window last saw activity (`#{window_activity}`).
974    pub idle_secs: u64,
975    /// The currently active/visible pane is never reaped, regardless of idle time.
976    pub is_active_pane: bool,
977    /// Only an agent-doc pane parked in the `stash` window is eligible.
978    pub is_agent_doc_stash_pane: bool,
979}
980
981/// `#stash-session-ttl-prune`: pure, **non-destructive** decision for whether a
982/// stash-parked agent-doc pane is eligible for opt-in TTL reaping. Conservative
983/// by construction (see `tasks/agent-doc/plan-stash-session-ttl-prune.md`): the
984/// actual `kill-pane` wiring, the idle-signal query, the config knob, and live
985/// verification are all gated — this is only the reusable decision core.
986///
987/// Returns true only when ALL hold: TTL is enabled (`ttl_secs > 0`; `0`/unset
988/// disables), the pane is an agent-doc pane parked in the stash window, it is not
989/// the active/visible pane, and it has been idle strictly longer than the TTL.
990pub fn stash_ttl_prune_candidate(
991    idle_secs: u64,
992    ttl_secs: u64,
993    is_active_pane: bool,
994    is_agent_doc_stash_pane: bool,
995) -> bool {
996    ttl_secs > 0 && is_agent_doc_stash_pane && !is_active_pane && idle_secs > ttl_secs
997}
998
999/// Filter a candidate list to the pane ids eligible for TTL reaping. With
1000/// `ttl_secs == 0` (disabled / unset) this always returns empty, so the feature
1001/// is inert until explicitly configured.
1002pub fn stash_ttl_prune_targets(candidates: &[StashTtlCandidate], ttl_secs: u64) -> Vec<String> {
1003    candidates
1004        .iter()
1005        .filter(|c| {
1006            stash_ttl_prune_candidate(
1007                c.idle_secs,
1008                ttl_secs,
1009                c.is_active_pane,
1010                c.is_agent_doc_stash_pane,
1011            )
1012        })
1013        .map(|c| c.pane_id.clone())
1014        .collect()
1015}
1016
1017pub fn transition_tmux(
1018    current: &TmuxRealtimeState,
1019    event: &TmuxObservation,
1020) -> Option<TmuxRealtimeState> {
1021    let mut next = current.clone();
1022    match event {
1023        TmuxObservation::PaneMissing => next.pane = TmuxPaneActivity::Missing,
1024        TmuxObservation::PaneExited => next.pane = TmuxPaneActivity::Exited,
1025        TmuxObservation::PromptReady => next.pane = TmuxPaneActivity::PromptReady,
1026        TmuxObservation::Busy => next.pane = TmuxPaneActivity::Busy,
1027        TmuxObservation::OutputAdvanced { watermark } => {
1028            next.pane = TmuxPaneActivity::OutputActive;
1029            next.last_output_watermark = Some(watermark.clone());
1030        }
1031        TmuxObservation::SupervisorHeartbeat => next.supervisor = TmuxSupervisorHealth::Healthy,
1032        TmuxObservation::SupervisorStale => next.supervisor = TmuxSupervisorHealth::Stale,
1033        TmuxObservation::SupervisorCrashed => next.supervisor = TmuxSupervisorHealth::Crashed,
1034    }
1035    Some(next)
1036}
1037
1038pub struct TmuxModelMachine {
1039    ctx: ThreadSafeContext,
1040    machine: ThreadSafeStateMachine<TmuxRealtimeState, TmuxObservation>,
1041}
1042
1043impl TmuxModelMachine {
1044    pub fn new(initial: TmuxRealtimeState) -> Self {
1045        let ctx = ThreadSafeContext::new();
1046        let machine = ThreadSafeStateMachine::new(&ctx, initial, transition_tmux);
1047        Self { ctx, machine }
1048    }
1049
1050    pub fn default_tmux() -> Self {
1051        Self::new(TmuxRealtimeState::default())
1052    }
1053
1054    pub fn send(&self, event: TmuxObservation) -> bool {
1055        self.machine.send(&self.ctx, event)
1056    }
1057
1058    pub fn state(&self) -> TmuxRealtimeState {
1059        self.machine.state(&self.ctx)
1060    }
1061}
1062
1063#[cfg(test)]
1064mod tests {
1065    use super::*;
1066
1067    fn layout_col(raw: &str, agent_doc: Option<&str>) -> TmuxLayoutColumn {
1068        TmuxLayoutColumn::new(raw, agent_doc.map(str::to_string))
1069    }
1070
1071    #[test]
1072    fn classify_sync_layout_columns_marks_agent_doc_from_callback() {
1073        let columns = classify_sync_layout_columns(
1074            &["plain.md".to_string(), "left.md,right.md".to_string()],
1075            |col| {
1076                col.split(',')
1077                    .find(|item| item.trim() == "right.md")
1078                    .map(str::to_string)
1079            },
1080        );
1081
1082        assert_eq!(columns[0], layout_col("plain.md", None));
1083        assert_eq!(columns[1], layout_col("left.md,right.md", Some("right.md")));
1084    }
1085
1086    #[test]
1087    fn auto_start_candidate_files_dedupes_repeated_documents_preserving_order() {
1088        let col_args = vec![
1089            "editor.md,notes.md".to_string(),
1090            "editor.md".to_string(),
1091            "other.md, notes.md".to_string(),
1092        ];
1093        let files = auto_start_candidate_files(&col_args);
1094        assert_eq!(
1095            files,
1096            vec![
1097                PathBuf::from("editor.md"),
1098                PathBuf::from("notes.md"),
1099                PathBuf::from("other.md"),
1100            ],
1101            "duplicate document requests must collapse to one first-seen auto-start candidate"
1102        );
1103    }
1104
1105    #[test]
1106    fn auto_start_candidate_files_keeps_distinct_documents() {
1107        let col_args = vec!["a.md".to_string(), "b.md".to_string(), "c.md".to_string()];
1108        let files = auto_start_candidate_files(&col_args);
1109        assert_eq!(
1110            files,
1111            vec![
1112                PathBuf::from("a.md"),
1113                PathBuf::from("b.md"),
1114                PathBuf::from("c.md"),
1115            ],
1116            "distinct documents must each remain an auto-start candidate"
1117        );
1118    }
1119
1120    #[test]
1121    fn projected_sync_pane_count_dedupes_canonical_files_and_ignores_empty_entries() {
1122        let tmp = tempfile::TempDir::new().unwrap();
1123        let file = tmp.path().join("doc.md");
1124        std::fs::write(&file, "# doc\n").unwrap();
1125        let col_args = vec![
1126            format!("{}, ,missing.md", file.display()),
1127            file.display().to_string(),
1128        ];
1129
1130        assert_eq!(
1131            projected_sync_pane_count(&col_args),
1132            2,
1133            "existing paths should canonicalize for dedupe while missing paths fall back to the original path"
1134        );
1135    }
1136
1137    #[test]
1138    fn focused_column_index_matches_exact_and_canonical_paths() {
1139        let tmp = tempfile::TempDir::new().unwrap();
1140        let root = tmp.path();
1141        let left = root.join("tasks/left.md");
1142        let right = root.join("tasks/right.md");
1143        std::fs::create_dir_all(left.parent().unwrap()).unwrap();
1144        std::fs::write(&left, "").unwrap();
1145        std::fs::write(&right, "").unwrap();
1146        let saved_layout = vec![
1147            left.to_string_lossy().to_string(),
1148            format!("notes.md,{}", right.to_string_lossy()),
1149        ];
1150
1151        assert_eq!(
1152            focused_column_index(&saved_layout, Some(&right.to_string_lossy())),
1153            Some(1)
1154        );
1155        assert_eq!(
1156            focused_column_index(&saved_layout, Some(&left.to_string_lossy())),
1157            Some(0)
1158        );
1159        assert_eq!(focused_column_index(&saved_layout, Some("   ")), None);
1160    }
1161
1162    #[test]
1163    fn same_sync_file_rejects_empty_paths() {
1164        assert!(!same_sync_file("", ""));
1165        assert!(!same_sync_file("left.md", ""));
1166        assert!(same_sync_file("left.md", "left.md"));
1167    }
1168
1169    fn associated_candidate(
1170        pane_id: &str,
1171        window_id: &str,
1172        window_name: &str,
1173        sources: &[AssociatedPaneSource],
1174    ) -> AssociatedPaneCandidate {
1175        AssociatedPaneCandidate {
1176            pane_id: pane_id.to_string(),
1177            pane_pid: "100".to_string(),
1178            session_name: "14".to_string(),
1179            window_id: window_id.to_string(),
1180            window_name: window_name.to_string(),
1181            current_command: "agent-doc".to_string(),
1182            sources: sources.iter().cloned().collect(),
1183        }
1184    }
1185
1186    fn stash_ttl_candidate(
1187        pane: &str,
1188        idle: u64,
1189        active: bool,
1190        agentdoc_stash: bool,
1191    ) -> StashTtlCandidate {
1192        StashTtlCandidate {
1193            pane_id: pane.to_string(),
1194            idle_secs: idle,
1195            is_active_pane: active,
1196            is_agent_doc_stash_pane: agentdoc_stash,
1197        }
1198    }
1199
1200    #[test]
1201    fn prompt_ready_updates_pane_activity() {
1202        let machine = TmuxModelMachine::default_tmux();
1203
1204        assert!(machine.send(TmuxObservation::PromptReady));
1205
1206        assert_eq!(machine.state().pane, TmuxPaneActivity::PromptReady);
1207    }
1208
1209    #[test]
1210    fn output_advanced_records_watermark() {
1211        let machine = TmuxModelMachine::default_tmux();
1212
1213        assert!(machine.send(TmuxObservation::OutputAdvanced {
1214            watermark: "42".to_string()
1215        }));
1216
1217        let state = machine.state();
1218        assert_eq!(state.pane, TmuxPaneActivity::OutputActive);
1219        assert_eq!(state.last_output_watermark.as_deref(), Some("42"));
1220    }
1221
1222    #[test]
1223    fn focus_decision_keeps_candidate_when_no_live_owner() {
1224        assert_eq!(
1225            decide_focus_pane("%36", None),
1226            FocusPaneDecision::UseCandidate
1227        );
1228    }
1229
1230    #[test]
1231    fn focus_decision_keeps_candidate_when_owner_matches() {
1232        assert_eq!(
1233            decide_focus_pane("%8", Some("%8")),
1234            FocusPaneDecision::UseCandidate
1235        );
1236    }
1237
1238    #[test]
1239    fn focus_decision_repairs_to_live_owner_when_candidate_is_stale() {
1240        assert_eq!(
1241            decide_focus_pane("%36", Some("%8")),
1242            FocusPaneDecision::RepairToLiveOwner("%8".to_string())
1243        );
1244    }
1245
1246    #[test]
1247    fn focus_decision_ignores_empty_live_owner() {
1248        assert_eq!(
1249            decide_focus_pane("%36", Some("")),
1250            FocusPaneDecision::UseCandidate
1251        );
1252    }
1253
1254    #[test]
1255    fn first_column_requires_layout_context() {
1256        let file = Path::new("tasks/agent-doc.md");
1257        assert!(!is_first_column(file, &[]));
1258        assert!(!is_first_column(file, &["tasks/agent-doc.md".to_string()]));
1259    }
1260
1261    #[test]
1262    fn first_column_detects_first_and_second_columns() {
1263        let cols = vec![
1264            "tasks/agent-doc.md".to_string(),
1265            "tasks/email.md".to_string(),
1266        ];
1267        assert!(is_first_column(Path::new("tasks/agent-doc.md"), &cols));
1268        assert!(!is_first_column(Path::new("tasks/email.md"), &cols));
1269    }
1270
1271    #[test]
1272    fn first_column_accepts_comma_separated_entries() {
1273        let cols = vec![
1274            "tasks/agent-doc.md,tasks/corky.md".to_string(),
1275            "tasks/email.md".to_string(),
1276        ];
1277        assert!(is_first_column(Path::new("tasks/agent-doc.md"), &cols));
1278        assert!(is_first_column(Path::new("tasks/corky.md"), &cols));
1279    }
1280
1281    #[test]
1282    fn pane_position_selection_uses_tmux_geometry() {
1283        let panes = "%left 0 0 80 24\n%right 120 0 80 24\n%bottom 0 24 160 24\n";
1284
1285        assert_eq!(
1286            select_pane_by_position(panes, "left", "test").unwrap(),
1287            "%left"
1288        );
1289        assert_eq!(
1290            select_pane_by_position(panes, "right", "test").unwrap(),
1291            "%right"
1292        );
1293        assert_eq!(
1294            select_pane_by_position(panes, "bottom", "test").unwrap(),
1295            "%bottom"
1296        );
1297    }
1298
1299    #[test]
1300    fn pane_position_selection_rejects_unknown_direction() {
1301        let err = select_pane_by_position("%0 0 0 80 24\n%1 80 0 80 24\n", "middle", "test")
1302            .unwrap_err()
1303            .to_string();
1304
1305        assert!(err.contains("invalid position 'middle'"));
1306    }
1307
1308    #[test]
1309    fn pane_geometry_parser_treats_bad_numbers_as_zero() {
1310        assert_eq!(
1311            parse_tmux_pane_geometry("%0 bad 3 80 nope\n"),
1312            vec![TmuxPaneGeometry {
1313                id: "%0".to_string(),
1314                left: 0,
1315                top: 3,
1316                width: 80,
1317                height: 0,
1318            }]
1319        );
1320    }
1321
1322    #[test]
1323    fn session_window_parser_reads_tmux_list_windows_output() {
1324        assert_eq!(
1325            parse_session_windows("0 @1 agent-doc\n1 @2 stash\n2 @3 notes window\nbad\n"),
1326            vec![
1327                ("0".to_string(), "@1".to_string(), "agent-doc".to_string()),
1328                ("1".to_string(), "@2".to_string(), "stash".to_string()),
1329                (
1330                    "2".to_string(),
1331                    "@3".to_string(),
1332                    "notes window".to_string()
1333                ),
1334            ]
1335        );
1336    }
1337
1338    #[test]
1339    fn pane_current_command_classifies_bare_shells() {
1340        for shell in [
1341            "zsh", "bash", "sh", "fish", "dash", "ksh", "tcsh", "csh", "-zsh", "-bash", " zsh ",
1342        ] {
1343            assert!(
1344                pane_current_command_is_bare_shell(shell),
1345                "{shell:?} should classify as a bare shell"
1346            );
1347        }
1348        for not_shell in [
1349            "claude",
1350            "node",
1351            "codex",
1352            "opencode",
1353            "bun",
1354            "agent-doc",
1355            "sleep",
1356            "cat",
1357            "vim",
1358            "",
1359        ] {
1360            assert!(
1361                !pane_current_command_is_bare_shell(not_shell),
1362                "{not_shell:?} should NOT classify as a bare shell"
1363            );
1364        }
1365    }
1366
1367    #[test]
1368    fn pane_process_kind_classifies_current_command() {
1369        assert!(matches!(
1370            pane_process_kind_from_current_command("zsh"),
1371            TmuxPaneProcessKind::IdleShell(cmd) if cmd == "zsh"
1372        ));
1373        assert!(matches!(
1374            pane_process_kind_from_current_command("agent-doc"),
1375            TmuxPaneProcessKind::Agent(cmd) if cmd == "agent-doc"
1376        ));
1377        assert!(matches!(
1378            pane_process_kind_from_current_command("sleep"),
1379            TmuxPaneProcessKind::Foreign(cmd) if cmd == "sleep"
1380        ));
1381        assert!(matches!(
1382            pane_process_kind_from_current_command(""),
1383            TmuxPaneProcessKind::UnknownTransient
1384        ));
1385    }
1386
1387    #[test]
1388    fn pane_process_kind_samples_require_stable_foreign_command() {
1389        assert!(matches!(
1390            pane_process_kind_from_current_command_samples([Some("vim"), Some("vim"), Some("vim")]),
1391            TmuxPaneProcessKind::Foreign(cmd) if cmd == "vim"
1392        ));
1393    }
1394
1395    #[test]
1396    fn pane_process_kind_samples_return_unknown_for_empty_or_changing_foreign() {
1397        assert!(matches!(
1398            pane_process_kind_from_current_command_samples([Some(""), Some(""), Some("")]),
1399            TmuxPaneProcessKind::UnknownTransient
1400        ));
1401        assert!(matches!(
1402            pane_process_kind_from_current_command_samples([Some("mv"), Some("sed"), Some("sed")]),
1403            TmuxPaneProcessKind::UnknownTransient
1404        ));
1405        assert!(matches!(
1406            pane_process_kind_from_current_command_samples([None, Some("vim"), Some("vim")]),
1407            TmuxPaneProcessKind::UnknownTransient
1408        ));
1409    }
1410
1411    #[test]
1412    fn pane_process_kind_samples_prefer_agent_or_idle_shell_immediately() {
1413        assert!(matches!(
1414            pane_process_kind_from_current_command_samples([Some("mv"), Some("codex")]),
1415            TmuxPaneProcessKind::Agent(cmd) if cmd == "codex"
1416        ));
1417        assert!(matches!(
1418            pane_process_kind_from_current_command_samples([Some("mv"), Some("bash")]),
1419            TmuxPaneProcessKind::IdleShell(cmd) if cmd == "bash"
1420        ));
1421    }
1422
1423    #[test]
1424    fn pane_inventory_parser_reads_tmux_tab_separated_fields() {
1425        let candidate =
1426            parse_pane_inventory_line("%419\t22401\t@3\tagent-doc\tsession-a\tcargo").unwrap();
1427
1428        assert_eq!(candidate.pane_id, "%419");
1429        assert_eq!(candidate.pane_pid, "22401");
1430        assert_eq!(candidate.window_id, "@3");
1431        assert_eq!(candidate.window_name, "agent-doc");
1432        assert_eq!(candidate.session_name, "session-a");
1433        assert_eq!(candidate.current_command, "cargo");
1434        assert!(candidate.sources.is_empty());
1435    }
1436
1437    #[test]
1438    fn pane_inventory_parser_rejects_blank_pane_id() {
1439        assert!(parse_pane_inventory_line("\t22401\t@3\tagent-doc\tsession-a\tcargo").is_none());
1440    }
1441
1442    #[test]
1443    fn associated_pane_source_summary_is_stable() {
1444        let candidate = associated_candidate(
1445            "%419",
1446            "@3",
1447            "agent-doc",
1448            &[
1449                AssociatedPaneSource::SupervisorPid,
1450                AssociatedPaneSource::Registered,
1451                AssociatedPaneSource::ProcessTree,
1452            ],
1453        );
1454
1455        assert_eq!(
1456            candidate.source_summary(),
1457            "registered,process-tree,supervisor-pid"
1458        );
1459    }
1460
1461    #[test]
1462    fn associated_pane_candidates_detail_formats_log_fields() {
1463        let active = associated_candidate(
1464            "%419",
1465            "@3",
1466            "agent-doc",
1467            &[
1468                AssociatedPaneSource::Registered,
1469                AssociatedPaneSource::SupervisorPid,
1470            ],
1471        );
1472        let stashed =
1473            associated_candidate("%417", "@9", "stash", &[AssociatedPaneSource::ProcessTree]);
1474
1475        assert_eq!(
1476            associated_pane_candidates_detail([&active, &stashed]),
1477            "%419:agent-doc:@3:registered,supervisor-pid, %417:stash:@9:process-tree"
1478        );
1479    }
1480
1481    #[test]
1482    fn missing_pane_manual_repair_reason_formats_phase_specific_detail() {
1483        assert_eq!(
1484            format_missing_pane_manual_repair_reason("tasks/left.md", "response_captured"),
1485            "normal sync will not auto-repair response_captured for tasks/left.md (a captured response still needs explicit closeout recovery). Run `agent-doc repair tasks/left.md` or `agent-doc session doctor tasks/left.md --repair` before syncing again"
1486        );
1487        assert_eq!(
1488            format_missing_pane_manual_repair_reason("tasks/left.md", "write_applied"),
1489            "normal sync will not auto-repair write_applied for tasks/left.md (the write reached disk but the commit boundary is still open). Run `agent-doc repair tasks/left.md` or `agent-doc session doctor tasks/left.md --repair` before syncing again"
1490        );
1491    }
1492
1493    #[test]
1494    fn missing_pane_manual_repair_reason_formats_unknown_phase_fallback() {
1495        assert_eq!(
1496            format_missing_pane_manual_repair_reason("tasks/left.md", "custom_phase"),
1497            "normal sync will not auto-repair custom_phase for tasks/left.md (manual repair is still required). Run `agent-doc repair tasks/left.md` or `agent-doc session doctor tasks/left.md --repair` before syncing again"
1498        );
1499    }
1500
1501    #[test]
1502    fn missing_pane_closeout_block_reason_formats_error_detail() {
1503        assert_eq!(
1504            format_missing_pane_closeout_block_reason(
1505                "tasks/left.md",
1506                "response_captured",
1507                Some("pending/backlog patch changed non-list content"),
1508            ),
1509            "closeout recovery for response_captured failed and needs manual repair (pending/backlog patch changed non-list content). Re-run `agent-doc repair tasks/left.md` before syncing again"
1510        );
1511    }
1512
1513    #[test]
1514    fn missing_pane_closeout_block_reason_formats_unknown_error_fallback() {
1515        assert_eq!(
1516            format_missing_pane_closeout_block_reason("tasks/left.md", "write_applied", None),
1517            "closeout recovery for write_applied failed and needs manual repair (unknown). Re-run `agent-doc repair tasks/left.md` before syncing again"
1518        );
1519    }
1520
1521    #[test]
1522    fn associated_pane_resolution_error_formats_manual_recovery_steps() {
1523        let candidates = vec![
1524            associated_candidate(
1525                "%419",
1526                "@3",
1527                "agent-doc",
1528                &[AssociatedPaneSource::Registered],
1529            ),
1530            associated_candidate("%417", "@9", "stash", &[AssociatedPaneSource::ProcessTree]),
1531        ];
1532
1533        let error =
1534            format_associated_pane_resolution_error("tasks/left.md", &candidates, Some("@3"));
1535
1536        assert_eq!(
1537            error,
1538            [
1539                "multiple tmux panes are associated with tasks/left.md; route cannot safely auto-pick one.",
1540                "Preferred active window: @3. Resolve by inspecting one pane, claiming it explicitly, then killing the redundant panes.",
1541                "  - %419 session=14 window=@3 (agent-doc) cmd=agent-doc sources=registered",
1542                "    view: tmux capture-pane -pt %419 | tail -n 80",
1543                "    assign: agent-doc claim tasks/left.md --pane %419 --force",
1544                "    kill: tmux kill-pane -t %419",
1545                "  - %417 session=14 window=@9 (stash) cmd=agent-doc sources=process-tree",
1546                "    view: tmux capture-pane -pt %417 | tail -n 80",
1547                "    assign: agent-doc claim tasks/left.md --pane %417 --force",
1548                "    kill: tmux kill-pane -t %417",
1549            ]
1550            .join("\n")
1551        );
1552    }
1553
1554    #[test]
1555    fn associated_pane_selected_error_formats_fail_closed_claim_guidance() {
1556        let winner = associated_candidate(
1557            "%419",
1558            "@3",
1559            "agent-doc",
1560            &[
1561                AssociatedPaneSource::Registered,
1562                AssociatedPaneSource::SupervisorPid,
1563            ],
1564        );
1565        let redundant = vec![associated_candidate(
1566            "%417",
1567            "@9",
1568            "stash",
1569            &[AssociatedPaneSource::ProcessTree],
1570        )];
1571
1572        let error = format_associated_pane_selected_error("tasks/left.md", &winner, &redundant);
1573
1574        assert_eq!(
1575            error,
1576            [
1577                "route found legacy pane-association evidence for tasks/left.md, but the normal path will not re-elect ownership from %419.",
1578                "Inspect the candidate, claim it explicitly if it is authoritative, or kill it before rerouting.",
1579                "  - %419 session=14 window=@3 (agent-doc) cmd=agent-doc sources=registered,supervisor-pid",
1580                "    view: tmux capture-pane -pt %419 | tail -n 80",
1581                "    assign: agent-doc claim tasks/left.md --pane %419 --force",
1582                "    kill: tmux kill-pane -t %419",
1583                "  - redundant %417 session=14 window=@9 (stash) cmd=agent-doc sources=process-tree",
1584            ]
1585            .join("\n")
1586        );
1587    }
1588
1589    #[test]
1590    fn associated_pane_fix_error_formats_resync_manual_recovery_steps() {
1591        let candidates = vec![associated_candidate(
1592            "%419",
1593            "@3",
1594            "agent-doc",
1595            &[AssociatedPaneSource::Registered],
1596        )];
1597
1598        let error = format_associated_pane_fix_error("tasks/left.md", &candidates, Some("@3"));
1599
1600        assert_eq!(
1601            error,
1602            [
1603                "multiple tmux panes are associated with tasks/left.md; fix will not auto-pick one.",
1604                "Preferred active window: @3. Inspect one pane, claim it explicitly, then kill the redundant panes.",
1605                "  - %419 session=14 window=@3 (agent-doc) cmd=agent-doc sources=registered",
1606                "    view: tmux capture-pane -pt %419 | tail -n 80",
1607                "    assign: agent-doc claim tasks/left.md --pane %419 --force",
1608                "    kill: tmux kill-pane -t %419",
1609            ]
1610            .join("\n")
1611        );
1612    }
1613
1614    #[test]
1615    fn resolve_associated_panes_prefers_unique_active_window() {
1616        let candidates = vec![
1617            associated_candidate("%417", "@9", "stash", &[AssociatedPaneSource::ProcessTree]),
1618            associated_candidate(
1619                "%419",
1620                "@3",
1621                "agent-doc",
1622                &[
1623                    AssociatedPaneSource::Registered,
1624                    AssociatedPaneSource::SupervisorPid,
1625                ],
1626            ),
1627        ];
1628
1629        let resolution = resolve_associated_panes(candidates, Some("@3"));
1630        match resolution {
1631            AssociatedPaneResolution::Selected { winner, redundant } => {
1632                assert_eq!(winner.pane_id, "%419");
1633                assert_eq!(redundant.len(), 1);
1634                assert_eq!(redundant[0].pane_id, "%417");
1635            }
1636            other => panic!("expected selected winner, got {other:?}"),
1637        }
1638    }
1639
1640    #[test]
1641    fn resolve_associated_panes_accepts_single_stash_candidate() {
1642        let candidates = vec![associated_candidate(
1643            "%420",
1644            "@9",
1645            "stash",
1646            &[AssociatedPaneSource::ProcessTree],
1647        )];
1648
1649        let resolution = resolve_associated_panes(candidates, Some("@7"));
1650        match resolution {
1651            AssociatedPaneResolution::Selected { winner, redundant } => {
1652                assert_eq!(winner.pane_id, "%420");
1653                assert!(redundant.is_empty());
1654            }
1655            other => panic!("expected selected stash winner, got {other:?}"),
1656        }
1657    }
1658
1659    #[test]
1660    fn resolve_associated_panes_reports_ambiguity_when_multiple_candidates_remain() {
1661        let candidates = vec![
1662            associated_candidate("%417", "@9", "stash", &[AssociatedPaneSource::ProcessTree]),
1663            associated_candidate(
1664                "%419",
1665                "@3",
1666                "agent-doc",
1667                &[AssociatedPaneSource::Registered],
1668            ),
1669            associated_candidate(
1670                "%420",
1671                "@5",
1672                "agent-doc",
1673                &[AssociatedPaneSource::SupervisorPid],
1674            ),
1675        ];
1676
1677        let resolution = resolve_associated_panes(candidates, Some("@7"));
1678        match resolution {
1679            AssociatedPaneResolution::Ambiguous(candidates) => {
1680                assert_eq!(candidates.len(), 3);
1681            }
1682            other => panic!("expected ambiguous resolution, got {other:?}"),
1683        }
1684    }
1685
1686    #[test]
1687    fn column_memory_restores_empty_placeholder_columns() {
1688        let remembered = vec!["tasks/left.md".to_string(), String::new()];
1689        let cols = vec![
1690            layout_col("", None),
1691            layout_col("tasks/right.md", Some("tasks/right.md")),
1692        ];
1693
1694        let applied = apply_column_memory(&cols, &remembered);
1695        assert_eq!(
1696            applied.columns,
1697            vec!["tasks/left.md".to_string(), "tasks/right.md".to_string()],
1698            "blank editor columns should keep their position long enough to restore remembered panes"
1699        );
1700        assert_eq!(
1701            applied.restorations,
1702            vec![ColumnMemoryRestoration {
1703                column_index: 0,
1704                remembered: "tasks/left.md".to_string()
1705            }]
1706        );
1707    }
1708
1709    #[test]
1710    fn column_memory_skips_duplicate_remembered_doc_already_visible_elsewhere() {
1711        let remembered = vec!["tasks/right.md".to_string(), String::new()];
1712        let cols = vec![
1713            layout_col("", None),
1714            layout_col("tasks/right.md", Some("tasks/right.md")),
1715        ];
1716
1717        let applied = apply_column_memory(&cols, &remembered);
1718        assert_eq!(
1719            applied.columns,
1720            vec![String::new(), "tasks/right.md".to_string()],
1721            "a remembered doc should not be duplicated into an empty sibling column when it is already visible"
1722        );
1723        assert!(applied.restorations.is_empty());
1724    }
1725
1726    #[test]
1727    fn build_layout_state_preserves_prior_distinct_doc_when_current_cols_duplicate() {
1728        let saved_layout = vec![
1729            layout_col("tasks/left.md", Some("tasks/left.md")),
1730            layout_col("tasks/right.md", Some("tasks/right.md")),
1731        ];
1732        let duplicate_cols = vec![
1733            layout_col("tasks/right.md", Some("tasks/right.md")),
1734            layout_col("tasks/right.md", Some("tasks/right.md")),
1735        ];
1736
1737        assert_eq!(
1738            build_layout_state(&duplicate_cols, &saved_layout),
1739            vec!["tasks/left.md".to_string(), "tasks/right.md".to_string()],
1740            "duplicate current columns should not overwrite a previously distinct remembered layout"
1741        );
1742    }
1743
1744    #[test]
1745    fn column_memory_round_trip_persists_and_restores_across_cycles() {
1746        let left_path = "tasks/left.md".to_string();
1747        let right_path = "tasks/right.md".to_string();
1748
1749        let cols_filled = vec![
1750            layout_col(&left_path, Some(&left_path)),
1751            layout_col(&right_path, Some(&right_path)),
1752        ];
1753        let no_prior = vec![];
1754        let state_1 = build_layout_state(&cols_filled, &no_prior);
1755        assert_eq!(state_1, vec![left_path.clone(), right_path.clone()]);
1756
1757        let cols_empty_left = vec![
1758            layout_col("", None),
1759            layout_col(&right_path, Some(&right_path)),
1760        ];
1761        let restored = apply_column_memory(&cols_empty_left, &state_1);
1762        assert_eq!(
1763            restored.columns,
1764            vec![left_path.clone(), right_path.clone()],
1765            "round-trip: empty left column should be restored from prior cycle's layout state"
1766        );
1767
1768        let restored_cols = vec![
1769            layout_col(&left_path, Some(&left_path)),
1770            layout_col(&right_path, Some(&right_path)),
1771        ];
1772        let saved_cols = vec![
1773            layout_col(&left_path, Some(&left_path)),
1774            layout_col(&right_path, Some(&right_path)),
1775        ];
1776        let state_2 = build_layout_state(&restored_cols, &saved_cols);
1777        assert_eq!(
1778            state_2,
1779            vec![left_path.clone(), right_path.clone()],
1780            "round-trip: layout state should survive through restore + re-persist"
1781        );
1782    }
1783
1784    #[test]
1785    fn column_memory_cross_root_doc_restores_from_submodule_path() {
1786        let root_path = "/repo/tasks/bugs.md".to_string();
1787        let child_path = "/repo/src/sample-app/tasks/sampleorders.md".to_string();
1788        let saved = vec![root_path.clone(), child_path.clone()];
1789        let cols = vec![
1790            layout_col("", None),
1791            layout_col(&child_path, Some(&child_path)),
1792        ];
1793
1794        let restored = apply_column_memory(&cols, &saved);
1795        assert_eq!(
1796            restored.columns,
1797            vec![root_path.clone(), child_path.clone()],
1798            "cross-root doc in submodule path should restore from column memory"
1799        );
1800    }
1801
1802    #[test]
1803    fn column_memory_preserves_right_column_when_left_is_empty() {
1804        let right_path = "tasks/right.md".to_string();
1805        let cols = vec![
1806            layout_col("", None),
1807            layout_col(&right_path, Some(&right_path)),
1808        ];
1809        let no_saved: Vec<String> = vec![];
1810        let result = apply_column_memory(&cols, &no_saved);
1811        assert_eq!(
1812            result.columns,
1813            vec![String::new(), right_path.clone()],
1814            "right-column doc must stay in position even with no column memory to restore"
1815        );
1816
1817        let state = build_layout_state(&cols, &[]);
1818        assert_eq!(
1819            state,
1820            vec![String::new(), right_path],
1821            "layout state must preserve column positions including empty slots"
1822        );
1823    }
1824
1825    #[test]
1826    fn safe_passive_focus_only_switch_expands_active_column_from_memory() {
1827        let saved_layout = vec!["tasks/left.md".to_string(), "tasks/right.md".to_string()];
1828        let focused = vec!["tasks/new-left.md".to_string()];
1829
1830        let expanded = expand_focus_only_columns_for_editor_switch(
1831            &focused,
1832            &saved_layout,
1833            Some(0),
1834            TmuxFocusOnlyExpansionMode::SafePassive,
1835        );
1836        assert_eq!(
1837            expanded.columns,
1838            vec![
1839                "tasks/new-left.md".to_string(),
1840                "tasks/right.md".to_string()
1841            ],
1842            "a focus-only editor switch should replace the active tmux side and keep the sibling side visible"
1843        );
1844        assert_eq!(
1845            expanded.event,
1846            Some(TmuxFocusOnlyExpansionEvent::Expanded {
1847                active_column_index: 0
1848            })
1849        );
1850
1851        let full_mode = expand_focus_only_columns_for_editor_switch(
1852            &focused,
1853            &saved_layout,
1854            Some(0),
1855            TmuxFocusOnlyExpansionMode::LiteralProjection,
1856        );
1857        assert_eq!(
1858            full_mode.columns, focused,
1859            "manual/full sync keeps the literal editor projection"
1860        );
1861        assert!(full_mode.event.is_none());
1862    }
1863
1864    #[test]
1865    fn exact_visible_projection_does_not_expand_from_remembered_focus_only_layout() {
1866        let saved_layout = vec![
1867            "tasks/tsift.md".to_string(),
1868            "tasks/software/corky.md".to_string(),
1869        ];
1870        let focused = vec!["tasks/tsift.md".to_string()];
1871
1872        let expanded = apply_focus_only_expansion_policy(
1873            &focused,
1874            &saved_layout,
1875            Some(0),
1876            TmuxFocusOnlyExpansionMode::SafePassive,
1877            false,
1878        );
1879        assert_eq!(
1880            expanded.columns, saved_layout,
1881            "legacy focus-only sync still preserves remembered sibling columns"
1882        );
1883
1884        let exact = apply_focus_only_expansion_policy(
1885            &focused,
1886            &saved_layout,
1887            Some(0),
1888            TmuxFocusOnlyExpansionMode::SafePassive,
1889            true,
1890        );
1891        assert_eq!(
1892            exact.columns, focused,
1893            "editor snapshots marked exact-visible must not reintroduce stale remembered siblings"
1894        );
1895        assert_eq!(
1896            exact.event,
1897            Some(TmuxFocusOnlyExpansionEvent::ExactVisibleProjection)
1898        );
1899    }
1900
1901    #[test]
1902    fn destructive_repair_throttled_within_interval_only() {
1903        let min = DESTRUCTIVE_REPAIR_MIN_INTERVAL_MS;
1904        assert!(!destructive_repair_throttled(None, 10_000, min));
1905        assert!(destructive_repair_throttled(Some(10_000), 10_000, min));
1906        assert!(destructive_repair_throttled(
1907            Some(10_000),
1908            10_000 + min - 1,
1909            min
1910        ));
1911        assert!(!destructive_repair_throttled(
1912            Some(10_000),
1913            10_000 + min,
1914            min
1915        ));
1916        assert!(!destructive_repair_throttled(
1917            Some(10_000),
1918            10_000 + min + 500,
1919            min
1920        ));
1921        assert!(!destructive_repair_throttled(Some(10_000), 9_000, min));
1922    }
1923
1924    #[test]
1925    fn repair_layout_rescue_phase_skips_zero_stash_target_tmuxsynccrash() {
1926        assert!(
1927            repair_layout_skips_rescue_phase(true, 0, false),
1928            "target+zero-stash is already converged for the destructive rescue phase"
1929        );
1930        assert!(repair_layout_skips_rescue_phase(true, 1, true));
1931        assert!(
1932            !repair_layout_skips_rescue_phase(true, 1, false),
1933            "a non-canonical single stash still needs normalization through repair"
1934        );
1935        assert!(!repair_layout_skips_rescue_phase(false, 0, false));
1936        assert!(!repair_layout_skips_rescue_phase(true, 2, true));
1937    }
1938
1939    #[test]
1940    fn stash_ttl_disabled_ttl_never_prunes() {
1941        assert!(!stash_ttl_prune_candidate(99_999, 0, false, true));
1942        let targets = stash_ttl_prune_targets(&[stash_ttl_candidate("%1", 99_999, false, true)], 0);
1943        assert!(targets.is_empty(), "disabled TTL must reap nothing");
1944    }
1945
1946    #[test]
1947    fn stash_ttl_active_pane_is_never_reaped() {
1948        assert!(!stash_ttl_prune_candidate(10_000, 300, true, true));
1949    }
1950
1951    #[test]
1952    fn stash_ttl_only_agent_doc_stash_panes_are_eligible() {
1953        assert!(!stash_ttl_prune_candidate(10_000, 300, false, false));
1954    }
1955
1956    #[test]
1957    fn stash_ttl_idle_must_strictly_exceed_ttl() {
1958        assert!(!stash_ttl_prune_candidate(300, 300, false, true));
1959        assert!(stash_ttl_prune_candidate(301, 300, false, true));
1960    }
1961
1962    #[test]
1963    fn stash_ttl_targets_filters_only_eligible_panes() {
1964        let candidates = vec![
1965            stash_ttl_candidate("%idle-old", 1_000, false, true),
1966            stash_ttl_candidate("%active", 1_000, true, true),
1967            stash_ttl_candidate("%fresh", 100, false, true),
1968            stash_ttl_candidate("%not-stash", 1_000, false, false),
1969        ];
1970        let targets = stash_ttl_prune_targets(&candidates, 300);
1971        assert_eq!(targets, vec!["%idle-old".to_string()]);
1972    }
1973}