supercode-interchange 0.4.2

Canonical, provider-neutral session interchange primitives for Supercode
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
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
//! Discovery and durable addressing for sessions written by external harnesses.
//!
//! [`HarnessCatalog`] is intentionally about persisted state. It does not
//! claim that the process which wrote a session is still alive or attachable.

use std::collections::{HashMap, HashSet};
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Read};
use std::path::{Component, Path, PathBuf};
use std::time::UNIX_EPOCH;

use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::native_store::load_native_store_family;
use crate::session::percent_decode_path;
use crate::{Error, Fidelity, Result, Session, SessionFollower};

/// Extensible identifier for a coding harness.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct HarnessId(pub String);

impl HarnessId {
    /// Claude Code's stable identifier.
    pub const CLAUDE_CODE: &'static str = "claude-code";
    /// Codex's stable identifier.
    pub const CODEX: &'static str = "codex";
    /// Pi's stable identifier.
    pub const PI: &'static str = "pi";
    /// OpenCode's stable identifier.
    pub const OPENCODE: &'static str = "opencode";
    /// Grok's stable identifier.
    pub const GROK: &'static str = "grok";
    /// Gemini CLI's stable identifier.
    pub const GEMINI: &'static str = "gemini";
    /// Goose's stable identifier.
    pub const GOOSE: &'static str = "goose";
    /// Supercode's native saved-session store.
    pub const SUPERCODE: &'static str = "supercode";

    /// Construct an identifier without restricting third-party harness names.
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Return the identifier as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<&str> for HarnessId {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

/// Durable storage address for a persisted session.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum StorageLocator {
    /// One session stored in one file.
    File {
        /// Absolute or caller-resolvable path to the transcript.
        path: PathBuf,
    },
    /// One logical session selected from a SQLite store.
    Sqlite {
        /// Path to the SQLite database.
        path: PathBuf,
        /// Harness-native stable selector, currently an OpenCode session id.
        selector: String,
    },
}

impl StorageLocator {
    /// Return the underlying file or database path.
    pub fn path(&self) -> &Path {
        match self {
            Self::File { path } | Self::Sqlite { path, .. } => path,
        }
    }
}

/// Stable identity for a persisted harness session.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SessionLocator {
    /// Harness which owns the storage format.
    pub harness: HarnessId,
    /// Harness-native session identity.
    pub session_id: String,
    /// Exact storage address needed to load the session again.
    pub storage: StorageLocator,
}

/// Lightweight metadata returned by catalog discovery.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SessionDescriptor {
    /// Durable address accepted by [`HarnessCatalog::load`] and
    /// [`HarnessCatalog::follow`].
    pub locator: SessionLocator,
    /// Working directory recorded by the harness.
    pub cwd: Option<PathBuf>,
    /// Harness-provided title, when cheaply available.
    pub title: Option<String>,
    /// Last update time as Unix epoch milliseconds.
    pub updated_at_ms: Option<u64>,
    /// Harness message-record count, when available without loading the session.
    pub message_count: Option<usize>,
    /// Model recorded in lightweight session metadata.
    pub model: Option<String>,
}

/// One stable newest-first discovery page.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DiscoveryPage {
    /// Sessions in this page.
    pub sessions: Vec<SessionDescriptor>,
    /// Opaque cursor for the next page, or `None` at the end.
    pub next_cursor: Option<String>,
}

/// Configurable session roots for the built-in harnesses.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct HarnessHomes {
    /// Directory containing Claude Code project session directories.
    pub claude_code: PathBuf,
    /// Directory containing Codex rollout sessions.
    pub codex: PathBuf,
    /// Directory containing Pi project session directories.
    pub pi: PathBuf,
    /// OpenCode data root, or an explicit `opencode*.db` path.
    pub opencode: PathBuf,
    /// Grok session root containing percent-encoded workspace directories.
    pub grok: PathBuf,
    /// Gemini CLI configuration root containing `projects.json` and `tmp/`.
    pub gemini: PathBuf,
    /// Goose `sessions.db`, or a directory containing it.
    pub goose: PathBuf,
    /// Supercode's native saved-session directory.
    pub supercode: PathBuf,
}

impl Default for HarnessHomes {
    fn default() -> Self {
        let home = std::env::var_os("HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("."));
        let claude_root = std::env::var_os("CLAUDE_CONFIG_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|| home.join(".claude"));
        let codex_root = std::env::var_os("CODEX_HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| home.join(".codex"));
        let pi = std::env::var_os("PI_CODING_AGENT_SESSION_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|| {
                std::env::var_os("PI_CODING_AGENT_DIR")
                    .map(PathBuf::from)
                    .unwrap_or_else(|| home.join(".pi/agent"))
                    .join("sessions")
            });
        let opencode = std::env::var_os("OPENCODE_DB")
            .map(PathBuf::from)
            .unwrap_or_else(|| {
                std::env::var_os("XDG_DATA_HOME")
                    .map(PathBuf::from)
                    .unwrap_or_else(|| home.join(".local/share"))
                    .join("opencode")
            });
        let grok = std::env::var_os("GROK_HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| home.join(".grok"))
            .join("sessions");
        let gemini = std::env::var_os("GEMINI_CLI_HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| home.join(".gemini"));
        let goose = std::env::var_os("GOOSE_PATH_ROOT")
            .map(PathBuf::from)
            .map(|root| root.join("data/sessions/sessions.db"))
            .unwrap_or_else(|| {
                #[cfg(target_os = "macos")]
                {
                    home.join("Library/Application Support/Block/goose/sessions/sessions.db")
                }
                #[cfg(target_os = "windows")]
                {
                    std::env::var_os("APPDATA")
                        .map(PathBuf::from)
                        .unwrap_or_else(|| home.join("AppData/Roaming"))
                        .join("Block/goose/sessions/sessions.db")
                }
                #[cfg(not(any(target_os = "macos", target_os = "windows")))]
                {
                    std::env::var_os("XDG_DATA_HOME")
                        .map(PathBuf::from)
                        .unwrap_or_else(|| home.join(".local/share"))
                        .join("goose/sessions/sessions.db")
                }
            });
        let supercode = std::env::var_os("SUPERCODE_HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| {
                std::env::var_os("XDG_CONFIG_HOME")
                    .map(PathBuf::from)
                    .unwrap_or_else(|| home.join(".config"))
                    .join("supercode")
            })
            .join("sessions");
        Self {
            claude_code: claude_root.join("projects"),
            codex: codex_root.join("sessions"),
            gemini,
            goose,
            supercode,
            pi,
            opencode,
            grok,
        }
    }
}

/// Filters and roots used for one catalog scan.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct DiscoveryQuery {
    /// Only return sessions whose recorded working directory is this path.
    pub workspace: Option<PathBuf>,
    /// Harnesses to scan. Empty means all built-ins.
    pub harnesses: Vec<HarnessId>,
    /// Storage roots to scan.
    pub homes: HarnessHomes,
    /// Case-insensitive search over harness, id, title, workspace, and model.
    pub query: Option<String>,
    /// Opaque cursor returned by a prior [`HarnessCatalog::discover_page`].
    pub cursor: Option<String>,
    /// Maximum number of results after newest-first sorting.
    pub limit: Option<usize>,
}

/// Read-only entry point for discovering, loading, and following persisted
/// harness sessions.
#[derive(Debug, Default, Clone, Copy)]
pub struct HarnessCatalog;

impl HarnessCatalog {
    /// Construct a catalog. It holds no cache or global mutable state.
    pub fn new() -> Self {
        Self
    }

    /// Discover sessions using lightweight headers/indexes rather than full
    /// transcript normalization. Malformed or concurrently-created entries
    /// are skipped without aborting the rest of the scan.
    pub fn discover(&self, query: &DiscoveryQuery) -> Result<Vec<SessionDescriptor>> {
        Ok(self.discover_page(query)?.sessions)
    }

    /// Discover one stable page and return the cursor for its successor.
    pub fn discover_page(&self, query: &DiscoveryQuery) -> Result<DiscoveryPage> {
        let selected: HashSet<&str> = if query.harnesses.is_empty() {
            [
                HarnessId::CLAUDE_CODE,
                HarnessId::CODEX,
                HarnessId::PI,
                HarnessId::OPENCODE,
                HarnessId::GROK,
                HarnessId::GEMINI,
                HarnessId::GOOSE,
                HarnessId::SUPERCODE,
            ]
            .into_iter()
            .collect()
        } else {
            query.harnesses.iter().map(HarnessId::as_str).collect()
        };
        let mut found = Vec::new();
        if selected.contains(HarnessId::CLAUDE_CODE) {
            discover_jsonl(
                &query.homes.claude_code,
                HarnessId::CLAUDE_CODE,
                query.workspace.as_deref(),
                &mut found,
            );
        }
        if selected.contains(HarnessId::CODEX) {
            discover_jsonl(
                &query.homes.codex,
                HarnessId::CODEX,
                query.workspace.as_deref(),
                &mut found,
            );
        }
        if selected.contains(HarnessId::PI) {
            discover_jsonl(
                &query.homes.pi,
                HarnessId::PI,
                query.workspace.as_deref(),
                &mut found,
            );
        }
        if selected.contains(HarnessId::OPENCODE) {
            discover_opencode(
                &query.homes.opencode,
                query.workspace.as_deref(),
                &mut found,
            );
        }
        if selected.contains(HarnessId::GROK) {
            discover_grok(&query.homes.grok, query.workspace.as_deref(), &mut found);
        }
        if selected.contains(HarnessId::GEMINI) {
            discover_gemini(&query.homes.gemini, query.workspace.as_deref(), &mut found);
        }
        if selected.contains(HarnessId::GOOSE) {
            discover_goose(&query.homes.goose, query.workspace.as_deref(), &mut found);
        }
        if selected.contains(HarnessId::SUPERCODE) {
            discover_supercode(
                &query.homes.supercode,
                query.workspace.as_deref(),
                &mut found,
            );
        }
        found.sort_by(|a, b| {
            b.updated_at_ms
                .cmp(&a.updated_at_ms)
                .then_with(|| a.locator.harness.cmp(&b.locator.harness))
                .then_with(|| a.locator.session_id.cmp(&b.locator.session_id))
        });
        if let Some(search) = query
            .query
            .as_deref()
            .map(str::trim)
            .filter(|q| !q.is_empty())
        {
            let search = search.to_lowercase();
            found.retain(|descriptor| descriptor_matches(descriptor, &search));
        }
        let start = match query.cursor.as_deref() {
            Some(cursor) => {
                let key = decode_cursor(cursor)?;
                found
                    .iter()
                    .position(|descriptor| descriptor_cursor_key(descriptor) == key)
                    .map(|index| index + 1)
                    .ok_or_else(|| Error::Other("discovery cursor is stale or invalid".into()))?
            }
            None => 0,
        };
        let end = query
            .limit
            .map(|limit| start.saturating_add(limit).min(found.len()))
            .unwrap_or(found.len());
        let sessions = found[start.min(found.len())..end].to_vec();
        let next_cursor = (end < found.len())
            .then(|| sessions.last().map(encode_cursor))
            .flatten();
        Ok(DiscoveryPage {
            sessions,
            next_cursor,
        })
    }

    /// Load the complete normalized session named by a durable locator.
    pub fn load(&self, locator: &SessionLocator) -> Result<Session> {
        self.load_with_fidelity(locator, Fidelity::ByteLossless)
    }

    /// [`Self::load`] at a declared fidelity.
    ///
    /// Read-only surfaces (a session mirror, `follow`) pass
    /// [`Fidelity::Semantic`] so a compacted transcript renders instead of
    /// erroring; every continuation/transfer/export caller keeps the strict
    /// default. See [`Session::load_with_fidelity`].
    pub fn load_with_fidelity(
        &self,
        locator: &SessionLocator,
        fidelity: Fidelity,
    ) -> Result<Session> {
        match &locator.storage {
            StorageLocator::File { path } => {
                if let Some(session) = load_native_store_family(path)? {
                    Ok(session)
                } else {
                    Ok(Session::load_with_fidelity(path, fidelity)?)
                }
            }
            StorageLocator::Sqlite { path, selector } => {
                if locator.harness.as_str() == HarnessId::GOOSE {
                    Ok(Session::from_goose_sqlite(path, selector)?)
                } else {
                    Ok(Session::from_opencode_sqlite(path, Some(selector))?)
                }
            }
        }
    }

    /// Load the selected parent transcript without recursively attaching
    /// Claude Code child sessions. This is the bounded frontend-view seam;
    /// lossless operations continue to use [`Self::load_with_fidelity`].
    #[doc(hidden)]
    pub fn load_parent_with_fidelity(
        &self,
        locator: &SessionLocator,
        fidelity: Fidelity,
    ) -> Result<Session> {
        match &locator.storage {
            StorageLocator::File { path } => {
                if let Some(session) = load_native_store_family(path)? {
                    Ok(session)
                } else {
                    Ok(Session::load_parent_with_fidelity(path, fidelity)?)
                }
            }
            StorageLocator::Sqlite { path, selector } => {
                if locator.harness.as_str() == HarnessId::GOOSE {
                    Ok(Session::from_goose_sqlite(path, selector)?)
                } else {
                    Ok(Session::from_opencode_sqlite(path, Some(selector))?)
                }
            }
        }
    }

    /// Load bounded parent-only human-visible history. Codex compaction
    /// changes resumable context but does not erase earlier visible turns.
    #[doc(hidden)]
    pub fn load_display_view(
        &self,
        locator: &SessionLocator,
        fidelity: Fidelity,
        message_limit: usize,
    ) -> Result<Session> {
        match &locator.storage {
            StorageLocator::File { path } => {
                if let Some(mut session) = load_native_store_family(path)? {
                    if session.messages.len() > message_limit.max(1) {
                        session
                            .messages
                            .drain(..session.messages.len() - message_limit.max(1));
                    }
                    Ok(session)
                } else {
                    Ok(Session::load_display_view(path, fidelity, message_limit)?)
                }
            }
            StorageLocator::Sqlite { path, selector } => {
                let mut session = if locator.harness.as_str() == HarnessId::GOOSE {
                    Session::from_goose_sqlite_display(path, selector, message_limit)?
                } else {
                    Session::from_opencode_sqlite(path, Some(selector))?
                };
                if session.messages.len() > message_limit.max(1) {
                    session
                        .messages
                        .drain(..session.messages.len() - message_limit.max(1));
                }
                Ok(session)
            }
        }
    }

    /// Open a passive change-triggered follower for a durable locator.
    pub fn follow(&self, locator: &SessionLocator) -> Result<SessionFollower> {
        self.follow_with_fidelity(locator, Fidelity::ByteLossless)
    }

    /// [`Self::follow`] at a declared fidelity — see [`Self::load_with_fidelity`].
    pub fn follow_with_fidelity(
        &self,
        locator: &SessionLocator,
        fidelity: Fidelity,
    ) -> Result<SessionFollower> {
        SessionFollower::open_locator_with_fidelity(locator, fidelity)
    }

    /// Follow a read-only view with explicit child-tree and history bounds.
    #[doc(hidden)]
    pub fn follow_read_view(
        &self,
        locator: &SessionLocator,
        fidelity: Fidelity,
        include_subagents: bool,
        message_limit: Option<usize>,
        max_message_chars: Option<usize>,
        display_history: bool,
    ) -> Result<SessionFollower> {
        SessionFollower::open_locator_with_view(
            locator,
            fidelity,
            include_subagents,
            message_limit,
            max_message_chars,
            display_history,
        )
    }
}

fn descriptor_matches(descriptor: &SessionDescriptor, search: &str) -> bool {
    [
        Some(descriptor.locator.harness.as_str()),
        Some(descriptor.locator.session_id.as_str()),
        descriptor.title.as_deref(),
        descriptor.cwd.as_ref().and_then(|path| path.to_str()),
        descriptor.model.as_deref(),
    ]
    .into_iter()
    .flatten()
    .any(|value| value.to_lowercase().contains(search))
}

fn descriptor_cursor_key(descriptor: &SessionDescriptor) -> (Option<u64>, String, String) {
    (
        descriptor.updated_at_ms,
        descriptor.locator.harness.as_str().to_string(),
        descriptor.locator.session_id.clone(),
    )
}

fn encode_cursor(descriptor: &SessionDescriptor) -> String {
    let json = serde_json::to_vec(&descriptor_cursor_key(descriptor)).unwrap_or_default();
    let mut encoded = String::with_capacity(json.len() * 2);
    for byte in json {
        use std::fmt::Write;
        let _ = write!(&mut encoded, "{byte:02x}");
    }
    encoded
}

fn decode_cursor(cursor: &str) -> Result<(Option<u64>, String, String)> {
    if cursor.len() % 2 != 0 {
        return Err(Error::Other("discovery cursor is invalid".into()));
    }
    let bytes = (0..cursor.len())
        .step_by(2)
        .map(|index| u8::from_str_radix(&cursor[index..index + 2], 16))
        .collect::<std::result::Result<Vec<_>, _>>()
        .map_err(|_| Error::Other("discovery cursor is invalid".into()))?;
    serde_json::from_slice(&bytes).map_err(|_| Error::Other("discovery cursor is invalid".into()))
}

#[derive(Default)]
struct HeaderMeta {
    session_id: Option<String>,
    cwd: Option<PathBuf>,
    model: Option<String>,
}

fn discover_jsonl(
    root: &Path,
    harness: &str,
    workspace: Option<&Path>,
    found: &mut Vec<SessionDescriptor>,
) {
    let mut files = Vec::new();
    collect_jsonl(root, harness, &mut files);
    for path in files {
        let Ok(meta) = read_header(&path, harness) else {
            continue;
        };
        if workspace.is_some_and(|wanted| {
            meta.cwd
                .as_deref()
                .is_none_or(|cwd| !recorded_cwd_matches(cwd, wanted))
        }) {
            continue;
        }
        let session_id = meta.session_id.unwrap_or_else(|| {
            path.file_stem()
                .and_then(|value| value.to_str())
                .unwrap_or("unknown")
                .to_string()
        });
        found.push(SessionDescriptor {
            locator: SessionLocator {
                harness: HarnessId::new(harness),
                session_id,
                storage: StorageLocator::File { path: path.clone() },
            },
            cwd: meta.cwd,
            title: None,
            updated_at_ms: modified_ms(&path),
            message_count: None,
            model: meta.model,
        });
    }
}

fn collect_jsonl(root: &Path, harness: &str, out: &mut Vec<PathBuf>) {
    let Ok(entries) = fs::read_dir(root) else {
        return;
    };
    for entry in entries.flatten() {
        let Ok(kind) = entry.file_type() else {
            continue;
        };
        let path = entry.path();
        if kind.is_dir() {
            if harness == HarnessId::CLAUDE_CODE
                && path.file_name().and_then(|v| v.to_str()) == Some("subagents")
            {
                continue;
            }
            collect_jsonl(&path, harness, out);
        } else if kind.is_file() && path.extension().and_then(|v| v.to_str()) == Some("jsonl") {
            out.push(path);
        }
    }
}

fn read_header(path: &Path, harness: &str) -> Result<HeaderMeta> {
    let file = File::open(path)?;
    let mut result = HeaderMeta::default();
    let mut bytes = 0usize;
    for line in BufReader::new(file).lines().take(32) {
        let line = line?;
        bytes += line.len();
        if bytes > 256 * 1024 {
            break;
        }
        let Ok(value) = serde_json::from_str::<Value>(&line) else {
            continue;
        };
        match harness {
            HarnessId::CLAUDE_CODE => {
                fill_string(&mut result.session_id, value.get("sessionId"));
                fill_path(&mut result.cwd, value.get("cwd"));
                fill_string(
                    &mut result.model,
                    value.get("message").and_then(|v| v.get("model")),
                );
            }
            HarnessId::CODEX => {
                let payload = value.get("payload").unwrap_or(&Value::Null);
                if value.get("type").and_then(Value::as_str) == Some("session_meta") {
                    fill_string(&mut result.session_id, payload.get("id"));
                    fill_path(&mut result.cwd, payload.get("cwd"));
                }
                if value.get("type").and_then(Value::as_str) == Some("turn_context") {
                    fill_path(&mut result.cwd, payload.get("cwd"));
                    fill_string(&mut result.model, payload.get("model"));
                }
            }
            HarnessId::PI => {
                if value.get("type").and_then(Value::as_str) == Some("session") {
                    fill_string(&mut result.session_id, value.get("id"));
                    fill_path(&mut result.cwd, value.get("cwd"));
                }
                fill_string(
                    &mut result.model,
                    value.get("message").and_then(|v| v.get("model")),
                );
            }
            _ => {}
        }
        if result.session_id.is_some() && result.cwd.is_some() && result.model.is_some() {
            break;
        }
    }
    if result.session_id.is_none() && result.cwd.is_none() {
        return Err(Error::Other(format!(
            "{} has no recognizable {harness} session header",
            path.display()
        )));
    }
    Ok(result)
}

fn discover_gemini(root: &Path, workspace: Option<&Path>, found: &mut Vec<SessionDescriptor>) {
    let slug_to_cwd = std::fs::read_to_string(root.join("projects.json"))
        .ok()
        .and_then(|text| serde_json::from_str::<Value>(&text).ok())
        .and_then(|value| value.get("projects").and_then(Value::as_object).cloned())
        .map(|projects| {
            projects
                .into_iter()
                .filter_map(|(cwd, slug)| Some((slug.as_str()?.to_string(), PathBuf::from(cwd))))
                .collect::<HashMap<_, _>>()
        })
        .unwrap_or_default();
    let mut files = Vec::new();
    collect_jsonl(&root.join("tmp"), HarnessId::GEMINI, &mut files);
    let worker_count = std::thread::available_parallelism()
        .map(usize::from)
        .unwrap_or(4)
        .clamp(1, 8)
        .min(files.len().max(1));
    let chunk_size = files.len().max(1).div_ceil(worker_count);
    let discovered = std::thread::scope(|scope| {
        files
            .chunks(chunk_size)
            .map(|paths| {
                scope.spawn(|| {
                    paths
                        .iter()
                        .filter_map(|path| gemini_descriptor(path, &slug_to_cwd, workspace))
                        .collect::<Vec<_>>()
                })
            })
            .collect::<Vec<_>>()
            .into_iter()
            .flat_map(|worker| {
                worker
                    .join()
                    .expect("Gemini discovery worker must not panic")
            })
            .collect::<Vec<_>>()
    });
    found.extend(discovered);
}

fn gemini_descriptor(
    path: &Path,
    slug_to_cwd: &HashMap<String, PathBuf>,
    workspace: Option<&Path>,
) -> Option<SessionDescriptor> {
    if path
        .parent()
        .and_then(Path::file_name)
        .and_then(|name| name.to_str())
        != Some("chats")
    {
        return None;
    }
    let slug = path
        .parent()
        .and_then(Path::parent)
        .and_then(Path::file_name)
        .and_then(|name| name.to_str());
    let cwd = slug.and_then(|slug| slug_to_cwd.get(slug)).cloned();
    if workspace.is_some_and(|wanted| {
        cwd.as_deref()
            .is_none_or(|actual| !recorded_cwd_matches(actual, wanted))
    }) {
        return None;
    }

    // The native session id lives on line one. A small decoration budget keeps
    // the common title/model case without turning 1,800 sessions into a
    // sequential 60 MiB read before the list can render.
    let file = File::open(path).ok()?;
    let mut reader = BufReader::new(file.take(64 * 1024));
    let mut header = String::new();
    reader.read_line(&mut header).ok()?;
    let header = serde_json::from_str::<Value>(&header).ok()?;
    let session_id = header.get("sessionId")?.as_str()?.to_string();
    let mut model = None;
    let mut title = None;
    for line in reader
        .take(4 * 1024)
        .lines()
        .map_while(std::result::Result::ok)
    {
        let Ok(value) = serde_json::from_str::<Value>(&line) else {
            continue;
        };
        let kind = value.get("type").and_then(Value::as_str);
        if kind != Some("user") && kind != Some("gemini") {
            continue;
        }
        if model.is_none() {
            model = value
                .get("model")
                .and_then(Value::as_str)
                .map(str::to_string);
        }
        if title.is_none() && kind == Some("user") {
            title = display_text(value.get("content")).filter(|text| !text.is_empty());
        }
        if model.is_some() && title.is_some() {
            break;
        }
    }
    Some(SessionDescriptor {
        locator: SessionLocator {
            harness: HarnessId::from(HarnessId::GEMINI),
            session_id,
            storage: StorageLocator::File {
                path: path.to_path_buf(),
            },
        },
        cwd,
        title: title.map(|title| truncate_title(&title)),
        updated_at_ms: modified_ms(path),
        message_count: None,
        model,
    })
}

fn display_text(content: Option<&Value>) -> Option<String> {
    match content? {
        Value::String(text) => Some(text.clone()),
        Value::Array(parts) => Some(
            parts
                .iter()
                .filter_map(|part| part.get("text").and_then(Value::as_str))
                .collect::<Vec<_>>()
                .join(" ")
                .trim()
                .to_string(),
        ),
        _ => None,
    }
}

fn truncate_title(title: &str) -> String {
    const MAX_CHARS: usize = 120;
    let mut value = title.chars().take(MAX_CHARS).collect::<String>();
    if title.chars().count() > MAX_CHARS {
        value.push('');
    }
    value
}

fn discover_supercode(root: &Path, workspace: Option<&Path>, found: &mut Vec<SessionDescriptor>) {
    for info in list_native_store(root) {
        let path = if info.archived {
            root.join("archived").join(format!("{}.jsonl", info.name))
        } else {
            root.join(format!("{}.jsonl", info.name))
        };
        let loaded = workspace
            .is_some()
            .then(|| load_native_store_family(&path))
            .transpose()
            .ok()
            .flatten()
            .flatten();
        if workspace.is_some_and(|wanted| {
            loaded
                .as_ref()
                .and_then(|session| session.meta.cwd.as_deref())
                .is_none_or(|cwd| !recorded_cwd_matches(cwd, wanted))
        }) {
            continue;
        }
        let title = (!info.title.trim().is_empty()).then_some(info.title);
        let updated_at_ms =
            modified_ms(&path).or_else(|| modified_ms(&path.with_extension("sidecar.jsonl")));
        found.push(SessionDescriptor {
            locator: SessionLocator {
                harness: HarnessId::from(HarnessId::SUPERCODE),
                session_id: info.name,
                storage: StorageLocator::File { path: path.clone() },
            },
            cwd: loaded.as_ref().and_then(|session| session.meta.cwd.clone()),
            title,
            updated_at_ms,
            message_count: loaded.as_ref().map(|session| session.messages.len()),
            model: loaded.and_then(|session| session.meta.model),
        });
    }
}

#[derive(Deserialize)]
struct NativeStoreInfo {
    name: String,
    #[serde(default)]
    title: String,
    #[serde(skip)]
    archived: bool,
}

fn list_native_store(root: &Path) -> Vec<NativeStoreInfo> {
    let mut sessions = Vec::new();
    for archived in [false, true] {
        let directory = if archived {
            root.join("archived")
        } else {
            root.to_path_buf()
        };
        let Ok(entries) = fs::read_dir(directory) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.to_string_lossy().ends_with(".meta.json") {
                continue;
            }
            let Ok(text) = fs::read_to_string(path) else {
                continue;
            };
            let Ok(mut info) = serde_json::from_str::<NativeStoreInfo>(&text) else {
                continue;
            };
            info.archived = archived;
            sessions.push(info);
        }
    }
    sessions.sort_by(|left, right| left.name.cmp(&right.name));
    sessions
}

fn discover_grok(root: &Path, workspace: Option<&Path>, found: &mut Vec<SessionDescriptor>) {
    let Ok(workspaces) = fs::read_dir(root) else {
        return;
    };
    for workspace_entry in workspaces.flatten() {
        let encoded = workspace_entry.file_name();
        let Some(cwd) = encoded
            .to_str()
            .and_then(percent_decode_path)
            .map(PathBuf::from)
        else {
            continue;
        };
        if workspace.is_some_and(|wanted| !recorded_cwd_matches(&cwd, wanted)) {
            continue;
        }
        let Ok(sessions) = fs::read_dir(workspace_entry.path()) else {
            continue;
        };
        for session_entry in sessions.flatten() {
            let session_dir = session_entry.path();
            if !session_dir.is_dir() {
                continue;
            }
            let transcript = session_dir.join("chat_history.jsonl");
            if !transcript.is_file() {
                continue;
            }
            let Some(session_id) = session_dir
                .file_name()
                .and_then(|name| name.to_str())
                .map(str::to_string)
            else {
                continue;
            };
            let summary = fs::read_to_string(session_dir.join("summary.json"))
                .ok()
                .and_then(|text| serde_json::from_str::<Value>(&text).ok());
            let title = summary
                .as_ref()
                .and_then(|value| value.get("generated_title"))
                .and_then(Value::as_str)
                .filter(|title| !title.is_empty())
                .map(str::to_string);
            let model = summary
                .as_ref()
                .and_then(|value| value.get("current_model_id"))
                .and_then(Value::as_str)
                .map(str::to_string);
            let message_count = summary
                .as_ref()
                .and_then(|value| value.get("num_chat_messages"))
                .and_then(Value::as_u64)
                .and_then(|count| usize::try_from(count).ok());
            let updated_at_ms = summary
                .as_ref()
                .and_then(|value| value.get("updated_at"))
                .and_then(Value::as_str)
                .and_then(crate::sidecar::rfc3339_to_ms)
                .and_then(|millis| u64::try_from(millis).ok())
                .or_else(|| modified_ms(&transcript));
            found.push(SessionDescriptor {
                locator: SessionLocator {
                    harness: HarnessId::from(HarnessId::GROK),
                    session_id,
                    storage: StorageLocator::File { path: transcript },
                },
                cwd: Some(cwd.clone()),
                title,
                updated_at_ms,
                message_count,
                model,
            });
        }
    }
}

fn discover_opencode(root: &Path, workspace: Option<&Path>, found: &mut Vec<SessionDescriptor>) {
    let mut dbs = Vec::new();
    if root.is_file() {
        dbs.push(root.to_path_buf());
    } else if let Ok(entries) = fs::read_dir(root) {
        dbs.extend(entries.flatten().map(|entry| entry.path()).filter(|path| {
            path.file_name()
                .and_then(|v| v.to_str())
                .is_some_and(|name| name.starts_with("opencode") && name.ends_with(".db"))
        }));
    }
    dbs.sort();
    for db in dbs {
        let Ok(conn) = Connection::open_with_flags(
            &db,
            rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
        ) else {
            continue;
        };
        let has_model = conn.prepare("SELECT model FROM session LIMIT 0").is_ok();
        let model_column = if has_model { "s.model" } else { "NULL" };
        let query = format!(
            "SELECT s.id, s.directory, s.title, s.time_updated, {model_column}, COUNT(m.id) \
             FROM session s LEFT JOIN message m ON m.session_id = s.id \
             GROUP BY s.id ORDER BY s.time_updated DESC"
        );
        let Ok(mut stmt) = conn.prepare(&query) else {
            continue;
        };
        let Ok(rows) = stmt.query_map([], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
                row.get::<_, i64>(3)?,
                row.get::<_, Option<String>>(4)?,
                row.get::<_, i64>(5)?,
            ))
        }) else {
            continue;
        };
        for row in rows.flatten() {
            let (id, cwd, title, updated, model, messages) = row;
            let cwd = PathBuf::from(cwd);
            if workspace.is_some_and(|wanted| !recorded_cwd_matches(&cwd, wanted)) {
                continue;
            }
            found.push(SessionDescriptor {
                locator: SessionLocator {
                    harness: HarnessId::from(HarnessId::OPENCODE),
                    session_id: id.clone(),
                    storage: StorageLocator::Sqlite {
                        path: db.clone(),
                        selector: id,
                    },
                },
                cwd: Some(cwd),
                title: (!title.is_empty()).then_some(title),
                updated_at_ms: u64::try_from(updated).ok(),
                message_count: usize::try_from(messages).ok(),
                model,
            });
        }
    }
}

fn discover_goose(root: &Path, workspace: Option<&Path>, found: &mut Vec<SessionDescriptor>) {
    let db = if root.is_file() {
        root.to_path_buf()
    } else if root.join("sessions.db").is_file() {
        root.join("sessions.db")
    } else {
        root.join("sessions/sessions.db")
    };
    let Ok(connection) = Connection::open_with_flags(
        &db,
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
    ) else {
        return;
    };
    let Ok(mut statement) = connection.prepare(
        "SELECT s.id, s.working_dir, s.name, s.updated_at, s.model_config_json, \
                COUNT(m.id) \
         FROM sessions s LEFT JOIN messages m ON m.session_id = s.id \
         WHERE s.archived_at IS NULL \
         GROUP BY s.id ORDER BY s.updated_at DESC",
    ) else {
        return;
    };
    let Ok(rows) = statement.query_map([], |row| {
        Ok((
            row.get::<_, String>(0)?,
            row.get::<_, String>(1)?,
            row.get::<_, String>(2)?,
            row.get::<_, String>(3)?,
            row.get::<_, Option<String>>(4)?,
            row.get::<_, i64>(5)?,
        ))
    }) else {
        return;
    };
    for row in rows.flatten() {
        let (id, cwd, title, updated_at, model_config, message_count) = row;
        let cwd = PathBuf::from(cwd);
        if workspace.is_some_and(|wanted| !recorded_cwd_matches(&cwd, wanted)) {
            continue;
        }
        let model = model_config
            .as_deref()
            .and_then(|value| serde_json::from_str::<Value>(value).ok())
            .and_then(|value| {
                value
                    .get("model_name")
                    .or_else(|| value.get("modelName"))
                    .and_then(Value::as_str)
                    .map(str::to_string)
            });
        let updated_at_ms = crate::sidecar::rfc3339_to_ms(&updated_at)
            .or_else(|| {
                // SQLite's CURRENT_TIMESTAMP uses `YYYY-MM-DD HH:MM:SS`.
                crate::sidecar::rfc3339_to_ms(&format!("{}Z", updated_at.replace(' ', "T")))
            })
            .and_then(|value| u64::try_from(value).ok());
        found.push(SessionDescriptor {
            locator: SessionLocator {
                harness: HarnessId::from(HarnessId::GOOSE),
                session_id: id.clone(),
                storage: StorageLocator::Sqlite {
                    path: db.clone(),
                    selector: id,
                },
            },
            cwd: Some(cwd),
            title: (!title.trim().is_empty()).then_some(title),
            updated_at_ms,
            message_count: usize::try_from(message_count).ok(),
            model,
        });
    }
}

fn fill_string(target: &mut Option<String>, value: Option<&Value>) {
    if target.is_none() {
        *target = value.and_then(Value::as_str).map(str::to_owned);
    }
}

fn fill_path(target: &mut Option<PathBuf>, value: Option<&Value>) {
    if target.is_none() {
        *target = value.and_then(Value::as_str).map(PathBuf::from);
    }
}

fn modified_ms(path: &Path) -> Option<u64> {
    fs::metadata(path)
        .ok()?
        .modified()
        .ok()?
        .duration_since(UNIX_EPOCH)
        .ok()
        .and_then(|duration| u64::try_from(duration.as_millis()).ok())
}

/// A workspace filter is satisfiable only by a session whose RECORDED working
/// directory is absolute. A relative recorded cwd (OpenCode has shipped
/// literal `"."` session rows) carries no information about where the session
/// ran; resolving it against the discoverer's own current directory made such
/// a session match every workspace discovery happened to run from.
fn recorded_cwd_matches(recorded: &Path, wanted: &Path) -> bool {
    recorded.is_absolute() && same_path(recorded, wanted)
}

fn same_path(left: &Path, right: &Path) -> bool {
    match (fs::canonicalize(left), fs::canonicalize(right)) {
        (Ok(left), Ok(right)) => left == right,
        _ => normalize_path(left) == normalize_path(right),
    }
}

fn normalize_path(path: &Path) -> PathBuf {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("."))
            .join(path)
    };
    let mut normalized = PathBuf::new();
    for component in absolute.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                normalized.pop();
            }
            other => normalized.push(other.as_os_str()),
        }
    }
    normalized
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_dir(label: &str) -> PathBuf {
        let nonce = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let path = std::env::temp_dir().join(format!(
            "supercode-catalog-{label}-{}-{nonce}",
            std::process::id()
        ));
        fs::create_dir_all(&path).unwrap();
        path
    }

    #[test]
    fn locator_json_round_trip_preserves_sqlite_selector() {
        let locator = SessionLocator {
            harness: HarnessId::from(HarnessId::OPENCODE),
            session_id: "ses_123".into(),
            storage: StorageLocator::Sqlite {
                path: PathBuf::from("/tmp/opencode-dev.db"),
                selector: "ses_123".into(),
            },
        };
        let encoded = serde_json::to_string(&locator).unwrap();
        assert_eq!(
            serde_json::from_str::<SessionLocator>(&encoded).unwrap(),
            locator
        );
    }

    #[test]
    fn discovers_filters_loads_and_follows_three_jsonl_harnesses() {
        let root = temp_dir("jsonl");
        let workspace = root.join("workspace");
        let other = root.join("other");
        fs::create_dir_all(&workspace).unwrap();
        fs::create_dir_all(&other).unwrap();

        let claude = root.join("claude");
        let codex = root.join("codex");
        let pi = root.join("pi");
        fs::create_dir_all(&claude).unwrap();
        fs::create_dir_all(&codex).unwrap();
        fs::create_dir_all(&pi).unwrap();
        fs::write(
            claude.join("claude.jsonl"),
            format!(
                "{{\"type\":\"user\",\"sessionId\":\"cc-1\",\"cwd\":{},\"message\":{{\"role\":\"user\",\"content\":\"hi\"}}}}\n",
                serde_json::to_string(&workspace.to_string_lossy()).unwrap()
            ),
        )
        .unwrap();
        fs::write(
            codex.join("rollout.jsonl"),
            format!(
                "{{\"timestamp\":\"2026-01-01T00:00:00Z\",\"type\":\"session_meta\",\"payload\":{{\"id\":\"cx-1\",\"cwd\":{}}}}}\n",
                serde_json::to_string(&workspace.to_string_lossy()).unwrap()
            ),
        )
        .unwrap();
        fs::write(
            pi.join("pi.jsonl"),
            format!(
                "{{\"type\":\"session\",\"version\":3,\"id\":\"pi-1\",\"timestamp\":\"2026-01-01T00:00:00Z\",\"cwd\":{}}}\n",
                serde_json::to_string(&workspace.to_string_lossy()).unwrap()
            ),
        )
        .unwrap();
        fs::write(
            pi.join("unrelated.jsonl"),
            format!(
                "{{\"type\":\"session\",\"version\":3,\"id\":\"pi-2\",\"timestamp\":\"2026-01-01T00:00:00Z\",\"cwd\":{}}}\n",
                serde_json::to_string(&other.to_string_lossy()).unwrap()
            ),
        )
        .unwrap();
        fs::write(claude.join("partial.jsonl"), "{truncated").unwrap();

        let query = DiscoveryQuery {
            workspace: Some(workspace),
            homes: HarnessHomes {
                claude_code: claude,
                codex,
                pi,
                opencode: root.join("missing-opencode"),
                grok: root.join("missing-grok"),
                gemini: root.join("missing-gemini"),
                goose: root.join("missing-goose"),
                supercode: root.join("missing-supercode"),
            },
            ..DiscoveryQuery::default()
        };
        let catalog = HarnessCatalog::new();
        let found = catalog.discover(&query).unwrap();
        assert_eq!(found.len(), 3);
        assert_eq!(
            found
                .iter()
                .map(|item| item.locator.harness.as_str())
                .collect::<HashSet<_>>(),
            HashSet::from([HarnessId::CLAUDE_CODE, HarnessId::CODEX, HarnessId::PI])
        );
        for descriptor in found {
            let loaded = catalog.load(&descriptor.locator).unwrap();
            assert_eq!(
                loaded.meta.session_id.as_deref(),
                Some(descriptor.locator.session_id.as_str())
            );
            let mut follower = catalog.follow(&descriptor.locator).unwrap();
            assert!(matches!(
                follower.poll().unwrap(),
                Some(crate::SessionWatchEvent::SessionSnapshot { .. })
            ));
        }
        fs::remove_dir_all(root).ok();
    }

    #[test]
    fn discovers_loads_and_follows_opencode_sqlite() {
        let db = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../harness/tests/fixtures/opencode_fixture/opencode.db");
        let catalog = HarnessCatalog::new();
        let found = catalog
            .discover(&DiscoveryQuery {
                harnesses: vec![HarnessId::from(HarnessId::OPENCODE)],
                homes: HarnessHomes {
                    opencode: db,
                    ..HarnessHomes::default()
                },
                ..DiscoveryQuery::default()
            })
            .unwrap();
        assert!(!found.is_empty());
        for descriptor in found {
            assert_eq!(descriptor.locator.harness.as_str(), HarnessId::OPENCODE);
            assert_eq!(
                catalog.load(&descriptor.locator).unwrap().meta.session_id,
                Some(descriptor.locator.session_id.clone())
            );
            assert!(catalog.follow(&descriptor.locator).is_ok());
        }
    }

    #[test]
    fn discovers_loads_and_follows_gemini_conversation_records() {
        let root = temp_dir("gemini");
        let workspace = root.join("workspace");
        let chats = root.join("gemini/tmp/demo/chats");
        fs::create_dir_all(&workspace).unwrap();
        fs::create_dir_all(&chats).unwrap();
        fs::write(
            root.join("gemini/projects.json"),
            serde_json::json!({
                "projects": {workspace.to_string_lossy(): "demo"}
            })
            .to_string(),
        )
        .unwrap();
        let transcript = chats.join("gemini-id.jsonl");
        fs::write(
            &transcript,
            include_str!("../../harness/tests/fixtures/gemini_session.jsonl"),
        )
        .unwrap();

        let catalog = HarnessCatalog::new();
        let found = catalog
            .discover(&DiscoveryQuery {
                harnesses: vec![HarnessId::from(HarnessId::GEMINI)],
                homes: HarnessHomes {
                    gemini: root.join("gemini"),
                    ..HarnessHomes::default()
                },
                workspace: Some(workspace.clone()),
                ..DiscoveryQuery::default()
            })
            .unwrap();

        assert_eq!(found.len(), 1);
        assert_eq!(found[0].cwd.as_deref(), Some(workspace.as_path()));
        assert_eq!(found[0].message_count, None);
        assert_eq!(found[0].model.as_deref(), Some("gemini-2.5-pro"));
        assert_eq!(found[0].title.as_deref(), Some("Inspect the fixture."));
        let loaded = catalog.load(&found[0].locator).unwrap();
        assert_eq!(
            loaded.meta.session_id.as_deref(),
            Some("11111111-1111-4111-8111-111111111111")
        );
        assert_eq!(loaded.messages.len(), 4);
        assert!(matches!(
            catalog.follow(&found[0].locator).unwrap().poll().unwrap(),
            Some(crate::SessionWatchEvent::SessionSnapshot { .. })
        ));
        fs::remove_dir_all(root).ok();
    }

    #[test]
    fn discovers_native_store_and_pages_search_results() {
        let root = temp_dir("supercode");
        let store_root = root.join("sessions");
        fs::create_dir_all(&store_root).unwrap();
        for (name, title) in [
            ("alpha", "Alpha planning"),
            ("beta", "Beta implementation"),
            ("gamma", "Gamma review"),
        ] {
            fs::write(
                store_root.join(format!("{name}.jsonl")),
                format!("{{\"role\":\"user\",\"content\":\"{title}\"}}\n"),
            )
            .unwrap();
            fs::write(
                store_root.join(format!("{name}.meta.json")),
                serde_json::json!({"name": name, "title": title}).to_string(),
            )
            .unwrap();
        }
        let catalog = HarnessCatalog::new();
        let base = DiscoveryQuery {
            harnesses: vec![HarnessId::from(HarnessId::SUPERCODE)],
            homes: HarnessHomes {
                supercode: store_root,
                ..HarnessHomes::default()
            },
            limit: Some(1),
            ..DiscoveryQuery::default()
        };

        let first = catalog.discover_page(&base).unwrap();
        assert_eq!(first.sessions.len(), 1);
        assert!(first.next_cursor.is_some());
        let second = catalog
            .discover_page(&DiscoveryQuery {
                cursor: first.next_cursor,
                ..base.clone()
            })
            .unwrap();
        assert_eq!(second.sessions.len(), 1);
        assert_ne!(
            first.sessions[0].locator.session_id,
            second.sessions[0].locator.session_id
        );
        let search = catalog
            .discover_page(&DiscoveryQuery {
                limit: None,
                query: Some("implementation".into()),
                ..base
            })
            .unwrap();
        assert_eq!(search.sessions.len(), 1);
        assert_eq!(search.sessions[0].locator.session_id, "beta");
        assert_eq!(search.sessions[0].message_count, None);
        assert_eq!(
            catalog
                .load(&search.sessions[0].locator)
                .unwrap()
                .messages
                .len(),
            1
        );
        fs::remove_dir_all(root).ok();
    }

    #[test]
    fn discovers_current_opencode_schema_without_a_session_model_column() {
        let root = temp_dir("opencode-current");
        let db = root.join("opencode.db");
        let conn = Connection::open(&db).unwrap();
        conn.execute_batch(
            "CREATE TABLE session (
                id TEXT PRIMARY KEY,
                directory TEXT NOT NULL,
                title TEXT NOT NULL,
                time_updated INTEGER NOT NULL
             );
             CREATE TABLE message (
                id TEXT PRIMARY KEY,
                session_id TEXT NOT NULL
             );
             INSERT INTO session VALUES ('ses_current', '/tmp/work', 'Current', 42);
             INSERT INTO message VALUES ('msg_current', 'ses_current');",
        )
        .unwrap();
        drop(conn);

        let found = HarnessCatalog::new()
            .discover(&DiscoveryQuery {
                harnesses: vec![HarnessId::from(HarnessId::OPENCODE)],
                homes: HarnessHomes {
                    opencode: db,
                    ..HarnessHomes::default()
                },
                ..DiscoveryQuery::default()
            })
            .unwrap();

        assert_eq!(found.len(), 1);
        assert_eq!(found[0].locator.session_id, "ses_current");
        assert_eq!(found[0].message_count, Some(1));
        assert_eq!(found[0].model, None);
        fs::remove_dir_all(root).ok();
    }

    #[test]
    fn workspace_filter_never_matches_a_relative_recorded_cwd() {
        // OpenCode has shipped session rows whose `directory` is the literal
        // ".". Resolving that against the discoverer's own cwd made the
        // session match every workspace discovery ran from — the workspace
        // here IS the test process cwd, the exact aliasing that leaked.
        let root = temp_dir("opencode-relative-cwd");
        let db = root.join("opencode.db");
        let conn = Connection::open(&db).unwrap();
        let here = std::env::current_dir().unwrap();
        conn.execute_batch(&format!(
            "CREATE TABLE session (
                id TEXT PRIMARY KEY,
                directory TEXT NOT NULL,
                title TEXT NOT NULL,
                time_updated INTEGER NOT NULL
             );
             CREATE TABLE message (
                id TEXT PRIMARY KEY,
                session_id TEXT NOT NULL
             );
             INSERT INTO session VALUES ('ses_relative', '.', 'Ghost', 41);
             INSERT INTO session VALUES ('ses_here', '{}', 'Real', 42);",
            here.display()
        ))
        .unwrap();
        drop(conn);

        let found = HarnessCatalog::new()
            .discover(&DiscoveryQuery {
                workspace: Some(here),
                harnesses: vec![HarnessId::from(HarnessId::OPENCODE)],
                homes: HarnessHomes {
                    opencode: db,
                    ..HarnessHomes::default()
                },
                ..DiscoveryQuery::default()
            })
            .unwrap();

        assert_eq!(found.len(), 1);
        assert_eq!(found[0].locator.session_id, "ses_here");
        fs::remove_dir_all(root).ok();
    }
}