ouija 0.1.0-alpha.211

Cross-machine AI session daemon — bridges Claude Code sessions via tmux injection and Nostr P2P
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
use std::path::{Path, PathBuf};

use super::{CodingAssistant, DeliveryMode, InjectConfig, ResumeOpts, StartOpts};

// --- Embedded Codex hook scripts ---
// Compiled into the binary so `ouija start-server` can bootstrap Codex hook
// integration without needing the source repo on disk. Codex-specific: they
// emit `hookSpecificOutput.additionalContext` / `{"continue":true}` per the
// Codex hook output contract, and Stop is turn-scoped (never unregisters).
mod embedded {
    pub const SCRIPT_REGISTER: &str = include_str!("../../scripts/codex/codex-register.sh");
    pub const SCRIPT_PROMPT_SUBMIT: &str =
        include_str!("../../scripts/codex/codex-prompt-submit.sh");
    pub const SCRIPT_STOP: &str = include_str!("../../scripts/codex/codex-stop.sh");
    /// The shared ouija skill, installed into Codex's skill-discovery path so a
    /// Codex session can activate it on incoming `<msg>` tags, exactly as Claude
    /// Code and OpenCode do. The stock skill is safe for Codex because its bash
    /// tool inherits `OUIJA_SESSION_ID` (exported via `tmux::pane_env_args`), so
    /// `ouija whoami` and sender auto-resolution work; section 7 already teaches
    /// `ouija whoami`/`OUIJA_SESSION_ID` and forbids guessing a `--from` (#1445).
    pub const SKILL_MD: &str = include_str!("../../skills/ouija/SKILL.md");
}

/// Codex hook events wired by Ouija, paired with the script that handles each.
/// SessionStart registers the pane; UserPromptSubmit signals activity; Stop is
/// turn-scoped bookkeeping. There is deliberately no SessionEnd/unregister hook —
/// Codex has no such event and cleanup relies on pane/process liveness (#1442).
const HOOKS: &[(&str, &str, &str)] = &[
    ("SessionStart", "codex-register.sh", embedded::SCRIPT_REGISTER),
    (
        "UserPromptSubmit",
        "codex-prompt-submit.sh",
        embedded::SCRIPT_PROMPT_SUBMIT,
    ),
    ("Stop", "codex-stop.sh", embedded::SCRIPT_STOP),
];

/// Directory under CODEX_HOME where Ouija writes its hook scripts.
fn hooks_dir(codex_home: &Path) -> PathBuf {
    codex_home.join("ouija-hooks")
}

/// Build the merged `hooks.json` content for Codex, layering Ouija's hook
/// entries onto any existing config without clobbering the user's own hooks.
///
/// Returns `None` when `existing` is present but does not parse as JSON — the
/// caller must then leave the file untouched rather than overwrite it, so a
/// routine `start-server` never silently discards user hook config (finding f3).
/// This is conservative even if Codex accepts a JSON superset: a serde parse
/// failure would not prove the user's file is actually invalid, so overwriting
/// it would be wrong. `None`/absent existing installs fresh onto `{}`.
///
/// Idempotent: an Ouija-owned group is identified by a `command` that lives under
/// `hooks_dir`. For each managed event we drop any prior Ouija group and append a
/// fresh one, so re-installs neither duplicate nor accumulate stale script paths.
/// Non-Ouija hooks (other events, and the user's own groups within a managed
/// event) are preserved verbatim.
fn merge_hooks_json(existing: Option<&str>, hooks_dir: &Path) -> Option<serde_json::Value> {
    let dir_prefix = format!("{}/", hooks_dir.display());
    let is_ouija_group = |group: &serde_json::Value| -> bool {
        group["hooks"].as_array().is_some_and(|inner| {
            inner.iter().any(|h| {
                h["command"]
                    .as_str()
                    .is_some_and(|c| c.starts_with(&dir_prefix))
            })
        })
    };

    let mut root: serde_json::Value = match existing {
        // Present but unparseable → refuse to touch it (return None).
        Some(s) => serde_json::from_str(s).ok()?,
        None => serde_json::json!({}),
    };
    if !root.is_object() {
        root = serde_json::json!({});
    }
    let hooks = root
        .as_object_mut()
        .expect("root normalized to object")
        .entry("hooks")
        .or_insert_with(|| serde_json::json!({}));
    if !hooks.is_object() {
        *hooks = serde_json::json!({});
    }
    let hooks = hooks.as_object_mut().expect("hooks normalized to object");

    for (event, script, _) in HOOKS {
        let command = hooks_dir.join(script).display().to_string();
        let entry = hooks
            .entry((*event).to_string())
            .or_insert_with(|| serde_json::json!([]));
        let arr = match entry.as_array_mut() {
            Some(a) => a,
            None => {
                *entry = serde_json::json!([]);
                entry.as_array_mut().expect("just set to array")
            }
        };
        arr.retain(|g| !is_ouija_group(g));
        arr.push(serde_json::json!({
            "hooks": [ { "type": "command", "command": command } ]
        }));
    }
    Some(root)
}

/// Write the shared ouija skill into Codex's skill-discovery path
/// (`$CODEX_HOME/skills/ouija/SKILL.md`). Idempotent: only the `ouija` subdir is
/// created/overwritten, so unrelated user skills under `skills/` are untouched.
fn install_skill_to(codex_home: &Path) -> anyhow::Result<()> {
    let skill_dir = codex_home.join("skills/ouija");
    std::fs::create_dir_all(&skill_dir)?;
    std::fs::write(skill_dir.join("SKILL.md"), embedded::SKILL_MD)?;
    Ok(())
}

/// Write Ouija's Codex hook scripts and merged `hooks.json` under `codex_home`,
/// plus the shared ouija skill under `skills/ouija/`. Idempotent (see
/// [`merge_hooks_json`] and [`install_skill_to`]); scripts are made executable on
/// unix.
fn install_to(codex_home: &Path) -> anyhow::Result<()> {
    let dir = hooks_dir(codex_home);
    std::fs::create_dir_all(&dir)?;

    for (_, script, content) in HOOKS {
        let dest = dir.join(script);
        std::fs::write(&dest, content)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&dest, std::fs::Permissions::from_mode(0o755))?;
        }
    }

    let hooks_path = codex_home.join("hooks.json");
    let existing = std::fs::read_to_string(&hooks_path).ok();
    match merge_hooks_json(existing.as_deref(), &dir) {
        Some(merged) => std::fs::write(&hooks_path, serde_json::to_string_pretty(&merged)?)?,
        // Existing hooks.json is present but does not parse. Leave it untouched
        // rather than silently discard the user's config; warn so it's visible.
        None => eprintln!(
            "warning: {} is not valid JSON — leaving it untouched. Ouija Codex hooks were not \
             merged; fix or remove the file and re-run to enable them.",
            hooks_path.display()
        ),
    }

    // Install the ouija skill so Codex can activate it on incoming `<msg>` tags,
    // matching Claude/OpenCode. Independent of the hooks.json merge above.
    install_skill_to(codex_home)?;
    Ok(())
}

/// Recursively collect `*.jsonl` rollout files under `dir` (Codex nests session
/// logs as `sessions/YYYY/MM/DD/rollout-*.jsonl`). Missing/unreadable dirs are
/// skipped silently.
fn collect_rollout_files(dir: &Path, out: &mut Vec<PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            collect_rollout_files(&path, out);
        } else if path.extension().and_then(|s| s.to_str()) == Some("jsonl") {
            out.push(path);
        }
    }
}

/// Read only the first line of a rollout file (the `session_meta` record).
fn first_line(path: &Path) -> Option<String> {
    use std::io::BufRead;
    let file = std::fs::File::open(path).ok()?;
    let mut line = String::new();
    std::io::BufReader::new(file).read_line(&mut line).ok()?;
    (!line.trim().is_empty()).then_some(line)
}

/// Find the most recent Codex session whose recorded cwd matches `project_dir`,
/// returning its session id, or `None` if none match.
///
/// Each rollout file's first line is a `session_meta` record carrying
/// `payload.session_id`, `payload.cwd`, and `payload.timestamp`; only that line
/// is read. Recency is by `payload.timestamp` (ISO-8601, lexically sortable).
/// `None` (absent dir or no cwd match) lets the caller fall back to
/// `codex resume --last`. The cwd match is exact: Ouija launches Codex with
/// `--cd <project_dir>`, so the recorded cwd is that same string.
fn latest_session_id_for_cwd(sessions_root: &Path, project_dir: &str) -> Option<String> {
    let mut files = Vec::new();
    collect_rollout_files(sessions_root, &mut files);

    let mut best: Option<(String, String)> = None; // (timestamp, session_id)
    for file in files {
        let Some(line) = first_line(&file) else {
            continue;
        };
        let Ok(v) = serde_json::from_str::<serde_json::Value>(&line) else {
            continue;
        };
        if v.get("type").and_then(|t| t.as_str()) != Some("session_meta") {
            continue;
        }
        let payload = &v["payload"];
        if payload.get("cwd").and_then(|c| c.as_str()) != Some(project_dir) {
            continue;
        }
        let (Some(ts), Some(sid)) = (
            payload.get("timestamp").and_then(|t| t.as_str()),
            payload.get("session_id").and_then(|s| s.as_str()),
        ) else {
            continue;
        };
        if best.as_ref().is_none_or(|(best_ts, _)| ts > best_ts.as_str()) {
            best = Some((ts.to_string(), sid.to_string()));
        }
    }
    best.map(|(_, sid)| sid)
}

/// Resolve CODEX_HOME, honoring the `CODEX_HOME` override before `~/.codex`,
/// matching the Codex CLI's own resolution order.
fn resolve_codex_home() -> Option<PathBuf> {
    if let Ok(h) = std::env::var("CODEX_HOME") {
        if !h.is_empty() {
            return Some(PathBuf::from(h));
        }
    }
    std::env::var("HOME").ok().map(|h| PathBuf::from(h).join(".codex"))
}

/// Autonomy flags for Ouija-launched Codex sessions.
///
/// `--dangerously-bypass-approvals-and-sandbox` gives Ouija-managed Codex
/// sessions the same full-power local-worker posture as Claude Code's
/// `bypassPermissions`: no per-command approval prompts and no Codex sandbox
/// boundary. Ouija still launches inside the selected Ouija/Hub worktree, but
/// that worktree is cwd/scoping, not isolation. This is intended for trusted
/// local automation now and for an external sandbox boundary (for example
/// Docker) later. `--no-alt-screen` keeps terminal scrollback so pane capture
/// and debugging work. Both flags are verified present on `codex` and
/// `codex resume` (#1442, #1445).
const AUTONOMY_FLAGS: &str = "--dangerously-bypass-approvals-and-sandbox --no-alt-screen";

/// Render a ` --model <X>` fragment for the codex CLI, or an empty string.
///
/// The value is shell-escaped so it embeds safely in the surrounding
/// `format!`-built command. Empty / whitespace-only values are treated as
/// absent — emitting `codex --model ''` would just fail at the CLI, so omitting
/// the flag is the safer default. Codex has no verified `--effort` flag, so
/// reasoning effort is intentionally not mapped here.
fn format_model_flag(model: Option<&str>) -> String {
    match model.map(str::trim).filter(|m| !m.is_empty()) {
        Some(m) => format!(" --model {}", crate::scheduler::shell_escape(m)),
        None => String::new(),
    }
}

#[derive(Debug)]
pub struct Codex;

impl CodingAssistant for Codex {
    fn name(&self) -> &str {
        "codex-cli"
    }

    fn cli_name(&self) -> &str {
        "codex"
    }

    fn process_names(&self) -> &[&str] {
        // The `codex` launcher is often an npx/node wrapper whose foreground
        // `pane_current_command` reads as `node`; the long-running agent is a
        // descendant `codex` vendor binary. Ouija's process-tree walks
        // (`find_assistant_panes`, `pane_alive`, `detect_backend_in_pane`)
        // match this descendant, so listing `codex` here is sufficient.
        &["codex"]
    }

    fn delivery_mode(&self) -> DeliveryMode {
        DeliveryMode::TuiInjection
    }

    fn build_start_command(&self, opts: &StartOpts) -> String {
        let escaped_dir = crate::scheduler::shell_escape(&opts.project_dir);
        let model = format_model_flag(opts.model.as_deref());
        // WorktreeMode is intentionally ignored: Codex CLI has no verified
        // `--worktree` flag. Ouija sets up the worktree/cwd before launch and
        // Codex is started inside it. `effort` is intentionally ignored too:
        // Codex CLI exposes no verified `--effort` flag (#1442).
        format!("cd {escaped_dir} && codex {AUTONOMY_FLAGS}{model}")
    }

    fn build_resume_command(&self, opts: &ResumeOpts) -> Option<String> {
        let escaped_dir = crate::scheduler::shell_escape(&opts.project_dir);
        let model = format_model_flag(opts.model.as_deref());
        // `codex resume --last` is the documented non-picker path for
        // continuing the most recent session in this cwd; an explicit
        // SESSION_ID targets a specific thread. WorktreeMode/effort ignored as
        // in `build_start_command`.
        let target = match &opts.session_id {
            Some(sid) => crate::scheduler::shell_escape(sid),
            None => "--last".to_string(),
        };
        Some(format!(
            "cd {escaped_dir} && codex resume {target} {AUTONOMY_FLAGS}{model}"
        ))
    }

    fn detect_session_id(&self, project_dir: &str) -> Option<String> {
        // Codex records sessions globally under `$CODEX_HOME/sessions/YYYY/MM/DD`.
        // Resolve the most recent session whose recorded cwd matches this project
        // so resume can target it explicitly (`codex resume <id>`); `None` falls
        // back to `codex resume --last`.
        let sessions_root = resolve_codex_home()?.join("sessions");
        latest_session_id_for_cwd(&sessions_root, project_dir)
    }

    fn tui_ready_pattern(&self) -> Option<&str> {
        // Codex's interactive prompt glyph is U+203A (SINGLE RIGHT-POINTING
        // ANGLE QUOTATION MARK), observed as the visible `›` prompt.
        Some("\u{203A}")
    }

    fn inject_config(&self) -> InjectConfig {
        // Verified against a live Codex 0.142.5 TUI pane (2026-07-05): inner
        // bracketed paste + a 300ms settle before Enter delivers text intact
        // (special chars/quotes preserved, no dropped keystrokes), multi-line
        // input sanitizes to spaces without premature submit, and Enter reliably
        // submits the composed prompt. The pane was interactive within ~2s, so
        // the 5s startup delay is a safe conservative margin. See followup #692.
        InjectConfig {
            paste_settle_ms: 300,
            use_inner_bracketed_paste: true,
            startup_inject_delay_secs: 5,
        }
    }

    fn config_dir_name(&self) -> &str {
        ".codex"
    }

    fn has_project_history(&self, _dir: &Path) -> bool {
        // Codex keeps session history globally under `$CODEX_HOME`, so there is
        // no per-project marker directory to probe.
        false
    }

    fn exit_command(&self) -> Option<&str> {
        // Codex `Stop` is turn-scoped and there is no documented `/exit` slash
        // command; Ouija tears panes down via respawn/kill instead.
        None
    }

    fn install(&self) -> anyhow::Result<()> {
        // Bootstrap Codex hook integration: write ouija hook scripts + merge
        // hooks.json under CODEX_HOME (~/.codex). Skip silently if Codex isn't
        // set up on this host (no resolvable home), matching the other backends'
        // best-effort install semantics.
        match resolve_codex_home() {
            Some(home) => install_to(&home),
            None => Ok(()),
        }
    }

    // is_available: uses the timeout-aware default so the npx/node `codex`
    // wrapper's slow `--version` cannot stall startup or registration.

    fn description_file_priority(&self) -> &[&str] {
        // Codex reads AGENTS.md as its project guidance file.
        &["AGENTS.md", "README.md"]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::{ResumeOpts, StartOpts, WorktreeMode};

    fn backend() -> Codex {
        Codex
    }

    fn start_opts(dir: &str) -> StartOpts {
        StartOpts {
            project_dir: dir.to_string(),
            worktree: None,
            model: None,
            effort: None,
            permission_mode: None,
        }
    }

    fn resume_opts(dir: &str, session_id: Option<&str>) -> ResumeOpts {
        ResumeOpts {
            project_dir: dir.to_string(),
            session_id: session_id.map(String::from),
            worktree: None,
            model: None,
            effort: None,
            permission_mode: None,
        }
    }

    #[test]
    fn identity_and_delivery() {
        let b = backend();
        assert_eq!(b.name(), "codex-cli");
        assert_eq!(b.cli_name(), "codex");
        assert_eq!(b.process_names(), &["codex"]);
        assert!(matches!(b.delivery_mode(), DeliveryMode::TuiInjection));
        assert_eq!(b.config_dir_name(), ".codex");
    }

    #[test]
    fn start_command_basic() {
        let cmd = backend().build_start_command(&start_opts("/home/user/myproject"));
        assert_eq!(
            cmd,
            "cd '/home/user/myproject' && codex --dangerously-bypass-approvals-and-sandbox --no-alt-screen"
        );
    }

    #[test]
    fn start_command_with_model() {
        let cmd = backend().build_start_command(&StartOpts {
            model: Some("gpt-5.5".into()),
            ..start_opts("/home/user/myproject")
        });
        assert_eq!(
            cmd,
            "cd '/home/user/myproject' && codex --dangerously-bypass-approvals-and-sandbox --no-alt-screen --model 'gpt-5.5'"
        );
    }

    #[test]
    fn start_command_ignores_worktree_and_effort() {
        // Codex has no verified --worktree or --effort flag; both must be
        // dropped rather than guessed onto the command line (#1442).
        let cmd = backend().build_start_command(&StartOpts {
            worktree: Some(WorktreeMode::Named("feature-x".to_string())),
            effort: Some("high".into()),
            ..start_opts("/home/user/myproject")
        });
        assert!(!cmd.contains("--worktree"), "must not emit --worktree: {cmd}");
        assert!(!cmd.contains("--effort"), "must not emit --effort: {cmd}");
        assert!(!cmd.contains("feature-x"), "must not emit worktree name: {cmd}");
        assert!(!cmd.contains("high"), "must not emit effort value: {cmd}");
    }

    #[test]
    fn start_and_resume_use_full_power_worker_mode() {
        // Ouija runs Codex as a full-power local worker, matching Claude Code's
        // bypassPermissions posture. The chosen Ouija/Hub worktree is cwd/scope,
        // not isolation; future deployments can supply an external runner sandbox
        // around the process (#1445).
        let yolo = "--dangerously-bypass-approvals-and-sandbox";
        let start = backend().build_start_command(&start_opts("/home/user/myproject"));
        assert!(start.contains(yolo), "start must bypass approvals/sandbox: {start}");
        let resume = backend()
            .build_resume_command(&resume_opts("/home/user/myproject", None))
            .unwrap();
        assert!(
            resume.contains(yolo),
            "resume must bypass approvals/sandbox: {resume}"
        );
        assert!(!start.contains("--sandbox workspace-write"), "{start}");
        assert!(!start.contains("sandbox_workspace_write.network_access"), "{start}");
    }

    #[test]
    fn resume_command_without_session_id_uses_last() {
        let cmd = backend().build_resume_command(&resume_opts("/home/user/myproject", None));
        assert_eq!(
            cmd,
            Some(
                "cd '/home/user/myproject' && codex resume --last --dangerously-bypass-approvals-and-sandbox --no-alt-screen"
                    .to_string()
            )
        );
    }

    #[test]
    fn resume_command_with_session_id() {
        let cmd =
            backend().build_resume_command(&resume_opts("/home/user/myproject", Some("abc-123")));
        assert_eq!(
            cmd,
            Some(
                "cd '/home/user/myproject' && codex resume 'abc-123' --dangerously-bypass-approvals-and-sandbox --no-alt-screen"
                    .to_string()
            )
        );
    }

    #[test]
    fn resume_command_with_model() {
        let cmd = backend().build_resume_command(&ResumeOpts {
            model: Some("gpt-5.5".into()),
            ..resume_opts("/home/user/myproject", None)
        });
        assert_eq!(
            cmd,
            Some(
                "cd '/home/user/myproject' && codex resume --last --dangerously-bypass-approvals-and-sandbox --no-alt-screen --model 'gpt-5.5'"
                    .to_string()
            )
        );
    }

    #[test]
    fn resume_command_ignores_worktree() {
        let cmd = backend().build_resume_command(&ResumeOpts {
            worktree: Some(WorktreeMode::Disposable),
            ..resume_opts("/home/user/myproject", Some("abc-123"))
        });
        let cmd = cmd.unwrap();
        assert!(!cmd.contains("--worktree"), "must not emit --worktree: {cmd}");
    }

    #[test]
    fn format_model_flag_drops_empty() {
        assert_eq!(format_model_flag(None), "");
        assert_eq!(format_model_flag(Some("")), "");
        assert_eq!(format_model_flag(Some("   ")), "");
        assert_eq!(format_model_flag(Some("gpt-5.5")), " --model 'gpt-5.5'");
    }

    fn write_session_meta(path: &Path, cwd: &str, timestamp: &str, session_id: &str) {
        // First line mirrors the real Codex rollout `session_meta` record; a
        // second line ensures only the first is read.
        let meta = serde_json::json!({
            "type": "session_meta",
            "payload": { "session_id": session_id, "cwd": cwd, "timestamp": timestamp }
        });
        std::fs::write(path, format!("{meta}\n{{\"type\":\"event\"}}\n")).unwrap();
    }

    #[test]
    fn latest_session_id_for_cwd_picks_most_recent_match() {
        let tmp = tempfile::tempdir().unwrap();
        let day = tmp.path().join("2026/07/05");
        std::fs::create_dir_all(&day).unwrap();
        write_session_meta(&day.join("a.jsonl"), "/proj", "2026-07-05T14:44:15.000Z", "uuid-old");
        write_session_meta(&day.join("b.jsonl"), "/proj", "2026-07-05T15:00:00.000Z", "uuid-new");
        write_session_meta(&day.join("c.jsonl"), "/other", "2026-07-05T16:00:00.000Z", "uuid-other");
        assert_eq!(
            latest_session_id_for_cwd(tmp.path(), "/proj"),
            Some("uuid-new".to_string())
        );
        // No session recorded for this cwd → None (caller falls back to --last).
        assert_eq!(latest_session_id_for_cwd(tmp.path(), "/nope"), None);
    }

    #[test]
    fn latest_session_id_for_cwd_none_for_missing_dir() {
        let tmp = tempfile::tempdir().unwrap();
        assert_eq!(
            latest_session_id_for_cwd(&tmp.path().join("sessions"), "/proj"),
            None
        );
    }

    #[test]
    fn latest_session_id_for_cwd_skips_malformed_lines() {
        let tmp = tempfile::tempdir().unwrap();
        let day = tmp.path().join("2026/07/05");
        std::fs::create_dir_all(&day).unwrap();
        std::fs::write(day.join("bad.jsonl"), "not json at all\n").unwrap();
        write_session_meta(&day.join("good.jsonl"), "/proj", "2026-07-05T15:00:00.000Z", "uuid-good");
        assert_eq!(
            latest_session_id_for_cwd(tmp.path(), "/proj"),
            Some("uuid-good".to_string())
        );
    }

    #[test]
    fn tui_ready_pattern_is_prompt_glyph() {
        assert_eq!(backend().tui_ready_pattern(), Some("\u{203A}"));
    }

    #[test]
    fn inject_config_matches_live_verified_values() {
        // Locks the values verified against a live Codex TUI pane (followup #692).
        // If injection tuning ever needs to change, re-verify against a live pane
        // and update both this test and the doc comment together.
        let cfg = backend().inject_config();
        assert_eq!(cfg.paste_settle_ms, 300);
        assert!(cfg.use_inner_bracketed_paste);
        assert_eq!(cfg.startup_inject_delay_secs, 5);
    }

    #[test]
    fn has_project_history_always_false() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::create_dir(tmp.path().join(".codex")).unwrap();
        // Even with a local .codex dir, history is global — no per-project marker.
        assert!(!backend().has_project_history(tmp.path()));
    }

    // --- Hook install (chunk 3) ---

    #[test]
    fn register_script_wraps_output_as_session_start_context() {
        let s = embedded::SCRIPT_REGISTER;
        // Registers via the shared session-start endpoint.
        assert!(s.contains("/api/hooks/session-start"), "{s}");
        // Wraps the daemon's `.output` into Codex additionalContext, keyed to the
        // SessionStart event so the TUI surfaces mesh instructions.
        assert!(s.contains("hookSpecificOutput"), "{s}");
        assert!(s.contains("additionalContext"), "{s}");
        assert!(s.contains("SessionStart"), "{s}");
        // Must never unregister on session start.
        assert!(!s.contains("session-end"), "{s}");
    }

    #[test]
    fn prompt_submit_script_signals_activity() {
        let s = embedded::SCRIPT_PROMPT_SUBMIT;
        assert!(s.contains("/api/hooks/prompt-submit"), "{s}");
        assert!(s.contains("UserPromptSubmit"), "{s}");
    }

    #[test]
    fn stop_script_is_turn_scoped_and_never_unregisters() {
        let s = embedded::SCRIPT_STOP;
        // Pings the turn-stop endpoint...
        assert!(s.contains("/api/hooks/stop"), "{s}");
        // ...returns {"continue":true} so Codex proceeds...
        assert!(s.contains(r#"{"continue":true}"#), "{s}");
        // ...and must NOT unregister (Codex Stop fires every turn).
        assert!(!s.contains("session-end"), "{s}");
    }

    #[test]
    fn merge_hooks_json_fresh_registers_all_three_events() {
        let hooks_dir = Path::new("/home/user/.codex/ouija-hooks");
        let merged = merge_hooks_json(None, hooks_dir).unwrap();
        let hooks = &merged["hooks"];
        for (event, script) in [
            ("SessionStart", "codex-register.sh"),
            ("UserPromptSubmit", "codex-prompt-submit.sh"),
            ("Stop", "codex-stop.sh"),
        ] {
            let cmd = hooks[event][0]["hooks"][0]["command"]
                .as_str()
                .unwrap_or_else(|| panic!("missing command for {event}: {merged}"));
            assert_eq!(cmd, format!("/home/user/.codex/ouija-hooks/{script}"));
            assert_eq!(hooks[event][0]["hooks"][0]["type"], "command");
        }
    }

    #[test]
    fn merge_hooks_json_is_idempotent() {
        let hooks_dir = Path::new("/home/user/.codex/ouija-hooks");
        let once = merge_hooks_json(None, hooks_dir).unwrap();
        let twice = merge_hooks_json(Some(&once.to_string()), hooks_dir).unwrap();
        assert_eq!(once, twice, "second install must not duplicate ouija hooks");
        // Exactly one SessionStart group (no duplication).
        assert_eq!(twice["hooks"]["SessionStart"].as_array().unwrap().len(), 1);
    }

    #[test]
    fn merge_hooks_json_preserves_user_hooks() {
        let hooks_dir = Path::new("/home/user/.codex/ouija-hooks");
        let existing = serde_json::json!({
            "hooks": {
                "PostToolUse": [
                    { "matcher": "Write", "hooks": [
                        { "type": "command", "command": "./scripts/user-thing.sh" }
                    ] }
                ],
                "SessionStart": [
                    { "hooks": [
                        { "type": "command", "command": "/opt/user/other-start.sh" }
                    ] }
                ]
            }
        })
        .to_string();
        let merged = merge_hooks_json(Some(&existing), hooks_dir).unwrap();
        // Unrelated event preserved verbatim.
        assert_eq!(
            merged["hooks"]["PostToolUse"][0]["hooks"][0]["command"],
            "./scripts/user-thing.sh"
        );
        // The user's own SessionStart group survives alongside ours.
        let starts = merged["hooks"]["SessionStart"].as_array().unwrap();
        assert_eq!(starts.len(), 2, "user + ouija groups: {merged}");
        assert!(
            starts
                .iter()
                .any(|g| g["hooks"][0]["command"] == "/opt/user/other-start.sh"),
            "user SessionStart hook must be preserved: {merged}"
        );
        assert!(
            starts.iter().any(|g| g["hooks"][0]["command"]
                == "/home/user/.codex/ouija-hooks/codex-register.sh"),
            "ouija SessionStart hook must be present: {merged}"
        );
    }

    #[test]
    fn merge_hooks_json_replaces_stale_ouija_command() {
        // A prior install wrote a different script path under ouija-hooks; a new
        // install must replace it, not accumulate a second ouija group.
        let hooks_dir = Path::new("/home/user/.codex/ouija-hooks");
        let stale = serde_json::json!({
            "hooks": {
                "Stop": [
                    { "hooks": [
                        { "type": "command",
                          "command": "/home/user/.codex/ouija-hooks/old-stop.sh" }
                    ] }
                ]
            }
        })
        .to_string();
        let merged = merge_hooks_json(Some(&stale), hooks_dir).unwrap();
        let stops = merged["hooks"]["Stop"].as_array().unwrap();
        assert_eq!(stops.len(), 1, "stale ouija group must be replaced: {merged}");
        assert_eq!(
            stops[0]["hooks"][0]["command"],
            "/home/user/.codex/ouija-hooks/codex-stop.sh"
        );
    }

    #[test]
    fn install_to_writes_scripts_and_hooks_json() {
        let home = tempfile::tempdir().unwrap();
        install_to(home.path()).unwrap();

        let hooks_dir = home.path().join("ouija-hooks");
        for script in ["codex-register.sh", "codex-prompt-submit.sh", "codex-stop.sh"] {
            let p = hooks_dir.join(script);
            assert!(p.is_file(), "missing script {script}");
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mode = std::fs::metadata(&p).unwrap().permissions().mode();
                assert_eq!(mode & 0o111, 0o111, "{script} must be executable");
            }
        }

        let hooks_json = std::fs::read_to_string(home.path().join("hooks.json")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&hooks_json).unwrap();
        assert_eq!(
            parsed["hooks"]["SessionStart"][0]["hooks"][0]["command"],
            hooks_dir.join("codex-register.sh").to_string_lossy().as_ref()
        );
    }

    #[test]
    fn install_to_is_idempotent_on_disk() {
        let home = tempfile::tempdir().unwrap();
        install_to(home.path()).unwrap();
        install_to(home.path()).unwrap();
        let hooks_json = std::fs::read_to_string(home.path().join("hooks.json")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&hooks_json).unwrap();
        assert_eq!(
            parsed["hooks"]["SessionStart"].as_array().unwrap().len(),
            1,
            "re-install must not duplicate hooks: {hooks_json}"
        );
    }

    #[test]
    fn merge_hooks_json_none_when_existing_unparseable() {
        // An existing-but-unparseable hooks.json must signal "do not touch",
        // never be silently treated as empty and overwritten (finding f3).
        let hooks_dir = Path::new("/home/user/.codex/ouija-hooks");
        assert!(merge_hooks_json(Some("{ not valid json"), hooks_dir).is_none());
        // A present-but-empty string is also unparseable → leave untouched.
        assert!(merge_hooks_json(Some(""), hooks_dir).is_none());
        // No existing file still installs fresh.
        assert!(merge_hooks_json(None, hooks_dir).is_some());
    }

    #[test]
    fn install_to_writes_ouija_skill() {
        let home = tempfile::tempdir().unwrap();
        install_to(home.path()).unwrap();
        let skill = home.path().join("skills/ouija/SKILL.md");
        assert!(skill.is_file(), "ouija SKILL.md must be installed");
        assert_eq!(std::fs::read_to_string(&skill).unwrap(), embedded::SKILL_MD);
    }

    #[test]
    fn install_skill_is_idempotent_and_preserves_unrelated_skills() {
        let home = tempfile::tempdir().unwrap();
        // A pre-existing unrelated user skill must survive install.
        let other = home.path().join("skills/my-skill");
        std::fs::create_dir_all(&other).unwrap();
        std::fs::write(other.join("SKILL.md"), "user skill body").unwrap();

        install_skill_to(home.path()).unwrap();
        install_skill_to(home.path()).unwrap(); // re-install must not error or duplicate

        // Ouija skill present with expected content.
        assert_eq!(
            std::fs::read_to_string(home.path().join("skills/ouija/SKILL.md")).unwrap(),
            embedded::SKILL_MD
        );
        // Unrelated skill untouched.
        assert_eq!(
            std::fs::read_to_string(other.join("SKILL.md")).unwrap(),
            "user skill body"
        );
    }

    #[test]
    fn install_to_leaves_unparseable_hooks_json_untouched() {
        let home = tempfile::tempdir().unwrap();
        let hooks_path = home.path().join("hooks.json");
        let garbage = "{ this is not valid json — user hand-edit in progress";
        std::fs::write(&hooks_path, garbage).unwrap();

        install_to(home.path()).unwrap();

        // The user's file must survive verbatim — never silently discarded.
        assert_eq!(std::fs::read_to_string(&hooks_path).unwrap(), garbage);
        // Scripts are still written (harmless); only hooks.json is left alone.
        assert!(home.path().join("ouija-hooks/codex-register.sh").is_file());
    }
}