workmux 0.1.262

An opinionated workflow tool that orchestrates git worktrees and tmux
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
//! Agent-specific conversation forking for resuming sessions across worktrees.

use anyhow::{Context, Result, bail};
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::time::SystemTime;

/// Information about a conversation session
#[derive(Debug, Clone)]
pub struct SessionInfo {
    /// Session UUID
    pub id: String,
    /// Full path to the session transcript
    pub path: PathBuf,
    /// Last modification time
    pub timestamp: SystemTime,
}

/// Trait for agent-specific conversation forking
pub trait ConversationForker: Send + Sync {
    /// Find the most recent conversation for a worktree path
    fn find_latest_conversation(&self, worktree_path: &Path) -> Result<Option<SessionInfo>>;

    /// Find a specific conversation by session ID (or prefix)
    fn find_conversation(
        &self,
        worktree_path: &Path,
        session_id: &str,
    ) -> Result<Option<SessionInfo>>;

    /// Make the session resumable from the target worktree.
    ///
    /// Agents that scope conversations by project directory copy the session
    /// there; agents that fork natively leave the stored session alone.
    /// Returns the session UUID for resume args.
    fn prepare_fork(&self, session: &SessionInfo, target_worktree: &Path) -> Result<String>;

    /// CLI args that resume a specific session in `worktree_path`
    /// (e.g., ["--resume", uuid])
    fn resume_args(&self, session_id: &str, worktree_path: &Path) -> Vec<String>;
}

/// Claude Code conversation forker
pub struct ClaudeForker {
    config_dir: PathBuf,
}

impl ClaudeForker {
    pub fn new() -> Self {
        let config_dir = std::env::var("CLAUDE_CONFIG_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| {
                home::home_dir()
                    .expect("could not determine home directory")
                    .join(".claude")
            });
        Self { config_dir }
    }

    /// Encode a path the same way Claude Code does for project directories.
    /// Non-alphanumeric characters (except `-`) become `-`.
    fn encode_path(path: &Path) -> String {
        path.to_string_lossy()
            .chars()
            .map(|c| {
                if c.is_alphanumeric() || c == '-' {
                    c
                } else {
                    '-'
                }
            })
            .collect()
    }

    fn projects_dir(&self) -> PathBuf {
        self.config_dir.join("projects")
    }

    fn project_dir_for(&self, worktree_path: &Path) -> PathBuf {
        self.projects_dir().join(Self::encode_path(worktree_path))
    }

    /// List all .jsonl sessions in a project dir, sorted by mtime descending
    fn list_sessions(&self, project_dir: &Path) -> Result<Vec<SessionInfo>> {
        if !project_dir.exists() {
            return Ok(Vec::new());
        }

        let mut sessions = Vec::new();
        for entry in fs::read_dir(project_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) == Some("jsonl")
                && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
            {
                let metadata = fs::metadata(&path)?;
                sessions.push(SessionInfo {
                    id: stem.to_string(),
                    path: path.clone(),
                    timestamp: metadata.modified()?,
                });
            }
        }

        sessions.sort_by_key(|session| std::cmp::Reverse(session.timestamp));
        Ok(sessions)
    }
}

impl ConversationForker for ClaudeForker {
    fn find_latest_conversation(&self, worktree_path: &Path) -> Result<Option<SessionInfo>> {
        let project_dir = self.project_dir_for(worktree_path);
        let sessions = self.list_sessions(&project_dir)?;
        Ok(sessions.into_iter().next())
    }

    fn find_conversation(
        &self,
        worktree_path: &Path,
        session_id: &str,
    ) -> Result<Option<SessionInfo>> {
        let project_dir = self.project_dir_for(worktree_path);
        let sessions = self.list_sessions(&project_dir)?;
        // Match by exact ID or prefix
        Ok(sessions
            .into_iter()
            .find(|s| s.id == session_id || s.id.starts_with(session_id)))
    }

    fn prepare_fork(&self, session: &SessionInfo, target_worktree: &Path) -> Result<String> {
        let target_dir = self.project_dir_for(target_worktree);
        fs::create_dir_all(&target_dir).context("Failed to create target project directory")?;

        // Copy the .jsonl file
        let target_jsonl = target_dir.join(format!("{}.jsonl", session.id));
        fs::copy(&session.path, &target_jsonl).context("Failed to copy conversation file")?;

        // Copy the session subdirectory if it exists (tool results, subagent data)
        let source_dir = session.path.parent().unwrap();
        let session_subdir = source_dir.join(&session.id);
        if session_subdir.is_dir() {
            let target_subdir = target_dir.join(&session.id);
            crate::workflow::file_ops::copy_dir_recursive(&session_subdir, &target_subdir)
                .context("Failed to copy session data directory")?;
        }

        Ok(session.id.clone())
    }

    fn resume_args(&self, session_id: &str, _worktree_path: &Path) -> Vec<String> {
        // The conversation was copied into the target worktree's project
        // directory, so Claude resumes it wherever it is launched.
        vec!["--resume".to_string(), session_id.to_string()]
    }
}

/// Length of the session UUID that terminates a Codex rollout filename.
const UUID_LEN: usize = 36;

/// Session sources that `codex fork` can resume. Other sources (`exec`, `mcp`,
/// subagents) are recorded but not offered as fork targets.
const CODEX_INTERACTIVE_SOURCES: &[&str] = &["cli", "vscode"];

/// Codex conversation forker.
///
/// Codex forks natively via `codex fork <session-id>` and keeps rollouts in its
/// own store, so workmux only resolves which session to fork.
pub struct CodexForker {
    codex_home: PathBuf,
    /// Session the current process was launched from, if any.
    thread_id: Option<String>,
}

/// Fields workmux reads from the `session_meta` line of a Codex rollout.
struct CodexSessionMeta {
    id: String,
    cwd: Option<PathBuf>,
    interactive: bool,
}

impl CodexForker {
    pub fn new() -> Self {
        let codex_home = std::env::var("CODEX_HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|_| {
                home::home_dir()
                    .expect("could not determine home directory")
                    .join(".codex")
            });
        let thread_id = std::env::var("CODEX_THREAD_ID")
            .ok()
            .filter(|id| !id.trim().is_empty());
        Self {
            codex_home,
            thread_id,
        }
    }

    fn sessions_dir(&self) -> PathBuf {
        self.codex_home.join("sessions")
    }

    /// Extract the session UUID from `rollout-<timestamp>-<uuid>.jsonl`.
    fn session_id_from_filename(path: &Path) -> Option<String> {
        let stem = path.file_stem().and_then(|s| s.to_str())?;
        let rest = stem.strip_prefix("rollout-")?;
        rest.get(rest.len().checked_sub(UUID_LEN)?..)
            .map(|id| id.to_string())
    }

    /// Read the `session_meta` line at the head of a rollout file.
    fn read_session_meta(path: &Path) -> Option<CodexSessionMeta> {
        let file = fs::File::open(path).ok()?;
        let mut head = String::new();
        BufReader::new(file).read_line(&mut head).ok()?;
        let line: serde_json::Value = serde_json::from_str(head.trim()).ok()?;
        if line.get("type").and_then(|t| t.as_str()) != Some("session_meta") {
            return None;
        }

        let payload = line.get("payload")?;
        let id = payload
            .get("id")
            .or_else(|| payload.get("session_id"))
            .and_then(|id| id.as_str())?
            .to_string();
        let cwd = payload
            .get("cwd")
            .and_then(|cwd| cwd.as_str())
            .map(PathBuf::from);
        // Sources recorded as objects describe subagent and internal threads.
        // Rollouts predating the field are interactive CLI sessions.
        let interactive = match payload.get("source") {
            None => true,
            Some(source) => source
                .as_str()
                .is_some_and(|source| CODEX_INTERACTIVE_SOURCES.contains(&source)),
        };

        Some(CodexSessionMeta {
            id,
            cwd,
            interactive,
        })
    }

    /// List every rollout file under `sessions/`, most recently modified first.
    fn list_sessions(&self) -> Result<Vec<SessionInfo>> {
        let mut sessions = Vec::new();
        collect_rollouts(&self.sessions_dir(), &mut sessions)?;
        sessions.sort_by_key(|session| std::cmp::Reverse(session.timestamp));
        Ok(sessions)
    }

    /// Return the session as a fork candidate when the rollout is interactive
    /// and was recorded in `worktree_path`, carrying the recorded session ID.
    fn fork_candidate(session: &SessionInfo, worktree_path: &Path) -> Option<SessionInfo> {
        let meta = Self::read_session_meta(&session.path)?;
        if !meta.interactive {
            return None;
        }
        if !meta
            .cwd
            .as_deref()
            .is_some_and(|cwd| paths_match(cwd, worktree_path))
        {
            return None;
        }
        Some(SessionInfo {
            id: meta.id,
            ..session.clone()
        })
    }
}

impl ConversationForker for CodexForker {
    fn find_latest_conversation(&self, worktree_path: &Path) -> Result<Option<SessionInfo>> {
        let sessions = self.list_sessions()?;

        // Codex exports the session it launched a command from, which is a more
        // precise answer than the newest rollout recorded for this directory.
        if let Some(thread_id) = &self.thread_id
            && let Some(session) = sessions.iter().find(|session| &session.id == thread_id)
        {
            return Ok(Some(session.clone()));
        }

        Ok(sessions
            .iter()
            .find_map(|session| Self::fork_candidate(session, worktree_path)))
    }

    fn find_conversation(
        &self,
        worktree_path: &Path,
        session_id: &str,
    ) -> Result<Option<SessionInfo>> {
        let matches: Vec<SessionInfo> = self
            .list_sessions()?
            .iter()
            .filter(|session| session.id.starts_with(session_id))
            .filter_map(|session| Self::fork_candidate(session, worktree_path))
            .collect();

        if let Some(exact) = matches.iter().find(|session| session.id == session_id) {
            return Ok(Some(exact.clone()));
        }
        if matches.len() > 1 {
            let ids: Vec<&str> = matches.iter().map(|session| session.id.as_str()).collect();
            bail!(
                "Multiple conversations match '{}': {}\n\
                 Use a longer session ID prefix.",
                session_id,
                ids.join(", ")
            );
        }
        Ok(matches.into_iter().next())
    }

    fn prepare_fork(&self, session: &SessionInfo, _target_worktree: &Path) -> Result<String> {
        // `codex fork` reads the session from Codex's own store and writes a new
        // rollout, so the parent conversation stays untouched.
        if !session.path.exists() {
            bail!(
                "Codex conversation file no longer exists: {}",
                session.path.display()
            );
        }
        Ok(session.id.clone())
    }

    fn resume_args(&self, session_id: &str, worktree_path: &Path) -> Vec<String> {
        // Without `-C`, Codex asks whether to run the fork in the directory the
        // parent session recorded or the current one, defaulting to the parent.
        // Passing the worktree pins the fork to it and skips the prompt.
        vec![
            "fork".to_string(),
            "-C".to_string(),
            worktree_path.to_string_lossy().to_string(),
            session_id.to_string(),
        ]
    }
}

/// Recursively collect `rollout-*.jsonl` files under `dir`.
fn collect_rollouts(dir: &Path, sessions: &mut Vec<SessionInfo>) -> Result<()> {
    if !dir.is_dir() {
        return Ok(());
    }

    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_dir() {
            collect_rollouts(&path, sessions)?;
            continue;
        }
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        if let Some(id) = CodexForker::session_id_from_filename(&path) {
            let metadata = entry.metadata()?;
            sessions.push(SessionInfo {
                id,
                path,
                timestamp: metadata.modified()?,
            });
        }
    }
    Ok(())
}

/// Compare paths, resolving symlinks so `/tmp` and `/private/tmp` agree.
fn paths_match(left: &Path, right: &Path) -> bool {
    if left == right {
        return true;
    }
    match (left.canonicalize(), right.canonicalize()) {
        (Ok(left), Ok(right)) => left == right,
        _ => false,
    }
}

/// Resolve a conversation forker for the given agent name.
/// Returns None if the agent doesn't support conversation forking.
pub fn resolve_forker(agent_name: &str) -> Option<Box<dyn ConversationForker>> {
    // Normalize: strip path, take basename
    let basename = agent_name.rsplit('/').next().unwrap_or(agent_name);
    let name = basename
        .split_whitespace()
        .next()
        .unwrap_or(basename)
        .to_lowercase();

    match name.as_str() {
        "claude" => Some(Box::new(ClaudeForker::new())),
        "codex" => Some(Box::new(CodexForker::new())),
        _ => None,
    }
}

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

    #[test]
    fn test_encode_path() {
        assert_eq!(
            ClaudeForker::encode_path(Path::new("/Users/raine/code/myproject")),
            "-Users-raine-code-myproject"
        );
    }

    #[test]
    fn test_encode_path_worktree() {
        assert_eq!(
            ClaudeForker::encode_path(Path::new("/Users/raine/code/myproject__worktrees/feature")),
            "-Users-raine-code-myproject--worktrees-feature"
        );
    }

    #[test]
    fn test_encode_path_dots_and_underscores() {
        assert_eq!(
            ClaudeForker::encode_path(Path::new("/home/user/.config/my_app")),
            "-home-user--config-my-app"
        );
    }

    #[test]
    fn test_resolve_forker_claude() {
        assert!(resolve_forker("claude").is_some());
        assert!(resolve_forker("Claude").is_some());
        assert!(resolve_forker("/usr/bin/claude --flag").is_some());
    }

    #[test]
    fn test_resolve_forker_codex() {
        assert!(resolve_forker("codex").is_some());
        assert!(resolve_forker("Codex").is_some());
        assert!(resolve_forker("/usr/local/bin/codex --yolo").is_some());
    }

    #[test]
    fn test_resolve_forker_unknown() {
        assert!(resolve_forker("unknown-agent").is_none());
    }

    #[test]
    fn test_list_sessions_ordering() {
        let tmp = tempfile::tempdir().unwrap();
        let forker = ClaudeForker {
            config_dir: tmp.path().to_path_buf(),
        };
        let project_dir = forker.project_dir_for(Path::new("/test/project"));
        fs::create_dir_all(&project_dir).unwrap();

        // Create two session files with a small delay to ensure different mtimes
        let old_file = project_dir.join("old-session.jsonl");
        fs::write(&old_file, "{}").unwrap();

        // Set the old file's mtime to the past
        let old_time = std::time::SystemTime::now() - std::time::Duration::from_secs(10);
        filetime::set_file_mtime(&old_file, filetime::FileTime::from_system_time(old_time))
            .unwrap();

        let new_file = project_dir.join("new-session.jsonl");
        fs::write(&new_file, "{}").unwrap();

        let sessions = forker.list_sessions(&project_dir).unwrap();
        assert_eq!(sessions.len(), 2);
        assert_eq!(sessions[0].id, "new-session");
        assert_eq!(sessions[1].id, "old-session");
    }

    #[test]
    fn test_list_sessions_empty_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let forker = ClaudeForker {
            config_dir: tmp.path().to_path_buf(),
        };
        let sessions = forker
            .list_sessions(Path::new("/nonexistent/path"))
            .unwrap();
        assert!(sessions.is_empty());
    }

    // === Codex ===

    /// Write a rollout file mirroring Codex's `sessions/YYYY/MM/DD` layout.
    fn write_codex_rollout(
        codex_home: &Path,
        day: &str,
        session_id: &str,
        cwd: &Path,
        source: serde_json::Value,
        modified_offset_secs: u64,
    ) -> PathBuf {
        let (year, month, day_of_month) = (&day[0..4], &day[5..7], &day[8..10]);
        let dir = codex_home
            .join("sessions")
            .join(year)
            .join(month)
            .join(day_of_month);
        fs::create_dir_all(&dir).unwrap();

        let path = dir.join(format!("rollout-{}T00-00-00-{}.jsonl", day, session_id));
        let meta = serde_json::json!({
            "timestamp": format!("{}T00:00:00.000Z", day),
            "type": "session_meta",
            "payload": {
                "id": session_id,
                "session_id": session_id,
                "timestamp": format!("{}T00:00:00Z", day),
                "cwd": cwd,
                "originator": "codex",
                "cli_version": "0.147.0",
                "source": source,
            },
        });
        fs::write(&path, format!("{}\n", meta)).unwrap();

        let modified =
            std::time::SystemTime::now() - std::time::Duration::from_secs(modified_offset_secs);
        filetime::set_file_mtime(&path, filetime::FileTime::from_system_time(modified)).unwrap();
        path
    }

    fn codex_forker(codex_home: &Path, thread_id: Option<&str>) -> CodexForker {
        CodexForker {
            codex_home: codex_home.to_path_buf(),
            thread_id: thread_id.map(|id| id.to_string()),
        }
    }

    #[test]
    fn test_codex_session_id_from_filename() {
        assert_eq!(
            CodexForker::session_id_from_filename(Path::new(
                "/home/u/.codex/sessions/2026/08/12/rollout-2026-08-12T23-59-14-019ff7c5-a9d3-77b3-8cab-253e05f6f729.jsonl"
            )),
            Some("019ff7c5-a9d3-77b3-8cab-253e05f6f729".to_string())
        );
        assert_eq!(
            CodexForker::session_id_from_filename(Path::new("/tmp/notes.jsonl")),
            None
        );
    }

    #[test]
    fn test_codex_find_latest_conversation_scopes_to_worktree() {
        let tmp = tempfile::tempdir().unwrap();
        let codex_home = tmp.path().join("codex");
        let worktree = tmp.path().join("project");
        let other = tmp.path().join("other-project");
        fs::create_dir_all(&worktree).unwrap();
        fs::create_dir_all(&other).unwrap();

        write_codex_rollout(
            &codex_home,
            "2026-08-11",
            "11111111-1111-1111-1111-111111111111",
            &worktree,
            serde_json::json!("cli"),
            60,
        );
        // Newer, but recorded for a different working directory.
        write_codex_rollout(
            &codex_home,
            "2026-08-12",
            "22222222-2222-2222-2222-222222222222",
            &other,
            serde_json::json!("cli"),
            10,
        );

        let session = codex_forker(&codex_home, None)
            .find_latest_conversation(&worktree)
            .unwrap()
            .expect("expected a session for the worktree");
        assert_eq!(session.id, "11111111-1111-1111-1111-111111111111");
    }

    #[test]
    fn test_codex_find_latest_conversation_skips_non_interactive_sources() {
        let tmp = tempfile::tempdir().unwrap();
        let codex_home = tmp.path().join("codex");
        let worktree = tmp.path().join("project");
        fs::create_dir_all(&worktree).unwrap();

        write_codex_rollout(
            &codex_home,
            "2026-08-11",
            "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
            &worktree,
            serde_json::json!("vscode"),
            60,
        );
        write_codex_rollout(
            &codex_home,
            "2026-08-12",
            "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
            &worktree,
            serde_json::json!("exec"),
            30,
        );
        write_codex_rollout(
            &codex_home,
            "2026-08-12",
            "cccccccc-cccc-cccc-cccc-cccccccccccc",
            &worktree,
            serde_json::json!({"subagent": {"depth": 1}}),
            10,
        );

        let session = codex_forker(&codex_home, None)
            .find_latest_conversation(&worktree)
            .unwrap()
            .expect("expected an interactive session");
        assert_eq!(session.id, "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
    }

    #[test]
    fn test_codex_find_latest_conversation_prefers_current_thread() {
        let tmp = tempfile::tempdir().unwrap();
        let codex_home = tmp.path().join("codex");
        let worktree = tmp.path().join("project");
        fs::create_dir_all(&worktree).unwrap();

        write_codex_rollout(
            &codex_home,
            "2026-08-11",
            "dddddddd-dddd-dddd-dddd-dddddddddddd",
            &worktree,
            serde_json::json!("cli"),
            60,
        );
        write_codex_rollout(
            &codex_home,
            "2026-08-12",
            "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee",
            &worktree,
            serde_json::json!("cli"),
            10,
        );

        let session = codex_forker(&codex_home, Some("dddddddd-dddd-dddd-dddd-dddddddddddd"))
            .find_latest_conversation(&worktree)
            .unwrap()
            .expect("expected the session workmux was launched from");
        assert_eq!(session.id, "dddddddd-dddd-dddd-dddd-dddddddddddd");
    }

    #[test]
    fn test_codex_find_latest_conversation_none_for_empty_home() {
        let tmp = tempfile::tempdir().unwrap();
        let worktree = tmp.path().join("project");
        fs::create_dir_all(&worktree).unwrap();

        let session = codex_forker(&tmp.path().join("codex"), None)
            .find_latest_conversation(&worktree)
            .unwrap();
        assert!(session.is_none());
    }

    #[test]
    fn test_codex_find_conversation_by_prefix() {
        let tmp = tempfile::tempdir().unwrap();
        let codex_home = tmp.path().join("codex");
        let worktree = tmp.path().join("project");
        fs::create_dir_all(&worktree).unwrap();

        write_codex_rollout(
            &codex_home,
            "2026-08-12",
            "019ff7c5-a9d3-77b3-8cab-253e05f6f729",
            &worktree,
            serde_json::json!("cli"),
            10,
        );
        let forker = codex_forker(&codex_home, None);

        let session = forker
            .find_conversation(&worktree, "019ff7c5")
            .unwrap()
            .expect("expected a prefix match");
        assert_eq!(session.id, "019ff7c5-a9d3-77b3-8cab-253e05f6f729");

        assert!(
            forker
                .find_conversation(&worktree, "does-not-exist")
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn test_codex_find_conversation_ambiguous_prefix_errors() {
        let tmp = tempfile::tempdir().unwrap();
        let codex_home = tmp.path().join("codex");
        let worktree = tmp.path().join("project");
        fs::create_dir_all(&worktree).unwrap();

        write_codex_rollout(
            &codex_home,
            "2026-08-11",
            "019ff7c5-1111-1111-1111-111111111111",
            &worktree,
            serde_json::json!("cli"),
            60,
        );
        write_codex_rollout(
            &codex_home,
            "2026-08-12",
            "019ff7c5-2222-2222-2222-222222222222",
            &worktree,
            serde_json::json!("cli"),
            10,
        );

        let error = codex_forker(&codex_home, None)
            .find_conversation(&worktree, "019ff7c5")
            .unwrap_err()
            .to_string();
        assert!(error.contains("Multiple conversations match"), "{}", error);
    }

    #[test]
    fn test_codex_find_conversation_prefers_exact_match() {
        let tmp = tempfile::tempdir().unwrap();
        let codex_home = tmp.path().join("codex");
        let worktree = tmp.path().join("project");
        fs::create_dir_all(&worktree).unwrap();

        // One session id is a prefix of the other only in the leading segment,
        // so an exact request must not be reported as ambiguous.
        write_codex_rollout(
            &codex_home,
            "2026-08-11",
            "019ff7c5-1111-1111-1111-111111111111",
            &worktree,
            serde_json::json!("cli"),
            60,
        );
        write_codex_rollout(
            &codex_home,
            "2026-08-12",
            "019ff7c5-2222-2222-2222-222222222222",
            &worktree,
            serde_json::json!("cli"),
            10,
        );

        let session = codex_forker(&codex_home, None)
            .find_conversation(&worktree, "019ff7c5-1111-1111-1111-111111111111")
            .unwrap()
            .expect("expected the exact match");
        assert_eq!(session.id, "019ff7c5-1111-1111-1111-111111111111");
    }

    #[test]
    fn test_codex_prepare_fork_leaves_parent_rollout_untouched() {
        let tmp = tempfile::tempdir().unwrap();
        let codex_home = tmp.path().join("codex");
        let worktree = tmp.path().join("project");
        let target = tmp.path().join("target");
        fs::create_dir_all(&worktree).unwrap();
        fs::create_dir_all(&target).unwrap();

        let rollout = write_codex_rollout(
            &codex_home,
            "2026-08-12",
            "019ff7c5-a9d3-77b3-8cab-253e05f6f729",
            &worktree,
            serde_json::json!("cli"),
            10,
        );
        let original = fs::read_to_string(&rollout).unwrap();
        let forker = codex_forker(&codex_home, None);
        let session = forker.find_latest_conversation(&worktree).unwrap().unwrap();

        let session_id = forker.prepare_fork(&session, &target).unwrap();

        assert_eq!(session_id, "019ff7c5-a9d3-77b3-8cab-253e05f6f729");
        assert_eq!(fs::read_to_string(&rollout).unwrap(), original);
        assert!(!target.join("sessions").exists());
    }

    #[test]
    fn test_codex_resume_args_pin_the_fork_to_the_worktree() {
        let tmp = tempfile::tempdir().unwrap();
        assert_eq!(
            codex_forker(tmp.path(), None).resume_args(
                "019ff7c5-a9d3-77b3-8cab-253e05f6f729",
                Path::new("/code/project__worktrees/feature")
            ),
            vec![
                "fork".to_string(),
                "-C".to_string(),
                "/code/project__worktrees/feature".to_string(),
                "019ff7c5-a9d3-77b3-8cab-253e05f6f729".to_string()
            ]
        );
    }

    #[test]
    fn test_fork_conversation_copies_files() {
        let tmp = tempfile::tempdir().unwrap();
        let forker = ClaudeForker {
            config_dir: tmp.path().to_path_buf(),
        };

        // Create source project dir with a session
        let source_dir = forker.project_dir_for(Path::new("/source/project"));
        fs::create_dir_all(&source_dir).unwrap();
        let session_file = source_dir.join("abc123.jsonl");
        fs::write(&session_file, "{\"test\": true}").unwrap();

        // Create session subdirectory with data
        let session_subdir = source_dir.join("abc123");
        fs::create_dir_all(&session_subdir).unwrap();
        fs::write(session_subdir.join("data.json"), "{}").unwrap();

        let session = SessionInfo {
            id: "abc123".to_string(),
            path: session_file,
            timestamp: std::time::SystemTime::now(),
        };

        let result = forker
            .prepare_fork(&session, Path::new("/target/project"))
            .unwrap();
        assert_eq!(result, "abc123");

        // Verify files were copied
        let target_dir = forker.project_dir_for(Path::new("/target/project"));
        assert!(target_dir.join("abc123.jsonl").exists());
        assert!(target_dir.join("abc123").join("data.json").exists());
    }

    #[test]
    fn test_find_conversation_by_prefix() {
        let tmp = tempfile::tempdir().unwrap();
        let forker = ClaudeForker {
            config_dir: tmp.path().to_path_buf(),
        };
        let project_dir = forker.project_dir_for(Path::new("/test/project"));
        fs::create_dir_all(&project_dir).unwrap();

        fs::write(project_dir.join("abc123-def456.jsonl"), "{}").unwrap();

        let session = forker
            .find_conversation(Path::new("/test/project"), "abc123")
            .unwrap();
        assert!(session.is_some());
        assert_eq!(session.unwrap().id, "abc123-def456");
    }
}