toolpath-gemini 0.3.0

Derive Toolpath provenance documents from Gemini CLI conversation logs
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
//! Higher-level filesystem operations over `PathResolver`.

use crate::error::Result;
use crate::paths::PathResolver;
use crate::reader::ConversationReader;
use crate::types::{ChatFile, Conversation, ConversationMetadata, GeminiRole, LogEntry};
use std::path::PathBuf;

/// First non-empty `"user"` prompt in a chat file, used as a session "title".
fn first_user_text(chat: &ChatFile) -> Option<String> {
    chat.messages
        .iter()
        .filter(|m| m.role == GeminiRole::User)
        .find_map(|m| {
            let text = m.content.text();
            let trimmed = text.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            }
        })
}

#[derive(Debug, Clone)]
pub struct ConvoIO {
    resolver: PathResolver,
}

impl Default for ConvoIO {
    fn default() -> Self {
        Self::new()
    }
}

impl ConvoIO {
    pub fn new() -> Self {
        Self {
            resolver: PathResolver::new(),
        }
    }

    pub fn with_resolver(resolver: PathResolver) -> Self {
        Self { resolver }
    }

    pub fn resolver(&self) -> &PathResolver {
        &self.resolver
    }

    pub fn gemini_dir_path(&self) -> Result<PathBuf> {
        self.resolver.gemini_dir()
    }

    pub fn exists(&self) -> bool {
        self.resolver.exists()
    }

    pub fn list_projects(&self) -> Result<Vec<String>> {
        self.resolver.list_project_dirs()
    }

    pub fn list_sessions(&self, project_path: &str) -> Result<Vec<String>> {
        self.resolver.list_sessions(project_path)
    }

    pub fn list_chat_files(&self, project_path: &str, session_uuid: &str) -> Result<Vec<String>> {
        self.resolver.list_chat_files(project_path, session_uuid)
    }

    pub fn project_exists(&self, project_path: &str) -> bool {
        self.resolver
            .project_dir(project_path)
            .map(|p| p.exists())
            .unwrap_or(false)
    }

    pub fn session_exists(&self, project_path: &str, session_id: &str) -> Result<bool> {
        // A session is "present" if ANY of: a main session file with that
        // stem, a main session file whose inner sessionId matches, or a
        // UUID directory of that name exists.
        if self
            .resolver
            .resolve_main_file(project_path, session_id)?
            .is_some()
        {
            return Ok(true);
        }
        let dir = self.resolver.session_dir(project_path, session_id)?;
        Ok(dir.exists())
    }

    /// Read a single chat file by name.
    pub fn read_chat(
        &self,
        project_path: &str,
        session_uuid: &str,
        chat_name: &str,
    ) -> Result<ChatFile> {
        let path = self
            .resolver
            .chat_file(project_path, session_uuid, chat_name)?;
        ConversationReader::read_chat_file(&path)
    }

    /// Read every chat file inside a session UUID directory.
    pub fn read_all_chats(
        &self,
        project_path: &str,
        session_uuid: &str,
    ) -> Result<Vec<(String, ChatFile)>> {
        let stems = self.list_chat_files(project_path, session_uuid)?;
        let mut out = Vec::with_capacity(stems.len());
        for stem in stems {
            let chat = self.read_chat(project_path, session_uuid, &stem)?;
            out.push((stem, chat));
        }
        Ok(out)
    }

    /// Load a full session.
    ///
    /// `session_id` may be:
    /// - A main-session file stem (e.g. `session-2026-04-17T18-09-b26d7f99`)
    ///   — the file is read, and a sibling `<inner-sessionId>/` dir (if
    ///   present) contributes sub-agent chats.
    /// - A full session UUID (the `sessionId` field inside a main chat
    ///   file, e.g. `f7cc36c0-980c-4914-ae79-439567272478`) — `chats/*.json`
    ///   is scanned for a file whose inner `sessionId` matches. This is
    ///   how Gemini CLI itself resolves `--resume <uuid>`.
    /// - A UUID directory name with no backing main file — every
    ///   `*.json` file inside is loaded; the one without `kind: "subagent"`
    ///   becomes the main.
    pub fn read_session(&self, project_path: &str, session_id: &str) -> Result<Conversation> {
        // Strategy A: resolve the main file either by file stem or by
        // inner sessionId.
        if let Some(main_path) = self.resolver.resolve_main_file(project_path, session_id)? {
            let main = ConversationReader::read_chat_file(&main_path)?;
            let uuid = main.session_id.clone();
            let sub_agents = if !uuid.is_empty() {
                let uuid_dir = self.resolver.session_dir(project_path, &uuid)?;
                if uuid_dir.exists() {
                    let stems = self.resolver.list_chat_files(project_path, &uuid)?;
                    let mut subs = Vec::with_capacity(stems.len());
                    for stem in stems {
                        match self.read_chat(project_path, &uuid, &stem) {
                            Ok(c) => subs.push(c),
                            Err(e) => eprintln!(
                                "Warning: failed to read sub-agent {}/{}: {}",
                                uuid, stem, e
                            ),
                        }
                    }
                    subs
                } else {
                    Vec::new()
                }
            } else {
                Vec::new()
            };

            let project_root: Option<String> = main
                .directories()
                .first()
                .map(|p| p.to_string_lossy().to_string());

            let mut convo = Conversation::new(session_id.to_string(), main);
            convo.project_path = project_root;
            convo.sub_agents = sub_agents;
            return Ok(convo);
        }

        // Strategy B: treat session_id as a UUID directory.
        let chats = self.read_all_chats(project_path, session_id)?;
        if chats.is_empty() {
            return Err(crate::error::ConvoError::ConversationNotFound(format!(
                "{}/{}",
                project_path, session_id
            )));
        }

        let (main_idx, _) = chats
            .iter()
            .enumerate()
            .find(|(_, (_, c))| c.kind.as_deref() != Some("subagent"))
            .unwrap_or((0, &chats[0]));

        let mut chats = chats;
        let (_, main) = chats.remove(main_idx);
        let sub_agents: Vec<ChatFile> = chats.into_iter().map(|(_, c)| c).collect();

        let project_root: Option<String> = main
            .directories()
            .first()
            .map(|p| p.to_string_lossy().to_string());

        let mut convo = Conversation::new(session_id.to_string(), main);
        convo.project_path = project_root;
        convo.sub_agents = sub_agents;
        Ok(convo)
    }

    /// Lightweight metadata for a single session.
    ///
    /// Accepts any identifier [`ConvoIO::read_session`] accepts:
    /// filename stem, inner session UUID, or a bare UUID directory name.
    pub fn read_session_metadata(
        &self,
        project_path: &str,
        session_id: &str,
    ) -> Result<ConversationMetadata> {
        // Case A: main session file resolvable by stem or inner sessionId.
        if let Some(main_path) = self.resolver.resolve_main_file(project_path, session_id)? {
            let main = ConversationReader::read_chat_file(&main_path)?;
            let uuid = main.session_id.clone();
            let mut sub_chats: Vec<ChatFile> = Vec::new();
            if !uuid.is_empty() {
                let uuid_dir = self.resolver.session_dir(project_path, &uuid)?;
                if uuid_dir.exists() {
                    for stem in self.resolver.list_chat_files(project_path, &uuid)? {
                        if let Ok(c) = self.read_chat(project_path, &uuid, &stem) {
                            sub_chats.push(c);
                        }
                    }
                }
            }
            let mut message_count = main.messages.len();
            for s in &sub_chats {
                message_count += s.messages.len();
            }
            let mut started_at = main.start_time;
            let mut last_activity = main.last_updated;
            for s in &sub_chats {
                if let Some(t) = s.start_time
                    && started_at.map(|x| t < x).unwrap_or(true)
                {
                    started_at = Some(t);
                }
                if let Some(t) = s.last_updated
                    && last_activity.map(|x| t > x).unwrap_or(true)
                {
                    last_activity = Some(t);
                }
            }
            let sub_agent_count = sub_chats
                .iter()
                .filter(|c| c.kind.as_deref() == Some("subagent"))
                .count();
            let project_root: String = main
                .directories()
                .first()
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_else(|| project_path.to_string());
            let first_user_message = first_user_text(&main);
            return Ok(ConversationMetadata {
                session_uuid: session_id.to_string(),
                project_path: project_root,
                file_path: main_path,
                message_count,
                started_at,
                last_activity,
                sub_agent_count,
                first_user_message,
            });
        }

        // Case B: orphan UUID directory.
        let chats = self.read_all_chats(project_path, session_id)?;
        let session_dir = self.resolver.session_dir(project_path, session_id)?;

        let main = chats
            .iter()
            .find(|(_, c)| c.kind.as_deref() != Some("subagent"))
            .or_else(|| chats.first())
            .ok_or_else(|| {
                crate::error::ConvoError::ConversationNotFound(format!(
                    "{}/{}",
                    project_path, session_id
                ))
            })?;

        let message_count: usize = chats.iter().map(|(_, c)| c.messages.len()).sum();
        let started_at = chats.iter().filter_map(|(_, c)| c.start_time).min();
        let last_activity = chats.iter().filter_map(|(_, c)| c.last_updated).max();
        let sub_agent_count = chats
            .iter()
            .filter(|(_, c)| c.kind.as_deref() == Some("subagent"))
            .count();

        let project_root: String = main
            .1
            .directories()
            .first()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_else(|| project_path.to_string());

        let first_user_message = first_user_text(&main.1);

        Ok(ConversationMetadata {
            session_uuid: session_id.to_string(),
            project_path: project_root,
            file_path: session_dir,
            message_count,
            started_at,
            last_activity,
            sub_agent_count,
            first_user_message,
        })
    }

    pub fn list_session_metadata(&self, project_path: &str) -> Result<Vec<ConversationMetadata>> {
        let sessions = self.list_sessions(project_path)?;
        let mut out = Vec::new();
        for uuid in sessions {
            match self.read_session_metadata(project_path, &uuid) {
                Ok(meta) => out.push(meta),
                Err(e) => eprintln!("Warning: Failed to read metadata for {}: {}", uuid, e),
            }
        }
        out.sort_by_key(|m| std::cmp::Reverse(m.last_activity));
        Ok(out)
    }

    pub fn read_logs(&self, project_path: &str) -> Result<Vec<LogEntry>> {
        let path = self.resolver.logs_file(project_path)?;
        ConversationReader::read_logs(&path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn setup() -> (TempDir, ConvoIO) {
        let temp = TempDir::new().unwrap();
        let gemini = temp.path().join(".gemini");
        let project_slot = gemini.join("tmp/myrepo");
        let session_dir = project_slot.join("chats/session-uuid");
        fs::create_dir_all(&session_dir).unwrap();
        fs::write(
            gemini.join("projects.json"),
            r#"{"projects":{"/abs/myrepo":"myrepo"}}"#,
        )
        .unwrap();
        fs::write(project_slot.join(".project_root"), "/abs/myrepo").unwrap();

        let main = r#"{
  "sessionId":"main-s",
  "projectHash":"h",
  "startTime":"2026-04-17T15:00:00Z",
  "lastUpdated":"2026-04-17T15:10:00Z",
  "directories":["/abs/myrepo"],
  "messages":[
    {"id":"m1","timestamp":"2026-04-17T15:00:00Z","type":"user","content":[{"text":"Fix the bug"}]},
    {"id":"m2","timestamp":"2026-04-17T15:01:00Z","type":"gemini","content":"Sure.","model":"gemini-3-flash-preview"}
  ]
}"#;
        fs::write(session_dir.join("main.json"), main).unwrap();

        let sub = r#"{
  "sessionId":"sub-s",
  "projectHash":"h",
  "startTime":"2026-04-17T15:05:00Z",
  "lastUpdated":"2026-04-17T15:08:00Z",
  "kind":"subagent",
  "summary":"found it",
  "messages":[
    {"id":"s1","timestamp":"2026-04-17T15:05:00Z","type":"user","content":[{"text":"Search"}]}
  ]
}"#;
        fs::write(session_dir.join("sub-s.json"), sub).unwrap();

        let resolver = PathResolver::new().with_gemini_dir(&gemini);
        (temp, ConvoIO::with_resolver(resolver))
    }

    #[test]
    fn test_list_projects() {
        let (_t, io) = setup();
        let p = io.list_projects().unwrap();
        assert_eq!(p, vec!["/abs/myrepo".to_string()]);
    }

    #[test]
    fn test_list_sessions() {
        let (_t, io) = setup();
        let s = io.list_sessions("/abs/myrepo").unwrap();
        assert_eq!(s, vec!["session-uuid".to_string()]);
    }

    #[test]
    fn test_list_chat_files() {
        let (_t, io) = setup();
        let files = io.list_chat_files("/abs/myrepo", "session-uuid").unwrap();
        assert_eq!(files, vec!["main".to_string(), "sub-s".to_string()]);
    }

    #[test]
    fn test_read_session_picks_main() {
        let (_t, io) = setup();
        let convo = io.read_session("/abs/myrepo", "session-uuid").unwrap();
        assert_eq!(convo.main.session_id, "main-s");
        assert!(convo.main.kind.is_none());
        assert_eq!(convo.sub_agents.len(), 1);
        assert_eq!(convo.sub_agents[0].session_id, "sub-s");
        assert_eq!(convo.sub_agents[0].summary.as_deref(), Some("found it"));
        assert_eq!(convo.project_path.as_deref(), Some("/abs/myrepo"));
    }

    #[test]
    fn test_read_session_metadata() {
        let (_t, io) = setup();
        let meta = io
            .read_session_metadata("/abs/myrepo", "session-uuid")
            .unwrap();
        assert_eq!(meta.session_uuid, "session-uuid");
        assert_eq!(meta.message_count, 3); // 2 main + 1 sub-agent
        assert_eq!(meta.sub_agent_count, 1);
        assert!(meta.started_at.is_some());
        assert!(meta.last_activity.is_some());
    }

    #[test]
    fn test_list_session_metadata() {
        let (_t, io) = setup();
        let metas = io.list_session_metadata("/abs/myrepo").unwrap();
        assert_eq!(metas.len(), 1);
        assert_eq!(metas[0].session_uuid, "session-uuid");
    }

    #[test]
    fn test_read_chat_by_name() {
        let (_t, io) = setup();
        let chat = io
            .read_chat("/abs/myrepo", "session-uuid", "sub-s")
            .unwrap();
        assert_eq!(chat.kind.as_deref(), Some("subagent"));
    }

    #[test]
    fn test_session_exists() {
        let (_t, io) = setup();
        assert!(io.session_exists("/abs/myrepo", "session-uuid").unwrap());
        assert!(!io.session_exists("/abs/myrepo", "missing").unwrap());
    }

    #[test]
    fn test_project_exists() {
        let (_t, io) = setup();
        assert!(io.project_exists("/abs/myrepo"));
        assert!(!io.project_exists("/never"));
    }

    #[test]
    fn test_read_session_missing() {
        let (_t, io) = setup();
        let err = io.read_session("/abs/myrepo", "missing").unwrap_err();
        matches!(err, crate::error::ConvoError::ConversationNotFound(_));
    }

    #[test]
    fn test_read_logs_absent() {
        let (_t, io) = setup();
        let logs = io.read_logs("/abs/myrepo").unwrap();
        assert!(logs.is_empty());
    }

    #[test]
    fn test_read_logs_present() {
        let (t, io) = setup();
        fs::write(
            t.path().join(".gemini/tmp/myrepo/logs.json"),
            r#"[{"sessionId":"s","messageId":0,"type":"user","message":"hi","timestamp":"t"}]"#,
        )
        .unwrap();
        let logs = io.read_logs("/abs/myrepo").unwrap();
        assert_eq!(logs.len(), 1);
    }

    #[test]
    fn test_read_session_only_subagents_uses_first() {
        // Edge case: session dir where every file is a sub-agent.
        let temp = TempDir::new().unwrap();
        let gemini = temp.path().join(".gemini");
        let session = gemini.join("tmp/p/chats/sess");
        fs::create_dir_all(&session).unwrap();
        fs::write(gemini.join("projects.json"), r#"{"projects":{"/p":"p"}}"#).unwrap();
        fs::write(
            session.join("a.json"),
            r#"{"sessionId":"a","kind":"subagent","messages":[]}"#,
        )
        .unwrap();
        fs::write(
            session.join("b.json"),
            r#"{"sessionId":"b","kind":"subagent","messages":[]}"#,
        )
        .unwrap();

        let io = ConvoIO::with_resolver(PathResolver::new().with_gemini_dir(&gemini));
        let convo = io.read_session("/p", "sess").unwrap();
        // Fell back to the first file as "main"
        assert_eq!(convo.sub_agents.len(), 1);
    }

    // ── Real-world layout: flat main file + sibling <uuid>/ sub-agent dir ──

    /// Build the canonical real-world layout:
    ///   chats/session-<ts>-<short>.json       (kind: "main")
    ///   chats/<full-uuid>/<name>.json         (kind: "subagent")
    fn setup_main_with_sibling_subagent() -> (TempDir, ConvoIO) {
        let temp = TempDir::new().unwrap();
        let gemini = temp.path().join(".gemini");
        let chats = gemini.join("tmp/p/chats");
        fs::create_dir_all(&chats).unwrap();
        fs::write(gemini.join("projects.json"), r#"{"projects":{"/p":"p"}}"#).unwrap();

        // Main session file at top of chats/
        fs::write(
            chats.join("session-2026-04-17-b26d.json"),
            r#"{
  "sessionId":"b26d-full-uuid-abc",
  "projectHash":"h",
  "kind":"main",
  "startTime":"2026-04-17T10:00:00Z",
  "lastUpdated":"2026-04-17T10:20:00Z",
  "directories":["/abs/p"],
  "messages":[
    {"id":"u1","timestamp":"2026-04-17T10:00:00Z","type":"user","content":[{"text":"go"}]},
    {"id":"a1","timestamp":"2026-04-17T10:00:01Z","type":"gemini","content":"delegating","model":"gemini-3-flash-preview","toolCalls":[
      {"id":"t","name":"task","args":{"prompt":"search"},"status":"success","timestamp":"2026-04-17T10:00:01Z","result":[{"functionResponse":{"id":"t","name":"task","response":{"output":"done"}}}]}
    ]}
  ]
}"#,
        )
        .unwrap();

        // Sibling sub-agent dir named with the full inner sessionId
        let sub_dir = chats.join("b26d-full-uuid-abc");
        fs::create_dir_all(&sub_dir).unwrap();
        fs::write(
            sub_dir.join("helper.json"),
            r#"{
  "sessionId":"helper-sub",
  "projectHash":"h",
  "kind":"subagent",
  "summary":"found it in auth.rs",
  "startTime":"2026-04-17T10:05:00Z",
  "lastUpdated":"2026-04-17T10:10:00Z",
  "messages":[
    {"id":"s1","timestamp":"2026-04-17T10:05:00Z","type":"user","content":[{"text":"search for auth bug"}]}
  ]
}"#,
        )
        .unwrap();

        let io = ConvoIO::with_resolver(PathResolver::new().with_gemini_dir(&gemini));
        (temp, io)
    }

    #[test]
    fn test_read_session_real_world_layout() {
        let (_t, io) = setup_main_with_sibling_subagent();
        let convo = io.read_session("/p", "session-2026-04-17-b26d").unwrap();
        assert_eq!(convo.main.session_id, "b26d-full-uuid-abc");
        assert_eq!(convo.main.kind.as_deref(), Some("main"));
        assert_eq!(convo.main.messages.len(), 2);
        assert_eq!(convo.sub_agents.len(), 1);
        assert_eq!(convo.sub_agents[0].session_id, "helper-sub");
        assert_eq!(
            convo.sub_agents[0].summary.as_deref(),
            Some("found it in auth.rs")
        );
        assert_eq!(convo.project_path.as_deref(), Some("/abs/p"));
    }

    #[test]
    fn test_read_session_metadata_real_world_layout() {
        let (_t, io) = setup_main_with_sibling_subagent();
        let meta = io
            .read_session_metadata("/p", "session-2026-04-17-b26d")
            .unwrap();
        // 2 main + 1 sub-agent
        assert_eq!(meta.message_count, 3);
        assert_eq!(meta.sub_agent_count, 1);
        assert!(meta.started_at.is_some());
        assert!(meta.last_activity.is_some());
    }

    #[test]
    fn test_list_session_metadata_real_world() {
        let (_t, io) = setup_main_with_sibling_subagent();
        let metas = io.list_session_metadata("/p").unwrap();
        assert_eq!(metas.len(), 1);
        assert_eq!(metas[0].session_uuid, "session-2026-04-17-b26d");
        assert_eq!(metas[0].sub_agent_count, 1);
    }

    #[test]
    fn test_read_session_main_without_sibling_dir() {
        // Main file exists but no sub-agent UUID dir — sub_agents stays empty.
        let temp = TempDir::new().unwrap();
        let gemini = temp.path().join(".gemini");
        let chats = gemini.join("tmp/p/chats");
        fs::create_dir_all(&chats).unwrap();
        fs::write(gemini.join("projects.json"), r#"{"projects":{"/p":"p"}}"#).unwrap();
        fs::write(
            chats.join("session-solo.json"),
            r#"{"sessionId":"solo-uuid","projectHash":"h","kind":"main","messages":[
  {"id":"u","timestamp":"ts","type":"user","content":"hi"}
]}"#,
        )
        .unwrap();

        let io = ConvoIO::with_resolver(PathResolver::new().with_gemini_dir(&gemini));
        let convo = io.read_session("/p", "session-solo").unwrap();
        assert_eq!(convo.main.session_id, "solo-uuid");
        assert!(convo.sub_agents.is_empty());
    }

    #[test]
    fn test_session_exists_main_file_case() {
        let (_t, io) = setup_main_with_sibling_subagent();
        assert!(io.session_exists("/p", "session-2026-04-17-b26d").unwrap());
        assert!(!io.session_exists("/p", "nope").unwrap());
    }

    #[test]
    fn test_list_sessions_real_world_has_no_duplicates() {
        let (_t, io) = setup_main_with_sibling_subagent();
        let sessions = io.list_sessions("/p").unwrap();
        // One main file → one session listed. Sibling UUID dir must not
        // show up as its own session.
        assert_eq!(sessions, vec!["session-2026-04-17-b26d".to_string()]);
    }

    // ── Small accessors ───────────────────────────────────────────────

    #[test]
    fn test_resolver_accessor() {
        let (_t, io) = setup();
        assert!(io.resolver().exists());
    }

    #[test]
    fn test_gemini_dir_path_accessor() {
        let (temp, io) = setup();
        let p = io.gemini_dir_path().unwrap();
        assert_eq!(p, temp.path().join(".gemini"));
    }

    #[test]
    fn test_exists_accessor() {
        let (_t, io) = setup();
        assert!(io.exists());
        let missing = ConvoIO::with_resolver(PathResolver::new().with_gemini_dir("/nowhere"));
        assert!(!missing.exists());
    }

    #[test]
    fn test_read_all_chats_returns_all_files() {
        let (_t, io) = setup();
        let chats = io.read_all_chats("/abs/myrepo", "session-uuid").unwrap();
        assert_eq!(chats.len(), 2);
        let names: Vec<_> = chats.iter().map(|(s, _)| s.as_str()).collect();
        assert!(names.contains(&"main"));
        assert!(names.contains(&"sub-s"));
    }
}