kaeru 0.1.8

Reopens your terminal tabs, and the coding agent sessions in them, after the terminal closes or the computer restarts.
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
//! Agents: programs that run in a tab and can resume a conversation, such as
//! Claude Code or Codex. There is one module per agent, and `kaeru hook`
//! runs from each agent's hook when a session starts.

pub mod claude;
pub mod codex;

use std::io::{BufRead, BufReader, Read};
use std::path::PathBuf;

use anyhow::{Context, Result, bail};
use serde::Deserialize;

use crate::engine::note::{AgentNote, Note, ShellNote};
use crate::engine::rules::Liveness;
use crate::os;
use crate::procs::system::SystemTable;
use crate::procs::{self, ProcInfo, ProcessTable};
use crate::shells::shell_name;
use crate::store::{self, Store};
use crate::terminals::{self, Env};

/// An agent whose hook kaeru understands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum Agent {
    Claude,
    Codex,
}

/// The JSON that an agent's `SessionStart` hook reads on standard input.
/// Claude Code and Codex send the same fields.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
struct HookInput {
    /// The session's id, a UUID.
    session_id: String,
    /// The folder the session runs in.
    cwd: String,
    /// Where the agent keeps the conversation.
    #[serde(default)]
    transcript_path: Option<String>,
    /// Why the session started, such as `startup` or `resume`.
    #[serde(default)]
    source: Option<String>,
}

/// What an agent's hook tells kaeru about a session that starts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionStart {
    /// The agent's id for the conversation.
    pub session_id: String,
    /// The folder the session runs in.
    pub cwd: String,
    /// Where the agent keeps the conversation, if the hook says.
    pub transcript_path: Option<String>,
    /// Why the session started, such as `startup` or `resume`, if the hook
    /// says.
    pub source: Option<String>,
}

impl Agent {
    /// Returns the agent's id, which notes store, such as `claude`. It never
    /// changes after a release.
    pub fn id(self) -> &'static str {
        match self {
            Agent::Claude => "claude",
            Agent::Codex => "codex",
        }
    }

    /// Returns the agent whose id is `id`, as notes store it.
    pub fn from_id(id: &str) -> Option<Agent> {
        [Agent::Claude, Agent::Codex]
            .into_iter()
            .find(|agent| agent.id() == id)
    }

    /// Returns the agent's name, as the picker shows it.
    pub fn name(self) -> &'static str {
        match self {
            Agent::Claude => "Claude Code",
            Agent::Codex => "Codex",
        }
    }

    /// Returns the file that holds a session's conversation, if there is
    /// one. A session that never got a message has none, and then it starts
    /// fresh.
    pub fn conversation_file(self, note: &AgentNote) -> Option<PathBuf> {
        let recorded = note
            .transcript
            .as_ref()
            .map(PathBuf::from)
            .filter(|path| path.is_file());
        match self {
            Agent::Claude => recorded
                .or_else(|| claude::find_transcript(&claude::config_dir()?, &note.conversation)),
            Agent::Codex => recorded,
        }
    }

    /// Returns the command that brings a session back in its tab. It resumes
    /// the conversation when the conversation's file exists.
    pub fn resume_command(self, note: &AgentNote) -> Vec<String> {
        let exists = self.conversation_file(note).is_some();
        match self {
            Agent::Claude => claude::resume_command(&note.conversation, exists),
            Agent::Codex => codex::resume_command(&note.conversation, exists),
        }
    }

    /// Returns what the hook's input says about the session.
    ///
    /// # Errors
    ///
    /// Fails when the input isn't JSON of the hook's shape, or when its
    /// session id isn't a UUID, which also keeps it safe to put in a command
    /// line.
    fn parse(self, input: &str) -> Result<SessionStart> {
        // Some programs put a byte order mark before what they pipe.
        let input: HookInput = serde_json::from_str(input.trim_start_matches('\u{feff}'))?;
        if !is_uuid(&input.session_id) {
            bail!("not a {} session id: {:?}", self.id(), input.session_id);
        }
        Ok(SessionStart {
            session_id: input.session_id,
            cwd: input.cwd,
            transcript_path: input.transcript_path,
            source: input.source,
        })
    }

    /// Returns whether a process is this agent's.
    fn is_process(self, process: &ProcInfo) -> bool {
        let command_line = process.command_line.as_deref().unwrap_or_default();
        match self {
            Agent::Claude => claude::is_claude_process(&process.name, command_line),
            Agent::Codex => codex::is_codex_process(&process.name, command_line),
        }
    }

    /// Returns whether the agent's process runs an interactive session,
    /// which runs in a tab, rather than a one-off run.
    fn is_interactive(self, process: &ProcInfo) -> bool {
        match self {
            Agent::Claude => {
                claude::is_interactive(process.command_line.as_deref().unwrap_or_default())
            }
            Agent::Codex => codex::is_interactive(&process.arguments),
        }
    }

    /// Returns the process id of a session from the agent's own records, for
    /// when the hook's process tree doesn't lead to the agent.
    fn registered_pid(self, session_id: &str) -> Option<u32> {
        match self {
            Agent::Claude => claude::registered_pid(&claude::config_dir()?, session_id),
            Agent::Codex => None,
        }
    }
}

/// Returns whether `text` is a UUID: groups of 8, 4, 4, 4 and 12 hex digits.
/// Agents use UUIDs as session ids.
pub fn is_uuid(text: &str) -> bool {
    let groups: Vec<&str> = text.split('-').collect();
    groups.len() == 5
        && groups.iter().zip([8, 4, 4, 4, 12]).all(|(group, length)| {
            group.len() == length && group.chars().all(|c| c.is_ascii_hexdigit())
        })
}

/// Runs an agent's hook, for `kaeru hook <agent>`. It prints nothing and
/// always succeeds, to avoid breaking the agent that runs it. Problems go to
/// the log.
pub fn run_hook(agent: Agent) -> Result<()> {
    let mut bytes = Vec::new();
    if std::io::stdin().read_to_end(&mut bytes).is_err() {
        return Ok(());
    }
    let input = String::from_utf8_lossy(&bytes);
    if let Ok(store) = Store::open()
        && let Err(error) = record(&store, agent, &input)
    {
        store.log(&format!("hook {}: {error:#}", agent.id()));
    }
    Ok(())
}

/// Writes the note of the session that the hook reports, replacing earlier
/// notes of the same conversation, and deletes the notes of closed tabs.
fn record(store: &Store, agent: Agent, input: &str) -> Result<()> {
    let start = agent.parse(input)?;
    let mut table = SystemTable::snapshot();
    let mut lineage = table.lineage(std::process::id());
    let index = match lineage.iter().position(|process| agent.is_process(process)) {
        Some(index) => index,
        None => {
            let pid = agent
                .registered_pid(&start.session_id)
                .context("the agent's process isn't above the hook")?;
            lineage = table.lineage(pid);
            if !lineage
                .first()
                .is_some_and(|process| agent.is_process(process))
            {
                bail!("process {pid} isn't the agent's");
            }
            0
        }
    };
    let from_agent = &lineage[index..];
    let session = os::session_id()?;
    let new = if agent == Agent::Codex && codex::is_shared_server(&from_agent[0].arguments) {
        server_session_note(store, start, &mut table, &session)
    } else if agent.is_interactive(&from_agent[0]) {
        let env: Env = std::env::vars().collect();
        let shells: Vec<ShellNote> = store
            .notes()
            .into_iter()
            .filter_map(|stored| match stored.note {
                Note::Shell(shell) => Some(shell),
                Note::Agent(_) => None,
            })
            .collect();
        // The tab's shell that the snippet names, when it still runs.
        let named = env
            .get(SHELL_PID_VAR)
            .and_then(|pid| pid.parse::<u32>().ok())
            .and_then(|pid| shells.iter().find(|shell| shell.process.pid == pid))
            .filter(|shell| procs::liveness(&table, &shell.process) == Liveness::Running)
            .map(|shell| NamedShell {
                note: shell.clone(),
                exe: table
                    .get(shell.process.pid)
                    .and_then(|process| process.exe)
                    .map(|exe| exe.display().to_string()),
            });
        agent_note(
            agent,
            start,
            from_agent,
            &env,
            &session,
            &shells,
            named.as_ref(),
        )?
    } else {
        None
    };
    let Some(new) = new else {
        return Ok(());
    };
    let (path, new) = save_agent_note(store, new)?;
    // A conversation runs in one place at a time, so an earlier note of it,
    // for example from before it was resumed, is done.
    for stored in store.notes() {
        if let Note::Agent(other) = &stored.note
            && other.agent == new.agent
            && other.conversation == new.conversation
            && stored.path != path
        {
            store.remove(&stored);
        }
    }
    crate::install::adopt::refresh(store, &mut table);
    store::review(store, &table, &session, store.config().single_window_close);
    Ok(())
}

/// The variable in which the bash snippet names the process id of the tab's
/// shell, for the programs that run in the tab.
const SHELL_PID_VAR: &str = "KAERU_SHELL_PID";

/// The tab's shell that the bash snippet names in [`SHELL_PID_VAR`], with
/// its executable. An agent that runs through `winpty` in mintty, as Claude
/// Code often does there, has a lineage that ends at `winpty`, because MSYS
/// starts `winpty` with a fork, so the variable is how the hook finds the
/// tab.
struct NamedShell {
    /// The shell's note.
    note: ShellNote,
    /// The shell's executable, if it can be read.
    exe: Option<String>,
}

/// Saves an agent's note, and returns where it went and the note as saved.
/// A later note of the same agent process keeps the folder of the first one.
/// An agent can change folders while it runs, as Claude Code does when it
/// changes directory, and it reports the new folder at its next
/// `SessionStart`, such as after it compacts the conversation. Its tab still
/// comes back in the folder the session started in.
///
/// # Errors
///
/// Fails when the note can't be written.
fn save_agent_note(store: &Store, mut note: AgentNote) -> Result<(PathBuf, AgentNote)> {
    if let Ok(Note::Agent(earlier)) = store.read(&store.path_of(&Note::Agent(note.clone()))) {
        note.cwd = earlier.cwd;
    }
    let path = store.save(&Note::Agent(note.clone()))?;
    Ok((path, note))
}

/// Returns the note for an agent session, from the lineage that starts at the
/// agent's process, or `None` when the agent doesn't run in a tab of a known
/// terminal. When the lineage doesn't reach the terminal, the tab is the one
/// of the nearest process above the agent that has a note in `shells`, as
/// [`terminals::tab_or_noted`] decides.
///
/// # Errors
///
/// Fails when the lineage is empty or the agent's start time can't be read.
fn agent_note(
    agent: Agent,
    start: SessionStart,
    from_agent: &[ProcInfo],
    env: &Env,
    session: &str,
    shells: &[ShellNote],
    named: Option<&NamedShell>,
) -> Result<Option<AgentNote>> {
    let process = from_agent
        .first()
        .context("there is no agent process")?
        .to_ref()
        .context("the agent's start time can't be read")?;
    let (shell, shell_name, shell_exe, terminal) =
        match terminals::tab_or_noted(&terminals::all(), env, from_agent, shells) {
            Some((index, terminal)) => {
                // The tab's shell is the process that the terminal started,
                // unless that is the agent itself.
                let shell = from_agent.get(index).filter(|_| index > 0);
                (
                    shell.and_then(ProcInfo::to_ref),
                    shell.map(|shell| shell_name(&shell.name)),
                    shell
                        .and_then(|shell| shell.exe.as_ref())
                        .map(|exe| exe.display().to_string()),
                    terminal,
                )
            }
            None => {
                let Some(named) = named else {
                    return Ok(None);
                };
                let Some(terminal) = named.note.terminal.clone() else {
                    return Ok(None);
                };
                (
                    Some(named.note.process),
                    Some(named.note.shell.clone()),
                    named.exe.clone(),
                    terminal,
                )
            }
        };
    Ok(Some(AgentNote {
        process,
        agent: agent.id().into(),
        conversation: start.session_id,
        cwd: start.cwd,
        shell,
        shell_name,
        shell_exe,
        terminal: Some(terminal),
        transcript: start.transcript_path,
        session: session.into(),
        offered: false,
    }))
}

/// Returns the note for a Codex session that Codex's shared server runs, or
/// `None` when kaeru can't tell which tab shows it. The server runs the hook,
/// so the hook's process tree doesn't lead to the tab. kaeru looks for the
/// Codex window that shows the session instead, as [`codex::window_of`]
/// decides, and then for the tab that the window runs in. When it can't be
/// sure, it says why in the log, unless it placed the session before.
fn server_session_note(
    store: &Store,
    start: SessionStart,
    table: &mut SystemTable,
    session: &str,
) -> Option<AgentNote> {
    let found = table.find(codex::may_be_codex);
    let windows = codex_windows(table, &found);
    let from_window = start
        .transcript_path
        .as_deref()
        .and_then(first_line)
        .is_none_or(|line| codex::created_by_a_window(&line));
    let server_session = codex::ServerSession {
        id: &start.session_id,
        cwd: &start.cwd,
        source: start.source.as_deref(),
        from_window,
    };
    let listed: Vec<codex::Window> = windows
        .iter()
        .map(|(window, _)| as_window(window))
        .collect();
    let (index, exact) = match codex::window_of(&server_session, &listed) {
        codex::Shown::In { window, exact } => (window, exact),
        codex::Shown::Unsure(reason) => {
            if !is_placed(store, table, &start.session_id) {
                store.log(&format!(
                    "hook codex: kaeru can't tell which tab shows session {}, because \
                     {reason}. Starting Codex with --no-daemon makes this exact.",
                    start.session_id
                ));
            }
            return None;
        }
        codex::Shown::Nowhere => return None,
    };
    // A guess never moves a session that kaeru placed before.
    if !exact && is_placed(store, table, &start.session_id) {
        return None;
    }
    let (window, lineage) = &windows[index];
    let shells: Vec<ShellNote> = store
        .notes()
        .into_iter()
        .filter_map(|stored| match stored.note {
            Note::Shell(shell) => Some(shell),
            Note::Agent(_) => None,
        })
        .collect();
    let shell = tab_shell(lineage, &shells)?;
    Some(AgentNote {
        process: window.to_ref()?,
        agent: Agent::Codex.id().into(),
        conversation: start.session_id,
        cwd: start.cwd,
        shell_exe: lineage
            .iter()
            .find(|process| process.pid == shell.process.pid)
            .and_then(|process| process.exe.as_ref())
            .map(|exe| exe.display().to_string()),
        shell: Some(shell.process),
        shell_name: Some(shell.shell.clone()),
        terminal: shell.terminal.clone(),
        transcript: start.transcript_path,
        session: session.into(),
        offered: false,
    })
}

/// Returns the Codex windows that run on this computer, each with its
/// lineage, from the processes that may be Codex. Codex's npm launcher and
/// the native executable that it starts are one window, so a window that is
/// an ancestor of another one is left out.
pub fn codex_windows(
    table: &dyn ProcessTable,
    found: &[ProcInfo],
) -> Vec<(ProcInfo, Vec<ProcInfo>)> {
    let windows: Vec<(ProcInfo, Vec<ProcInfo>)> = found
        .iter()
        .filter(|process| {
            codex::is_codex_process(
                &process.name,
                process.command_line.as_deref().unwrap_or_default(),
            ) && codex::is_interactive(&process.arguments)
                && !codex::is_shared_server(&process.arguments)
        })
        .map(|process| (process.clone(), procs::lineage(table, process.pid)))
        .collect();
    windows
        .iter()
        .filter(|(window, _)| {
            !windows.iter().any(|(other, lineage)| {
                other.pid != window.pid && lineage.iter().any(|process| process.pid == window.pid)
            })
        })
        .cloned()
        .collect()
}

/// Returns what [`codex::window_of`] needs to know about a Codex window.
pub fn as_window(window: &ProcInfo) -> codex::Window {
    codex::Window {
        started_ms: window.started_ms.unwrap_or(0),
        arguments: window.arguments.clone(),
        folder: codex::window_folder(&window.arguments, window.cwd.as_deref())
            .map(|folder| folder.display().to_string()),
    }
}

/// Returns the note of the tab that a lineage runs in: the first process in
/// it that a shell note names.
fn tab_shell<'a>(lineage: &[ProcInfo], shells: &'a [ShellNote]) -> Option<&'a ShellNote> {
    lineage
        .iter()
        .find_map(|process| shells.iter().find(|shell| process.is(&shell.process)))
}

/// Returns whether a note places this Codex session in a window that still
/// runs.
fn is_placed(store: &Store, table: &dyn ProcessTable, conversation: &str) -> bool {
    store.notes().iter().any(|stored| match &stored.note {
        Note::Agent(note) => {
            note.agent == Agent::Codex.id()
                && note.conversation == conversation
                && procs::liveness(table, &note.process) == Liveness::Running
        }
        Note::Shell(_) => false,
    })
}

/// Returns the first line of a file, or `None` when it can't be read.
fn first_line(path: &str) -> Option<String> {
    let file = std::fs::File::open(path).ok()?;
    BufReader::new(file).lines().next()?.ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::note::{ProcessRef, TerminalRef};
    use crate::engine::rules::TerminalShape;
    use crate::procs::{fake::FakeTable, lineage};

    const ID: &str = "00000000-0000-4000-8000-000000000001";

    fn start() -> SessionStart {
        SessionStart {
            session_id: ID.into(),
            cwd: r"C:\Users\demo\code\mobile-app".into(),
            transcript_path: None,
            source: Some("startup".into()),
        }
    }

    /// Codex in a tab of Windows Terminal (10): the tab's shell (20), Codex's
    /// npm launcher (30) and the window it starts (40). Codex's shared server
    /// (50) has no parent, and a one-off run (60) runs in the same tab.
    fn codex_table() -> FakeTable {
        FakeTable::new(&[
            (10, None, "WindowsTerminal.exe", Some(1_000)),
            (20, Some(10), "powershell.exe", Some(2_000)),
            (30, Some(20), "node.exe", Some(3_000)),
            (40, Some(30), "codex.exe", Some(3_000)),
            (50, None, "codex.exe", Some(500)),
            (60, Some(20), "codex.exe", Some(4_000)),
        ])
        .with_command_line(30, r"node C:\npm\node_modules\@openai\codex\bin\codex.js")
        .with_arguments(40, &["codex.exe"])
        .with_arguments(
            50,
            &[
                "codex.exe",
                "app-server",
                "--listen",
                "unix://",
                "--managed-daemon",
            ],
        )
        .with_arguments(60, &["codex.exe", "exec", "fix the tests"])
        .with_cwd(40, r"C:\Users\demo\code\mobile-app")
    }

    #[test]
    fn a_codex_window_is_found_once_and_the_server_is_not_one() {
        let table = codex_table();
        let windows = codex_windows(&table, &table.processes());
        let pids: Vec<u32> = windows.iter().map(|(window, _)| window.pid).collect();
        assert_eq!(pids, [40]);
        let window = as_window(&windows[0].0);
        assert_eq!(
            window.folder.as_deref(),
            Some(r"C:\Users\demo\code\mobile-app")
        );
    }

    #[test]
    fn a_window_is_in_the_tab_whose_shell_it_runs_under() {
        let table = codex_table();
        let windows = codex_windows(&table, &table.processes());
        let shell = |pid, started_ms| ShellNote {
            process: crate::engine::note::ProcessRef { pid, started_ms },
            shell: "powershell".into(),
            cwd: r"C:\Users\demo".into(),
            terminal: None,
            session: "win-1".into(),
            offered: false,
            adopted_ms: None,
        };
        let shells = [shell(70, 7_000), shell(20, 2_000)];
        let found = tab_shell(&windows[0].1, &shells).unwrap();
        assert_eq!(found.process.pid, 20);
        assert!(tab_shell(&windows[0].1, &shells[..1]).is_none());
    }

    fn tab_env() -> Env {
        Env::from([("WT_SESSION".to_string(), "x".to_string())])
    }

    #[test]
    fn a_later_note_of_an_agent_keeps_the_folder_it_started_in() {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::at(dir.path().to_path_buf()).unwrap();
        let note = |pid, cwd: &str| AgentNote {
            process: crate::engine::note::ProcessRef {
                pid,
                started_ms: 3_000,
            },
            agent: Agent::Claude.id().into(),
            conversation: ID.into(),
            cwd: cwd.into(),
            shell: None,
            shell_name: None,
            shell_exe: None,
            terminal: None,
            transcript: None,
            session: "win-1".into(),
            offered: false,
        };
        let started_in = r"C:\Users\demo\code";
        save_agent_note(&store, note(30, started_in)).unwrap();
        // Claude Code moved to a subfolder, then compacted the conversation.
        let (path, saved) =
            save_agent_note(&store, note(30, r"C:\Users\demo\code\web-ui")).unwrap();
        assert_eq!(saved.cwd, started_in);
        let Ok(Note::Agent(on_disk)) = store.read(&path) else {
            panic!("the agent's note is on disk");
        };
        assert_eq!(on_disk.cwd, started_in);
        // Another process, such as the conversation resumed in another tab,
        // starts in its own folder.
        let elsewhere = r"C:\Users\demo\code\api-server";
        let (_, resumed) = save_agent_note(&store, note(31, elsewhere)).unwrap();
        assert_eq!(resumed.cwd, elsewhere);
    }

    #[test]
    fn an_agent_in_a_tab_is_linked_to_its_shell() {
        let table = FakeTable::new(&[
            (50, Some(40), "kaeru.exe", Some(5_000)),
            (40, Some(30), "bash.exe", Some(4_000)),
            (30, Some(20), "claude.exe", Some(3_000)),
            (20, Some(10), "powershell.exe", Some(2_000)),
            (10, None, "WindowsTerminal.exe", Some(1_000)),
        ]);
        let chain = lineage(&table, 50);
        let index = chain
            .iter()
            .position(|p| Agent::Claude.is_process(p))
            .unwrap();
        let note = agent_note(
            Agent::Claude,
            start(),
            &chain[index..],
            &tab_env(),
            "win-1",
            &[],
            None,
        );
        let note = note.unwrap().unwrap();
        assert_eq!(note.process.pid, 30);
        assert_eq!(note.shell.map(|shell| shell.pid), Some(20));
        assert_eq!(note.shell_name.as_deref(), Some("powershell"));
        assert_eq!(note.terminal.unwrap().process.pid, 10);
        assert_eq!(note.conversation, ID);
    }

    #[test]
    fn an_agent_in_a_mintty_window_is_linked_through_its_shell_s_note() {
        // Windows doesn't know the parent of mintty's bash, so the lineage
        // ends there, after the bash that bash forked to start the agent.
        let table = FakeTable::new(&[
            (30, Some(25), "claude.exe", Some(3_000)),
            (25, Some(20), "bash.exe", Some(2_500)),
            (20, None, "bash.exe", Some(2_000)),
        ]);
        let shell = ShellNote {
            process: ProcessRef {
                pid: 20,
                started_ms: 2_000,
            },
            shell: "bash".into(),
            cwd: r"C:\Users\demo\code\api-server".into(),
            terminal: Some(TerminalRef {
                adapter: "mintty".into(),
                process: ProcessRef {
                    pid: 10,
                    started_ms: 1_000,
                },
                shape: TerminalShape::SingleWindow,
                tab_id: None,
                profile: None,
                exe: None,
            }),
            session: "win-1".into(),
            offered: false,
            adopted_ms: None,
        };
        let chain = lineage(&table, 30);
        let note = agent_note(
            Agent::Claude,
            start(),
            &chain,
            &Env::new(),
            "win-1",
            &[],
            None,
        );
        assert!(note.unwrap().is_none(), "no terminal without the note");
        let note = agent_note(
            Agent::Claude,
            start(),
            &chain,
            &Env::new(),
            "win-1",
            std::slice::from_ref(&shell),
            None,
        );
        let note = note.unwrap().unwrap();
        assert_eq!(note.shell.map(|shell| shell.pid), Some(20));
        assert_eq!(note.shell_name.as_deref(), Some("bash"));
        assert_eq!(note.terminal.unwrap().adapter, "mintty");
        // Through winpty, the lineage ends before the shell, and the shell
        // that the snippet names is the tab.
        let table = FakeTable::new(&[
            (30, Some(25), "claude.exe", Some(3_000)),
            (25, Some(24), "winpty-agent.exe", Some(2_600)),
            (24, None, "winpty.exe", Some(2_500)),
        ]);
        let named = NamedShell {
            note: shell.clone(),
            exe: Some(r"C:\Program Files\Git\usr\bin\bash.exe".into()),
        };
        let chain = lineage(&table, 30);
        let note = agent_note(
            Agent::Claude,
            start(),
            &chain,
            &Env::new(),
            "win-1",
            std::slice::from_ref(&shell),
            Some(&named),
        );
        let note = note.unwrap().unwrap();
        assert_eq!(note.shell.map(|shell| shell.pid), Some(20));
        assert_eq!(note.shell_exe, named.exe);
        assert_eq!(note.terminal.unwrap().adapter, "mintty");
    }

    #[test]
    fn an_agent_that_the_terminal_started_has_no_shell() {
        let table = FakeTable::new(&[
            (30, Some(10), "claude.exe", Some(3_000)),
            (10, None, "WindowsTerminal.exe", Some(1_000)),
        ]);
        let note = agent_note(
            Agent::Claude,
            start(),
            &lineage(&table, 30),
            &tab_env(),
            "win-1",
            &[],
            None,
        );
        let note = note.unwrap().unwrap();
        assert_eq!(note.shell, None);
        assert!(note.terminal.is_some());
    }

    #[test]
    fn an_agent_outside_known_terminals_gets_no_note() {
        let table = FakeTable::new(&[
            (30, Some(20), "claude.exe", Some(3_000)),
            (20, None, "powershell.exe", Some(2_000)),
        ]);
        let note = agent_note(
            Agent::Claude,
            start(),
            &lineage(&table, 30),
            &tab_env(),
            "win-1",
            &[],
            None,
        );
        assert!(note.unwrap().is_none());
    }

    #[test]
    fn the_npm_build_of_claude_code_is_recognized() {
        let table = FakeTable::new(&[(30, None, "node.exe", Some(3_000))]).with_command_line(
            30,
            r"node C:\npm\node_modules\@anthropic-ai\claude-code\cli.js",
        );
        assert!(Agent::Claude.is_process(&lineage(&table, 30)[0]));
    }

    #[test]
    fn hook_input_may_start_with_a_byte_order_mark() {
        let json = format!("\u{feff}{{\"session_id\":\"{ID}\",\"cwd\":\"C:\\\\demo\"}}");
        assert_eq!(Agent::Claude.parse(&json).unwrap().session_id, ID);
    }

    #[test]
    fn parses_session_start_input() {
        let json = format!(
            r#"{{"session_id":"{ID}","transcript_path":"/home/demo/.claude/projects/x/{ID}.jsonl",
                "cwd":"/home/demo/code/mobile-app","hook_event_name":"SessionStart","source":"startup",
                "model":"some-model","permission_mode":"default"}}"#
        );
        for agent in [Agent::Claude, Agent::Codex] {
            let start = agent.parse(&json).unwrap();
            assert_eq!(start.session_id, ID);
            assert_eq!(start.cwd, "/home/demo/code/mobile-app");
            assert_eq!(start.source.as_deref(), Some("startup"));
            assert!(start.transcript_path.unwrap().ends_with(".jsonl"));
        }
    }

    #[test]
    fn rejects_bad_input() {
        assert!(Agent::Claude.parse("not json").is_err());
        assert!(
            Agent::Codex
                .parse(r#"{"session_id":"x; rm -rf /","cwd":"/"}"#)
                .is_err()
        );
    }

    #[test]
    fn session_ids_are_uuids() {
        assert!(is_uuid(ID));
        assert!(!is_uuid("00000000-0000-4000-8000-00000000000"));
        assert!(!is_uuid("0000000g-0000-4000-8000-000000000001"));
        assert!(!is_uuid(""));
    }

    #[test]
    fn codex_on_windows_is_found_below_its_launcher() {
        // The npm launcher runs in node and starts the native codex.exe, which
        // runs the hook.
        let table = FakeTable::new(&[
            (60, Some(50), "kaeru.exe", Some(6_000)),
            (50, Some(40), "cmd.exe", Some(5_000)),
            (40, Some(30), "codex.exe", Some(4_000)),
            (30, Some(20), "node.exe", Some(3_000)),
            (20, Some(10), "pwsh.exe", Some(2_000)),
            (10, None, "WindowsTerminal.exe", Some(1_000)),
        ])
        .with_command_line(30, r"node C:\npm\node_modules\@openai\codex\bin\codex.js");
        let chain = lineage(&table, 60);
        let index = chain
            .iter()
            .position(|p| Agent::Codex.is_process(p))
            .unwrap();
        let note = agent_note(
            Agent::Codex,
            start(),
            &chain[index..],
            &tab_env(),
            "win-1",
            &[],
            None,
        );
        let note = note.unwrap().unwrap();
        assert_eq!(note.agent, "codex");
        assert_eq!(note.process.pid, 40);
        assert_eq!(note.shell_name.as_deref(), Some("pwsh"));
    }
}