recursive-agent 0.8.2

A Rust coding-agent platform: kernel, tools, multi-agent orchestration, HTTP API, MCP, and TUI
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
//! Session reader for loading transcripts and metadata from JSONL session files.
//!
//! Split from `session.rs` during the Goal 221 module refactor.

use std::io::BufRead;
use std::path::{Path, PathBuf};

use super::orphan::OrphanToolCall;
use super::serialize::{entry_to_message, CompactBoundaryEntry, LoadedEntry, TranscriptEntry};
use super::SessionMeta;

/// Reader for loading sessions from JSONL files.
pub struct SessionReader;

impl SessionReader {
    /// Load all transcript entries from a session directory.
    ///
    /// If the JSONL contains a `compact_boundary` system entry (g157), all
    /// entries **before** the last such boundary are discarded—they were
    /// already summarised and the summary is the first entry after the
    /// boundary. This makes resume `O(post-compaction size)`.
    pub fn load_transcript(session_dir: &Path) -> std::io::Result<Vec<TranscriptEntry>> {
        let jsonl_path = session_dir.join("transcript.jsonl");
        let file = std::fs::File::open(&jsonl_path)?;
        let reader = std::io::BufReader::new(file);

        let mut all_entries: Vec<TranscriptEntry> = Vec::new();
        // Index of the line immediately after the last compact_boundary we saw.
        let mut boundary_after: usize = 0;

        for line in reader.lines() {
            let line = line?;
            if line.trim().is_empty() {
                continue;
            }
            // g157: detect compact_boundary system entries before trying to
            // parse as TranscriptEntry (they have a different shape).
            if let Ok(sys) = serde_json::from_str::<CompactBoundaryEntry>(&line) {
                if sys.entry_type == "system" && sys.subtype == "compact_boundary" {
                    // Everything before this boundary is superseded; restart.
                    boundary_after = all_entries.len();
                    continue;
                }
            }
            match serde_json::from_str::<TranscriptEntry>(&line) {
                Ok(entry) => all_entries.push(entry),
                Err(e) => {
                    // Skip corrupt lines gracefully
                    eprintln!(
                        "warning: skipping corrupt line in {}: {}",
                        jsonl_path.display(),
                        e
                    );
                    continue;
                }
            }
        }
        // Discard pre-boundary entries (g157).
        Ok(all_entries.split_off(boundary_after))
    }

    /// Load the **full** on-disk history without discarding messages
    /// folded away by cross-turn compaction.
    ///
    /// Unlike [`load_transcript`](Self::load_transcript) / [`load_messages`](Self::load_messages)
    /// (which drop everything before the last `compact_boundary` so the
    /// model seed matches the post-compaction context), this keeps every
    /// line and surfaces each compaction as a
    /// [`LoadedEntry::CompactBoundary`] marker. Use this for
    /// **user-facing** paths — TUI session resume, `session show`,
    /// `session export` — where the user expects to see the whole
    /// conversation, not just the post-compaction tail.
    ///
    /// The model / resume-seed paths keep using `load_messages`; do not
    /// feed `load_full_history` output into the runtime transcript.
    pub fn load_full_history(session_dir: &Path) -> std::io::Result<Vec<LoadedEntry>> {
        let jsonl_path = session_dir.join("transcript.jsonl");
        let file = std::fs::File::open(&jsonl_path)?;
        let reader = std::io::BufReader::new(file);

        let mut out: Vec<LoadedEntry> = Vec::new();
        for line in reader.lines() {
            let line = line?;
            if line.trim().is_empty() {
                continue;
            }
            // g157: detect compact_boundary system entries before trying to
            // parse as TranscriptEntry (they have a different shape).
            if let Ok(sys) = serde_json::from_str::<CompactBoundaryEntry>(&line) {
                if sys.entry_type == "system" && sys.subtype == "compact_boundary" {
                    out.push(LoadedEntry::CompactBoundary {
                        turn: sys.turn,
                        removed: sys.compacted_count.unwrap_or(0),
                    });
                    continue;
                }
            }
            match serde_json::from_str::<TranscriptEntry>(&line) {
                Ok(entry) => out.push(LoadedEntry::Message(Box::new(entry))),
                Err(e) => {
                    // Skip corrupt lines gracefully (mirrors load_transcript).
                    eprintln!(
                        "warning: skipping corrupt line in {}: {}",
                        jsonl_path.display(),
                        e
                    );
                    continue;
                }
            }
        }
        Ok(out)
    }

    /// Load the transcript and build a UUID → `TranscriptEntry` index
    /// alongside the ordered vec. Enables O(1) lookup by UUID (g155).
    pub fn load_transcript_indexed(
        session_dir: &Path,
    ) -> std::io::Result<(
        Vec<TranscriptEntry>,
        std::collections::HashMap<String, TranscriptEntry>,
    )> {
        let entries = Self::load_transcript(session_dir)?;
        let mut index = std::collections::HashMap::with_capacity(entries.len());
        for entry in &entries {
            if !entry.uuid.is_empty() {
                index.insert(entry.uuid.clone(), entry.clone());
            }
        }
        Ok((entries, index))
    }

    /// Load the transcript and convert each `TranscriptEntry` to a
    /// runtime [`Message`]. Persistence-only fields (`id`,
    /// `parent_id`, `uuid`, `parent_uuid`, `timestamp`, `usage`)
    /// are dropped here. The result is what `run_resumed` expects
    /// as its `seed` argument.
    ///
    /// The `system` role is **kept** in the returned vec; callers
    /// that want to rebuild the system prompt from `Config` can
    /// filter it out manually.
    pub fn load_messages(session_dir: &Path) -> std::io::Result<Vec<crate::message::Message>> {
        let entries = Self::load_transcript(session_dir)?;
        Ok(entries.into_iter().map(entry_to_message).collect())
    }

    /// Goal-153: scan the transcript for "orphan" tool calls — tool_calls
    /// in the last assistant message that have no matching `tool` reply.
    ///
    /// Returns an empty vec when the transcript is clean (no orphans).
    /// Returns the orphan descriptions when one or more tool calls from the
    /// last assistant message have no corresponding `tool` result message.
    ///
    /// This is the **detection** side of durable execution; the *handling*
    /// (skip / redo / abort) is done by the caller (`cmd_resume`).
    ///
    /// `registry` is used to determine `side_effect_at_call` for orphans
    /// (their `AuditMeta` was never written because the process died before
    /// the call returned).
    pub fn scan_orphan_tool_calls(
        session_dir: &Path,
        registry: &crate::tools::ToolRegistry,
    ) -> std::io::Result<Vec<OrphanToolCall>> {
        let entries = Self::load_transcript(session_dir)?;
        if entries.is_empty() {
            return Ok(Vec::new());
        }

        // Find the last assistant message with tool_calls.
        let last_assistant = entries
            .iter()
            .enumerate()
            .rev()
            .find(|(_, e)| e.role == "assistant" && !e.tool_calls.is_empty());

        let Some((asst_idx, asst_entry)) = last_assistant else {
            return Ok(Vec::new());
        };

        // Collect the set of tool_call_ids that have a matching tool result
        // at any position *after* the assistant message.
        let answered: std::collections::HashSet<String> = entries[asst_idx + 1..]
            .iter()
            .filter(|e| e.role == "tool")
            .filter_map(|e| e.tool_call_id.clone())
            .collect();

        let mut orphans = Vec::new();
        for tc in &asst_entry.tool_calls {
            if !answered.contains(&tc.id) {
                let side_effect = registry
                    .get(&tc.name)
                    .map(|t| t.side_effect_class())
                    .unwrap_or(crate::tools::ToolSideEffect::External);
                let args_hash = {
                    let canonical = tc.arguments.to_string();
                    let hash = blake3::hash(canonical.as_bytes());
                    hash.to_hex().to_string()
                };
                orphans.push(OrphanToolCall {
                    assistant_msg_id: asst_entry.id.clone(),
                    tool_call_id: tc.id.clone(),
                    tool_name: tc.name.clone(),
                    args_hash,
                    side_effect_at_call: side_effect,
                });
            }
        }
        Ok(orphans)
    }

    /// Load the session metadata from a session directory.
    ///
    /// Refuses to deserialize a session whose `schema_version` is
    /// newer than this build supports (Goal 269). Pre-Goal-269
    /// session files have no `schema_version` field and load
    /// successfully via the `#[serde(default)]` on the struct.
    pub fn load_meta(session_dir: &Path) -> std::io::Result<SessionMeta> {
        let meta_path = session_dir.join(".meta.json");
        let bytes = std::fs::read(&meta_path)?;
        let meta: SessionMeta = serde_json::from_slice(&bytes)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        if meta.schema_version > super::SUPPORTED_SESSION_SCHEMA_VERSION {
            let err = crate::error::Error::SchemaTooNew {
                session_id: meta.session_id.clone(),
                found: meta.schema_version,
                supported: super::SUPPORTED_SESSION_SCHEMA_VERSION,
            };
            tracing::warn!("{}", err);
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                err.to_string(),
            ));
        }
        Ok(meta)
    }

    /// List all session directories for a given workspace.
    ///
    /// Returns a list of session directories sorted by name (which is
    /// timestamp-prefixed, so chronological).
    pub fn list_sessions(workspace: &Path) -> std::io::Result<Vec<PathBuf>> {
        let base = match crate::paths::user_sessions_dir(workspace) {
            Ok(d) => d,
            Err(_) => workspace.join(".recursive").join("sessions"),
        };
        if !base.is_dir() {
            return Ok(Vec::new());
        }

        let mut sessions = Vec::new();
        // Iterate workspace slugs
        for entry in std::fs::read_dir(&base)? {
            let entry = entry?;
            let slug_dir = entry.path();
            if !slug_dir.is_dir() {
                continue;
            }
            // Iterate session IDs within each slug
            for session_entry in std::fs::read_dir(&slug_dir)? {
                let session_entry = session_entry?;
                let session_dir = session_entry.path();
                if session_dir.is_dir() && session_dir.join(".meta.json").is_file() {
                    sessions.push(session_dir);
                }
            }
        }
        sessions.sort();
        Ok(sessions)
    }

    /// List all session directories sorted by `.meta.json`
    /// `updated_at` descending (most recently active first).
    ///
    /// Used by `recursive resume` (g151) to pick the most-recent
    /// session when no ID is given. Tiebreaks: when two sessions
    /// share the same `updated_at` string (RFC3339 has 1-second
    /// granularity, so ties happen during fast tests), fall back
    /// to `transcript.jsonl` mtime, then session_id lexicographically.
    ///
    /// Sessions whose `.meta.json` cannot be read are silently
    /// excluded — they're either being created or corrupted.
    pub fn list_sessions_sorted_by_updated_at(
        workspace: &Path,
    ) -> std::io::Result<Vec<(PathBuf, SessionMeta)>> {
        let dirs = Self::list_sessions(workspace)?;

        let mut entries: Vec<(PathBuf, SessionMeta, std::time::SystemTime)> = Vec::new();
        for dir in dirs {
            let meta = match Self::load_meta(&dir) {
                Ok(m) => m,
                Err(_) => continue,
            };
            // Tiebreak: mtime of transcript.jsonl. Falls back to
            // UNIX_EPOCH if the file doesn't exist or stat fails.
            let mtime = std::fs::metadata(dir.join("transcript.jsonl"))
                .and_then(|m| m.modified())
                .unwrap_or(std::time::SystemTime::UNIX_EPOCH);
            entries.push((dir, meta, mtime));
        }

        entries.sort_by(|a, b| {
            // Primary: updated_at desc (lexicographic on RFC3339
            // is chronological, so reverse comparison sorts desc).
            b.1.updated_at
                .cmp(&a.1.updated_at)
                // Secondary: mtime desc.
                .then_with(|| b.2.cmp(&a.2))
                // Tertiary: session_id asc (deterministic).
                .then_with(|| a.1.session_id.cmp(&b.1.session_id))
        });

        Ok(entries.into_iter().map(|(p, m, _)| (p, m)).collect())
    }

    /// List all session directories across all workspaces under a base path.
    pub fn list_all_sessions(base: &Path) -> std::io::Result<Vec<PathBuf>> {
        let sessions_dir = base.join(".recursive").join("sessions");
        if !sessions_dir.is_dir() {
            return Ok(Vec::new());
        }

        let mut sessions = Vec::new();
        for entry in std::fs::read_dir(&sessions_dir)? {
            let entry = entry?;
            let slug_dir = entry.path();
            if !slug_dir.is_dir() {
                continue;
            }
            for session_entry in std::fs::read_dir(&slug_dir)? {
                let session_entry = session_entry?;
                let session_dir = session_entry.path();
                if session_dir.is_dir() && session_dir.join(".meta.json").is_file() {
                    sessions.push(session_dir);
                }
            }
        }
        sessions.sort();
        Ok(sessions)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::llm::ToolSpec;
    use crate::message::{Message, Role};
    use crate::session::{hash_tool_specs, SessionStatus, SessionWriter};

    #[test]
    fn session_reader_round_trips() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();

        let mut writer = SessionWriter::create(ws, "round trip", "gpt-4o", "openai").unwrap();

        writer
            .append(&Message::system("You are a bot."), None, None)
            .unwrap();
        writer
            .append(&Message::user("do something"), None, None)
            .unwrap();
        writer
            .append(&Message::assistant("I will do it."), None, None)
            .unwrap();

        let session_dir = writer.session_dir().to_path_buf();
        writer.finish(SessionStatus::Completed).unwrap();

        let entries = SessionReader::load_transcript(&session_dir).unwrap();
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].role, "system");
        assert_eq!(entries[1].role, "user");
        assert_eq!(entries[2].role, "assistant");
    }

    #[test]
    fn crash_partial_line_skipped() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();

        let mut writer = SessionWriter::create(ws, "crash test", "gpt-4o", "openai").unwrap();
        writer
            .append(&Message::user("good line"), None, None)
            .unwrap();
        let session_dir = writer.session_dir().to_path_buf();
        writer.finish(SessionStatus::Crashed).unwrap();

        // Append a corrupt line manually
        use std::io::Write;
        let jsonl_path = session_dir.join("transcript.jsonl");
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(&jsonl_path)
            .unwrap();
        writeln!(f, "this is not json").unwrap();
        drop(f);

        // Should still load the good line
        let entries = SessionReader::load_transcript(&session_dir).unwrap();
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].content, "good line");
    }

    #[test]
    fn load_messages_drops_persistence_fields() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();
        let mut writer = SessionWriter::create(ws, "g151 test", "model", "openai").unwrap();
        let session_dir = writer.session_dir().to_path_buf();

        writer
            .append(&Message::user("hello".to_string()), None, None)
            .unwrap();
        writer
            .append(&Message::assistant("hi back".to_string()), None, None)
            .unwrap();
        writer.finish(SessionStatus::Completed).unwrap();
        drop(writer);

        // load_messages strips id / parent_id / timestamp.
        let msgs = SessionReader::load_messages(&session_dir).unwrap();
        assert_eq!(msgs.len(), 2);
        assert_eq!(msgs[0].role, Role::User);
        assert_eq!(msgs[0].content, "hello");
        assert_eq!(msgs[1].role, Role::Assistant);
        assert_eq!(msgs[1].content, "hi back");

        // Confirm the persisted entries actually had the fields we
        // claim to drop, so this test isn't a no-op.
        let entries = SessionReader::load_transcript(&session_dir).unwrap();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].id, "msg_001");
        assert!(!entries[0].timestamp.is_empty());
    }

    #[test]
    fn meta_round_trip_with_tool_registry_hash() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();

        let specs = vec![ToolSpec {
            name: "Read".into(),
            description: "Read".into(),
            parameters: serde_json::json!({"type":"object"}),
        }];
        let writer =
            SessionWriter::create_with_tools(ws, "with hash", "model", "openai", &specs, None)
                .unwrap();
        let session_dir = writer.session_dir().to_path_buf();
        drop(writer);

        let meta = SessionReader::load_meta(&session_dir).unwrap();
        let hash = meta
            .tool_registry_hash
            .as_ref()
            .expect("expected hash to be Some(_)");
        assert_eq!(*hash, hash_tool_specs(&specs));
    }

    #[test]
    fn meta_round_trip_old_format_no_hash() {
        // Synthesise a `.meta.json` that lacks the `tool_registry_hash`
        // field (representing a pre-g151 session record). Reload and
        // confirm it parses cleanly with `tool_registry_hash: None`.
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let session_dir = tmp
            .path()
            .join(".recursive")
            .join("sessions")
            .join("legacy");
        std::fs::create_dir_all(&session_dir).unwrap();

        let raw = r#"{
  "session_id": "legacy-id",
  "goal": "old goal",
  "model": "model",
  "provider": "openai",
  "created_at": "2020-01-01T00:00:00Z",
  "updated_at": "2020-01-01T00:00:00Z",
  "message_count": 0,
  "status": "active"
}"#;
        std::fs::write(session_dir.join(".meta.json"), raw).unwrap();
        std::fs::write(session_dir.join("transcript.jsonl"), "").unwrap();

        let meta = SessionReader::load_meta(&session_dir).unwrap();
        assert_eq!(meta.session_id, "legacy-id");
        assert!(meta.tool_registry_hash.is_none());
    }

    #[test]
    fn append_bumps_updated_at() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();
        let mut writer = SessionWriter::create(ws, "bump", "model", "openai").unwrap();
        let session_dir = writer.session_dir().to_path_buf();

        let meta_before = SessionReader::load_meta(&session_dir).unwrap();
        // Sleep a hair past the 1-sec timestamp granularity so the
        // RFC3339 string actually changes. chrono_lite_now() rounds
        // to the second.
        std::thread::sleep(std::time::Duration::from_millis(1100));

        writer
            .append(&Message::user("ping".to_string()), None, None)
            .unwrap();

        let meta_after = SessionReader::load_meta(&session_dir).unwrap();
        assert_ne!(
            meta_before.updated_at, meta_after.updated_at,
            "expected updated_at to advance after append; before={} after={}",
            meta_before.updated_at, meta_after.updated_at
        );
    }

    #[test]
    fn open_existing_continues_msg_numbering() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();
        let mut writer = SessionWriter::create(ws, "resume-num", "model", "openai").unwrap();
        let session_dir = writer.session_dir().to_path_buf();

        writer
            .append(&Message::user("u1".to_string()), None, None)
            .unwrap();
        writer
            .append(&Message::assistant("a1".to_string()), None, None)
            .unwrap();
        writer
            .append(&Message::user("u2".to_string()), None, None)
            .unwrap();
        // Drop the writer WITHOUT calling finish() — the lock file is
        // released on Drop, but we never marked the session done.
        drop(writer);

        // Re-open and append more.
        let mut writer2 = SessionWriter::open_existing(&session_dir).unwrap();
        let id = writer2
            .append(&Message::assistant("a2".to_string()), None, None)
            .unwrap();
        // append now returns a UUID; just verify it's non-empty
        assert!(!id.is_empty(), "expected non-empty UUID from append");
        drop(writer2);

        let entries = SessionReader::load_transcript(&session_dir).unwrap();
        assert_eq!(entries.len(), 4);
        assert_eq!(entries[0].id, "msg_001");
        assert_eq!(entries[1].id, "msg_002");
        assert_eq!(entries[2].id, "msg_003");
        assert_eq!(entries[3].id, "msg_004");
        assert_eq!(entries[3].parent_id.as_deref(), Some("msg_003"));
    }

    #[test]
    fn list_sessions_finds_sessions() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();

        // No sessions yet
        let sessions = SessionReader::list_sessions(ws).unwrap();
        assert!(sessions.is_empty());

        // Create one session
        let writer = SessionWriter::create(ws, "session1", "gpt-4o", "openai").unwrap();
        let dir1 = writer.session_dir().to_path_buf();
        drop(writer);

        let sessions = SessionReader::list_sessions(ws).unwrap();
        assert_eq!(sessions.len(), 1);
        assert_eq!(sessions[0], dir1);
    }

    #[test]
    fn list_sessions_sorted_by_updated_at_returns_one_session_with_meta() {
        // kills function-level replacement of list_sessions_sorted_by_updated_at
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();

        // Create one session
        let w1 = SessionWriter::create(ws, "sort-test-goal", "gpt-4o", "openai").unwrap();
        drop(w1);

        let sorted = SessionReader::list_sessions_sorted_by_updated_at(ws).unwrap();
        assert_eq!(sorted.len(), 1, "must find 1 session");
        // Second tuple element is SessionMeta — its session_id must be non-empty
        assert!(!sorted[0].1.session_id.is_empty());
    }

    #[test]
    fn list_all_sessions_returns_empty_for_no_sessions() {
        // kills function-level replacement of list_all_sessions
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();
        let sessions = SessionReader::list_all_sessions(ws).unwrap();
        assert!(sessions.is_empty(), "must be empty when no sessions exist");
    }

    #[test]
    fn scan_orphan_tool_calls_returns_empty_for_no_assistant_with_tool_calls() {
        // kills `let Some(...) = last_assistant else { return Ok(Vec::new()) }` guard removal
        use crate::message::Message;
        use crate::session::{SessionStatus, SessionWriter};

        let tmp = crate::test_util::IsolatedWorkspace::new();
        let mut w = SessionWriter::create(tmp.path(), "g", "m", "p").unwrap();
        // Only user+assistant (no tool_calls) messages — last_assistant returns None
        w.append(&Message::user("hi".to_string()), None, None)
            .unwrap();
        w.append(&Message::assistant("hello".to_string()), None, None)
            .unwrap();
        w.finish(SessionStatus::Completed).unwrap();

        let reg = crate::tools::ToolRegistry::local();
        let orphans = SessionReader::scan_orphan_tool_calls(w.session_dir(), &reg).unwrap();
        assert!(
            orphans.is_empty(),
            "no assistant tool_calls → no orphans; got: {orphans:?}"
        );
    }

    #[test]
    fn scan_orphan_tool_calls_returns_empty_when_all_answered() {
        // kills `if !answered.contains(&tc.id)` guard removal mutation
        use crate::message::Message;
        use crate::session::{SessionStatus, SessionWriter};

        let tmp = crate::test_util::IsolatedWorkspace::new();
        let mut w = SessionWriter::create(tmp.path(), "g", "m", "p").unwrap();

        // Build: user → assistant with tool_call → tool result
        let mut asst = Message::assistant("calling tool".to_string());
        asst.tool_calls = vec![crate::llm::ToolCall {
            id: "tc-001".to_string(),
            name: "Read".to_string(),
            arguments: serde_json::json!({"path": "foo.txt"}),
        }];

        let tool_result = Message {
            role: crate::message::Role::Tool,
            content: "file contents".to_string(),
            tool_calls: vec![],
            tool_call_id: Some("tc-001".to_string()),
            reasoning_content: None,
            is_compaction_summary: false,
        };

        w.append(&Message::user("do something".to_string()), None, None)
            .unwrap();
        w.append(&asst, None, None).unwrap();
        w.append(&tool_result, None, None).unwrap();
        w.finish(SessionStatus::Completed).unwrap();

        let reg = crate::tools::ToolRegistry::local();
        let orphans = SessionReader::scan_orphan_tool_calls(w.session_dir(), &reg).unwrap();
        assert!(
            orphans.is_empty(),
            "all tool calls answered → no orphans; got: {orphans:?}"
        );
    }

    #[test]
    fn scan_orphan_tool_calls_detects_unanswered_call() {
        // kills `if !answered.contains(&tc.id)` guard-flip mutation
        use crate::message::Message;
        use crate::session::{SessionStatus, SessionWriter};

        let tmp = crate::test_util::IsolatedWorkspace::new();
        let mut w = SessionWriter::create(tmp.path(), "g", "m", "p").unwrap();

        // Build: user → assistant with tool_call — no tool result follows
        let mut asst = Message::assistant("calling tool".to_string());
        asst.tool_calls = vec![crate::llm::ToolCall {
            id: "tc-orphan".to_string(),
            name: "Read".to_string(),
            arguments: serde_json::json!({"path": "missing.txt"}),
        }];

        w.append(&Message::user("do something".to_string()), None, None)
            .unwrap();
        w.append(&asst, None, None).unwrap();
        // No tool result appended!
        w.finish(SessionStatus::Completed).unwrap();

        let reg = crate::tools::ToolRegistry::local();
        let orphans = SessionReader::scan_orphan_tool_calls(w.session_dir(), &reg).unwrap();
        assert_eq!(
            orphans.len(),
            1,
            "one unanswered tool call must be reported as orphan"
        );
        assert_eq!(orphans[0].tool_call_id, "tc-orphan");
        assert_eq!(orphans[0].tool_name, "Read");
    }

    // Goal: TUI resume / session show should display the full conversation,
    // not just the post-compaction tail. `load_full_history` keeps every
    // message and surfaces each compact_boundary as a `CompactBoundary`
    // marker, while `load_messages` (model seed) keeps stripping them.
    #[test]
    fn load_full_history_includes_pre_compact_messages_and_boundaries() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();
        let mut w = SessionWriter::create(ws, "full history", "model", "openai").unwrap();
        let session_dir = w.session_dir().to_path_buf();

        // Pre-compact messages (these get folded at runtime, but stay on disk).
        w.append(&Message::user("turn 1".to_string()), None, None)
            .unwrap();
        w.append(&Message::assistant("reply 1".to_string()), None, None)
            .unwrap();
        w.append(&Message::user("turn 2".to_string()), None, None)
            .unwrap();
        w.append(&Message::assistant("reply 2".to_string()), None, None)
            .unwrap();
        // Boundary: folds the 4 messages above into a summary.
        w.write_compact_boundary(3, 4, None).unwrap();
        // Post-compact summary + a fresh exchange.
        w.append(
            &Message::system("summary of turn 1-2".to_string()),
            None,
            None,
        )
        .unwrap();
        w.append(&Message::user("turn 3".to_string()), None, None)
            .unwrap();
        w.append(&Message::assistant("reply 3".to_string()), None, None)
            .unwrap();
        w.finish(SessionStatus::Completed).unwrap();

        // load_full_history keeps everything: 7 messages + 1 boundary marker.
        let loaded = SessionReader::load_full_history(&session_dir).unwrap();
        assert_eq!(loaded.len(), 8, "all messages + the boundary marker");

        // The boundary sits between the folded messages and the summary.
        let boundary_idx = loaded
            .iter()
            .position(
                |e| matches!(e, LoadedEntry::CompactBoundary { removed, .. } if *removed == 4),
            )
            .expect("a CompactBoundary marker with removed=4");
        assert_eq!(boundary_idx, 4, "boundary follows the 4 folded messages");

        // Messages before and after the boundary are all present.
        let pre = &loaded[..boundary_idx];
        assert_eq!(pre.len(), 4);
        assert!(pre.iter().all(|e| matches!(e, LoadedEntry::Message(_))));

        let post = &loaded[boundary_idx + 1..];
        assert_eq!(post.len(), 3);
        assert!(post.iter().all(|e| matches!(e, LoadedEntry::Message(_))));

        // The summary is the first message after the boundary.
        if let LoadedEntry::Message(m) = &post[0] {
            assert_eq!(m.role, "system");
            assert_eq!(m.content, "summary of turn 1-2");
        } else {
            panic!("expected a Message after the boundary");
        }

        // Model seed path is unchanged: load_messages still strips the
        // 4 folded messages, leaving summary + turn 3 exchange (3 msgs).
        let seed = SessionReader::load_messages(&session_dir).unwrap();
        assert_eq!(
            seed.len(),
            3,
            "load_messages keeps only post-compaction tail"
        );
        assert_eq!(seed[0].content, "summary of turn 1-2");
    }

    #[test]
    fn load_full_history_no_boundary_returns_all_messages() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();
        let mut w = SessionWriter::create(ws, "no compact", "model", "openai").unwrap();
        let session_dir = w.session_dir().to_path_buf();
        w.append(&Message::user("hi".to_string()), None, None)
            .unwrap();
        w.append(&Message::assistant("hello".to_string()), None, None)
            .unwrap();
        w.finish(SessionStatus::Completed).unwrap();

        let loaded = SessionReader::load_full_history(&session_dir).unwrap();
        assert_eq!(loaded.len(), 2);
        assert!(
            loaded.iter().all(|e| matches!(e, LoadedEntry::Message(_))),
            "no CompactBoundary markers when the session never compacted"
        );
    }
}