agent-doc 0.32.3

Interactive document sessions with AI agents
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
//! # Module: sessions
//!
//! Session registry — maps session UUIDs to tmux pane IDs and metadata.
//!
//! Registry lives at `.agent-doc/sessions.json` relative to the project root.
//! Re-exports `Tmux`, `IsolatedTmux`, `RegistryEntry` (as `SessionEntry`),
//! `RegistryLock`, and `Registry` (as `SessionRegistry`) from `tmux-router`.
//! Agent-doc-specific operations (capture_pane, send_key, registry load/save
//! with the hardcoded `.agent-doc/sessions.json` path, pane/window queries,
//! positional pane resolution) live here.
//!
//! ## Spec
//! - `registry_path()` returns the canonical `.agent-doc/sessions.json` path.
//! - `load()` deserialises the registry from disk; returns an empty map when the file
//!   does not exist. Not locked internally — read-only callers may call directly.
//! - `save(registry)` serialises the registry to disk with pretty-printing. Callers
//!   MUST hold a `RegistryLock` before calling.
//! - `register(session_id, pane_id, file)` acquires the lock, calls
//!   `register_with_pid` using the current process ID.
//! - `register_with_pid` queries the pane's window and delegates to `register_full`.
//! - `register_full` enforces single-session-per-pane by evicting stale entries that
//!   share the same pane before inserting the new `SessionEntry`.
//! - `lookup(session_id)` returns the pane ID for a session, or `None` if not found.
//! - `lookup_entry(session_id)` returns the full `SessionEntry`, or `None`.
//! - `current_pane()` reads `TMUX_PANE` env var; falls back to querying tmux for the
//!   active pane (works from IDE processes outside a tmux shell).
//! - `pane_pid(pane_id)` queries the foreground process PID of a pane via
//!   `tmux display-message`.
//! - `pane_window(pane_id)` returns the tmux window ID (`@N`) for a pane.
//! - `capture_pane(tmux, pane_id)` returns visible pane content via
//!   `tmux capture-pane -p`.
//! - `send_key(tmux, pane_id, key)` sends a single named key (e.g. `"Enter"`,
//!   `"Up"`) — does NOT append a newline, unlike `Tmux::send_keys`.
//! - `pane_by_position(position)` resolves a pane in the current window by
//!   positional hint: `left`, `right`, `top`, `bottom`.
//! - `pane_by_position_in_window(position, window)` is the same but scoped to a
//!   specific window ID.
//! - `in_tmux()` returns `true` when the `TMUX` env var is set.
//!
//! ## Agentic Contracts
//! - The registry file path is always `.agent-doc/sessions.json` relative to CWD at
//!   call time; callers must ensure CWD is the project root.
//! - `load` and `save` are NOT self-locking. Any read-modify-write cycle must acquire
//!   `RegistryLock` first; prefer `tmux_router::with_registry` for safe cycles.
//! - `register_full` guarantees at most one registry entry per pane ID; pre-existing
//!   entries pointing to the same pane are removed before the new entry is inserted.
//! - `capture_pane` and `send_key` propagate tmux errors as `anyhow::Error` — callers
//!   should treat failures as non-fatal warnings when used for display or navigation.
//! - `pane_by_position` errors on unrecognised position strings with an explicit
//!   message; valid values are exactly `left`, `right`, `top`, `bottom`.
//! - `current_pane` never returns an empty string; an empty tmux response is an error.
//!
//! ## Evals
//! - registry_roundtrip: save a `SessionEntry` → load from same dir → entry is
//!   preserved with identical fields.
//! - load_empty_returns_empty_map: load from a dir with no sessions.json → empty map.
//! - registry_multiple_sessions_isolated: two entries with distinct pane IDs round-trip
//!   independently without cross-contamination.
//! - registry_overwrite_existing_session: inserting the same session_id twice replaces
//!   the entry; registry length stays at 1.
//! - prune_removes_dead_panes: retain entries whose pane is alive removes fabricated
//!   dead pane IDs, leaving an empty registry.
//! - register_full_deduplicates_pane: seeding two sessions with the same pane then
//!   calling `register_full` with a third session leaves only the third in the registry.
//! - pane_alive_returns_false_for_nonexistent: `pane_alive("%99999")` returns `false`.
//! - tmux_create_session_and_verify: isolated server → `new_session` → pane ID starts
//!   with `%` and `pane_alive` returns `true`.
//! - tmux_auto_start_cascade: auto_start on no-server, no-session, and existing-session
//!   each produce a live pane in the correct session.

use anyhow::{Context, Result};
use std::path::PathBuf;
use std::process::Command;

// Re-export Tmux types from tmux-router.
pub use tmux_router::Tmux;
#[cfg(test)]
pub use tmux_router::IsolatedTmux;
pub use tmux_router::{RegistryEntry as SessionEntry, RegistryLock, Registry as SessionRegistry};
pub use tmux_router::PaneMoveOp;

const SESSIONS_FILE: &str = ".agent-doc/sessions.json";

/// Return the path to the sessions registry file.
pub fn registry_path() -> PathBuf {
    PathBuf::from(SESSIONS_FILE)
}

// ---------------------------------------------------------------------------
// Agent-doc-specific tmux operations (not in tmux-router)
// ---------------------------------------------------------------------------

/// Capture the visible content of a tmux pane.
pub fn capture_pane(tmux: &Tmux, pane_id: &str) -> Result<String> {
    let output = tmux
        .cmd()
        .args(["capture-pane", "-t", pane_id, "-p"])
        .output()
        .context("failed to capture tmux pane")?;
    if !output.status.success() {
        anyhow::bail!("tmux capture-pane failed for {}", pane_id);
    }
    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

/// Swap two panes only if both belong to `expected_session`.
///
/// `tmux swap-pane` works across sessions, which has caused bugs where panes
/// from one tmux session were moved into another. This wrapper validates both
/// panes before allowing the swap.
///
/// Returns `Err` if either pane is in the wrong session — callers should fall
/// back to `join-pane` or provision a new pane instead.
pub fn swap_pane_guarded(
    tmux: &Tmux,
    src: &str,
    dst: &str,
    expected_session: &str,
) -> Result<()> {
    let src_session = tmux
        .cmd()
        .args(["display-message", "-t", src, "-p", "#{session_name}"])
        .output()
        .ok()
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_default();
    if src_session != expected_session {
        anyhow::bail!(
            "swap_pane_guarded: src pane {} is in session '{}', expected '{}' — refusing cross-session swap",
            src, src_session, expected_session
        );
    }
    let dst_session = tmux
        .cmd()
        .args(["display-message", "-t", dst, "-p", "#{session_name}"])
        .output()
        .ok()
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_default();
    if dst_session != expected_session {
        anyhow::bail!(
            "swap_pane_guarded: dst pane {} is in session '{}', expected '{}' — refusing cross-session swap",
            dst, dst_session, expected_session
        );
    }
    tmux.swap_pane(src, dst)
}

/// Send a single key (not literal text) to a tmux pane.
///
/// Unlike `Tmux::send_keys` (which sends literal text + Enter), this sends
/// a single key name like "Up", "Down", "Enter" — used for TUI navigation.
pub fn send_key(tmux: &Tmux, pane_id: &str, key: &str) -> Result<()> {
    let status = tmux
        .cmd()
        .args(["send-keys", "-t", pane_id, key])
        .status()
        .context("failed to send key to tmux pane")?;
    if !status.success() {
        anyhow::bail!("tmux send-keys failed for pane {}", pane_id);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Free functions — registry operations and env-based checks
// ---------------------------------------------------------------------------

/// Load the session registry from disk. Returns empty map if file doesn't exist.
///
/// **Not locked internally.** Callers performing read-modify-write must acquire
/// `RegistryLock` first (or use `tmux_router::with_registry`). Read-only callers
/// can call this directly for a point-in-time snapshot.
pub(crate) fn load() -> Result<SessionRegistry> {
    let path = PathBuf::from(SESSIONS_FILE);
    if !path.exists() {
        return Ok(SessionRegistry::new());
    }
    let content = std::fs::read_to_string(&path)
        .with_context(|| format!("failed to read {}", SESSIONS_FILE))?;
    let registry: SessionRegistry = serde_json::from_str(&content)
        .with_context(|| format!("failed to parse {}", SESSIONS_FILE))?;
    Ok(registry)
}

/// Save the session registry to disk.
///
/// **Not locked internally.** Callers MUST hold `RegistryLock` before calling.
/// Prefer `tmux_router::with_registry()` for safe read-modify-write cycles.
pub(crate) fn save(registry: &SessionRegistry) -> Result<()> {
    let path = PathBuf::from(SESSIONS_FILE);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let content = serde_json::to_string_pretty(registry)?;
    std::fs::write(&path, content)
        .with_context(|| format!("failed to write {}", SESSIONS_FILE))?;
    Ok(())
}

/// Register a session → pane mapping.
/// Get the PID of the foreground process in a tmux pane.
pub fn pane_pid(pane_id: &str) -> Result<u32> {
    let output = Command::new("tmux")
        .args(["display-message", "-t", pane_id, "-p", "#{pane_pid}"])
        .output()
        .context("failed to query tmux pane PID")?;
    if !output.status.success() {
        anyhow::bail!("tmux display-message failed for pane {}", pane_id);
    }
    let pid_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
    pid_str
        .parse::<u32>()
        .with_context(|| format!("invalid PID '{}' for pane {}", pid_str, pane_id))
}

pub fn register(session_id: &str, pane_id: &str, file: &str) -> Result<()> {
    register_with_pid(session_id, pane_id, file, std::process::id())
}

pub fn register_with_pid(session_id: &str, pane_id: &str, file: &str, pid: u32) -> Result<()> {
    // Query the window ID for this pane
    let window = pane_window(pane_id).unwrap_or_default();
    register_full(session_id, pane_id, file, pid, &window)
}

pub fn register_full(
    session_id: &str,
    pane_id: &str,
    file: &str,
    pid: u32,
    window: &str,
) -> Result<()> {
    let _lock = RegistryLock::acquire(&registry_path())?;
    let mut registry = load()?;
    let cwd = std::env::current_dir()
        .map(|p| p.to_string_lossy().to_string())
        .unwrap_or_default();
    let started = chrono_now();

    // Enforce single session per pane: remove stale entries pointing to same pane
    let stale_keys: Vec<String> = registry
        .iter()
        .filter(|(k, e)| e.pane == pane_id && k.as_str() != session_id)
        .map(|(k, _)| k.clone())
        .collect();
    for key in &stale_keys {
        eprintln!(
            "[registry] removing stale session {} (was pane {})",
            key, pane_id
        );
        registry.remove(key);
    }

    registry.insert(
        session_id.to_string(),
        SessionEntry {
            pane: pane_id.to_string(),
            pid,
            cwd,
            started,
            file: file.to_string(),
            window: window.to_string(),
        },
    );
    save(&registry)
}

/// Query the tmux window ID for a pane.
pub fn pane_window(pane_id: &str) -> Result<String> {
    let output = Command::new("tmux")
        .args(["display-message", "-t", pane_id, "-p", "#{window_id}"])
        .output()
        .context("failed to query tmux window ID")?;
    if !output.status.success() {
        anyhow::bail!("tmux display-message failed for pane {}", pane_id);
    }
    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

/// Look up the pane ID for a session.
pub fn lookup(session_id: &str) -> Result<Option<String>> {
    let registry = load()?;
    Ok(registry.get(session_id).map(|e| e.pane.clone()))
}

/// Look up a full registry entry by session ID.
pub fn lookup_entry(session_id: &str) -> Result<Option<SessionEntry>> {
    let registry = load()?;
    Ok(registry.get(session_id).cloned())
}

/// Get the pane ID of the current pane.
/// Tries TMUX_PANE env var first, then falls back to querying tmux
/// for the active pane (works from outside tmux, e.g. IDE processes).
pub fn current_pane() -> Result<String> {
    if let Ok(pane) = std::env::var("TMUX_PANE") {
        return Ok(pane);
    }
    // Fallback: query tmux for the active pane
    let output = Command::new("tmux")
        .args(["display-message", "-p", "#{pane_id}"])
        .output()
        .context("failed to query tmux for active pane — is tmux running?")?;
    if !output.status.success() {
        anyhow::bail!("tmux display-message failed — not inside tmux and no tmux server found");
    }
    let pane = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if pane.is_empty() {
        anyhow::bail!("tmux returned empty pane ID");
    }
    Ok(pane)
}

/// Resolve a pane by positional hint (left, right, top, bottom).
/// Queries `tmux list-panes` for the current window and selects the pane
/// at the requested position based on coordinates.
pub fn pane_by_position(position: &str) -> Result<String> {
    let output = Command::new("tmux")
        .args([
            "list-panes",
            "-F",
            "#{pane_id} #{pane_left} #{pane_top} #{pane_width} #{pane_height}",
        ])
        .output()
        .context("failed to query tmux panes")?;
    if !output.status.success() {
        anyhow::bail!("tmux list-panes failed");
    }
    let text = String::from_utf8_lossy(&output.stdout);
    let mut panes: Vec<(String, u32, u32, u32, u32)> = Vec::new();
    for line in text.lines() {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 5 {
            let id = parts[0].to_string();
            let left: u32 = parts[1].parse().unwrap_or(0);
            let top: u32 = parts[2].parse().unwrap_or(0);
            let width: u32 = parts[3].parse().unwrap_or(0);
            let height: u32 = parts[4].parse().unwrap_or(0);
            panes.push((id, left, top, width, height));
        }
    }
    if panes.is_empty() {
        anyhow::bail!("no panes found in current tmux window");
    }
    if panes.len() == 1 {
        return Ok(panes[0].0.clone());
    }
    let selected = match position {
        "left" => panes.iter().min_by_key(|p| p.1),
        "right" => panes.iter().max_by_key(|p| p.1 + p.3),
        "top" => panes.iter().min_by_key(|p| p.2),
        "bottom" => panes.iter().max_by_key(|p| p.2 + p.4),
        _ => anyhow::bail!(
            "invalid position '{}' — use left, right, top, or bottom",
            position
        ),
    };
    match selected {
        Some(pane) => Ok(pane.0.clone()),
        None => anyhow::bail!("could not resolve pane for position '{}'", position),
    }
}

/// Resolve a pane by positional hint within a specific tmux window.
/// Like `pane_by_position` but scoped to the given window ID (e.g. `@1`).
pub fn pane_by_position_in_window(position: &str, window: &str) -> Result<String> {
    let output = Command::new("tmux")
        .args([
            "list-panes",
            "-t",
            window,
            "-F",
            "#{pane_id} #{pane_left} #{pane_top} #{pane_width} #{pane_height}",
        ])
        .output()
        .context("failed to query tmux panes")?;
    if !output.status.success() {
        anyhow::bail!("tmux list-panes failed for window {}", window);
    }
    let text = String::from_utf8_lossy(&output.stdout);
    let mut panes: Vec<(String, u32, u32, u32, u32)> = Vec::new();
    for line in text.lines() {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 5 {
            let id = parts[0].to_string();
            let left: u32 = parts[1].parse().unwrap_or(0);
            let top: u32 = parts[2].parse().unwrap_or(0);
            let width: u32 = parts[3].parse().unwrap_or(0);
            let height: u32 = parts[4].parse().unwrap_or(0);
            panes.push((id, left, top, width, height));
        }
    }
    if panes.is_empty() {
        anyhow::bail!("no panes found in tmux window {}", window);
    }
    if panes.len() == 1 {
        return Ok(panes[0].0.clone());
    }
    let selected = match position {
        "left" => panes.iter().min_by_key(|p| p.1),
        "right" => panes.iter().max_by_key(|p| p.1 + p.3),
        "top" => panes.iter().min_by_key(|p| p.2),
        "bottom" => panes.iter().max_by_key(|p| p.2 + p.4),
        _ => anyhow::bail!(
            "invalid position '{}' — use left, right, top, or bottom",
            position
        ),
    };
    match selected {
        Some(pane) => Ok(pane.0.clone()),
        None => anyhow::bail!("could not resolve pane for position '{}'", position),
    }
}

/// Check if we're inside tmux.
pub fn in_tmux() -> bool {
    std::env::var("TMUX").is_ok()
}

/// Simple UTC timestamp without pulling in chrono.
fn chrono_now() -> String {
    let output = Command::new("date")
        .args(["-u", "+%Y-%m-%dT%H:%M:%SZ"])
        .output();
    match output {
        Ok(out) => String::from_utf8_lossy(&out.stdout).trim().to_string(),
        Err(_) => "unknown".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn registry_roundtrip() {
        let dir = TempDir::new().unwrap();
        let _guard = std::env::set_current_dir(dir.path());

        let mut reg = SessionRegistry::new();
        reg.insert(
            "test-session".to_string(),
            SessionEntry {
                pane: "%42".to_string(),
                pid: 12345,
                cwd: "/tmp".to_string(),
                started: "2026-01-01T00:00:00Z".to_string(),
                file: "test.md".to_string(),
                window: String::new(),
            },
        );
        save(&reg).unwrap();
        let loaded = load().unwrap();
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded["test-session"].pane, "%42");
    }

    #[test]
    fn load_empty_returns_empty_map() {
        let dir = TempDir::new().unwrap();
        let _guard = std::env::set_current_dir(dir.path());
        let reg = load().unwrap();
        assert!(reg.is_empty());
    }

    #[test]
    fn pane_alive_returns_false_for_nonexistent() {
        assert!(!Tmux::default_server().pane_alive("%99999"));
    }

    #[test]
    fn registry_multiple_sessions_isolated() {
        let mut reg = SessionRegistry::new();
        reg.insert(
            "session-a".to_string(),
            SessionEntry {
                pane: "%10".to_string(),
                pid: 1000,
                cwd: "/tmp/a".to_string(),
                started: "2026-01-01T00:00:00Z".to_string(),
                file: String::new(),
                window: String::new(),
            },
        );
        reg.insert(
            "session-b".to_string(),
            SessionEntry {
                pane: "%20".to_string(),
                pid: 2000,
                cwd: "/tmp/b".to_string(),
                started: "2026-01-01T00:01:00Z".to_string(),
                file: String::new(),
                window: String::new(),
            },
        );

        let json = serde_json::to_string_pretty(&reg).unwrap();
        let loaded: SessionRegistry = serde_json::from_str(&json).unwrap();

        assert_eq!(loaded.len(), 2);
        assert_eq!(loaded["session-a"].pane, "%10");
        assert_eq!(loaded["session-b"].pane, "%20");
        assert_ne!(loaded["session-a"].pane, loaded["session-b"].pane);
        assert_ne!(loaded["session-a"].pid, loaded["session-b"].pid);
    }

    #[test]
    fn registry_overwrite_existing_session() {
        let mut reg = SessionRegistry::new();
        reg.insert(
            "session-x".to_string(),
            SessionEntry {
                pane: "%old".to_string(),
                pid: 100,
                cwd: "/tmp".to_string(),
                started: "2026-01-01T00:00:00Z".to_string(),
                file: String::new(),
                window: String::new(),
            },
        );
        reg.insert(
            "session-x".to_string(),
            SessionEntry {
                pane: "%new".to_string(),
                pid: 200,
                cwd: "/tmp".to_string(),
                started: "2026-01-01T00:05:00Z".to_string(),
                file: String::new(),
                window: String::new(),
            },
        );

        assert_eq!(reg.len(), 1);
        assert_eq!(reg["session-x"].pane, "%new");
        assert_eq!(reg["session-x"].pid, 200);
    }

    #[test]
    fn prune_removes_dead_panes_from_map() {
        let tmux = Tmux::default_server();
        let mut reg = SessionRegistry::new();
        reg.insert(
            "dead-session-1".to_string(),
            SessionEntry {
                pane: "%99998".to_string(),
                pid: 1,
                cwd: "/tmp".to_string(),
                started: "2026-01-01T00:00:00Z".to_string(),
                file: String::new(),
                window: String::new(),
            },
        );
        reg.insert(
            "dead-session-2".to_string(),
            SessionEntry {
                pane: "%99997".to_string(),
                pid: 2,
                cwd: "/tmp".to_string(),
                started: "2026-01-01T00:00:00Z".to_string(),
                file: String::new(),
                window: String::new(),
            },
        );

        let before = reg.len();
        reg.retain(|_, entry| tmux.pane_alive(&entry.pane));
        let removed = before - reg.len();

        assert_eq!(removed, 2);
        assert!(reg.is_empty());
    }

    // -----------------------------------------------------------------------
    // Tmux isolation tests — use `-L` to create independent tmux servers
    // -----------------------------------------------------------------------

    #[test]
    fn tmux_isolated_server_not_running_initially() {
        let t = IsolatedTmux::new("agent-doc-test-not-running");
        assert!(!t.running());
    }

    #[test]
    fn tmux_create_session_and_verify() {
        let t = IsolatedTmux::new("agent-doc-test-create-session");
        let tmp = TempDir::new().unwrap();

        let pane_id = t.new_session("test-session", tmp.path()).unwrap();
        assert!(!pane_id.is_empty(), "pane_id should not be empty");
        assert!(pane_id.starts_with('%'), "pane_id should start with %");

        assert!(t.running());
        assert!(t.session_exists("test-session"));
        assert!(t.pane_alive(&pane_id));
    }

    #[test]
    fn tmux_session_exists_returns_false_for_missing() {
        let t = IsolatedTmux::new("agent-doc-test-session-missing");
        let tmp = TempDir::new().unwrap();

        t.new_session("existing", tmp.path()).unwrap();

        assert!(t.session_exists("existing"));
        assert!(!t.session_exists("nonexistent"));
    }

    #[test]
    fn tmux_new_window_creates_second_pane() {
        let t = IsolatedTmux::new("agent-doc-test-new-window");
        let tmp = TempDir::new().unwrap();

        let pane1 = t.new_session("test", tmp.path()).unwrap();
        let pane2 = t.new_window("test", tmp.path()).unwrap();

        assert_ne!(pane1, pane2, "two windows should have different pane IDs");
        assert!(t.pane_alive(&pane1));
        assert!(t.pane_alive(&pane2));
    }

    #[test]
    fn tmux_send_keys_to_pane() {
        let t = IsolatedTmux::new("agent-doc-test-send-keys");
        let tmp = TempDir::new().unwrap();

        let pane_id = t.new_session("test", tmp.path()).unwrap();
        t.send_keys(&pane_id, "echo hello").unwrap();
    }

    #[test]
    fn tmux_pane_alive_returns_false_after_kill() {
        let t = IsolatedTmux::new("agent-doc-test-pane-kill");
        let tmp = TempDir::new().unwrap();

        let pane_id = t.new_session("test", tmp.path()).unwrap();
        assert!(t.pane_alive(&pane_id));

        // Create a second window so we can kill the first without killing the session
        let _pane2 = t.new_window("test", tmp.path()).unwrap();

        let _ = t.cmd().args(["kill-pane", "-t", &pane_id]).status();

        assert!(!t.pane_alive(&pane_id));
    }

    #[test]
    fn tmux_auto_start_cascade_no_server() {
        let t = IsolatedTmux::new("agent-doc-test-autostart-no-server");
        let tmp = TempDir::new().unwrap();

        assert!(!t.running());
        let pane_id = t.auto_start("claude", tmp.path()).unwrap();
        assert!(!pane_id.is_empty());
        assert!(t.running());
        assert!(t.session_exists("claude"));
        assert!(t.pane_alive(&pane_id));
    }

    #[test]
    fn tmux_auto_start_cascade_no_session() {
        let t = IsolatedTmux::new("agent-doc-test-autostart-no-session");
        let tmp = TempDir::new().unwrap();

        t.new_session("other", tmp.path()).unwrap();
        assert!(t.running());
        assert!(!t.session_exists("claude"));

        let pane_id = t.auto_start("claude", tmp.path()).unwrap();
        assert!(t.session_exists("claude"));
        assert!(t.pane_alive(&pane_id));
    }

    #[test]
    fn tmux_auto_start_cascade_session_exists() {
        let t = IsolatedTmux::new("agent-doc-test-autostart-exists");
        let tmp = TempDir::new().unwrap();

        let pane1 = t.new_session("claude", tmp.path()).unwrap();

        let pane2 = t.auto_start("claude", tmp.path()).unwrap();
        assert_ne!(pane1, pane2, "should be a different pane (new window)");
        assert!(t.pane_alive(&pane1));
        assert!(t.pane_alive(&pane2));
    }

    #[test]
    #[ignore] // uses set_current_dir which is not thread-safe with other tests
    fn register_full_deduplicates_pane() {
        // When a new session claims a pane, old sessions pointing to the same pane are removed
        let dir = TempDir::new().unwrap();
        std::env::set_current_dir(dir.path()).unwrap();
        std::fs::create_dir_all(".agent-doc").unwrap();

        // Seed registry with two sessions pointing to the same pane
        let mut reg = SessionRegistry::new();
        reg.insert(
            "session-a".to_string(),
            SessionEntry {
                pane: "%42".to_string(),
                pid: 100,
                cwd: "/tmp".to_string(),
                started: "2026-01-01T00:00:00Z".to_string(),
                file: "old-file.md".to_string(),
                window: "@1".to_string(),
            },
        );
        reg.insert(
            "session-b".to_string(),
            SessionEntry {
                pane: "%42".to_string(),
                pid: 100,
                cwd: "/tmp".to_string(),
                started: "2026-01-01T00:01:00Z".to_string(),
                file: "another-old.md".to_string(),
                window: "@1".to_string(),
            },
        );
        save(&reg).unwrap();

        // Now register session-c with the same pane %42
        register_full("session-c", "%42", "new-file.md", 200, "@1").unwrap();

        let loaded = load().unwrap();
        // Only session-c should remain for pane %42
        assert!(loaded.contains_key("session-c"), "new session should exist");
        assert!(!loaded.contains_key("session-a"), "old session-a should be removed");
        assert!(!loaded.contains_key("session-b"), "old session-b should be removed");
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded["session-c"].file, "new-file.md");
    }
}