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
//! Session state persistence.
//!
//! Saves and loads session data to disk for recovery after crashes, reboots,
//! or `stop`. One session per repository, stored as JSON under the XDG data
//! directory (`~/.local/share/git-paw/sessions/`).

use std::fmt;
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::error::PawError;

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Status of a persisted session.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SessionStatus {
    /// Tmux session is (believed to be) running.
    Active,
    /// Tmux session has been stopped or crashed; state is recoverable.
    Stopped,
}

impl fmt::Display for SessionStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Active => write!(f, "active"),
            Self::Stopped => write!(f, "stopped"),
        }
    }
}

/// A worktree entry within a session.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorktreeEntry {
    /// The branch checked out in this worktree.
    pub branch: String,
    /// Absolute path to the worktree directory.
    pub worktree_path: PathBuf,
    /// The AI CLI assigned to this worktree.
    pub cli: String,
    /// Whether git-paw created this branch (vs. it already existing).
    /// When `true`, `purge` will delete the branch after removing the worktree.
    #[serde(default)]
    pub branch_created: bool,
}

/// Persisted session state for a git-paw session.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[allow(clippy::struct_field_names)]
pub struct Session {
    /// Tmux session name (also used as the filename stem).
    pub session_name: String,
    /// Absolute path to the repository root.
    pub repo_path: PathBuf,
    /// Human-readable project name (derived from the repo directory name).
    pub project_name: String,
    /// ISO 8601 timestamp of session creation (UTC).
    #[serde(
        serialize_with = "serialize_system_time",
        deserialize_with = "deserialize_system_time"
    )]
    pub created_at: SystemTime,
    /// Current session status.
    pub status: SessionStatus,
    /// Worktrees managed by this session.
    pub worktrees: Vec<WorktreeEntry>,

    /// Broker port (when broker is enabled).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub broker_port: Option<u16>,

    /// Broker bind address (when broker is enabled).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub broker_bind: Option<String>,

    /// Path to the broker log file (when broker is enabled).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub broker_log_path: Option<PathBuf>,
}

impl Session {
    /// Returns the effective status by combining the on-disk status with a
    /// tmux liveness check.
    ///
    /// If the recorded status is `Active` but the tmux session is not alive,
    /// returns `Stopped`.
    pub fn effective_status(&self, is_tmux_alive: impl Fn(&str) -> bool) -> SessionStatus {
        if self.status == SessionStatus::Active && !is_tmux_alive(&self.session_name) {
            return SessionStatus::Stopped;
        }
        self.status.clone()
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Atomically writes a session to disk.
///
/// Serializes the session to JSON, writes to a temporary file in the same
/// directory, then renames to the final path. This prevents corruption if
/// the process is killed mid-write.
pub fn save_session(session: &Session) -> Result<(), PawError> {
    save_session_in(session, &sessions_dir()?)
}

/// Finds the session associated with a given repository path.
///
/// Scans all `.json` files in the sessions directory and returns the first
/// session whose `repo_path` matches the given path.
pub fn find_session_for_repo(repo_path: &Path) -> Result<Option<Session>, PawError> {
    find_session_for_repo_in(repo_path, &sessions_dir()?)
}

/// Deletes a session file by name.
///
/// Returns `Ok(())` even if the file does not exist (idempotent).
pub fn delete_session(session_name: &str) -> Result<(), PawError> {
    delete_session_in(session_name, &sessions_dir()?)
}

// ---------------------------------------------------------------------------
// Directory-parameterized implementations (public for integration tests)
// ---------------------------------------------------------------------------

/// Atomically writes a session to the given directory.
pub fn save_session_in(session: &Session, dir: &Path) -> Result<(), PawError> {
    fs::create_dir_all(dir)
        .map_err(|e| PawError::SessionError(format!("failed to create sessions dir: {e}")))?;

    let json = serde_json::to_string_pretty(session)
        .map_err(|e| PawError::SessionError(format!("failed to serialize session: {e}")))?;

    let final_path = dir.join(format!("{}.json", session.session_name));
    let tmp_path = dir.join(format!("{}.tmp", session.session_name));

    fs::write(&tmp_path, json.as_bytes())
        .map_err(|e| PawError::SessionError(format!("failed to write temp file: {e}")))?;

    fs::rename(&tmp_path, &final_path)
        .map_err(|e| PawError::SessionError(format!("failed to rename temp file: {e}")))?;

    Ok(())
}

/// Loads a session by name from the given directory.
pub fn load_session_from(session_name: &str, dir: &Path) -> Result<Option<Session>, PawError> {
    let path = dir.join(format!("{session_name}.json"));

    let contents = match fs::read_to_string(&path) {
        Ok(s) => s,
        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
        Err(e) => {
            return Err(PawError::SessionError(format!(
                "failed to read session file: {e}"
            )));
        }
    };

    let session: Session = serde_json::from_str(&contents)
        .map_err(|e| PawError::SessionError(format!("failed to parse session file: {e}")))?;

    Ok(Some(session))
}

/// Finds the session for a repo path, scanning the given directory.
pub fn find_session_for_repo_in(repo_path: &Path, dir: &Path) -> Result<Option<Session>, PawError> {
    let entries = match fs::read_dir(dir) {
        Ok(e) => e,
        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
        Err(e) => {
            return Err(PawError::SessionError(format!(
                "failed to read sessions dir: {e}"
            )));
        }
    };

    for entry in entries {
        let entry =
            entry.map_err(|e| PawError::SessionError(format!("failed to read dir entry: {e}")))?;
        let path = entry.path();

        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }

        let contents = fs::read_to_string(&path).map_err(|e| {
            PawError::SessionError(format!("failed to read {}: {e}", path.display()))
        })?;

        let session: Session = match serde_json::from_str(&contents) {
            Ok(s) => s,
            Err(_) => continue, // skip malformed files
        };

        if session.repo_path == repo_path {
            return Ok(Some(session));
        }
    }

    Ok(None)
}

/// Deletes a session file by name from the given directory.
pub fn delete_session_in(session_name: &str, dir: &Path) -> Result<(), PawError> {
    let path = dir.join(format!("{session_name}.json"));

    match fs::remove_file(&path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
        Err(e) => Err(PawError::SessionError(format!(
            "failed to delete session file: {e}"
        ))),
    }
}

// ---------------------------------------------------------------------------
// Path helpers
// ---------------------------------------------------------------------------

/// Returns the sessions directory (`~/.local/share/git-paw/sessions/`).
///
/// Also used by the broker to place `broker.log` alongside session state.
pub fn session_state_dir() -> Result<PathBuf, PawError> {
    sessions_dir()
}

/// Returns the sessions directory (`~/.local/share/git-paw/sessions/`).
fn sessions_dir() -> Result<PathBuf, PawError> {
    let base = crate::dirs::data_dir().ok_or_else(|| {
        PawError::SessionError("could not determine XDG data directory".to_string())
    })?;
    Ok(base.join("git-paw").join("sessions"))
}

// ---------------------------------------------------------------------------
// ISO 8601 helpers
// ---------------------------------------------------------------------------

/// Formats a `SystemTime` as an ISO 8601 UTC string (`YYYY-MM-DDTHH:MM:SSZ`).
fn format_iso8601(time: SystemTime) -> Result<String, PawError> {
    let secs = time
        .duration_since(UNIX_EPOCH)
        .map_err(|e| PawError::SessionError(format!("time before unix epoch: {e}")))?
        .as_secs();

    let (year, month, day, hour, min, sec) = secs_to_civil(secs);
    Ok(format!(
        "{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}Z"
    ))
}

/// Parses an ISO 8601 UTC string (`YYYY-MM-DDTHH:MM:SSZ`) into a `SystemTime`.
fn parse_iso8601(s: &str) -> Result<SystemTime, PawError> {
    let err = || PawError::SessionError(format!("invalid ISO 8601 timestamp: {s}"));

    // Expected format: YYYY-MM-DDTHH:MM:SSZ
    let s = s.strip_suffix('Z').ok_or_else(err)?;
    let (date, time) = s.split_once('T').ok_or_else(err)?;

    let date_parts: Vec<&str> = date.split('-').collect();
    let time_parts: Vec<&str> = time.split(':').collect();

    if date_parts.len() != 3 || time_parts.len() != 3 {
        return Err(err());
    }

    let year: u64 = date_parts[0].parse().map_err(|_| err())?;
    let month: u64 = date_parts[1].parse().map_err(|_| err())?;
    let day: u64 = date_parts[2].parse().map_err(|_| err())?;
    let hour: u64 = time_parts[0].parse().map_err(|_| err())?;
    let min: u64 = time_parts[1].parse().map_err(|_| err())?;
    let sec: u64 = time_parts[2].parse().map_err(|_| err())?;

    let secs = civil_to_secs(year, month, day, hour, min, sec).ok_or_else(err)?;
    Ok(UNIX_EPOCH + Duration::from_secs(secs))
}

/// Converts seconds since Unix epoch to (year, month, day, hour, minute, second) in UTC.
fn secs_to_civil(secs: u64) -> (u64, u64, u64, u64, u64, u64) {
    let sec_of_day = secs % 86400;
    let hour = sec_of_day / 3600;
    let min = (sec_of_day % 3600) / 60;
    let sec = sec_of_day % 60;

    // Days since epoch (1970-01-01)
    // Algorithm from Howard Hinnant's chrono-compatible date library.
    #[allow(clippy::cast_possible_wrap)]
    let mut days = (secs / 86400).cast_signed();

    days += 719_468; // shift epoch from 1970-01-01 to 0000-03-01
    let era = days / 146_097;
    let doe = days - era * 146_097; // day of era [0, 146096]
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // day of year [0, 365]
    let mp = (5 * doy + 2) / 153; // month index [0, 11]
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };

    #[allow(clippy::cast_sign_loss)]
    (
        y.cast_unsigned(),
        m.cast_unsigned(),
        d.cast_unsigned(),
        hour,
        min,
        sec,
    )
}

/// Converts (year, month, day, hour, min, sec) to seconds since Unix epoch.
fn civil_to_secs(year: u64, month: u64, day: u64, hour: u64, min: u64, sec: u64) -> Option<u64> {
    if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || min > 59 || sec > 59 {
        return None;
    }

    #[allow(clippy::cast_possible_wrap)]
    let y = year.cast_signed();
    #[allow(clippy::cast_possible_wrap)]
    let m = month.cast_signed();
    #[allow(clippy::cast_possible_wrap)]
    let d = day.cast_signed();

    // Shift to March-based year
    let (y, m) = if m <= 2 { (y - 1, m + 9) } else { (y, m - 3) };
    let era = y / 400;
    let yoe = y - era * 400;
    let doy = (153 * m + 2) / 5 + d - 1;
    let doe = 365 * yoe + yoe / 4 - yoe / 100 + doy;
    let days = era * 146_097 + doe - 719_468;

    if days < 0 {
        return None;
    }

    #[allow(clippy::cast_sign_loss)]
    Some(days.cast_unsigned() * 86400 + hour * 3600 + min * 60 + sec)
}

// ---------------------------------------------------------------------------
// Serde helpers for SystemTime ↔ ISO 8601
// ---------------------------------------------------------------------------

fn serialize_system_time<S: Serializer>(time: &SystemTime, ser: S) -> Result<S::Ok, S::Error> {
    let s = format_iso8601(*time).map_err(serde::ser::Error::custom)?;
    ser.serialize_str(&s)
}

fn deserialize_system_time<'de, D: Deserializer<'de>>(de: D) -> Result<SystemTime, D::Error> {
    let s: String = Deserialize::deserialize(de)?;
    parse_iso8601(&s).map_err(serde::de::Error::custom)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    /// Creates a sample session with 3 worktrees for testing.
    fn sample_session() -> Session {
        Session {
            session_name: "paw-my-project".to_string(),
            repo_path: PathBuf::from("/Users/test/code/my-project"),
            project_name: "my-project".to_string(),
            created_at: UNIX_EPOCH + Duration::from_secs(1_711_200_000),
            status: SessionStatus::Active,
            worktrees: vec![
                WorktreeEntry {
                    branch: "feature/auth".to_string(),
                    worktree_path: PathBuf::from("/Users/test/code/my-project-feature-auth"),
                    cli: "claude".to_string(),
                    branch_created: false,
                },
                WorktreeEntry {
                    branch: "fix/api".to_string(),
                    worktree_path: PathBuf::from("/Users/test/code/my-project-fix-api"),
                    cli: "gemini".to_string(),
                    branch_created: false,
                },
                WorktreeEntry {
                    branch: "feature/logging".to_string(),
                    worktree_path: PathBuf::from("/Users/test/code/my-project-feature-logging"),
                    cli: "claude".to_string(),
                    branch_created: false,
                },
            ],
            broker_port: None,
            broker_bind: None,
            broker_log_path: None,
        }
    }

    // -- save_session: GIVEN an active session with 3 worktrees,
    //    WHEN save_session() is called, THEN JSON file created with all fields --

    #[test]
    fn saved_session_can_be_loaded_with_all_fields_intact() {
        let dir = TempDir::new().unwrap();
        let session = sample_session();
        save_session_in(&session, dir.path()).unwrap();

        let loaded = load_session_from("paw-my-project", dir.path())
            .unwrap()
            .expect("session should exist");

        assert_eq!(loaded.session_name, "paw-my-project");
        assert_eq!(
            loaded.repo_path,
            PathBuf::from("/Users/test/code/my-project")
        );
        assert_eq!(loaded.project_name, "my-project");
        assert_eq!(loaded.created_at, session.created_at);
        assert_eq!(loaded.status, SessionStatus::Active);
        assert_eq!(loaded.worktrees.len(), 3);
        assert_eq!(loaded.worktrees[0].branch, "feature/auth");
        assert_eq!(loaded.worktrees[0].cli, "claude");
        assert_eq!(loaded.worktrees[1].branch, "fix/api");
        assert_eq!(loaded.worktrees[1].cli, "gemini");
        assert_eq!(loaded.worktrees[2].branch, "feature/logging");
    }

    // -- save_session: saving again replaces the previous state --

    #[test]
    fn saving_again_replaces_previous_state() {
        let dir = TempDir::new().unwrap();
        let mut session = sample_session();
        save_session_in(&session, dir.path()).unwrap();

        session.status = SessionStatus::Stopped;
        session.worktrees.pop();
        save_session_in(&session, dir.path()).unwrap();

        let loaded = load_session_from("paw-my-project", dir.path())
            .unwrap()
            .expect("session should exist");

        assert_eq!(loaded.status, SessionStatus::Stopped);
        assert_eq!(loaded.worktrees.len(), 2);
    }

    // -- load_session: WHEN load_session("nonexistent") is called, THEN returns None --

    #[test]
    fn loading_nonexistent_session_returns_none() {
        let dir = TempDir::new().unwrap();
        let result = load_session_from("nonexistent", dir.path()).unwrap();
        assert!(result.is_none());
    }

    // -- find_session_for_repo: GIVEN two sessions,
    //    WHEN find_session_for_repo is called, THEN returns the matching one --

    #[test]
    fn finds_correct_session_among_multiple_by_repo_path() {
        let dir = TempDir::new().unwrap();

        let mut session_a = sample_session();
        session_a.session_name = "paw-project-a".to_string();
        session_a.repo_path = PathBuf::from("/Users/test/code/project-a");

        let mut session_b = sample_session();
        session_b.session_name = "paw-project-b".to_string();
        session_b.repo_path = PathBuf::from("/Users/test/code/project-b");

        save_session_in(&session_a, dir.path()).unwrap();
        save_session_in(&session_b, dir.path()).unwrap();

        let found = find_session_for_repo_in(Path::new("/Users/test/code/project-b"), dir.path())
            .unwrap()
            .expect("should find session for project-b");

        assert_eq!(found.session_name, "paw-project-b");
        assert_eq!(found.repo_path, PathBuf::from("/Users/test/code/project-b"));
    }

    #[test]
    fn find_returns_none_when_no_repo_matches() {
        let dir = TempDir::new().unwrap();
        save_session_in(&sample_session(), dir.path()).unwrap();

        let found =
            find_session_for_repo_in(Path::new("/Users/test/code/other-project"), dir.path())
                .unwrap();
        assert!(found.is_none());
    }

    #[test]
    fn find_returns_none_when_no_sessions_exist() {
        let dir = TempDir::new().unwrap();
        let missing = dir.path().join("does-not-exist");
        let found = find_session_for_repo_in(Path::new("/any"), &missing).unwrap();
        assert!(found.is_none());
    }

    // -- delete_session: removes file, load returns None afterwards --

    #[test]
    fn deleted_session_is_no_longer_loadable() {
        let dir = TempDir::new().unwrap();
        save_session_in(&sample_session(), dir.path()).unwrap();

        delete_session_in("paw-my-project", dir.path()).unwrap();

        let loaded = load_session_from("paw-my-project", dir.path()).unwrap();
        assert!(loaded.is_none());
    }

    #[test]
    fn deleting_nonexistent_session_succeeds() {
        let dir = TempDir::new().unwrap();
        delete_session_in("nonexistent", dir.path()).unwrap();
    }

    // -- Status check: combines file existence + tmux liveness --

    #[test]
    fn file_says_active_and_tmux_alive_means_active() {
        let session = sample_session();
        assert_eq!(session.effective_status(|_| true), SessionStatus::Active);
    }

    #[test]
    fn file_says_active_but_tmux_dead_means_stopped() {
        let session = sample_session();
        assert_eq!(session.effective_status(|_| false), SessionStatus::Stopped);
    }

    #[test]
    fn file_says_stopped_stays_stopped_regardless_of_tmux() {
        let mut session = sample_session();
        session.status = SessionStatus::Stopped;
        // Even if tmux is somehow alive, stopped means stopped.
        assert_eq!(session.effective_status(|_| true), SessionStatus::Stopped);
    }

    // -- SessionStatus Display --

    #[test]
    fn session_status_displays_as_lowercase_string() {
        assert_eq!(SessionStatus::Active.to_string(), "active");
        assert_eq!(SessionStatus::Stopped.to_string(), "stopped");
    }

    // -- Recovery: save → tmux dies → state has everything to reconstruct --

    // -- Broker fields --

    #[test]
    fn session_with_broker_fields_round_trips() {
        let dir = TempDir::new().unwrap();
        let mut session = sample_session();
        session.broker_port = Some(9119);
        session.broker_bind = Some("127.0.0.1".to_string());
        session.broker_log_path = Some(PathBuf::from("/tmp/broker.log"));

        save_session_in(&session, dir.path()).unwrap();

        let loaded = load_session_from("paw-my-project", dir.path())
            .unwrap()
            .expect("session should exist");

        assert_eq!(loaded.broker_port, Some(9119));
        assert_eq!(loaded.broker_bind.as_deref(), Some("127.0.0.1"));
        assert_eq!(
            loaded.broker_log_path,
            Some(PathBuf::from("/tmp/broker.log"))
        );
    }

    #[test]
    fn v020_session_json_loads_with_broker_fields_as_none() {
        let dir = TempDir::new().unwrap();
        // Simulate a v0.2.0 session JSON that has no broker fields
        let json = r#"{
            "session_name": "paw-legacy",
            "repo_path": "/tmp/legacy-repo",
            "project_name": "legacy",
            "created_at": "2024-03-23T12:00:00Z",
            "status": "active",
            "worktrees": []
        }"#;
        std::fs::write(dir.path().join("paw-legacy.json"), json).unwrap();

        let loaded = load_session_from("paw-legacy", dir.path())
            .unwrap()
            .expect("session should load");

        assert!(loaded.broker_port.is_none());
        assert!(loaded.broker_bind.is_none());
        assert!(loaded.broker_log_path.is_none());
        assert_eq!(loaded.session_name, "paw-legacy");
    }

    #[test]
    fn session_with_broker_fields_serializes_them() {
        let dir = TempDir::new().unwrap();
        let mut session = sample_session();
        session.broker_port = Some(9119);
        session.broker_bind = Some("127.0.0.1".to_string());
        session.broker_log_path = Some(PathBuf::from("/tmp/broker.log"));
        save_session_in(&session, dir.path()).unwrap();

        let json = std::fs::read_to_string(dir.path().join("paw-my-project.json")).unwrap();
        assert!(
            json.contains("broker_port"),
            "JSON should contain broker_port"
        );
        assert!(
            json.contains("broker_bind"),
            "JSON should contain broker_bind"
        );
        assert!(
            json.contains("broker_log_path"),
            "JSON should contain broker_log_path"
        );
    }

    #[test]
    fn session_without_broker_fields_omits_them_from_json() {
        let dir = TempDir::new().unwrap();
        let session = sample_session(); // broker fields are all None
        save_session_in(&session, dir.path()).unwrap();

        let json = std::fs::read_to_string(dir.path().join("paw-my-project.json")).unwrap();
        assert!(
            !json.contains("broker_port"),
            "JSON should not contain broker_port when None"
        );
        assert!(
            !json.contains("broker_bind"),
            "JSON should not contain broker_bind when None"
        );
        assert!(
            !json.contains("broker_log_path"),
            "JSON should not contain broker_log_path when None"
        );
    }

    // -- Recovery with broker fields --

    #[test]
    fn recovery_after_tmux_crash_has_all_data_to_reconstruct() {
        let dir = TempDir::new().unwrap();
        let session = sample_session();
        save_session_in(&session, dir.path()).unwrap();

        // Simulate: tmux crashed, we reload from disk.
        let recovered = load_session_from("paw-my-project", dir.path())
            .unwrap()
            .expect("session state should survive tmux crash");

        // Has the tmux session name to recreate.
        assert_eq!(recovered.session_name, "paw-my-project");
        // Has the repo path to cd into.
        assert_eq!(
            recovered.repo_path,
            PathBuf::from("/Users/test/code/my-project")
        );
        // Has every worktree's branch, path, and CLI — enough to relaunch.
        assert_eq!(recovered.worktrees.len(), 3);
        for wt in &recovered.worktrees {
            assert!(!wt.branch.is_empty());
            assert!(!wt.worktree_path.as_os_str().is_empty());
            assert!(!wt.cli.is_empty());
        }
        // Status correctly reflects that tmux is gone.
        assert_eq!(
            recovered.effective_status(|_| false),
            SessionStatus::Stopped
        );
    }
}