path-cli 0.13.0

CLI for deriving, querying, and visualizing Toolpath provenance (binary: path)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
//! `path share` — interactive Pathbase upload across installed agent
//! harnesses. See `docs/superpowers/specs/2026-05-07-path-share-command-design.md`.

#![cfg(not(target_os = "emscripten"))]

use anyhow::Result;
use chrono::{DateTime, Utc};
use clap::{Args, ValueEnum};
use std::path::PathBuf;

use crate::cmd_export::RepoSpec;

#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lower")]
pub enum HarnessArg {
    Claude,
    Gemini,
    Codex,
    Opencode,
    Pi,
}

#[derive(Args, Debug)]
pub struct ShareArgs {
    /// Pathbase server URL (defaults to the stored session's server)
    #[arg(long)]
    pub url: Option<String>,

    /// Force the anonymous endpoint, ignoring any stored credentials
    #[arg(long, conflicts_with_all = ["repo", "public"])]
    pub anon: bool,

    /// Target a specific repo as `owner/name` instead of `<you>/pathstash`
    #[arg(long, value_parser = crate::cmd_export::parse_repo_spec)]
    pub repo: Option<RepoSpec>,

    /// Human-readable display label for the uploaded graph
    /// (defaults to the toolpath document id). Free-form; not used
    /// in the URL — graphs are addressed by UUID server-side.
    #[arg(long, alias = "slug")]
    pub name: Option<String>,

    /// Mark the uploaded graph public (default: unlisted, addressable only by UUID)
    #[arg(long)]
    pub public: bool,

    /// Narrow the picker to one harness, or skip the picker entirely
    /// when used with --session.
    #[arg(long, value_enum)]
    pub harness: Option<HarnessArg>,

    /// Skip the picker. Requires --harness; requires --project for
    /// claude/gemini/pi.
    #[arg(long, requires = "harness")]
    pub session: Option<String>,

    /// Override cwd-as-project. Filters the picker to sessions tied to
    /// this project across all harnesses.
    #[arg(long)]
    pub project: Option<PathBuf>,

    /// Skip writing the cache; derive in-memory only
    #[arg(long)]
    pub no_cache: bool,
}

/// Which agent harness a session was produced by.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Harness {
    Claude,
    Gemini,
    Codex,
    Opencode,
    Pi,
}

impl Harness {
    pub(crate) fn name(&self) -> &'static str {
        match self {
            Harness::Claude => "claude",
            Harness::Gemini => "gemini",
            Harness::Codex => "codex",
            Harness::Opencode => "opencode",
            Harness::Pi => "pi",
        }
    }

    /// Padded so all five symbols line up in the fzf column.
    pub(crate) fn symbol(&self) -> &'static str {
        match self {
            Harness::Claude => "claude  ",
            Harness::Gemini => "gemini  ",
            Harness::Codex => "codex   ",
            Harness::Opencode => "opencode",
            Harness::Pi => "pi      ",
        }
    }

    /// True when the underlying provider keys sessions by project path.
    /// claude/gemini/pi: true. codex/opencode: false (sessions store cwd
    /// per-row, not as a directory key).
    pub(crate) fn project_keyed(&self) -> bool {
        matches!(self, Harness::Claude | Harness::Gemini | Harness::Pi)
    }

    pub(crate) fn from_arg(arg: HarnessArg) -> Self {
        match arg {
            HarnessArg::Claude => Harness::Claude,
            HarnessArg::Gemini => Harness::Gemini,
            HarnessArg::Codex => Harness::Codex,
            HarnessArg::Opencode => Harness::Opencode,
            HarnessArg::Pi => Harness::Pi,
        }
    }

    pub(crate) fn parse(s: &str) -> Option<Self> {
        match s {
            "claude" => Some(Harness::Claude),
            "gemini" => Some(Harness::Gemini),
            "codex" => Some(Harness::Codex),
            "opencode" => Some(Harness::Opencode),
            "pi" => Some(Harness::Pi),
            _ => None,
        }
    }
}

/// One row in the unified session picker.
#[derive(Debug, Clone)]
pub(crate) struct SessionRow {
    pub(crate) harness: Harness,
    /// Project path for keyed providers; `None` for codex/opencode.
    pub(crate) project: Option<String>,
    /// Recorded cwd from the session (codex/opencode only).
    pub(crate) cwd: Option<String>,
    pub(crate) session_id: String,
    pub(crate) title: String,
    pub(crate) last_activity: Option<DateTime<Utc>>,
    pub(crate) message_count: usize,
    pub(crate) matches_cwd: bool,
}

/// Bundle of provider managers used during aggregation. Production code
/// builds this from real `$HOME` via `from_environment`; tests construct
/// it directly with provider-specific resolvers.
#[derive(Default)]
pub(crate) struct HarnessBundle {
    pub(crate) claude: Option<toolpath_claude::ClaudeConvo>,
    pub(crate) gemini: Option<toolpath_gemini::GeminiConvo>,
    pub(crate) codex: Option<toolpath_codex::CodexConvo>,
    pub(crate) opencode: Option<toolpath_opencode::OpencodeConvo>,
    pub(crate) pi: Option<toolpath_pi::PiConvo>,
}

impl HarnessBundle {
    /// Build the production bundle. Each provider is included
    /// unconditionally (its `new()` doesn't fail on a missing home dir);
    /// `gather_sessions` skips the ones whose listing returns empty/NotFound.
    pub(crate) fn from_environment() -> Self {
        Self {
            claude: Some(toolpath_claude::ClaudeConvo::new()),
            gemini: Some(toolpath_gemini::GeminiConvo::new()),
            codex: Some(toolpath_codex::CodexConvo::new()),
            opencode: Some(toolpath_opencode::OpencodeConvo::new()),
            pi: Some(toolpath_pi::PiConvo::new()),
        }
    }
}

/// Aggregate sessions across the harnesses in `bundle`, ranked so that
/// rows whose project (or recorded cwd) canonicalizes to `cwd` come
/// first, sorted by descending `last_activity`.
///
/// Filters: `harness_filter` keeps only rows from one harness; `project_filter`
/// keeps only rows whose project (for keyed) or cwd (for session-keyed)
/// canonicalizes to that path.
pub(crate) fn gather_sessions(
    bundle: &HarnessBundle,
    cwd: &std::path::Path,
    harness_filter: Option<Harness>,
    project_filter: Option<&std::path::Path>,
) -> Vec<SessionRow> {
    let mut rows = Vec::new();
    let canonical_cwd = canonicalize_or_self(cwd);
    let canonical_project = project_filter.map(canonicalize_or_self);

    let want = |h: Harness| harness_filter.is_none_or(|f| f == h);

    if want(Harness::Claude)
        && let Some(mgr) = &bundle.claude
    {
        collect_claude(mgr, &canonical_cwd, canonical_project.as_deref(), &mut rows);
    }
    if want(Harness::Gemini)
        && let Some(mgr) = &bundle.gemini
    {
        collect_gemini(mgr, &canonical_cwd, canonical_project.as_deref(), &mut rows);
    }
    if want(Harness::Pi)
        && let Some(mgr) = &bundle.pi
    {
        collect_pi(mgr, &canonical_cwd, canonical_project.as_deref(), &mut rows);
    }
    if want(Harness::Codex)
        && let Some(mgr) = &bundle.codex
    {
        collect_codex(mgr, &canonical_cwd, canonical_project.as_deref(), &mut rows);
    }
    if want(Harness::Opencode)
        && let Some(mgr) = &bundle.opencode
    {
        collect_opencode(mgr, &canonical_cwd, canonical_project.as_deref(), &mut rows);
    }

    rows.sort_by(|a, b| {
        b.matches_cwd
            .cmp(&a.matches_cwd)
            .then_with(|| b.last_activity.cmp(&a.last_activity))
    });
    rows
}

fn canonicalize_or_self(p: &std::path::Path) -> std::path::PathBuf {
    std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
}

fn paths_match(a: &std::path::Path, b: &std::path::Path) -> bool {
    canonicalize_or_self(a) == canonicalize_or_self(b)
}

fn collect_claude(
    mgr: &toolpath_claude::ClaudeConvo,
    canonical_cwd: &std::path::Path,
    project_filter: Option<&std::path::Path>,
    out: &mut Vec<SessionRow>,
) {
    let projects = match mgr.list_projects() {
        Ok(ps) if !ps.is_empty() => ps,
        Ok(_) => return,
        Err(e) if is_not_found_claude(&e) => return,
        Err(e) => {
            eprintln!("warning: claude aggregation failed: {e}");
            return;
        }
    };
    for project in projects {
        let project_path = std::path::Path::new(&project);
        if let Some(filter) = project_filter
            && !paths_match(project_path, filter)
        {
            continue;
        }
        let metas = match mgr.list_conversation_metadata(&project) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("warning: claude project {project} failed: {e}");
                continue;
            }
        };
        let matches_cwd = paths_match(project_path, canonical_cwd);
        for m in metas {
            out.push(SessionRow {
                harness: Harness::Claude,
                project: Some(m.project_path),
                cwd: None,
                session_id: m.session_id,
                title: m
                    .first_user_message
                    .unwrap_or_else(|| "(no prompt)".to_string()),
                last_activity: m.last_activity,
                message_count: m.message_count,
                matches_cwd,
            });
        }
    }
}

fn collect_gemini(
    mgr: &toolpath_gemini::GeminiConvo,
    canonical_cwd: &std::path::Path,
    project_filter: Option<&std::path::Path>,
    out: &mut Vec<SessionRow>,
) {
    let projects = match mgr.list_projects() {
        Ok(ps) if !ps.is_empty() => ps,
        Ok(_) => return,
        Err(e) if is_not_found_gemini(&e) => return,
        Err(e) => {
            eprintln!("warning: gemini aggregation failed: {e}");
            return;
        }
    };
    for project in projects {
        let project_path = std::path::Path::new(&project);
        if let Some(filter) = project_filter
            && !paths_match(project_path, filter)
        {
            continue;
        }
        let metas = match mgr.list_conversation_metadata(&project) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("warning: gemini project {project} failed: {e}");
                continue;
            }
        };
        let matches_cwd = paths_match(project_path, canonical_cwd);
        for m in metas {
            out.push(SessionRow {
                harness: Harness::Gemini,
                project: Some(m.project_path),
                cwd: None,
                session_id: m.session_uuid,
                title: m
                    .first_user_message
                    .unwrap_or_else(|| "(no prompt)".to_string()),
                last_activity: m.last_activity,
                message_count: m.message_count,
                matches_cwd,
            });
        }
    }
}

fn collect_pi(
    mgr: &toolpath_pi::PiConvo,
    canonical_cwd: &std::path::Path,
    project_filter: Option<&std::path::Path>,
    out: &mut Vec<SessionRow>,
) {
    let projects = match mgr.list_projects() {
        Ok(ps) if !ps.is_empty() => ps,
        Ok(_) => return,
        Err(e) if is_not_found_pi(&e) => return,
        Err(e) => {
            eprintln!("warning: pi aggregation failed: {e}");
            return;
        }
    };
    for project in projects {
        let project_path = std::path::Path::new(&project);
        if let Some(filter) = project_filter
            && !paths_match(project_path, filter)
        {
            continue;
        }
        let metas = match mgr.list_sessions(&project) {
            Ok(m) => m,
            Err(e) => {
                eprintln!("warning: pi project {project} failed: {e}");
                continue;
            }
        };
        let matches_cwd = paths_match(project_path, canonical_cwd);
        for m in metas {
            // SessionMeta.timestamp is a String; parse to DateTime when possible.
            let last_activity = chrono::DateTime::parse_from_rfc3339(&m.timestamp)
                .ok()
                .map(|d| d.with_timezone(&Utc));
            out.push(SessionRow {
                harness: Harness::Pi,
                project: Some(project.clone()),
                cwd: None,
                session_id: m.id,
                title: m
                    .first_user_message
                    .unwrap_or_else(|| "(no prompt)".to_string()),
                last_activity,
                message_count: m.entry_count,
                matches_cwd,
            });
        }
    }
}

fn collect_codex(
    mgr: &toolpath_codex::CodexConvo,
    canonical_cwd: &std::path::Path,
    project_filter: Option<&std::path::Path>,
    out: &mut Vec<SessionRow>,
) {
    let metas = match mgr.list_sessions() {
        Ok(m) if !m.is_empty() => m,
        Ok(_) => return,
        Err(e) if is_not_found_codex(&e) => return,
        Err(e) => {
            eprintln!("warning: codex aggregation failed: {e}");
            return;
        }
    };
    for m in metas {
        let cwd_str = m.cwd.as_ref().map(|p| p.to_string_lossy().into_owned());
        if let Some(filter) = project_filter {
            let stored = match cwd_str.as_deref() {
                Some(s) => std::path::PathBuf::from(s),
                None => continue,
            };
            if !paths_match(&stored, filter) {
                continue;
            }
        }
        let matches_cwd = m
            .cwd
            .as_deref()
            .map(|p| paths_match(p, canonical_cwd))
            .unwrap_or(false);
        out.push(SessionRow {
            harness: Harness::Codex,
            project: None,
            cwd: cwd_str,
            session_id: m.id,
            title: m
                .first_user_message
                .unwrap_or_else(|| "(no prompt)".to_string()),
            last_activity: m.last_activity,
            message_count: m.line_count,
            matches_cwd,
        });
    }
}

fn collect_opencode(
    mgr: &toolpath_opencode::OpencodeConvo,
    canonical_cwd: &std::path::Path,
    project_filter: Option<&std::path::Path>,
    out: &mut Vec<SessionRow>,
) {
    let metas = match mgr.io().list_session_metadata(None) {
        Ok(m) if !m.is_empty() => m,
        Ok(_) => return,
        Err(e) if is_not_found_opencode(&e) => return,
        Err(e) => {
            eprintln!("warning: opencode aggregation failed: {e}");
            return;
        }
    };
    for m in metas {
        if let Some(filter) = project_filter
            && !paths_match(&m.directory, filter)
        {
            continue;
        }
        let matches_cwd = paths_match(&m.directory, canonical_cwd);
        let cwd_str = m.directory.to_string_lossy().into_owned();
        let title = match (&m.first_user_message, m.title.is_empty()) {
            (Some(s), _) if !s.is_empty() => s.clone(),
            (_, false) => m.title.clone(),
            _ => "(no prompt)".to_string(),
        };
        out.push(SessionRow {
            harness: Harness::Opencode,
            project: None,
            cwd: Some(cwd_str),
            session_id: m.id,
            title,
            last_activity: m.last_activity,
            message_count: m.message_count,
            matches_cwd,
        });
    }
}

fn is_not_found_claude(err: &toolpath_claude::ConvoError) -> bool {
    use toolpath_claude::ConvoError;
    matches!(err, ConvoError::Io(e) if e.kind() == std::io::ErrorKind::NotFound)
        || matches!(err, ConvoError::NoHomeDirectory)
        || matches!(err, ConvoError::ClaudeDirectoryNotFound(_))
}

fn is_not_found_gemini(err: &toolpath_gemini::ConvoError) -> bool {
    use toolpath_gemini::ConvoError;
    matches!(err, ConvoError::Io(e) if e.kind() == std::io::ErrorKind::NotFound)
        || matches!(err, ConvoError::NoHomeDirectory)
        || matches!(err, ConvoError::GeminiDirectoryNotFound(_))
}

fn is_not_found_pi(err: &toolpath_pi::PiError) -> bool {
    use toolpath_pi::PiError;
    matches!(err, PiError::Io(e) if e.kind() == std::io::ErrorKind::NotFound)
        || matches!(err, PiError::ProjectNotFound(_))
}

fn is_not_found_codex(err: &toolpath_codex::ConvoError) -> bool {
    use toolpath_codex::ConvoError;
    matches!(err, ConvoError::Io(e) if e.kind() == std::io::ErrorKind::NotFound)
        || matches!(err, ConvoError::NoHomeDirectory)
        || matches!(err, ConvoError::CodexDirectoryNotFound(_))
}

fn is_not_found_opencode(err: &toolpath_opencode::ConvoError) -> bool {
    use toolpath_opencode::ConvoError;
    matches!(err, ConvoError::Io(e) if e.kind() == std::io::ErrorKind::NotFound)
        || matches!(err, ConvoError::NoHomeDirectory)
        || matches!(err, ConvoError::OpencodeDirectoryNotFound(_))
        || matches!(err, ConvoError::DatabaseNotFound(_))
}

pub fn run(args: ShareArgs) -> Result<()> {
    let harness = args.harness.map(Harness::from_arg);

    if args.session.is_some() && harness.is_none() {
        anyhow::bail!("--session requires --harness");
    }

    // Build upload args + base URL once and reuse for both the explicit
    // path and the picker path. `needs_auth` decides whether preflight
    // can fall back to anon on credential failure.
    let upload_args = crate::cmd_export::PathbaseUploadArgs {
        url: args.url.clone(),
        anon: args.anon,
        repo: args.repo.clone(),
        name: args.name.clone(),
        public: args.public,
    };
    let base_url = crate::cmd_export::resolve_upload_base_url(&upload_args);
    let needs_auth = upload_args.repo.is_some() || upload_args.public || upload_args.name.is_some();

    if let (Some(h), Some(session)) = (harness, &args.session) {
        // Explicit-args: validate creds before derive so a credential
        // failure doesn't waste the derive/cache work.
        let auth = crate::cmd_pathbase::preflight_auth(&base_url, upload_args.anon, needs_auth)?;
        return share_explicit(h, session.as_str(), &args, auth, base_url);
    }

    let cwd = std::env::current_dir()?;
    let bundle = HarnessBundle::from_environment();
    let project_filter = args.project.as_deref();
    let rows = gather_sessions(&bundle, &cwd, harness, project_filter);

    if rows.is_empty() {
        return bail_no_sessions(&bundle, project_filter);
    }

    if !crate::fuzzy::available() {
        eprintln!(
            "Interactive `path share` needs `fzf` on PATH and a TTY.\n\
             \n\
             Manual recipe:\n  \
             path import <harness>      # writes a cache entry, prints its id\n  \
             path export pathbase --input <id>"
        );
        anyhow::bail!("fzf unavailable; run `path import <harness>` then `path export pathbase`");
    }

    // We have rows AND fzf available — now validate credentials before
    // making the user pick a session. If preflight returns Anon (either
    // explicit --anon, no creds + no auth flags, or auth probe failed
    // and fell back), the picker still fires with that knowledge baked in.
    let auth = crate::cmd_pathbase::preflight_auth(&base_url, upload_args.anon, needs_auth)?;

    let lines: Vec<String> = rows.iter().map(format_picker_row).collect();
    let header = format!("share an agent session (Enter = upload to {base_url})");
    let opts = crate::fuzzy::PickOptions {
        with_nth: "4",
        prompt: "share> ",
        preview: Some("{exe} show --ansi {1} --project {2} --session {3}"),
        // Stacked layout: preview above the list, list below. Fits narrow
        // terminals better than the default side-by-side and gives the
        // session preview the full terminal width to render `path show`.
        preview_window: "up:60%:wrap-word",
        header: Some(&header),
        tiebreak: "index",
        multi: false,
    };
    let line = match crate::fuzzy::pick(&lines, &opts)? {
        crate::fuzzy::PickResult::Selected(v) => match v.into_iter().next() {
            Some(l) => l,
            // Selected with an empty payload should not happen (fzf exits 0
            // only when at least one row was confirmed), but treat it like
            // no-match for safety.
            None => return Ok(()),
        },
        // No row matched the query — exit 0, same as today, no extra noise.
        crate::fuzzy::PickResult::NoMatch => return Ok(()),
        // Esc / Ctrl-C: deliberate user cancel. Signal to the shell with
        // exit 130 so it's distinguishable from a successful share.
        crate::fuzzy::PickResult::Cancelled => std::process::exit(130),
    };
    let (h, key, session, title) = parse_picker_row(&line)
        .ok_or_else(|| anyhow::anyhow!("internal: failed to parse picker row"))?;

    let explicit = ShareArgs {
        url: args.url.clone(),
        anon: args.anon,
        repo: args.repo.clone(),
        name: args.name.clone(),
        public: args.public,
        harness: Some(harness_to_arg(h)),
        session: None, // unused by share_explicit
        project: if h.project_keyed() {
            Some(PathBuf::from(&key))
        } else {
            None
        },
        no_cache: args.no_cache,
    };
    // Show the conversation title in the confirmation line; the session id
    // is opaque and doesn't help the user verify they picked the right
    // thing. `{:?}` adds the surrounding quotes per the spec.
    eprintln!("Picked {} session {:?}", h.name(), title);
    share_explicit(h, &session, &explicit, auth, base_url)
}

fn harness_to_arg(h: Harness) -> HarnessArg {
    match h {
        Harness::Claude => HarnessArg::Claude,
        Harness::Gemini => HarnessArg::Gemini,
        Harness::Codex => HarnessArg::Codex,
        Harness::Opencode => HarnessArg::Opencode,
        Harness::Pi => HarnessArg::Pi,
    }
}

fn bail_no_sessions(
    bundle: &HarnessBundle,
    project_filter: Option<&std::path::Path>,
) -> Result<()> {
    if let Some(p) = project_filter {
        anyhow::bail!(
            "No agent sessions found in project {}. Run without --project to see sessions across all projects.",
            p.display()
        );
    }

    let mut summary = String::from("No agent sessions found.\n");
    // Pad harness names so the path column lines up: "opencode:" is the
    // longest at 9 chars (8 + colon).
    let home = home_dir();
    summary.push_str(&format_status_line(
        "claude",
        &harness_status_claude(bundle, home.as_deref()),
    ));
    summary.push_str(&format_status_line(
        "gemini",
        &harness_status_gemini(bundle, home.as_deref()),
    ));
    summary.push_str(&format_status_line(
        "codex",
        &harness_status_codex(bundle, home.as_deref()),
    ));
    summary.push_str(&format_status_line(
        "opencode",
        &harness_status_opencode(bundle, home.as_deref()),
    ));
    summary.push_str(&format_status_line(
        "pi",
        &harness_status_pi(bundle, home.as_deref()),
    ));
    eprint!("{summary}");
    anyhow::bail!("no shareable sessions");
}

/// Cross-platform `$HOME` lookup matching the providers' internal helpers.
/// Returns `None` only when neither `$HOME` nor `$USERPROFILE` is set.
fn home_dir() -> Option<std::path::PathBuf> {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(std::path::PathBuf::from)
}

/// Human-readable status of a harness's on-disk store: either the (possibly
/// home-relative) path with a "(0 sessions)" hint, or the path with a
/// "not found" hint when the directory/database is absent.
#[derive(Debug, PartialEq, Eq)]
struct HarnessStatus {
    /// Display path (tilde-prefixed when under `$HOME`).
    path: String,
    /// True when the path exists on disk.
    exists: bool,
}

impl HarnessStatus {
    fn render(&self) -> String {
        if self.exists {
            format!("{} (0 sessions)", self.path)
        } else {
            format!("{} not found", self.path)
        }
    }

    /// Status when the resolver itself failed (e.g. no $HOME).
    fn unresolved() -> Self {
        Self {
            path: "<no home directory>".to_string(),
            exists: false,
        }
    }
}

/// Format a single status line, padding the harness name so that the path
/// column lines up across all five rows. The longest name is "opencode" (8).
fn format_status_line(name: &str, status: &HarnessStatus) -> String {
    format!("  {:<9} {}\n", format!("{name}:"), status.render())
}

fn harness_status_claude(bundle: &HarnessBundle, home: Option<&std::path::Path>) -> HarnessStatus {
    let Some(mgr) = &bundle.claude else {
        return HarnessStatus::unresolved();
    };
    match mgr.resolver().projects_dir() {
        Ok(p) => HarnessStatus {
            path: home_relative(&p, home),
            exists: p.exists(),
        },
        Err(_) => HarnessStatus::unresolved(),
    }
}

fn harness_status_gemini(bundle: &HarnessBundle, home: Option<&std::path::Path>) -> HarnessStatus {
    let Some(mgr) = &bundle.gemini else {
        return HarnessStatus::unresolved();
    };
    match mgr.resolver().tmp_dir() {
        Ok(p) => HarnessStatus {
            path: home_relative(&p, home),
            exists: p.exists(),
        },
        Err(_) => HarnessStatus::unresolved(),
    }
}

fn harness_status_codex(bundle: &HarnessBundle, home: Option<&std::path::Path>) -> HarnessStatus {
    let Some(mgr) = &bundle.codex else {
        return HarnessStatus::unresolved();
    };
    match mgr.resolver().sessions_root() {
        Ok(p) => HarnessStatus {
            path: home_relative(&p, home),
            exists: p.exists(),
        },
        Err(_) => HarnessStatus::unresolved(),
    }
}

fn harness_status_opencode(
    bundle: &HarnessBundle,
    home: Option<&std::path::Path>,
) -> HarnessStatus {
    let Some(mgr) = &bundle.opencode else {
        return HarnessStatus::unresolved();
    };
    match mgr.resolver().db_path() {
        Ok(p) => HarnessStatus {
            path: home_relative(&p, home),
            exists: p.exists(),
        },
        Err(_) => HarnessStatus::unresolved(),
    }
}

fn harness_status_pi(bundle: &HarnessBundle, home: Option<&std::path::Path>) -> HarnessStatus {
    let Some(mgr) = &bundle.pi else {
        return HarnessStatus::unresolved();
    };
    let p = mgr.resolver().sessions_dir().to_path_buf();
    HarnessStatus {
        path: home_relative(&p, home),
        exists: p.exists(),
    }
}

/// Display `path` as `~/relative/part` when it's under `home`, otherwise
/// return its absolute lossy form. Pure helper — does no filesystem I/O.
fn home_relative(path: &std::path::Path, home: Option<&std::path::Path>) -> String {
    if let Some(home) = home
        && let Ok(rest) = path.strip_prefix(home)
    {
        // strip_prefix returns the empty path when path == home; treat that
        // as plain "~".
        if rest.as_os_str().is_empty() {
            return "~".to_string();
        }
        return format!("~/{}", rest.display());
    }
    path.display().to_string()
}

fn share_explicit(
    harness: Harness,
    session: &str,
    args: &ShareArgs,
    auth: crate::cmd_pathbase::AuthMode,
    base_url: String,
) -> Result<()> {
    let project = match (harness.project_keyed(), args.project.as_ref()) {
        (true, Some(p)) => Some(p.to_string_lossy().into_owned()),
        (true, None) => anyhow::bail!(
            "--project required when --harness is {} and --session is set",
            harness.name()
        ),
        (false, _) => None,
    };

    let derived = derive_session(harness, project.as_deref(), session)?;
    let summary = format!("{} session {}", harness.name(), derived.cache_id);

    if !args.no_cache {
        // The cache entry should always reflect what was just uploaded.
        // `path share` is "ship the current state of this session"; if
        // the conversation has grown since a prior share, the in-memory
        // body has the new turns but a stale cache file would not — and
        // the upload uses the fresh body, not the cache. Always
        // overwrite so cache and upload agree (use `--no-cache` to skip
        // the cache write entirely).
        let path = crate::cmd_cache::write_cached(&derived.cache_id, &derived.doc, true)?;
        eprintln!(
            "Cached {} session → {} ({})",
            harness.name(),
            derived.cache_id,
            path.display()
        );
    }

    let body = derived.doc.to_json()?;
    let upload = crate::cmd_export::PathbaseUploadArgs {
        url: args.url.clone(),
        anon: args.anon,
        repo: args.repo.clone(),
        name: args.name.clone(),
        public: args.public,
    };
    crate::cmd_export::run_pathbase_inner(auth, base_url, upload, &body, &summary)
}

/// Build the TSV line fed to the picker. Three hidden parser-only
/// columns lead the row (harness key, project/cwd, session id); a
/// fourth column carries the pre-formatted display string from
/// `fuzzy::render_row`; a fifth carries the raw title so
/// `parse_picker_row` can recover it without reparsing the display.
///
/// The display column is space-padded rather than tab-separated so the
/// columns line up consistently across pickers — terminal tab stops
/// produce ugly variable gaps in both fzf and skim.
fn format_picker_row(row: &SessionRow) -> String {
    let key = row
        .project
        .clone()
        .or_else(|| row.cwd.clone())
        .unwrap_or_default();
    let scope = if row.matches_cwd { "·" } else { " " };
    let leading = format!("{scope} {}", row.harness.symbol());
    let display = render_row(
        Some(&leading),
        row.last_activity,
        &count(row.message_count, "msgs"),
        Some(&project_short(&key)),
        &row.title,
    );
    let title = clean_for_picker_display(&row.title);
    format!(
        "{}\t{}\t{}\t{}\t{}",
        row.harness.name(),
        tab_safe(&key),
        tab_safe(&row.session_id),
        display,
        tab_safe(&title),
    )
}

/// Inverse of [`format_picker_row`] — pulls (harness, key, session,
/// title) back out of the line the picker returned. Returns `None` if
/// the line is malformed.
fn parse_picker_row(line: &str) -> Option<(Harness, String, String, String)> {
    let mut parts = line.split('\t');
    let h = Harness::parse(parts.next()?)?;
    let key = parts.next()?.to_string();
    let session = parts.next()?.to_string();
    if session.is_empty() {
        return None;
    }
    // Skip the pre-formatted display column (col 4) to reach the raw
    // title at col 5.
    let title = parts.nth(1).unwrap_or("").to_string();
    Some((h, key, session, title))
}

use crate::fuzzy::{clean_for_picker_display, count, project_short, render_row, tab_safe};

fn derive_session(
    harness: Harness,
    project: Option<&str>,
    session: &str,
) -> Result<crate::cmd_import::DerivedDoc> {
    match harness {
        Harness::Claude => {
            crate::cmd_import::derive_claude_session(project.expect("project_keyed"), session)
        }
        Harness::Gemini => crate::cmd_import::derive_gemini_session(
            project.expect("project_keyed"),
            session,
            false,
        ),
        Harness::Pi => {
            crate::cmd_import::derive_pi_session(project.expect("project_keyed"), session, None)
        }
        Harness::Codex => crate::cmd_import::derive_codex_session(session),
        Harness::Opencode => crate::cmd_import::derive_opencode_session(session, false),
    }
}

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

    #[test]
    fn harness_name_and_symbol_are_distinct() {
        let all = [
            Harness::Claude,
            Harness::Gemini,
            Harness::Codex,
            Harness::Opencode,
            Harness::Pi,
        ];
        let names: Vec<&str> = all.iter().map(|h| h.name()).collect();
        let symbols: Vec<&str> = all.iter().map(|h| h.symbol()).collect();
        assert_eq!(names.len(), 5);
        assert_eq!(
            names.iter().collect::<std::collections::HashSet<_>>().len(),
            5,
            "names must be unique"
        );
        assert_eq!(
            symbols
                .iter()
                .collect::<std::collections::HashSet<_>>()
                .len(),
            5,
            "symbols must be unique"
        );
    }

    #[test]
    fn harness_project_keyed_matches_design() {
        assert!(Harness::Claude.project_keyed());
        assert!(Harness::Gemini.project_keyed());
        assert!(Harness::Pi.project_keyed());
        assert!(!Harness::Codex.project_keyed());
        assert!(!Harness::Opencode.project_keyed());
    }

    #[test]
    fn harness_from_arg_roundtrips() {
        for (arg, harness) in [
            (HarnessArg::Claude, Harness::Claude),
            (HarnessArg::Gemini, Harness::Gemini),
            (HarnessArg::Codex, Harness::Codex),
            (HarnessArg::Opencode, Harness::Opencode),
            (HarnessArg::Pi, Harness::Pi),
        ] {
            assert_eq!(Harness::from_arg(arg), harness);
        }
    }

    use std::path::Path;
    use tempfile::TempDir;

    fn write_claude_session(claude_dir: &Path, project_slug: &str, session: &str, prompt: &str) {
        let project_dir = claude_dir.join("projects").join(project_slug);
        std::fs::create_dir_all(&project_dir).unwrap();
        let user = format!(
            r#"{{"type":"user","uuid":"u-{session}","timestamp":"2024-01-02T00:00:00Z","cwd":"/test/project","message":{{"role":"user","content":"{prompt}"}}}}"#
        );
        let asst = format!(
            r#"{{"type":"assistant","uuid":"a-{session}","timestamp":"2024-01-02T00:00:01Z","message":{{"role":"assistant","content":"hi"}}}}"#
        );
        std::fs::write(
            project_dir.join(format!("{session}.jsonl")),
            format!("{user}\n{asst}\n"),
        )
        .unwrap();
    }

    fn claude_only_bundle(home: &Path) -> HarnessBundle {
        let claude_dir = home.join(".claude");
        std::fs::create_dir_all(&claude_dir).unwrap();
        let resolver = toolpath_claude::PathResolver::new().with_claude_dir(&claude_dir);
        HarnessBundle {
            claude: Some(toolpath_claude::ClaudeConvo::with_resolver(resolver)),
            ..Default::default()
        }
    }

    #[test]
    fn gather_sessions_includes_claude_rows_for_a_project() {
        let temp = TempDir::new().unwrap();
        write_claude_session(
            &temp.path().join(".claude"),
            "-test-project",
            "abc-session-one",
            "Add a feature",
        );
        let bundle = claude_only_bundle(temp.path());
        let cwd = Path::new("/test/project");
        let rows = gather_sessions(&bundle, cwd, None, None);

        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].harness, Harness::Claude);
        assert_eq!(rows[0].session_id, "abc-session-one");
        assert_eq!(rows[0].project.as_deref(), Some("/test/project"));
        assert!(rows[0].matches_cwd, "cwd should match the project path");
    }

    #[test]
    fn gather_sessions_marks_non_matching_project_rows() {
        let temp = TempDir::new().unwrap();
        write_claude_session(
            &temp.path().join(".claude"),
            "-test-project",
            "abc-session-one",
            "Add a feature",
        );
        let bundle = claude_only_bundle(temp.path());
        let cwd = Path::new("/some/other/place");
        let rows = gather_sessions(&bundle, cwd, None, None);

        assert_eq!(rows.len(), 1);
        assert!(!rows[0].matches_cwd);
    }

    #[test]
    fn gather_sessions_skips_harness_with_no_home_dir() {
        // Empty bundle => no rows, no panic.
        let bundle = HarnessBundle::default();
        let rows = gather_sessions(&bundle, Path::new("/anywhere"), None, None);
        assert!(rows.is_empty());
    }

    #[test]
    fn gather_sessions_filters_by_harness() {
        let temp = TempDir::new().unwrap();
        write_claude_session(
            &temp.path().join(".claude"),
            "-test-project",
            "abc-session-one",
            "hi",
        );
        let bundle = claude_only_bundle(temp.path());
        let cwd = Path::new("/test/project");
        let rows = gather_sessions(&bundle, cwd, Some(Harness::Codex), None);
        assert!(rows.is_empty(), "filter to codex must drop claude rows");
    }

    fn codex_only_bundle(home: &Path) -> HarnessBundle {
        let codex_dir = home.join(".codex");
        std::fs::create_dir_all(&codex_dir).unwrap();
        let resolver = toolpath_codex::PathResolver::new().with_codex_dir(&codex_dir);
        HarnessBundle {
            codex: Some(toolpath_codex::CodexConvo::with_resolver(resolver)),
            ..Default::default()
        }
    }

    fn write_codex_session(codex_dir: &Path, id: &str, cwd: &str) {
        // Date-bucketed layout: ~/.codex/sessions/YYYY/MM/DD/rollout-*-<id>.jsonl
        let dir = codex_dir.join("sessions/2026/05/07");
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join(format!("rollout-2026-05-07T00-00-00-{id}.jsonl"));
        let meta = format!(
            r#"{{"timestamp":"2026-05-07T00:00:00Z","type":"session_meta","payload":{{"id":"{id}","timestamp":"2026-05-07T00:00:00Z","cwd":"{cwd}","originator":"codex-tui","cli_version":"test","source":"cli","model_provider":"openai"}}}}"#
        );
        let user = r#"{"timestamp":"2026-05-07T00:00:01Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}}"#;
        std::fs::write(file, format!("{meta}\n{user}\n")).unwrap();
    }

    #[test]
    fn gather_sessions_includes_codex_rows_with_cwd_match() {
        let temp = TempDir::new().unwrap();
        write_codex_session(
            &temp.path().join(".codex"),
            "00000000-0000-0000-0000-0000000000aa",
            "/work/proj",
        );
        let bundle = codex_only_bundle(temp.path());
        let rows = gather_sessions(&bundle, Path::new("/work/proj"), None, None);
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].harness, Harness::Codex);
        assert_eq!(rows[0].cwd.as_deref(), Some("/work/proj"));
        assert!(rows[0].matches_cwd);
    }

    #[test]
    fn gather_sessions_ranks_cwd_matches_first() {
        // Two claude sessions: one in cwd (older), one elsewhere (newer).
        // Despite the elsewhere row being newer, the cwd-match must come first.
        let temp = TempDir::new().unwrap();
        let claude_dir = temp.path().join(".claude");
        write_claude_session(&claude_dir, "-cwd-project", "in-cwd-session", "hi");
        // Bump activity on the not-in-cwd session by writing a later timestamp.
        let not_dir = claude_dir.join("projects").join("-other-project");
        std::fs::create_dir_all(&not_dir).unwrap();
        std::fs::write(
            not_dir.join("not-in-cwd-session.jsonl"),
            r#"{"type":"user","uuid":"u-x","timestamp":"2030-01-01T00:00:00Z","cwd":"/other/project","message":{"role":"user","content":"later"}}"#.to_string()
                + "\n",
        )
        .unwrap();
        let bundle = claude_only_bundle(temp.path());
        let rows = gather_sessions(&bundle, Path::new("/cwd/project"), None, None);

        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].session_id, "in-cwd-session");
        assert!(rows[0].matches_cwd);
        assert!(!rows[1].matches_cwd);
    }

    #[test]
    #[cfg(unix)]
    fn paths_match_canonicalizes_through_symlink() {
        // `paths_match` is the function that produces `SessionRow.matches_cwd`
        // (collect_* all delegate to it). Without canonicalization, a user who
        // navigated to a project via a symlink would see their cwd-row sink
        // in the picker because the symlink path string ≠ the project path
        // string. Verify both arguments are canonicalized.
        //
        // Note: we test `paths_match` directly rather than going through
        // `gather_sessions` because Claude's project-dir slug encoding is
        // lossy (sanitize_project_path: '/', '_', '.' → '-'; unsanitize: only
        // '-' → '/'). On macOS, tempdir paths contain '.' and end up under
        // /private/var/..., so the unsanitized slug never round-trips back to
        // the real on-disk path. This direct test covers the canonicalization
        // bug regardless of platform-specific tempdir layouts.
        let temp = TempDir::new().unwrap();
        let real_project = temp.path().join("real-project");
        std::fs::create_dir_all(&real_project).unwrap();
        let symlink_path = temp.path().join("symlink-to-project");
        std::os::unix::fs::symlink(&real_project, &symlink_path).unwrap();

        // Sanity-check the setup: the symlink and its target are different
        // string-paths but resolve to the same canonical path.
        assert_ne!(real_project, symlink_path);
        assert_eq!(
            std::fs::canonicalize(&real_project).unwrap(),
            std::fs::canonicalize(&symlink_path).unwrap(),
        );

        // The actual property under test.
        assert!(
            paths_match(&real_project, &symlink_path),
            "paths_match must canonicalize both sides so symlink == target"
        );
        // And symmetric.
        assert!(
            paths_match(&symlink_path, &real_project),
            "paths_match must be symmetric across the symlink"
        );
    }

    #[test]
    fn parse_picker_row_roundtrips_keyed() {
        let row = SessionRow {
            harness: Harness::Claude,
            project: Some("/tmp/proj".to_string()),
            cwd: None,
            session_id: "sess-abc".to_string(),
            title: "Hello\tworld".to_string(),
            last_activity: None,
            message_count: 3,
            matches_cwd: true,
        };
        let line = format_picker_row(&row);
        let (harness, key, session, title) = parse_picker_row(&line).unwrap();
        assert_eq!(harness, Harness::Claude);
        assert_eq!(key, "/tmp/proj");
        assert_eq!(session, "sess-abc");
        // tab_safe replaces the tab with a space, but the title content
        // otherwise round-trips.
        assert_eq!(title, "Hello world");
    }

    #[test]
    fn parse_picker_row_roundtrips_session_keyed() {
        let row = SessionRow {
            harness: Harness::Codex,
            project: None,
            cwd: Some("/work/proj".to_string()),
            session_id: "0190abcd".to_string(),
            title: "(no prompt)".to_string(),
            last_activity: None,
            message_count: 0,
            matches_cwd: false,
        };
        let line = format_picker_row(&row);
        let (harness, key, session, title) = parse_picker_row(&line).unwrap();
        assert_eq!(harness, Harness::Codex);
        assert_eq!(key, "/work/proj"); // codex has no project; cwd carried as the keyed slot
        assert_eq!(session, "0190abcd");
        assert_eq!(title, "(no prompt)");
    }

    #[test]
    fn parse_picker_row_carries_title_with_unicode() {
        let row = SessionRow {
            harness: Harness::Gemini,
            project: Some("/work/proj".to_string()),
            cwd: None,
            session_id: "11111111-2222-3333-4444-555555555555".to_string(),
            title: "Add the share command — finally".to_string(),
            last_activity: None,
            message_count: 42,
            matches_cwd: true,
        };
        let line = format_picker_row(&row);
        let (_, _, _, title) = parse_picker_row(&line).unwrap();
        assert_eq!(title, "Add the share command — finally");
    }

    #[test]
    fn home_relative_strips_home_prefix() {
        let home = Path::new("/Users/alex");
        assert_eq!(
            home_relative(Path::new("/Users/alex/.claude/projects"), Some(home)),
            "~/.claude/projects"
        );
    }

    #[test]
    fn home_relative_returns_tilde_for_home_itself() {
        let home = Path::new("/Users/alex");
        assert_eq!(home_relative(home, Some(home)), "~");
    }

    #[test]
    fn home_relative_passes_through_paths_outside_home() {
        let home = Path::new("/Users/alex");
        assert_eq!(
            home_relative(Path::new("/tmp/elsewhere"), Some(home)),
            "/tmp/elsewhere"
        );
    }

    #[test]
    fn home_relative_passes_through_when_no_home() {
        assert_eq!(home_relative(Path::new("/foo/bar"), None), "/foo/bar");
    }

    #[test]
    fn harness_status_renders_existing_path_with_zero_sessions() {
        let s = HarnessStatus {
            path: "~/.claude/projects".to_string(),
            exists: true,
        };
        assert_eq!(s.render(), "~/.claude/projects (0 sessions)");
    }

    #[test]
    fn harness_status_renders_missing_path_as_not_found() {
        let s = HarnessStatus {
            path: "~/.gemini/tmp".to_string(),
            exists: false,
        };
        assert_eq!(s.render(), "~/.gemini/tmp not found");
    }

    #[test]
    fn format_status_line_pads_for_alignment() {
        let s = HarnessStatus {
            path: "~/.codex/sessions".to_string(),
            exists: true,
        };
        // "claude:" (7) needs 2 trailing spaces; "opencode:" (9) needs 0;
        // "pi:" (3) needs 6. The visible-path column should always start at
        // the same offset.
        let claude_line = format_status_line("claude", &s);
        let opencode_line = format_status_line("opencode", &s);
        let pi_line = format_status_line("pi", &s);
        let offset = |line: &str| line.find('~').unwrap();
        assert_eq!(offset(&claude_line), offset(&opencode_line));
        assert_eq!(offset(&claude_line), offset(&pi_line));
    }

    #[test]
    fn harness_status_for_missing_claude_dir_reports_not_found() {
        // Bundle whose claude resolver points at a directory that doesn't
        // exist on disk; the status should still resolve a path and report
        // it as missing rather than going through the `unresolved` branch.
        let temp = TempDir::new().unwrap();
        let claude_dir = temp.path().join(".claude"); // never created
        let resolver = toolpath_claude::PathResolver::new().with_claude_dir(&claude_dir);
        let bundle = HarnessBundle {
            claude: Some(toolpath_claude::ClaudeConvo::with_resolver(resolver)),
            ..Default::default()
        };
        let status = harness_status_claude(&bundle, None);
        assert!(!status.exists, "missing dir must report exists=false");
        assert!(
            status.path.contains("projects"),
            "path must include the projects subdir (got {:?})",
            status.path
        );
    }

    #[test]
    fn harness_status_for_present_claude_dir_reports_existence() {
        let temp = TempDir::new().unwrap();
        let claude_dir = temp.path().join(".claude");
        std::fs::create_dir_all(claude_dir.join("projects")).unwrap();
        let resolver = toolpath_claude::PathResolver::new().with_claude_dir(&claude_dir);
        let bundle = HarnessBundle {
            claude: Some(toolpath_claude::ClaudeConvo::with_resolver(resolver)),
            ..Default::default()
        };
        let status = harness_status_claude(&bundle, None);
        assert!(status.exists);
    }

    #[test]
    fn harness_status_for_empty_bundle_is_unresolved() {
        let bundle = HarnessBundle::default();
        // Every harness slot is None, so each status hits the unresolved branch.
        for status in [
            harness_status_claude(&bundle, None),
            harness_status_gemini(&bundle, None),
            harness_status_codex(&bundle, None),
            harness_status_opencode(&bundle, None),
            harness_status_pi(&bundle, None),
        ] {
            assert_eq!(status, HarnessStatus::unresolved());
            assert!(!status.exists);
        }
    }
}