git-paw 0.3.0

Parallel AI Worktrees — orchestrate multiple AI coding CLI sessions across git worktrees
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
//! Tmux session and pane orchestration.
//!
//! Checks tmux availability, creates sessions, splits panes, sends commands,
//! applies layouts, and manages attach/reattach. Uses a builder pattern for
//! testability and dry-run support.

use std::process::Command;

use crate::error::PawError;

/// Maximum number of session name collision retries.
const MAX_COLLISION_RETRIES: u32 = 10;

/// A single tmux CLI invocation, stored as its argument list.
///
/// Can be inspected as a string (for dry-run / testing) or executed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TmuxCommand {
    args: Vec<String>,
}

impl TmuxCommand {
    /// Create a new tmux command from the given arguments.
    fn new(args: &[&str]) -> Self {
        Self {
            args: args.iter().map(|&s| s.to_owned()).collect(),
        }
    }

    /// Return a human-readable command string (e.g. `tmux new-session -d -s paw-proj`).
    // Not called by production code — used by `TmuxSession::command_strings()` for
    // dry-run contract tests that verify the commands shown to users via `--dry-run`.
    #[allow(dead_code)]
    pub fn as_command_string(&self) -> String {
        format!("tmux {}", self.args.join(" "))
    }

    /// Execute the command against the live tmux server.
    fn execute(&self) -> Result<String, PawError> {
        let output = Command::new("tmux")
            .args(&self.args)
            .output()
            .map_err(|e| PawError::TmuxError(format!("failed to run tmux: {e}")))?;

        if output.status.success() {
            String::from_utf8(output.stdout)
                .map_err(|e| PawError::TmuxError(format!("invalid utf-8 in tmux output: {e}")))
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            Err(PawError::TmuxError(stderr.trim().to_owned()))
        }
    }
}

/// Specification for a single pane: which branch/worktree to `cd` into and which CLI to run.
#[derive(Debug, Clone)]
pub struct PaneSpec {
    /// Branch name (e.g. `feat/auth`). Used for the pane title.
    pub branch: String,
    /// Absolute path to the git worktree directory.
    pub worktree: String,
    /// The CLI command to execute inside the pane.
    pub cli_command: String,
}

/// A fully-resolved tmux session ready to execute or inspect.
#[derive(Debug)]
pub struct TmuxSession {
    /// The resolved session name (e.g. `paw-myproject` or `paw-myproject-2`).
    pub name: String,
    commands: Vec<TmuxCommand>,
}

impl TmuxSession {
    /// Execute all accumulated tmux commands against the live tmux server.
    pub fn execute(&self) -> Result<(), PawError> {
        for cmd in &self.commands {
            cmd.execute()?;
        }
        Ok(())
    }

    /// Return all commands as human-readable strings (for dry-run / testing).
    // Not called by production code — used by unit tests as the dry-run contract
    // surface to verify the tmux commands shown to users via `--dry-run`.
    #[allow(dead_code)]
    pub fn command_strings(&self) -> Vec<String> {
        self.commands
            .iter()
            .map(TmuxCommand::as_command_string)
            .collect()
    }

    /// Queue a `pipe-pane` command to capture pane output to a log file.
    ///
    /// Appends `tmux pipe-pane -o -t <pane_target> "cat >> <log_path>"` to the
    /// command queue. Should be called after the pane has been created.
    pub fn pipe_pane(&mut self, pane_target: &str, log_path: &std::path::Path) -> &mut Self {
        self.commands.push(TmuxCommand::new(&[
            "pipe-pane",
            "-o",
            "-t",
            pane_target,
            &format!("cat >> {}", log_path.display()),
        ]));
        self
    }
}

/// Builder that accumulates tmux operations for creating and configuring a session.
///
/// Can either execute operations against a live tmux server or return them
/// as command strings for testing and dry-run.
///
/// # Examples
///
/// ```no_run
/// use git_paw::tmux::{TmuxSessionBuilder, PaneSpec};
///
/// let session = TmuxSessionBuilder::new("my-project")
///     .add_pane(PaneSpec {
///         branch: "feat/auth".into(),
///         worktree: "/tmp/my-project-feat-auth".into(),
///         cli_command: "claude".into(),
///     })
///     .mouse_mode(true)
///     .build()?;
///
/// // Dry-run: inspect commands
/// for cmd in session.command_strings() {
///     println!("{cmd}");
/// }
///
/// // Or execute for real
/// session.execute()?;
/// # Ok::<(), git_paw::error::PawError>(())
/// ```
#[derive(Debug)]
pub struct TmuxSessionBuilder {
    project_name: String,
    panes: Vec<PaneSpec>,
    mouse_mode: bool,
    session_name_override: Option<String>,
    env_vars: Vec<(String, String)>,
}

impl TmuxSessionBuilder {
    /// Create a new builder for the given project name.
    ///
    /// The session will be named `paw-<project_name>` unless overridden
    /// with [`session_name`](Self::session_name).
    pub fn new(project_name: &str) -> Self {
        Self {
            project_name: project_name.to_owned(),
            panes: Vec::new(),
            mouse_mode: true,
            session_name_override: None,
            env_vars: Vec::new(),
        }
    }

    /// Override the session name instead of deriving it from the project name.
    ///
    /// Use this with [`resolve_session_name`] to handle name collisions.
    #[must_use]
    pub fn session_name(mut self, name: String) -> Self {
        self.session_name_override = Some(name);
        self
    }

    /// Add a pane that will `cd` into the worktree and run the CLI command.
    #[must_use]
    pub fn add_pane(mut self, spec: PaneSpec) -> Self {
        self.panes.push(spec);
        self
    }

    /// Enable or disable mouse mode for the session (default: `true`).
    ///
    /// When enabled, users can click to switch panes, drag borders to resize,
    /// and scroll. This is set per-session and does not affect other tmux sessions.
    #[must_use]
    pub fn mouse_mode(mut self, enabled: bool) -> Self {
        self.mouse_mode = enabled;
        self
    }

    /// Set a session-level environment variable.
    ///
    /// The resulting `tmux set-environment -t <session> <key> <value>` command
    /// is emitted before any `send-keys` commands so all panes inherit it.
    #[must_use]
    pub fn set_environment(mut self, key: &str, value: &str) -> Self {
        self.env_vars.push((key.to_owned(), value.to_owned()));
        self
    }

    /// Build the full sequence of tmux commands without executing anything.
    ///
    /// Returns a [`TmuxSession`] that can be executed or inspected.
    /// Returns an error if no panes have been added.
    #[allow(clippy::too_many_lines)]
    pub fn build(self) -> Result<TmuxSession, PawError> {
        if self.panes.is_empty() {
            return Err(PawError::TmuxError(
                "cannot create a session with no panes".to_owned(),
            ));
        }

        let session_name = self
            .session_name_override
            .unwrap_or_else(|| format!("paw-{}", self.project_name));
        let mut commands = Vec::new();

        // 1. Create detached session (pane 0 is implicit)
        // Use -c to set pane 0's working directory directly, avoiding a race
        // condition where send-keys fires before the shell is ready.
        let first_worktree = &self.panes[0].worktree;
        commands.push(TmuxCommand::new(&[
            "new-session",
            "-d",
            "-s",
            &session_name,
            "-c",
            first_worktree,
        ]));

        // 2. Mouse mode
        if self.mouse_mode {
            commands.push(TmuxCommand::new(&[
                "set-option",
                "-t",
                &session_name,
                "mouse",
                "on",
            ]));
        }

        // 3. Pane border titles — show branch/CLI in each pane's border
        commands.push(TmuxCommand::new(&[
            "set-option",
            "-t",
            &session_name,
            "pane-border-status",
            "top",
        ]));
        commands.push(TmuxCommand::new(&[
            "set-option",
            "-t",
            &session_name,
            "pane-border-format",
            " #{pane_title} ",
        ]));

        // 4. Session-level environment variables (before any send-keys)
        for (key, value) in &self.env_vars {
            commands.push(TmuxCommand::new(&[
                "set-environment",
                "-t",
                &session_name,
                key,
                value,
            ]));
        }

        // 5. First pane — already exists as pane 0 (directory set by -c above)
        let first = &self.panes[0];
        let pane_target = format!("{session_name}:0.0");
        let pane_title = format!("{} \u{2192} {}", first.branch, first.cli_command);
        commands.push(TmuxCommand::new(&[
            "select-pane",
            "-t",
            &pane_target,
            "-T",
            &pane_title,
        ]));
        commands.push(TmuxCommand::new(&[
            "send-keys",
            "-t",
            &pane_target,
            &first.cli_command,
            "Enter",
        ]));

        // 6. Subsequent panes — tiled layout before each split
        for (i, pane) in self.panes.iter().enumerate().skip(1) {
            // Apply tiled layout before split to ensure space
            commands.push(TmuxCommand::new(&[
                "select-layout",
                "-t",
                &session_name,
                "tiled",
            ]));

            // Split window to create new pane
            commands.push(TmuxCommand::new(&["split-window", "-t", &session_name]));

            // Title and command for the new pane
            let pane_target = format!("{session_name}:0.{i}");
            let pane_title = format!("{} \u{2192} {}", pane.branch, pane.cli_command);
            let pane_cmd = format!("cd {} && {}", pane.worktree, pane.cli_command);
            commands.push(TmuxCommand::new(&[
                "select-pane",
                "-t",
                &pane_target,
                "-T",
                &pane_title,
            ]));
            commands.push(TmuxCommand::new(&[
                "send-keys",
                "-t",
                &pane_target,
                &pane_cmd,
                "Enter",
            ]));
        }

        // 7. Final tiled layout for clean alignment
        commands.push(TmuxCommand::new(&[
            "select-layout",
            "-t",
            &session_name,
            "tiled",
        ]));

        Ok(TmuxSession {
            name: session_name,
            commands,
        })
    }
}

/// Check that tmux is installed on PATH.
///
/// Returns `Ok(())` if found, or `Err(PawError::TmuxNotInstalled)` with
/// install instructions if missing.
pub fn ensure_tmux_installed() -> Result<(), PawError> {
    which::which("tmux").map_err(|_| PawError::TmuxNotInstalled)?;
    Ok(())
}

/// Check whether a tmux session with the given name is currently alive.
pub fn is_session_alive(name: &str) -> Result<bool, PawError> {
    let status = Command::new("tmux")
        .args(["has-session", "-t", name])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .map_err(|e| PawError::TmuxError(format!("failed to run tmux: {e}")))?;

    Ok(status.success())
}

/// Resolve a unique session name, handling collisions with existing sessions.
///
/// Starts with `paw-<project_name>` and appends `-2`, `-3`, etc. if the name
/// is already taken by another session.
pub fn resolve_session_name(project_name: &str) -> Result<String, PawError> {
    let base = format!("paw-{project_name}");

    if !is_session_alive(&base)? {
        return Ok(base);
    }

    for suffix in 2..=MAX_COLLISION_RETRIES + 1 {
        let candidate = format!("{base}-{suffix}");
        if !is_session_alive(&candidate)? {
            return Ok(candidate);
        }
    }

    Err(PawError::TmuxError(format!(
        "too many session name collisions for '{base}'"
    )))
}

/// Attach the current terminal to the named tmux session.
///
/// This replaces the current process's stdio. Returns an error if the
/// session does not exist or tmux fails.
pub fn attach(name: &str) -> Result<(), PawError> {
    let status = Command::new("tmux")
        .args(["attach-session", "-t", name])
        .status()
        .map_err(|e| PawError::TmuxError(format!("failed to attach to tmux session: {e}")))?;

    if status.success() {
        Ok(())
    } else {
        Err(PawError::TmuxError(format!(
            "failed to attach to session '{name}'"
        )))
    }
}

/// Kill the named tmux session.
pub fn kill_session(name: &str) -> Result<(), PawError> {
    let output = Command::new("tmux")
        .args(["kill-session", "-t", name])
        .output()
        .map_err(|e| PawError::TmuxError(format!("failed to kill tmux session: {e}")))?;

    if output.status.success() {
        Ok(())
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        Err(PawError::TmuxError(stderr.trim().to_owned()))
    }
}

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

    fn make_pane(branch: &str, worktree: &str, cli: &str) -> PaneSpec {
        PaneSpec {
            branch: branch.to_owned(),
            worktree: worktree.to_owned(),
            cli_command: cli.to_owned(),
        }
    }

    /// Helper: extract command strings matching a keyword from a session's commands.
    fn commands_containing(cmds: &[String], keyword: &str) -> Vec<String> {
        cmds.iter()
            .filter(|c| c.contains(keyword))
            .cloned()
            .collect()
    }

    // -----------------------------------------------------------------------
    // AC: Checks tmux presence with actionable error
    // Behavioral: verifies the public contract — does the system detect tmux?
    // -----------------------------------------------------------------------

    #[test]
    #[serial_test::serial]
    fn ensure_tmux_installed_succeeds_when_present() {
        // Requires #[serial] because detect tests modify PATH.
        assert!(ensure_tmux_installed().is_ok());
    }

    // -----------------------------------------------------------------------
    // AC: Creates named sessions, handles collision
    // Behavioral: session name is a public field used by attach, status, and
    // dry-run output. The exact naming convention is the public contract.
    // -----------------------------------------------------------------------

    #[test]
    fn session_is_named_after_project() {
        let session = TmuxSessionBuilder::new("my-project")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .build()
            .unwrap();

        assert_eq!(session.name, "paw-my-project");
    }

    #[test]
    fn session_creation_command_uses_session_name() {
        let session = TmuxSessionBuilder::new("app")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .build()
            .unwrap();

        let cmds = session.command_strings();
        assert!(
            cmds.iter()
                .any(|c| c.contains("new-session") && c.contains("paw-app")),
            "should create a tmux session named paw-app"
        );
    }

    #[test]
    fn session_name_override_replaces_default() {
        let session = TmuxSessionBuilder::new("my-project")
            .session_name("custom-session-name".to_string())
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .build()
            .unwrap();

        assert_eq!(session.name, "custom-session-name");
        let cmds = session.command_strings();
        assert!(
            cmds.iter()
                .any(|c| c.contains("new-session") && c.contains("custom-session-name")),
            "should use overridden session name"
        );
    }

    // -----------------------------------------------------------------------
    // AC: Dynamic pane count based on input
    // Dry-run contract: verifies the number of commands matches the number of
    // panes the user requested. Actual pane creation verified by e2e test
    // tmux_session_with_five_panes_and_different_clis.
    // -----------------------------------------------------------------------

    #[test]
    fn pane_count_matches_input_for_two_panes() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("feat/auth", "/tmp/wt1", "claude"))
            .add_pane(make_pane("feat/api", "/tmp/wt2", "codex"))
            .build()
            .unwrap();

        let cmds = session.command_strings();
        let send_keys = commands_containing(&cmds, "send-keys");
        assert_eq!(
            send_keys.len(),
            2,
            "should send commands to exactly 2 panes"
        );
    }

    #[test]
    fn pane_count_matches_input_for_five_panes() {
        let mut builder = TmuxSessionBuilder::new("proj");
        for i in 0..5 {
            builder = builder.add_pane(make_pane(
                &format!("feat/b{i}"),
                &format!("/tmp/wt{i}"),
                "claude",
            ));
        }
        let session = builder.build().unwrap();

        let cmds = session.command_strings();
        let send_keys = commands_containing(&cmds, "send-keys");
        assert_eq!(
            send_keys.len(),
            5,
            "should send commands to exactly 5 panes"
        );
    }

    #[test]
    fn building_with_no_panes_is_an_error() {
        let result = TmuxSessionBuilder::new("proj").build();
        assert!(result.is_err(), "session with no panes should fail");
    }

    // -----------------------------------------------------------------------
    // AC: Correct commands sent to panes
    // Dry-run contract: users see these exact commands in --dry-run output,
    // so the format (cd + cli, Enter, pane indices) is user-facing.
    // -----------------------------------------------------------------------

    #[test]
    fn each_pane_receives_cd_and_cli_command() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("feat/auth", "/home/user/wt-auth", "claude"))
            .add_pane(make_pane("feat/api", "/home/user/wt-api", "gemini"))
            .build()
            .unwrap();

        let cmds = session.command_strings();
        let send_keys = commands_containing(&cmds, "send-keys");

        // Pane 0 uses -c on new-session for its directory, so just runs the CLI
        assert!(
            send_keys[0].contains("claude"),
            "first pane should run claude"
        );
        // Subsequent panes use cd && cli
        assert!(
            send_keys[1].contains("cd /home/user/wt-api && gemini"),
            "second pane should cd into wt-api and run gemini"
        );
    }

    #[test]
    fn pane_commands_are_submitted_with_enter() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("main", "/tmp/wt", "aider"))
            .build()
            .unwrap();

        let cmds = session.command_strings();
        let send_keys = commands_containing(&cmds, "send-keys");
        assert!(
            send_keys[0].contains("Enter"),
            "send-keys should press Enter to submit"
        );
    }

    #[test]
    fn each_pane_targets_a_distinct_pane_index() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("feat/a", "/tmp/a", "claude"))
            .add_pane(make_pane("feat/b", "/tmp/b", "codex"))
            .add_pane(make_pane("feat/c", "/tmp/c", "gemini"))
            .build()
            .unwrap();

        let cmds = session.command_strings();
        let send_keys = commands_containing(&cmds, "send-keys");

        assert!(
            send_keys[0].contains(":0.0"),
            "first pane should target :0.0"
        );
        assert!(
            send_keys[1].contains(":0.1"),
            "second pane should target :0.1"
        );
        assert!(
            send_keys[2].contains(":0.2"),
            "third pane should target :0.2"
        );
    }

    // -----------------------------------------------------------------------
    // AC: Pane titles show branch and CLI
    // Dry-run contract: title format is user-visible in both --dry-run output
    // and tmux pane borders. Actual tmux titles verified by e2e test
    // tmux_session_with_five_panes_and_different_clis.
    // -----------------------------------------------------------------------

    #[test]
    fn each_pane_is_titled_with_branch_and_cli() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("feat/auth", "/tmp/wt1", "claude"))
            .add_pane(make_pane("fix/api", "/tmp/wt2", "gemini"))
            .build()
            .unwrap();

        let cmds = session.command_strings();
        let select_panes = commands_containing(&cmds, "select-pane");

        assert_eq!(select_panes.len(), 2, "each pane should get a title");
        assert!(
            select_panes[0].contains("feat/auth \u{2192} claude"),
            "first pane title should be 'feat/auth \u{2192} claude', got: {}",
            select_panes[0]
        );
        assert!(
            select_panes[1].contains("fix/api \u{2192} gemini"),
            "second pane title should be 'fix/api \u{2192} gemini', got: {}",
            select_panes[1]
        );
    }

    #[test]
    fn pane_border_status_is_configured() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .build()
            .unwrap();

        let cmds = session.command_strings();
        assert!(
            cmds.iter()
                .any(|c| c.contains("pane-border-status") && c.contains("top")),
            "should configure pane-border-status to top"
        );
        assert!(
            cmds.iter()
                .any(|c| c.contains("pane-border-format") && c.contains("#{pane_title}")),
            "should configure pane-border-format to show pane title"
        );
    }

    // -----------------------------------------------------------------------
    // AC: Mouse mode (per-session, configurable, default on)
    // Dry-run contract: users see mouse config in --dry-run output.
    // Actual tmux behavior verified by e2e test tmux_mouse_mode_enabled_by_default.
    // -----------------------------------------------------------------------

    #[test]
    fn mouse_mode_enabled_by_default() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .build()
            .unwrap();

        let cmds = session.command_strings();
        assert!(
            cmds.iter().any(|c| c.contains("mouse on")),
            "mouse should be enabled by default"
        );
    }

    #[test]
    fn mouse_mode_can_be_disabled() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .mouse_mode(false)
            .build()
            .unwrap();

        let cmds = session.command_strings();
        assert!(
            !cmds.iter().any(|c| c.contains("mouse on")),
            "no mouse-on command should be emitted when disabled"
        );
    }

    // -----------------------------------------------------------------------
    // AC: Session liveness and collision handling
    // Behavioral: tests against a real tmux server — verifies observable
    // outcomes (session exists, session is killed, names are unique).
    // -----------------------------------------------------------------------

    /// Helper to create a detached tmux session for testing.
    fn create_test_session(name: &str) {
        let output = std::process::Command::new("tmux")
            .args(["new-session", "-d", "-s", name])
            .output()
            .expect("create tmux session");
        assert!(
            output.status.success(),
            "failed to create test session '{name}'"
        );
    }

    /// Helper to kill a tmux session, ignoring errors.
    fn cleanup_session(name: &str) {
        let _ = kill_session(name);
    }

    #[test]
    #[serial_test::serial]
    fn is_session_alive_returns_false_for_nonexistent() {
        let alive = is_session_alive("paw-definitely-does-not-exist-12345").unwrap();
        assert!(!alive);
    }

    #[test]
    #[serial_test::serial]
    fn session_lifecycle_create_check_kill() {
        let name = "paw-unit-test-lifecycle";
        cleanup_session(name);

        create_test_session(name);
        assert!(is_session_alive(name).unwrap());

        kill_session(name).unwrap();
        assert!(!is_session_alive(name).unwrap());
    }

    #[test]
    #[serial_test::serial]
    fn resolve_session_name_returns_base_when_no_collision() {
        let name = resolve_session_name("unit-test-no-collision-xyz").unwrap();
        assert_eq!(name, "paw-unit-test-no-collision-xyz");
    }

    #[test]
    #[serial_test::serial]
    fn resolve_session_name_appends_suffix_on_collision() {
        let base_name = "paw-unit-test-collision";
        cleanup_session(base_name);
        cleanup_session(&format!("{base_name}-2"));

        create_test_session(base_name);

        let resolved = resolve_session_name("unit-test-collision").unwrap();
        assert_eq!(resolved, format!("{base_name}-2"));

        cleanup_session(base_name);
    }

    // -----------------------------------------------------------------------
    // AC: pipe-pane logging integration
    // Dry-run contract: verifies the pipe-pane command is queued correctly.
    // -----------------------------------------------------------------------

    #[test]
    fn pipe_pane_queues_correct_command() {
        let mut session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("feat/auth", "/tmp/wt1", "claude"))
            .build()
            .unwrap();

        let log_path = std::path::PathBuf::from("/repo/.git-paw/logs/paw-proj/feat--auth.log");
        session.pipe_pane("paw-proj:0.0", &log_path);

        let cmds = session.command_strings();
        let pipe_cmds: Vec<&String> = cmds.iter().filter(|c| c.contains("pipe-pane")).collect();
        assert_eq!(pipe_cmds.len(), 1);
        assert!(pipe_cmds[0].contains("pipe-pane -o -t paw-proj:0.0"));
        assert!(pipe_cmds[0].contains("cat >> /repo/.git-paw/logs/paw-proj/feat--auth.log"));
    }

    // --- Gap #10: pipe-pane conditional on logging ---

    #[test]
    fn session_without_pipe_pane_has_no_pipe_pane_commands() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .build()
            .unwrap();

        let cmds = session.command_strings();
        assert!(
            !cmds.iter().any(|c| c.contains("pipe-pane")),
            "session built without pipe_pane calls should have no pipe-pane commands"
        );
    }

    #[test]
    fn session_with_pipe_pane_differs_from_without() {
        let session_without = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .build()
            .unwrap();
        let cmds_without = session_without.command_strings();

        let mut session_with = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .build()
            .unwrap();
        let log_path = std::path::PathBuf::from("/repo/.git-paw/logs/paw-proj/main.log");
        session_with.pipe_pane("paw-proj:0.0", &log_path);
        let cmds_with = session_with.command_strings();

        assert_ne!(
            cmds_without, cmds_with,
            "command lists should differ when pipe-pane is added"
        );
        assert!(
            cmds_with.iter().any(|c| c.contains("pipe-pane")),
            "session with pipe_pane should contain pipe-pane command"
        );
    }

    // --- Gap #11: pipe-pane ordering ---

    #[test]
    fn pipe_pane_appears_after_send_keys_for_pane() {
        let mut session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("feat/auth", "/tmp/wt1", "claude"))
            .add_pane(make_pane("feat/api", "/tmp/wt2", "codex"))
            .build()
            .unwrap();

        let log0 = std::path::PathBuf::from("/repo/logs/feat--auth.log");
        let log1 = std::path::PathBuf::from("/repo/logs/feat--api.log");
        session.pipe_pane("paw-proj:0.0", &log0);
        session.pipe_pane("paw-proj:0.1", &log1);

        let cmds = session.command_strings();

        // Find the last send-keys index and first pipe-pane index
        let last_send_keys = cmds
            .iter()
            .rposition(|c| c.contains("send-keys"))
            .expect("should have send-keys");
        let first_pipe_pane = cmds
            .iter()
            .position(|c| c.contains("pipe-pane"))
            .expect("should have pipe-pane");

        assert!(
            first_pipe_pane > last_send_keys,
            "pipe-pane commands (index {first_pipe_pane}) should appear after \
             all send-keys commands (last at index {last_send_keys})"
        );
    }

    #[test]
    fn pipe_pane_appears_in_dry_run_output() {
        let mut session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .build()
            .unwrap();

        let log_path = std::path::PathBuf::from("/repo/.git-paw/logs/paw-proj/main.log");
        session.pipe_pane("paw-proj:0.0", &log_path);

        let cmds = session.command_strings();
        assert!(
            cmds.iter().any(|c| c.starts_with("tmux pipe-pane")),
            "dry-run output should include pipe-pane command"
        );
    }

    // -----------------------------------------------------------------------
    // AC: set_environment emits correct commands
    // -----------------------------------------------------------------------

    #[test]
    fn set_environment_emits_correct_tmux_command() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .set_environment("GIT_PAW_BROKER_URL", "http://127.0.0.1:9119")
            .build()
            .unwrap();

        let cmds = session.command_strings();
        let env_cmds = commands_containing(&cmds, "set-environment");
        assert_eq!(env_cmds.len(), 1, "should have exactly one set-environment");
        assert!(
            env_cmds[0]
                .contains("set-environment -t paw-proj GIT_PAW_BROKER_URL http://127.0.0.1:9119"),
            "set-environment command should contain key and value, got: {}",
            env_cmds[0]
        );
    }

    #[test]
    fn set_environment_appears_before_send_keys() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("feat/a", "/tmp/a", "claude"))
            .add_pane(make_pane("feat/b", "/tmp/b", "codex"))
            .set_environment("GIT_PAW_BROKER_URL", "http://127.0.0.1:9119")
            .build()
            .unwrap();

        let cmds = session.command_strings();
        let first_env = cmds
            .iter()
            .position(|c| c.contains("set-environment"))
            .expect("should have set-environment");
        let first_send = cmds
            .iter()
            .position(|c| c.contains("send-keys"))
            .expect("should have send-keys");

        assert!(
            first_env < first_send,
            "set-environment (index {first_env}) should appear before first send-keys (index {first_send})"
        );
    }

    #[test]
    fn multiple_env_vars_both_appear() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .set_environment("A", "1")
            .set_environment("B", "2")
            .build()
            .unwrap();

        let cmds = session.command_strings();
        let env_cmds = commands_containing(&cmds, "set-environment");
        assert_eq!(
            env_cmds.len(),
            2,
            "should have two set-environment commands"
        );
        assert!(env_cmds[0].contains("A 1"));
        assert!(env_cmds[1].contains("B 2"));
    }

    #[test]
    fn set_environment_in_dry_run_output() {
        let session = TmuxSessionBuilder::new("proj")
            .add_pane(make_pane("main", "/tmp/wt", "claude"))
            .set_environment("MY_VAR", "my_val")
            .build()
            .unwrap();

        let cmds = session.command_strings();
        assert!(
            cmds.iter().any(|c| c.starts_with("tmux set-environment")),
            "dry-run output should include set-environment command"
        );
    }

    #[test]
    #[serial_test::serial]
    fn built_session_can_be_executed_and_killed() {
        let project = "unit-test-execute";
        let session_name = format!("paw-{project}");
        cleanup_session(&session_name);

        let session = TmuxSessionBuilder::new(project)
            .add_pane(make_pane("main", "/tmp", "echo hello"))
            .build()
            .unwrap();

        session.execute().unwrap();
        assert!(is_session_alive(&session_name).unwrap());

        kill_session(&session_name).unwrap();
        assert!(!is_session_alive(&session_name).unwrap());
    }
}