autofork 0.30.0

autofork CLI: Claude Code hook entrypoint and daemon control
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
//! User-facing commands: status, forks, run, logs, prune, doctor.

use crate::client::Client;
use autofork_core::config::Paths;
use autofork_core::project::project_root;
use autofork_core::protocol::{RequestBody, ResponseBody, StatusInfo};
use autofork_core::wake::{build_wake_payload, DueFork};
use std::time::Duration;

fn connect(paths: &Paths) -> Result<Client, String> {
    Client::connect_or_spawn(paths, Duration::from_secs(5)).map_err(|e| e.to_string())
}

/// Claude Code version at which the `fork` subagent type is enabled by default
/// in interactive sessions.
const FORK_DEFAULT_VERSION: [u64; 3] = [2, 1, 161];
/// Version at which the `fork` subagent type first exists (gated behind
/// `CLAUDE_CODE_FORK_SUBAGENT=1` until [`FORK_DEFAULT_VERSION`]).
const FORK_GATED_VERSION: [u64; 3] = [2, 1, 117];

/// The doctor hint printed for a fork-capable version: whether the force-enable
/// env is set, plus the confirmed remedy for a current version that still lacks
/// the fork type because of the staged server-side rollout.
fn fork_enable_hint() -> Vec<String> {
    fork_enable_hint_lines(std::env::var_os("CLAUDE_CODE_FORK_SUBAGENT").is_some())
}

fn fork_enable_hint_lines(env_set: bool) -> Vec<String> {
    let mut lines = Vec::new();
    lines.push(if env_set {
        "        CLAUDE_CODE_FORK_SUBAGENT is set (fork subagent force-enabled)".to_string()
    } else {
        "        note: CLAUDE_CODE_FORK_SUBAGENT is not set".to_string()
    });
    lines.push(
        "        a current version can still lack the fork type due to a staged server-side"
            .to_string(),
    );
    lines.push(
        "        rollout; force-enable it by adding {\"env\": {\"CLAUDE_CODE_FORK_SUBAGENT\": \"1\"}}"
            .to_string(),
    );
    lines.push(
        "        to ~/.claude/settings.json (persistent; preferred over a shell export)"
            .to_string(),
    );
    lines
}

/// Impostor `fork` agent definitions: a custom `fork.md` under `.claude/agents/`
/// (user-level and/or project-level) shadows the built-in fork subagent type
/// but does NOT inherit the conversation, so forks would silently lose context.
/// Returns the existing offenders.
fn impostor_agent_files(
    home: Option<&std::path::Path>,
    project_root: &std::path::Path,
) -> Vec<std::path::PathBuf> {
    let mut out = Vec::new();
    if let Some(h) = home {
        let p = h.join(".claude/agents/fork.md");
        if p.is_file() {
            out.push(p);
        }
    }
    let p = project_root.join(".claude/agents/fork.md");
    if p.is_file() && !out.contains(&p) {
        out.push(p);
    }
    out
}

/// Extract the first `x.y.z` triple from `claude --version` output (which may
/// be just the number or include trailing text). `None` if none is found.
fn parse_version(s: &str) -> Option<[u64; 3]> {
    for tok in s.split(|c: char| c.is_whitespace() || c == '(' || c == ')') {
        let mut it = tok.split('.');
        let a = it.next().and_then(|x| x.parse::<u64>().ok());
        let b = it.next().and_then(|x| x.parse::<u64>().ok());
        let c = it.next().and_then(|x| {
            let digits: String = x.chars().take_while(|ch| ch.is_ascii_digit()).collect();
            digits.parse::<u64>().ok()
        });
        if let (Some(a), Some(b), Some(c)) = (a, b, c) {
            return Some([a, b, c]);
        }
    }
    None
}

fn fmt_ago(now: i64, ts: i64) -> String {
    let d = (now - ts).max(0);
    match d {
        0..=59 => format!("{d}s ago"),
        60..=3599 => format!("{}m ago", d / 60),
        3600..=86399 => format!("{}h ago", d / 3600),
        _ => format!("{}d ago", d / 86400),
    }
}

fn now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0)
}

pub fn status(paths: &Paths) -> Result<(), String> {
    let mut client = connect(paths)?;
    let ResponseBody::StatusInfo(info) = client
        .request(RequestBody::Status)
        .map_err(|e| e.to_string())?
    else {
        return Err("unexpected response".into());
    };
    println!("autofork daemon v{} (pid {})", info.version, info.pid);
    print_sessions_header(&info);
    Ok(())
}

/// Width of a displayed session id. 8 chars of the id's random part keep
/// sessions apart (~1 in 10^5 odds of a clash across a lifetime of sessions)
/// while staying scannable in a column.
const SESSION_ID_WIDTH: usize = 8;

/// A short display form of a session id, taken from wherever that id keeps its
/// entropy so distinct sessions never render alike.
///
/// Claude Code's UUIDv4s are random from the first character, so the leading 8
/// identify them — and they match the `<uuid>.jsonl` transcript names, so the
/// head is the useful half.
///
/// The other two clients mint time-ordered ids whose *leading* characters are
/// shared by every session created near in time: opencode's are
/// `ses_<12 hex of time+counter><random>`, codex's are UUIDv7 (the leading 48
/// bits are a timestamp; the version nibble tells the two UUID kinds apart).
/// Truncating those from the front made a whole stretch of sessions display
/// identically ("the same session twice"), so they used to print whole — 28 and
/// 36 characters of column. Their entropy is at the end, so take the tail
/// instead: short *and* distinguishable, and it drops opencode's `ses_` on the
/// way.
fn display_session_id(id: &str) -> &str {
    let uuid_v7 = id.len() >= 15 && id.as_bytes().get(14) == Some(&b'7');
    let time_ordered = uuid_v7 || !id.contains('-');
    if time_ordered {
        // Slice on a char boundary: opencode's random part is base62, and a
        // hand-set id could hold anything.
        let start = id
            .char_indices()
            .rev()
            .nth(SESSION_ID_WIDTH - 1)
            .map(|(i, _)| i)
            .unwrap_or(0);
        &id[start..]
    } else {
        let end = id
            .char_indices()
            .nth(SESSION_ID_WIDTH)
            .map(|(i, _)| i)
            .unwrap_or(id.len());
        &id[..end]
    }
}

fn print_sessions_header(info: &StatusInfo) {
    let t = now();
    // Belt: the store keys sessions by id (PRIMARY KEY), so duplicates
    // shouldn't exist — but if a daemon ever hands back two rows for one id,
    // show only the most recently active (the list is ordered by activity).
    let mut seen = std::collections::HashSet::new();
    let sessions: Vec<_> = info
        .sessions
        .iter()
        .filter(|s| seen.insert(s.session_id.as_str()))
        .collect();
    println!("sessions: {}", sessions.len());
    for s in sessions {
        let tokens = s
            .prompt_tokens
            .map(|n| format!(", ~{n} prompt tokens"))
            .unwrap_or_default();
        let stale = if s.stale { " [stale?]" } else { "" };
        println!(
            "  session {} [{}]{stale} {} (active {}{tokens})",
            display_session_id(&s.session_id),
            s.status,
            s.project_root.display(),
            fmt_ago(t, s.last_activity),
        );
    }
    if !info.running.is_empty() {
        println!("fork runs in flight:");
        for r in &info.running {
            println!(
                "  {}{}{}",
                r.fork,
                display_session_id(&r.session_id),
                fmt_ago(t, r.started_at),
            );
        }
    }
    if !info.recent_closes.is_empty() {
        println!("recent closes:");
        for c in &info.recent_closes {
            println!(
                "  {}{}{}",
                display_session_id(&c.session_id),
                c.reason,
                fmt_ago(t, c.closed_at),
            );
        }
    }
    if !info.recent_runs.is_empty() {
        println!("recent wakes:");
        for r in &info.recent_runs {
            println!(
                "  {} ({}) — {}{}",
                r.fork,
                r.trigger,
                display_session_id(&r.session_id),
                fmt_ago(t, r.started_at),
            );
        }
    }
}

pub fn prune(paths: &Paths) -> Result<(), String> {
    let mut client = connect(paths)?;
    let ResponseBody::Pruned { sessions } = client
        .request(RequestBody::Prune)
        .map_err(|e| e.to_string())?
    else {
        return Err("unexpected response".into());
    };
    if sessions.is_empty() {
        println!("no stale sessions");
        return Ok(());
    }
    let t = now();
    println!(
        "closed {} stale session{}:",
        sessions.len(),
        if sessions.len() == 1 { "" } else { "s" }
    );
    for s in &sessions {
        println!(
            "  session {} {} (last active {})",
            display_session_id(&s.session_id),
            s.project_root.display(),
            fmt_ago(t, s.last_activity),
        );
    }
    Ok(())
}

pub fn list_forks(paths: &Paths, project: Option<std::path::PathBuf>) -> Result<(), String> {
    let cwd = project
        .or_else(|| std::env::current_dir().ok())
        .ok_or("cannot resolve cwd")?;
    let root = project_root(&cwd);
    let mut client = connect(paths)?;
    let ResponseBody::ForkList { items } = client
        .request(RequestBody::ListForks {
            project_root: root.clone(),
            cwd,
        })
        .map_err(|e| e.to_string())?
    else {
        return Err("unexpected response".into());
    };
    if items.is_empty() {
        println!("no forks discovered (looked for .autofork/forks/ up from here and user-level)");
        return Ok(());
    }
    println!("forks visible from {} :", root.display());
    for f in &items {
        println!(
            "  {}{}",
            f.name,
            f.description.as_deref().unwrap_or("(no description)")
        );
        let mut details = vec![format!("runs on: {}", f.triggers.join(", "))];
        if let Some(t) = f.throttle_secs {
            details.push(format!("throttle: {t}s"));
        }
        if !f.after.is_empty() {
            details.push(format!("after: {}", f.after.join(", ")));
        }
        if f.priority != 0 {
            details.push(format!("priority: {}", f.priority));
        }
        if f.chain {
            details.push("chain".into());
        }
        if f.gate {
            details.push("gate".into());
        }
        if let Some(m) = &f.model {
            details.push(format!("model: {m}"));
        }
        if let Some(m) = &f.mode {
            details.push(format!("mode: {m}"));
        }
        if !f.tags.is_empty() {
            details.push(format!("tags: {}", f.tags.join(", ")));
        }
        if f.overlap {
            details.push("overlap allowed".into());
        }
        println!("      {}", details.join(" | "));
        println!("      {}", f.path.display());
        if let Some(skill) = &f.skill {
            println!("      skill: {}", skill.display());
        }
        for w in &f.warnings {
            println!("      warning: {w}");
        }
    }
    Ok(())
}

/// List the lifecycle hooks visible from a directory. Pure filesystem
/// discovery — no daemon round trip (the daemon re-discovers per firing
/// anyway, so there is no daemon-side state to consult).
pub fn list_hooks(paths: &Paths, project: Option<std::path::PathBuf>) -> Result<(), String> {
    let cwd = project
        .or_else(|| std::env::current_dir().ok())
        .ok_or("cannot resolve cwd")?;
    let user_hooks = paths.base.join("hooks");
    let (entries, warnings) = autofork_core::hooks::discover_hooks(&cwd, Some(&user_hooks));
    if entries.is_empty() && warnings.is_empty() {
        println!(
            "no lifecycle hooks discovered (looked for .autofork/hooks/ up from here and {})",
            user_hooks.display()
        );
        return Ok(());
    }
    println!("lifecycle hooks visible from {} :", cwd.display());
    for h in &entries {
        println!(
            "  {}{}",
            h.name,
            h.parsed
                .def
                .description
                .as_deref()
                .unwrap_or("(no description)")
        );
        let on: Vec<String> = h.parsed.def.on.iter().map(|o| o.label()).collect();
        let throttle = match h.parsed.def.throttle_secs {
            Some(s) => format!(" | throttle: {s}s"),
            None => String::new(),
        };
        // A hook that delivers is a feed: say so, and say where its output
        // goes — the difference between "runs a command" and "puts text in
        // my session" is the thing a reader most needs from this listing.
        let deliver = if h.parsed.def.deliver.delivers() {
            format!(
                " | deliver: {} (max {} bytes)",
                h.parsed.def.deliver.label(),
                h.parsed.def.max_bytes
            )
        } else {
            String::new()
        };
        println!(
            "      on: {} | timeout: {}s{throttle}{deliver}",
            if on.is_empty() {
                "(nothing — never fires)".to_string()
            } else {
                on.join(", ")
            },
            h.parsed.def.timeout_secs
        );
        println!("      command: {}", h.parsed.def.command);
        println!("      {}", h.path.display());
        for w in &h.parsed.warnings {
            println!("      warning: {w}");
        }
    }
    for w in &warnings {
        println!("  warning: {w}");
    }
    Ok(())
}

/// `autofork emit <name>`: raise a named external event. Every open session
/// whose forks (`run_on: [event: <name>]`) or hooks (`on: [event: <name>]`)
/// listen for it is triggered — the non-filesystem sibling of `changed:`, for
/// when the thing that happened is not a file: a job finished, a deploy
/// landed, another tool wants this machine's sessions to know something.
pub fn emit_event(
    paths: &Paths,
    name: String,
    payload: Option<String>,
    project: bool,
    session: Option<String>,
) -> Result<(), String> {
    let name = name.trim().to_string();
    if name.is_empty() {
        return Err("an event name is required".into());
    }
    let project_root = if project {
        let cwd = std::env::current_dir().map_err(|e| e.to_string())?;
        Some(autofork_core::project::project_root(&cwd))
    } else {
        None
    };
    // A payload of `-` reads stdin, so a script can pipe a diff, a summary or
    // a file list into the event without shell quoting gymnastics.
    let payload = match payload.as_deref() {
        Some("-") => {
            let mut buf = String::new();
            use std::io::Read;
            std::io::stdin()
                .read_to_string(&mut buf)
                .map_err(|e| e.to_string())?;
            Some(buf.trim().to_string())
        }
        _ => payload,
    };
    let mut client = Client::connect_or_spawn(paths, Duration::from_secs(5))
        .map_err(|e| format!("cannot reach the daemon: {e}"))?;
    match client.request(RequestBody::Emit {
        name: name.clone(),
        payload,
        project_root,
        session_id: session,
    }) {
        Ok(ResponseBody::Emitted { sessions }) => {
            println!(
                "emitted '{name}' to {sessions} open session{}",
                if sessions == 1 { "" } else { "s" }
            );
            Ok(())
        }
        Ok(ResponseBody::Error { message, .. }) => Err(message),
        Ok(_) => Err("unexpected answer from the daemon".into()),
        Err(e) => Err(format!("cannot reach the daemon: {e}")),
    }
}

/// Manual runs can no longer spawn anything (forks are subagents of an
/// interactive session). Instead we print the wake-style spawn instruction to
/// paste into an interactive Claude Code session.
pub fn run_fork(paths: &Paths, name: Option<String>, tag: Option<String>) -> Result<(), String> {
    if name.is_none() && tag.is_none() {
        return Err("provide a fork name or --tag <tag>".into());
    }
    let cwd = std::env::current_dir().map_err(|e| e.to_string())?;
    let root = project_root(&cwd);
    let user_forks = paths.base.join("forks");
    let claude_dir = std::env::var_os("AUTOFORK_CLAUDE_DIR")
        .map(std::path::PathBuf::from)
        .or_else(|| autofork_core::sys::home_dir().map(|h| h.join(".claude")));
    let agents_dir = std::env::var_os("AUTOFORK_AGENTS_DIR")
        .map(std::path::PathBuf::from)
        .or_else(|| autofork_core::sys::home_dir().map(|h| h.join(".agents")));
    let (entries, _) = autofork_core::discovery::discover_forks(
        &cwd,
        Some(&user_forks),
        claude_dir.as_deref(),
        agents_dir.as_deref(),
    );

    let picked: Vec<_> = match (&name, &tag) {
        (Some(name), _) => match entries.into_iter().find(|e| &e.name == name) {
            Some(e) => vec![e],
            None => {
                return Err(format!(
                    "no fork named '{name}' visible from {}",
                    cwd.display()
                ));
            }
        },
        (None, Some(tag)) => {
            let matched: Vec<_> = entries
                .into_iter()
                .filter(|e| e.parsed.def.tags.iter().any(|t| t == tag))
                .collect();
            if matched.is_empty() {
                return Err(format!(
                    "no forks with tag '{tag}' visible from {}",
                    cwd.display()
                ));
            }
            matched
        }
        (None, None) => unreachable!(),
    };

    let due: Vec<DueFork> = picked
        .iter()
        .map(|e| DueFork {
            name: e.name.clone(),
            path: e.path.to_string_lossy().into_owned(),
            trigger: "manual".to_string(),
            overlap: e.parsed.def.overlap,
            after: Vec::new(),
            skill: autofork_core::discovery::skill_sibling(&e.path)
                .map(|p| p.to_string_lossy().into_owned()),
            chain: e.parsed.def.chain,
            // The manual print targets the Claude Code subagent path, which
            // cannot apply model/mode overrides.
            model: None,
            model_fallbacks: Vec::new(),
            mode: None,
            detail: None,
        })
        .collect();
    let payload = build_wake_payload(
        "(the current session)",
        "(the current conversation)",
        &root.to_string_lossy(),
        &due,
        &[],
    );

    println!(
        "autofork can no longer spawn forks itself — forks run as fork subagents of an\n\
         interactive session. Paste the following into an interactive Claude Code session\n\
         to run the selected fork(s) now:\n"
    );
    println!("{payload}");
    Ok(())
}

pub fn logs(paths: &Paths, follow: bool) -> Result<(), String> {
    let path = paths.daemon_log();
    let content = std::fs::read_to_string(&path).unwrap_or_default();
    let tail: Vec<&str> = content.lines().rev().take(100).collect();
    for line in tail.iter().rev() {
        println!("{line}");
    }
    if follow {
        use std::io::{Read, Seek, SeekFrom};
        let mut file = std::fs::File::open(&path).map_err(|e| e.to_string())?;
        let mut pos = file.metadata().map_err(|e| e.to_string())?.len();
        loop {
            std::thread::sleep(Duration::from_millis(500));
            let len = file.metadata().map_err(|e| e.to_string())?.len();
            if len < pos {
                pos = 0;
            }
            if len > pos {
                file.seek(SeekFrom::Start(pos)).map_err(|e| e.to_string())?;
                let mut buf = String::new();
                file.read_to_string(&mut buf).map_err(|e| e.to_string())?;
                print!("{buf}");
                pos = len;
            }
        }
    }
    Ok(())
}

pub fn doctor(paths: &Paths) -> Result<(), String> {
    let mut problems = 0;
    let ok = |msg: &str| println!("  ok: {msg}");
    println!("autofork doctor");

    // Binaries.
    match std::env::current_exe() {
        Ok(exe) => {
            ok(&format!(
                "cli: {} (v{})",
                exe.display(),
                env!("CARGO_PKG_VERSION")
            ));
            let daemon_bin = exe
                .parent()
                .map(|p| p.join(format!("autofork-daemon{}", autofork_core::sys::EXE_SUFFIX)));
            match daemon_bin {
                Some(p) if p.is_file() => ok(&format!("daemon binary: {}", p.display())),
                _ => {
                    problems += 1;
                    println!("  PROBLEM: autofork-daemon not found next to the CLI");
                }
            }
        }
        Err(e) => {
            problems += 1;
            println!("  PROBLEM: cannot resolve current exe: {e}");
        }
    }

    // Daemon liveness + version.
    match Client::connect(paths, Duration::from_secs(2)) {
        Ok(mut client) => match client.request(RequestBody::Hello {
            version: env!("CARGO_PKG_VERSION").to_string(),
        }) {
            Ok(ResponseBody::HelloInfo { version }) => {
                let endpoint = if cfg!(windows) {
                    paths.pipe_name()
                } else {
                    paths.socket().display().to_string()
                };
                ok(&format!("daemon answering at {endpoint} (v{version})"));
            }
            other => {
                problems += 1;
                println!("  PROBLEM: daemon handshake failed: {other:?}");
            }
        },
        Err(_) => {
            println!("  note: daemon not running (it auto-starts on the next hook event)");
        }
    }

    // The shell lifecycle hooks run through. On Windows that is Git for
    // Windows' bash — the same shell Claude Code runs hook commands with —
    // and without it hook commands fall back to cmd.exe, which no `.md`
    // hook written for `sh -c` will survive.
    if cfg!(windows) {
        let (shell, _) = autofork_core::sys::shell();
        if autofork_core::sys::shell_is_posix() {
            ok(&format!("hook shell: {}", shell.display()));
        } else {
            println!(
                "  WARN: no bash.exe found — install Git for Windows (or set \
                 CLAUDE_CODE_GIT_BASH_PATH); lifecycle hooks will run through cmd.exe"
            );
        }
    }

    // State db.
    if paths.db().is_file() {
        ok(&format!("state db: {}", paths.db().display()));
    } else {
        println!("  note: no state db yet at {}", paths.db().display());
    }

    // Claude Code version gating for the `fork` subagent type:
    //   >= 2.1.161            enabled by default in interactive sessions
    //   2.1.117 ..= 2.1.160   exists but gated behind CLAUDE_CODE_FORK_SUBAGENT=1
    //   < 2.1.117             no fork subagent — too old for autofork v0.5
    match std::process::Command::new("claude")
        .arg("--version")
        .output()
    {
        Ok(out) if out.status.success() => {
            let raw = String::from_utf8_lossy(&out.stdout);
            let raw = raw.trim();
            match parse_version(raw) {
                Some(v) if v >= FORK_DEFAULT_VERSION => {
                    ok(&format!("claude: {raw}"));
                    for line in fork_enable_hint() {
                        println!("{line}");
                    }
                }
                Some(v) if v >= FORK_GATED_VERSION => {
                    println!("  WARN: claude {raw}: the fork subagent is gated on this version —");
                    println!("        export CLAUDE_CODE_FORK_SUBAGENT=1 or upgrade to >= 2.1.161");
                }
                Some(_) => {
                    problems += 1;
                    println!(
                        "  PROBLEM: claude {raw} is too old for autofork v0.5 (needs the fork \
                         subagent, >= 2.1.117)"
                    );
                }
                None => println!("  note: could not parse 'claude --version' output ({raw:?})"),
            }
        }
        _ => println!("  note: could not run 'claude --version' to check fork subagent support"),
    }

    // The credential env forks will run with. What matters here is not that
    // a token exists — a keychain login needs none — but that whatever THIS
    // shell authenticates with is what the daemon will spawn its children
    // with, instead of the environment of whichever harness happened to
    // start it (see `autofork_core::runenv`).
    match autofork_core::runenv::capture() {
        Some(snap) if !snap.is_empty() => ok(&format!(
            "fork credentials: carrying {} to daemon-spawned runs",
            snap.set_names().join(", ")
        )),
        Some(_) => println!(
            "  note: fork credentials: nothing in this environment — forks use the \
             harness's own stored login"
        ),
        None => println!(
            "  WARN: fork credentials: AUTOFORK_NO_CARRY_ENV is set — daemon-spawned runs \
             (flush-on-close) inherit the daemon's environment instead of this session's"
        ),
    }
    // Claude Code scrubs CLAUDE_CODE_OAUTH_TOKEN from its hooks, so a token
    // in this shell never reaches autofork unless it is also exported under
    // the override name.
    use autofork_core::runenv::{oauth_token_override, OAUTH_TOKEN, OAUTH_TOKEN_OVERRIDE};
    if oauth_token_override().is_some() {
        ok(&format!(
            "fork credentials: {OAUTH_TOKEN_OVERRIDE} is set — claude fork runs authenticate \
             with it as {OAUTH_TOKEN}"
        ));
    } else if std::env::var_os(OAUTH_TOKEN).is_some() {
        println!(
            "  WARN: fork credentials: {OAUTH_TOKEN} is set here, but Claude Code strips it \
             from its hooks, so autofork never sees it — if that token is how your sessions \
             log in, export {OAUTH_TOKEN_OVERRIDE} with the same value"
        );
    }

    // opencode integration (only reported when opencode or the plugin is
    // present — a Claude-Code-only install stays quiet).
    for line in crate::opencode::doctor_lines() {
        if line.contains("plugin installed") {
            ok(&line);
        } else {
            println!("  WARN: {line}");
        }
    }

    // Codex CLI integration (likewise quiet unless codex or our hooks exist).
    for line in crate::codex::doctor_lines() {
        if line.contains("hooks installed (") {
            ok(&line);
        } else {
            println!("  WARN: {line}");
        }
    }

    // Impostor `fork` agent definitions (a context-less shadow of the built-in
    // type — see the wake payload's own prohibition against creating one).
    let home = autofork_core::sys::home_dir();
    let proot = std::env::current_dir()
        .ok()
        .map(|c| project_root(&c))
        .unwrap_or_else(|| std::path::PathBuf::from("."));
    for f in impostor_agent_files(home.as_deref(), &proot) {
        problems += 1;
        println!(
            "  PROBLEM: custom agent 'fork' at {} shadows/impersonates the",
            f.display()
        );
        println!("           built-in fork subagent type — autofork forks would silently lose");
        println!("           conversation context; delete it.");
    }

    println!(
        "  note: v0.5 forks run as fork subagents of your interactive session — no headless\n\
         \x20       fork subprocesses, and no separate fork-session transcripts to prune."
    );

    if problems == 0 {
        println!("all good");
        Ok(())
    } else {
        Err(format!("{problems} problem(s) found"))
    }
}

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

    #[test]
    fn session_ids_display_short_and_distinct_per_client() {
        // Claude Code (UUIDv4): random from char 0 — head, and it still
        // prefix-matches the `<uuid>.jsonl` transcript name.
        assert_eq!(
            display_session_id("2b08b037-f88a-41b8-8bc5-0b2c4d7c3a9e"),
            "2b08b037"
        );
        // Codex (UUIDv7): the leading 13 chars are a timestamp, so two sessions
        // minted in the same millisecond-ish window share them — take the tail.
        assert_eq!(
            display_session_id("01a01f41-013c-7f60-92dd-f333fdc264ce"),
            "fdc264ce"
        );
        // ...and the version nibble keeps the two UUID kinds apart: these two
        // v7 ids share everything but their random tail, and must not collide.
        assert_ne!(
            display_session_id("01a01f41-013c-7f60-92dd-f333fdc264ce"),
            display_session_id("01a01f41-013c-7f60-92dd-f333f0000001"),
        );
        // opencode: `ses_` + 12 hex of time/counter + random base62. The tail
        // drops the prefix for free.
        assert_eq!(
            display_session_id("ses_05520be3fffeAkRrvVv2zeqqvw"),
            "v2zeqqvw"
        );
        // Ids shorter than the width survive whole rather than panicking.
        assert_eq!(display_session_id("abc"), "abc");
        assert_eq!(display_session_id(""), "");
        // Multi-byte chars must not split mid-codepoint (a byte slice would
        // panic). Both branches: no dash = tail, dash = head.
        assert_eq!(display_session_id("ñññññññññ"), "ññññññññ");
        assert_eq!(display_session_id("áéíóúáéíóú-x"), "áéíóúáéí");
    }

    #[test]
    fn version_parsing_and_gating() {
        assert_eq!(parse_version("2.1.161"), Some([2, 1, 161]));
        assert_eq!(parse_version("2.1.161 (Claude Code)"), Some([2, 1, 161]));
        assert_eq!(parse_version("v2.1.117-beta"), None); // leading 'v' breaks the first token
        assert_eq!(parse_version("2.1.117-beta"), Some([2, 1, 117]));
        assert_eq!(parse_version("nonsense output"), None);

        // Gating thresholds.
        assert!(parse_version("2.1.161").unwrap() >= FORK_DEFAULT_VERSION);
        assert!(parse_version("2.2.0").unwrap() >= FORK_DEFAULT_VERSION);
        let gated = parse_version("2.1.150").unwrap();
        assert!(gated < FORK_DEFAULT_VERSION && gated >= FORK_GATED_VERSION);
        assert!(parse_version("2.1.116").unwrap() < FORK_GATED_VERSION);
        assert!(parse_version("2.0.999").unwrap() < FORK_GATED_VERSION);
    }

    #[test]
    fn fork_enable_hint_reflects_env_and_recommends_settings_pin() {
        let set = fork_enable_hint_lines(true).join("\n");
        assert!(set.contains("CLAUDE_CODE_FORK_SUBAGENT is set"));
        assert!(set.contains("force-enabled"));

        let unset = fork_enable_hint_lines(false).join("\n");
        assert!(unset.contains("CLAUDE_CODE_FORK_SUBAGENT is not set"));
        assert!(unset.contains("staged server-side"));
        assert!(unset.contains(r#"{"env": {"CLAUDE_CODE_FORK_SUBAGENT": "1"}}"#));
        assert!(unset.contains("~/.claude/settings.json"));
    }

    #[test]
    fn detects_impostor_fork_agents() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("home");
        let project = tmp.path().join("proj");
        std::fs::create_dir_all(project.join(".autofork")).unwrap();

        // Nothing yet.
        assert!(impostor_agent_files(Some(&home), &project).is_empty());

        // A user-level impostor.
        std::fs::create_dir_all(home.join(".claude/agents")).unwrap();
        std::fs::write(home.join(".claude/agents/fork.md"), "impostor").unwrap();
        let found = impostor_agent_files(Some(&home), &project);
        assert_eq!(found.len(), 1);
        assert!(found[0].ends_with(".claude/agents/fork.md"));

        // Plus a project-level impostor → both reported.
        std::fs::create_dir_all(project.join(".claude/agents")).unwrap();
        std::fs::write(project.join(".claude/agents/fork.md"), "impostor").unwrap();
        assert_eq!(impostor_agent_files(Some(&home), &project).len(), 2);

        // Same dir as home and project (dedup): no double-count.
        assert_eq!(impostor_agent_files(Some(&project), &project).len(), 1);
    }
}