procyon 0.1.2

Terminal development harness for Stellar and Soroban smart contracts, driven by a language model
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
use std::path::{Path, PathBuf};

use color_eyre::{eyre::bail, eyre::WrapErr, Result};
use serde::{Deserialize, Serialize};

use crate::agent::{ContentPart, Message};

/// Bumped when the record shape changes. A log written by a newer procyon is refused rather than
/// half-read, so the user is told to upgrade instead of shown a corrupt transcript.
pub const FORMAT_VERSION: u32 = 1;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TurnEnd {
    Complete,
    Failed,
    /// The turn did not finish: either the user stopped it with Esc, or crash repair found a turn
    /// with no end at all and closed it.
    Interrupted,
}

/// What actually happened, in order. Messages are derived from these, never stored directly, so
/// the log stays the single source of truth.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum SessionEvent {
    TurnStart,
    UserMessage {
        text: String,
    },
    AssistantMessage {
        blocks: Vec<ContentPart>,
    },
    /// Recorded and flushed *before* the tool runs, so a crash leaves evidence that it may have
    /// had an effect.
    ToolCall {
        id: String,
        name: String,
    },
    ToolResult {
        id: String,
        content: String,
        #[serde(default)]
        is_error: bool,
    },
    /// Replaces the first `replaced` messages with `checkpoint`, mirroring the splice that
    /// compaction performs on the live history. `checkpoint` is the full replacement message
    /// text, framing included, so the fold reproduces it byte for byte.
    Compacted {
        checkpoint: String,
        replaced: usize,
    },
    TurnEnd {
        reason: TurnEnd,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Record {
    seq: usize,
    #[serde(flatten)]
    event: SessionEvent,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionHeader {
    /// Always "session", so the first line is self-identifying.
    pub kind: String,
    pub version: u32,
    pub id: String,
    pub created_at: String,
    pub cwd: Option<String>,
}

// Messages for the synthetic results that close a turn killed by a crash. The wording matters:
// the model must not blindly retry something that may already have taken effect.
const TOOL_OUTCOME_UNKNOWN: &str =
    "Procyon exited while this tool was running, so its outcome is unknown. Retry it only if it \
     is read-only or idempotent; if it may have had an effect, verify the current state first or \
     ask the user.";
const TOOL_NOT_STARTED: &str =
    "Procyon exited before this tool started. Nothing happened, so retry it if it is still needed.";

/// Every `tool_use` must be answered by a `tool_result`, including the ones whose process died.
/// Without this a resumed transcript is rejected by the API.
pub fn interrupted_turn_closers(events: &[SessionEvent]) -> Vec<SessionEvent> {
    let mut open_turn = false;
    // call id -> whether a ToolCall was recorded for it
    let mut pending: Vec<(String, bool)> = Vec::new();

    for event in events {
        match event {
            SessionEvent::TurnStart => {
                open_turn = true;
                pending.clear();
            }
            SessionEvent::TurnEnd { .. } => {
                open_turn = false;
                pending.clear();
            }
            SessionEvent::AssistantMessage { blocks } => {
                for block in blocks {
                    if let ContentPart::ToolUse { id, .. } = block {
                        pending.push((id.clone(), false));
                    }
                }
            }
            SessionEvent::ToolCall { id, .. } => {
                if let Some(entry) = pending.iter_mut().find(|(pid, _)| pid == id) {
                    entry.1 = true;
                }
            }
            SessionEvent::ToolResult { id, .. } => {
                pending.retain(|(pid, _)| pid != id);
            }
            _ => {}
        }
    }

    if !open_turn {
        return Vec::new();
    }

    let mut closers: Vec<SessionEvent> = pending
        .into_iter()
        .map(|(id, started)| SessionEvent::ToolResult {
            id,
            content: if started {
                TOOL_OUTCOME_UNKNOWN.to_string()
            } else {
                TOOL_NOT_STARTED.to_string()
            },
            is_error: true,
        })
        .collect();

    closers.push(SessionEvent::TurnEnd {
        reason: TurnEnd::Interrupted,
    });
    closers
}

/// Rebuilds the conversation the model should see. Consecutive tool results collapse into one
/// user message, which is what the API requires for a turn with several calls.
pub fn fold_to_messages(events: &[SessionEvent]) -> Vec<Message> {
    let mut messages = Vec::new();
    let mut pending_results: Vec<(String, String)> = Vec::new();

    let flush = |messages: &mut Vec<Message>, results: &mut Vec<(String, String)>| {
        if !results.is_empty() {
            messages.push(Message::tool_results(std::mem::take(results)));
        }
    };

    for event in events {
        match event {
            SessionEvent::ToolResult { id, content, .. } => {
                pending_results.push((id.clone(), content.clone()));
                continue;
            }
            _ => flush(&mut messages, &mut pending_results),
        }

        match event {
            SessionEvent::UserMessage { text } => messages.push(Message::user(text)),
            SessionEvent::AssistantMessage { blocks } => {
                messages.push(Message::assistant(blocks.clone()))
            }
            SessionEvent::Compacted {
                checkpoint,
                replaced,
            } => {
                // Mirrors `history.splice(0..cut, [checkpoint])`: only the compacted head goes,
                // and the retained tail must survive or a resumed session would lose the recent
                // turns that were deliberately kept verbatim.
                let cut = (*replaced).min(messages.len());
                messages.drain(0..cut);
                messages.insert(0, Message::user(checkpoint));
            }
            _ => {}
        }
    }

    flush(&mut messages, &mut pending_results);
    messages
}

fn slug(path: &Path) -> String {
    let raw = path.to_string_lossy();
    let mut out: String = raw
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect();
    // Filesystems dislike very long components, and the tail is the distinguishing part.
    if out.len() > 120 {
        out = out[out.len() - 120..].to_string();
    }
    // A leading '-' makes the directory hostile to every shell tool, which read it as an option
    // flag: `head <dir>/x.jsonl` fails until you prefix `./`.
    let trimmed = out.trim_start_matches('-');
    if trimmed.is_empty() {
        "no-cwd".to_string()
    } else {
        trimmed.to_string()
    }
}

pub fn sessions_root() -> Result<PathBuf> {
    let base = dirs::data_dir()
        .ok_or_else(|| color_eyre::eyre::eyre!("Failed to locate a data directory"))?;
    Ok(base.join("procyon").join("sessions"))
}

fn session_dir(cwd: &Path) -> Result<PathBuf> {
    Ok(sessions_root()?.join(slug(cwd)))
}

// The root is a parameter rather than always `sessions_root()` so tests write inside their own
// temp directory. Deriving it from `cwd` alone meant a test passing a temp path still logged into
// the user's real data directory, which then filled up with fixtures.
fn session_dir_under(root: &Path, cwd: &Path) -> PathBuf {
    root.join(slug(cwd))
}

/// An append-only log for one conversation.
pub struct SessionLog {
    path: PathBuf,
    id: String,
    next_seq: usize,
    open_turn: bool,
    file: Option<tokio::fs::File>,
}

impl SessionLog {
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Where this session is being written. No longer announced at startup — the path was the
    /// longest line on an otherwise empty screen — but kept for `--resume` tooling and tests.
    #[allow(dead_code)]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Starts a fresh log. Persistence failures are not fatal to the harness: the caller may keep
    /// working without a log rather than refuse to start.
    pub async fn create(cwd: &Path) -> Result<Self> {
        Self::create_under(&sessions_root()?, cwd).await
    }

    pub async fn create_under(root: &Path, cwd: &Path) -> Result<Self> {
        let dir = session_dir_under(root, cwd);
        tokio::fs::create_dir_all(&dir).await?;

        let created_at = chrono::Utc::now();
        // Wall clock plus pid: unique per machine without pulling in a uuid dependency.
        let id = format!(
            "{}-{}",
            created_at.format("%Y%m%dT%H%M%S"),
            std::process::id()
        );
        let path = dir.join(format!("{}.jsonl", id));

        let header = SessionHeader {
            kind: "session".to_string(),
            version: FORMAT_VERSION,
            id: id.clone(),
            created_at: created_at.to_rfc3339(),
            cwd: Some(cwd.to_string_lossy().to_string()),
        };

        let mut log = Self {
            path,
            id,
            next_seq: 0,
            open_turn: false,
            file: None,
        };

        let mut line = serde_json::to_string(&header)?;
        line.push('\n');
        log.open_for_append().await?;
        log.write_raw(&line).await?;
        log.flush().await?;

        Ok(log)
    }

    async fn open_for_append(&mut self) -> Result<()> {
        let file = tokio::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&self.path)
            .await
            .wrap_err_with(|| format!("Failed to open {}", self.path.display()))?;
        self.file = Some(file);
        Ok(())
    }

    async fn write_raw(&mut self, line: &str) -> Result<()> {
        use tokio::io::AsyncWriteExt;
        if let Some(file) = self.file.as_mut() {
            file.write_all(line.as_bytes()).await?;
        }
        Ok(())
    }

    /// Durability barrier. Called before sending a request to the model and before running a tool
    /// that may have an effect, so a crash cannot lose the record of something that happened.
    pub async fn flush(&mut self) -> Result<()> {
        use tokio::io::AsyncWriteExt;
        if let Some(file) = self.file.as_mut() {
            file.flush().await?;
            file.sync_data().await?;
        }
        Ok(())
    }

    pub async fn append(&mut self, event: SessionEvent) -> Result<()> {
        // Turn enclosure: crash repair can only close turns, so an event outside one would be
        // indistinguishable from crash debris on reload.
        match &event {
            SessionEvent::TurnStart => self.open_turn = true,
            SessionEvent::TurnEnd { .. } => self.open_turn = false,
            _ if !self.open_turn => {
                bail!("{:?} appended outside a turn", event);
            }
            _ => {}
        }

        let record = Record {
            seq: self.next_seq,
            event,
        };
        self.next_seq += 1;

        let mut line = serde_json::to_string(&record)?;
        line.push('\n');
        self.write_raw(&line).await
    }
}

pub struct LoadedSession {
    pub header: SessionHeader,
    pub events: Vec<SessionEvent>,
    /// Synthetic events appended to close a turn that a crash left open.
    pub repaired: Vec<SessionEvent>,
}

impl LoadedSession {
    pub fn messages(&self) -> Vec<Message> {
        let mut all = self.events.clone();
        all.extend(self.repaired.clone());
        fold_to_messages(&all)
    }

    /// The conversation as the user saw it, for putting back on screen.
    ///
    /// Derived from the events rather than from `messages()`, which is shaped for the model: it
    /// folds tool results into user turns and drops whether they failed. What the user wants back
    /// is what they were looking at — their turns, the replies, and which calls worked.
    pub fn transcript(&self) -> Vec<crate::channels::TranscriptEntry> {
        use crate::channels::TranscriptEntry as Entry;

        let mut out = Vec::new();
        let mut names: std::collections::HashMap<&str, &str> = std::collections::HashMap::new();

        for event in self.events.iter().chain(self.repaired.iter()) {
            match event {
                SessionEvent::UserMessage { text } => out.push(Entry::User(text.clone())),
                SessionEvent::AssistantMessage { blocks } => {
                    for block in blocks {
                        if let ContentPart::Text { text } = block {
                            if !text.trim().is_empty() {
                                out.push(Entry::Agent(text.clone()));
                            }
                        }
                    }
                }
                SessionEvent::ToolCall { id, name } => {
                    names.insert(id.as_str(), name.as_str());
                }
                // Emitted on the result, not the call: that is the point at which the log knows
                // how it went, and a step with no outcome is what B4 was about.
                SessionEvent::ToolResult { id, is_error, .. } => out.push(Entry::Tool {
                    name: names
                        .get(id.as_str())
                        .copied()
                        .unwrap_or("tool")
                        .to_string(),
                    ok: !is_error,
                }),
                SessionEvent::Compacted { .. } => out.push(Entry::Compacted),
                SessionEvent::TurnStart | SessionEvent::TurnEnd { .. } => {}
            }
        }
        out
    }
}

/// Parses a log, discarding a torn final record and reporting how many bytes were committed.
fn parse_log(content: &str) -> Result<(SessionHeader, Vec<SessionEvent>, usize)> {
    let mut committed = 0usize;
    let mut lines = content.split_inclusive('\n');

    let header_line = lines
        .next()
        .ok_or_else(|| color_eyre::eyre::eyre!("Session log is empty"))?;
    if !header_line.ends_with('\n') {
        bail!("Session log has no complete header line");
    }
    let header: SessionHeader = serde_json::from_str(header_line.trim_end())
        .wrap_err("Session log header is not readable")?;

    // Checked before anything structural, so a future format says "upgrade", never "corrupt".
    if header.version != FORMAT_VERSION {
        bail!(
            "Session log is format version {}, but this build understands {}. Upgrade procyon.",
            header.version,
            FORMAT_VERSION
        );
    }
    committed += header_line.len();

    let mut events = Vec::new();
    for line in lines {
        // A final line without a newline is the tail of a crashed write.
        if !line.ends_with('\n') {
            break;
        }
        let trimmed = line.trim_end();
        if trimmed.is_empty() {
            committed += line.len();
            continue;
        }
        let Ok(record) = serde_json::from_str::<Record>(trimmed) else {
            break;
        };
        if record.seq != events.len() {
            break;
        }
        events.push(record.event);
        committed += line.len();
    }

    Ok((header, events, committed))
}

/// Reads a log, repairs a crash-interrupted turn, and physically drops any torn tail so the next
/// append starts from a clean boundary.
pub async fn load(path: &Path) -> Result<LoadedSession> {
    let content = tokio::fs::read_to_string(path)
        .await
        .wrap_err_with(|| format!("Failed to read {}", path.display()))?;

    let (header, events, committed) = parse_log(&content)?;

    if committed < content.len() {
        let file = tokio::fs::OpenOptions::new().write(true).open(path).await?;
        file.set_len(committed as u64).await?;
        file.sync_all().await?;
    }

    let repaired = interrupted_turn_closers(&events);

    Ok(LoadedSession {
        header,
        events,
        repaired,
    })
}

/// Reopens a log for appending, continuing its sequence. Repair events are written first so the
/// persisted transcript matches what the model is given.
/// A session put back together: what the model needs, and what the user should see.
pub struct Resumed {
    pub log: SessionLog,
    pub history: Vec<Message>,
    pub transcript: Vec<crate::channels::TranscriptEntry>,
}

pub async fn resume(path: &Path) -> Result<Resumed> {
    let loaded = load(path).await?;
    let messages = loaded.messages();
    let transcript = loaded.transcript();

    let mut log = SessionLog {
        path: path.to_path_buf(),
        id: loaded.header.id.clone(),
        next_seq: loaded.events.len(),
        open_turn: !loaded.repaired.is_empty(),
        file: None,
    };
    log.open_for_append().await?;

    for event in loaded.repaired {
        log.append(event).await?;
    }
    log.flush().await?;

    Ok(Resumed {
        log,
        history: messages,
        transcript,
    })
}

/// Newest first. Only the first line of each file is read, so listing stays cheap however long
/// the conversations are.
pub async fn list(cwd: &Path) -> Result<Vec<(PathBuf, SessionHeader)>> {
    match session_dir(cwd) {
        Ok(dir) => list_under(&dir).await,
        Err(_) => Ok(Vec::new()),
    }
}

async fn list_under(dir: &Path) -> Result<Vec<(PathBuf, SessionHeader)>> {
    if !tokio::fs::try_exists(dir).await.unwrap_or(false) {
        return Ok(Vec::new());
    }

    let mut entries = tokio::fs::read_dir(&dir).await?;
    let mut found = Vec::new();

    while let Some(entry) = entries.next_entry().await? {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
            continue;
        }
        let Ok(content) = tokio::fs::read_to_string(&path).await else {
            continue;
        };
        let Some(first) = content.lines().next() else {
            continue;
        };
        if let Ok(header) = serde_json::from_str::<SessionHeader>(first) {
            found.push((path, header));
        }
    }

    found.sort_by(|a, b| b.1.created_at.cmp(&a.1.created_at));
    Ok(found)
}

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

    fn call(id: &str) -> ContentPart {
        ContentPart::ToolUse {
            id: id.to_string(),
            name: "grep".to_string(),
            input: json!({}),
        }
    }

    #[test]
    fn a_completed_turn_needs_no_repair() {
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::UserMessage {
                text: "hi".to_string(),
            },
            SessionEvent::TurnEnd {
                reason: TurnEnd::Complete,
            },
        ];
        assert!(interrupted_turn_closers(&events).is_empty());
    }

    #[test]
    fn a_failed_turn_is_distinguishable_from_a_complete_one() {
        let complete = serde_json::to_string(&SessionEvent::TurnEnd {
            reason: TurnEnd::Complete,
        })
        .unwrap();
        let failed = serde_json::to_string(&SessionEvent::TurnEnd {
            reason: TurnEnd::Failed,
        })
        .unwrap();

        assert!(complete.contains("\"complete\""), "got {}", complete);
        assert!(failed.contains("\"failed\""), "got {}", failed);
        assert_ne!(complete, failed);
    }

    #[test]
    fn a_failed_turn_is_closed_and_needs_no_repair() {
        // Failure still ends the turn, so crash repair must not try to close it again.
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::UserMessage {
                text: "deploy it".to_string(),
            },
            SessionEvent::TurnEnd {
                reason: TurnEnd::Failed,
            },
        ];
        assert!(interrupted_turn_closers(&events).is_empty());
    }

    #[test]
    fn an_open_turn_is_closed() {
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::UserMessage {
                text: "hi".to_string(),
            },
        ];
        assert_eq!(
            interrupted_turn_closers(&events),
            vec![SessionEvent::TurnEnd {
                reason: TurnEnd::Interrupted
            }]
        );
    }

    #[test]
    fn a_call_that_started_is_marked_outcome_unknown() {
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::AssistantMessage {
                blocks: vec![call("a")],
            },
            SessionEvent::ToolCall {
                id: "a".to_string(),
                name: "grep".to_string(),
            },
        ];
        let closers = interrupted_turn_closers(&events);
        match &closers[0] {
            SessionEvent::ToolResult {
                id,
                content,
                is_error,
            } => {
                assert_eq!(id, "a");
                assert!(*is_error);
                assert!(content.contains("outcome is unknown"), "got {}", content);
                assert!(content.contains("verify the current state"));
            }
            other => panic!("expected a tool result, got {:?}", other),
        }
    }

    #[test]
    fn a_call_that_never_started_is_safe_to_retry() {
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::AssistantMessage {
                blocks: vec![call("a")],
            },
        ];
        let closers = interrupted_turn_closers(&events);
        match &closers[0] {
            SessionEvent::ToolResult { content, .. } => {
                assert!(content.contains("Nothing happened"), "got {}", content);
            }
            other => panic!("expected a tool result, got {:?}", other),
        }
    }

    #[test]
    fn an_answered_call_is_not_closed_again() {
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::AssistantMessage {
                blocks: vec![call("a")],
            },
            SessionEvent::ToolCall {
                id: "a".to_string(),
                name: "grep".to_string(),
            },
            SessionEvent::ToolResult {
                id: "a".to_string(),
                content: "ok".to_string(),
                is_error: false,
            },
        ];
        assert_eq!(
            interrupted_turn_closers(&events),
            vec![SessionEvent::TurnEnd {
                reason: TurnEnd::Interrupted
            }]
        );
    }

    #[test]
    fn every_parallel_call_gets_its_own_closer() {
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::AssistantMessage {
                blocks: vec![call("a"), call("b"), call("c")],
            },
            SessionEvent::ToolResult {
                id: "b".to_string(),
                content: "ok".to_string(),
                is_error: false,
            },
        ];
        let closers = interrupted_turn_closers(&events);
        assert_eq!(
            closers.len(),
            3,
            "two results plus the turn end: {:?}",
            closers
        );
    }

    #[test]
    fn a_repaired_transcript_pairs_every_call_with_a_result() {
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::UserMessage {
                text: "do it".to_string(),
            },
            SessionEvent::AssistantMessage {
                blocks: vec![call("a"), call("b")],
            },
        ];
        let mut all = events.clone();
        all.extend(interrupted_turn_closers(&events));
        let messages = fold_to_messages(&all);

        let calls: usize = messages
            .iter()
            .flat_map(|m| &m.content)
            .filter(|b| matches!(b, ContentPart::ToolUse { .. }))
            .count();
        let results: usize = messages
            .iter()
            .flat_map(|m| &m.content)
            .filter(|b| matches!(b, ContentPart::ToolResult { .. }))
            .count();
        assert_eq!(calls, results, "the API rejects an unpaired transcript");
    }

    #[test]
    fn results_of_one_turn_fold_into_a_single_user_message() {
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::AssistantMessage {
                blocks: vec![call("a"), call("b")],
            },
            SessionEvent::ToolResult {
                id: "a".to_string(),
                content: "ra".to_string(),
                is_error: false,
            },
            SessionEvent::ToolResult {
                id: "b".to_string(),
                content: "rb".to_string(),
                is_error: false,
            },
        ];
        let messages = fold_to_messages(&events);
        assert_eq!(messages.len(), 2, "{:?}", messages);
        assert_eq!(messages[1].role, crate::agent::Role::User);
        assert_eq!(messages[1].content.len(), 2);
    }

    fn text_of(message: &Message) -> &str {
        match &message.content[0] {
            ContentPart::Text { text } => text,
            other => panic!("expected text, got {:?}", other),
        }
    }

    #[test]
    fn a_checkpoint_replaces_only_the_compacted_head() {
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::UserMessage {
                text: "oldest".to_string(),
            },
            SessionEvent::UserMessage {
                text: "older".to_string(),
            },
            SessionEvent::UserMessage {
                text: "kept".to_string(),
            },
            SessionEvent::Compacted {
                checkpoint: "CHECKPOINT".to_string(),
                replaced: 2,
            },
        ];
        let messages = fold_to_messages(&events);
        let rendered: Vec<&str> = messages.iter().map(text_of).collect();
        assert_eq!(
            rendered,
            vec!["CHECKPOINT", "kept"],
            "the retained tail must survive compaction"
        );
    }

    #[test]
    fn a_second_checkpoint_folds_over_the_first() {
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::UserMessage {
                text: "a".to_string(),
            },
            SessionEvent::UserMessage {
                text: "b".to_string(),
            },
            SessionEvent::Compacted {
                checkpoint: "FIRST".to_string(),
                replaced: 1,
            },
            SessionEvent::UserMessage {
                text: "c".to_string(),
            },
            SessionEvent::Compacted {
                checkpoint: "SECOND".to_string(),
                replaced: 2,
            },
        ];
        let messages = fold_to_messages(&events);
        let rendered: Vec<&str> = messages.iter().map(text_of).collect();
        assert_eq!(rendered, vec!["SECOND", "c"]);
    }

    #[test]
    fn a_checkpoint_claiming_more_than_exists_does_not_panic() {
        let events = vec![
            SessionEvent::TurnStart,
            SessionEvent::UserMessage {
                text: "only".to_string(),
            },
            SessionEvent::Compacted {
                checkpoint: "CHECKPOINT".to_string(),
                replaced: 99,
            },
        ];
        let messages = fold_to_messages(&events);
        assert_eq!(messages.len(), 1);
        assert_eq!(text_of(&messages[0]), "CHECKPOINT");
    }

    fn header_line() -> String {
        serde_json::to_string(&SessionHeader {
            kind: "session".to_string(),
            version: FORMAT_VERSION,
            id: "s1".to_string(),
            created_at: "2026-08-21T00:00:00Z".to_string(),
            cwd: None,
        })
        .unwrap()
    }

    #[test]
    fn a_torn_final_line_is_discarded() {
        let good = serde_json::to_string(&Record {
            seq: 0,
            event: SessionEvent::TurnStart,
        })
        .unwrap();
        let content = format!(
            "{}\n{}\n{{\"seq\":1,\"event\":\"user_mes",
            header_line(),
            good
        );

        let (_, events, committed) = parse_log(&content).unwrap();
        assert_eq!(events.len(), 1, "the torn record must not be parsed");
        assert!(committed < content.len(), "the tail must be excluded");
    }

    #[test]
    fn a_gap_in_the_sequence_stops_the_read() {
        let first = serde_json::to_string(&Record {
            seq: 0,
            event: SessionEvent::TurnStart,
        })
        .unwrap();
        let skipped = serde_json::to_string(&Record {
            seq: 5,
            event: SessionEvent::TurnStart,
        })
        .unwrap();
        let content = format!("{}\n{}\n{}\n", header_line(), first, skipped);

        let (_, events, _) = parse_log(&content).unwrap();
        assert_eq!(events.len(), 1);
    }

    #[test]
    fn a_newer_format_is_refused_with_an_upgrade_message() {
        let mut header: serde_json::Value = serde_json::from_str(&header_line()).unwrap();
        header["version"] = json!(FORMAT_VERSION + 1);
        let content = format!("{}\n", header);

        let err = parse_log(&content).unwrap_err().to_string();
        assert!(err.contains("Upgrade procyon"), "got {}", err);
    }

    #[tokio::test]
    async fn appending_outside_a_turn_is_refused() {
        let temp = tempfile::tempdir().unwrap();
        let mut log = SessionLog {
            path: temp.path().join("s.jsonl"),
            id: "s".to_string(),
            next_seq: 0,
            open_turn: false,
            file: None,
        };
        log.open_for_append().await.unwrap();

        let err = log
            .append(SessionEvent::UserMessage {
                text: "stray".to_string(),
            })
            .await
            .unwrap_err()
            .to_string();
        assert!(err.contains("outside a turn"), "got {}", err);
    }

    #[tokio::test]
    async fn a_written_log_round_trips() {
        let temp = tempfile::tempdir().unwrap();
        let mut log = SessionLog::create_under(temp.path(), temp.path())
            .await
            .unwrap();

        log.append(SessionEvent::TurnStart).await.unwrap();
        log.append(SessionEvent::UserMessage {
            text: "olá".to_string(),
        })
        .await
        .unwrap();
        log.append(SessionEvent::TurnEnd {
            reason: TurnEnd::Complete,
        })
        .await
        .unwrap();
        log.flush().await.unwrap();

        let loaded = load(log.path()).await.unwrap();
        assert_eq!(loaded.events.len(), 3);
        assert!(loaded.repaired.is_empty());

        let messages = loaded.messages();
        assert_eq!(messages.len(), 1);
        assert!(matches!(&messages[0].content[0], ContentPart::Text { text } if text == "olá"));
    }

    #[tokio::test]
    async fn resuming_a_crashed_log_closes_the_turn_on_disk() {
        let temp = tempfile::tempdir().unwrap();
        let mut log = SessionLog::create_under(temp.path(), temp.path())
            .await
            .unwrap();

        log.append(SessionEvent::TurnStart).await.unwrap();
        log.append(SessionEvent::UserMessage {
            text: "do it".to_string(),
        })
        .await
        .unwrap();
        log.append(SessionEvent::AssistantMessage {
            blocks: vec![call("a")],
        })
        .await
        .unwrap();
        log.flush().await.unwrap();
        let path = log.path().to_path_buf();
        drop(log); // as if the process died mid-turn

        let messages = resume(&path).await.unwrap().history;

        // The synthetic result must be durable, not only in memory.
        let reloaded = load(&path).await.unwrap();
        assert!(
            reloaded.repaired.is_empty(),
            "a resumed log must no longer need repair"
        );
        assert!(matches!(
            reloaded.events.last(),
            Some(SessionEvent::TurnEnd {
                reason: TurnEnd::Interrupted
            })
        ));

        let results: usize = messages
            .iter()
            .flat_map(|m| &m.content)
            .filter(|b| matches!(b, ContentPart::ToolResult { .. }))
            .count();
        assert_eq!(results, 1, "the dead call must be answered");
    }

    // Writes a log by hand, chops it mid-record as a crash would, then resumes — the whole
    // recovery path against a real file.
    #[tokio::test]
    async fn a_log_truncated_mid_write_is_recovered_and_resumable() {
        let temp = tempfile::tempdir().unwrap();
        let mut log = SessionLog::create_under(temp.path(), temp.path())
            .await
            .unwrap();
        let path = log.path().to_path_buf();

        log.append(SessionEvent::TurnStart).await.unwrap();
        log.append(SessionEvent::UserMessage {
            text: "deploy it".to_string(),
        })
        .await
        .unwrap();
        log.append(SessionEvent::AssistantMessage {
            blocks: vec![call("a")],
        })
        .await
        .unwrap();
        log.append(SessionEvent::ToolCall {
            id: "a".to_string(),
            name: "caatinga_deploy".to_string(),
        })
        .await
        .unwrap();
        log.flush().await.unwrap();
        drop(log);

        // Simulate the process dying halfway through the next record.
        let mut raw = tokio::fs::read_to_string(&path).await.unwrap();
        raw.push_str("{\"seq\":4,\"event\":\"tool_res");
        tokio::fs::write(&path, &raw).await.unwrap();

        let messages = resume(&path).await.unwrap().history;

        // The torn tail must be physically gone so the next append is contiguous.
        let on_disk = tokio::fs::read_to_string(&path).await.unwrap();
        assert!(
            !on_disk.contains("tool_res\""),
            "the torn record survived: {}",
            on_disk
        );

        // A deploy that may have happened must be flagged, not reported as never started.
        let flagged = messages
            .iter()
            .flat_map(|m| &m.content)
            .filter_map(|b| match b {
                ContentPart::ToolResult { content, .. } => Some(content.as_str()),
                _ => None,
            })
            .any(|c| c.contains("outcome is unknown"));
        assert!(
            flagged,
            "a started tool must not look untouched: {:?}",
            messages
        );

        let reloaded = load(&path).await.unwrap();
        assert!(
            reloaded.repaired.is_empty(),
            "resume must leave a clean log"
        );
    }

    // --- what the user gets back on screen ---------------------------------------------------

    #[tokio::test]
    async fn a_resumed_transcript_carries_both_sides_of_the_conversation() {
        use crate::channels::TranscriptEntry as Entry;

        let temp = tempfile::tempdir().unwrap();
        let mut log = SessionLog::create(temp.path()).await.unwrap();
        log.append(SessionEvent::TurnStart).await.unwrap();
        log.append(SessionEvent::UserMessage {
            text: "liste os arquivos".to_string(),
        })
        .await
        .unwrap();
        log.append(SessionEvent::ToolCall {
            id: "t1".to_string(),
            name: "list_dir".to_string(),
        })
        .await
        .unwrap();
        log.append(SessionEvent::ToolResult {
            id: "t1".to_string(),
            content: "a.rs".to_string(),
            is_error: false,
        })
        .await
        .unwrap();
        log.append(SessionEvent::AssistantMessage {
            blocks: vec![ContentPart::Text {
                text: "sao estes".to_string(),
            }],
        })
        .await
        .unwrap();
        log.append(SessionEvent::TurnEnd {
            reason: TurnEnd::Complete,
        })
        .await
        .unwrap();
        log.flush().await.unwrap();
        let path = log.path().to_path_buf();
        drop(log);

        let transcript = resume(&path).await.unwrap().transcript;

        assert_eq!(
            transcript,
            vec![
                Entry::User("liste os arquivos".to_string()),
                Entry::Tool {
                    name: "list_dir".to_string(),
                    ok: true
                },
                Entry::Agent("sao estes".to_string()),
            ]
        );
    }

    // `messages()` folds tool results into user turns and keeps no record of failure, so a
    // transcript built from it would show every call as fine.
    #[tokio::test]
    async fn a_resumed_transcript_remembers_which_calls_failed() {
        use crate::channels::TranscriptEntry as Entry;

        let temp = tempfile::tempdir().unwrap();
        let mut log = SessionLog::create(temp.path()).await.unwrap();
        log.append(SessionEvent::TurnStart).await.unwrap();
        log.append(SessionEvent::ToolCall {
            id: "t1".to_string(),
            name: "caatinga_deploy".to_string(),
        })
        .await
        .unwrap();
        log.append(SessionEvent::ToolResult {
            id: "t1".to_string(),
            content: "Error: boom".to_string(),
            is_error: true,
        })
        .await
        .unwrap();
        log.flush().await.unwrap();
        let path = log.path().to_path_buf();
        drop(log);

        let transcript = resume(&path).await.unwrap().transcript;
        assert!(transcript.contains(&Entry::Tool {
            name: "caatinga_deploy".to_string(),
            ok: false
        }));
    }

    // The property that matters: after compaction, resuming must rebuild exactly the history the
    // live process is holding. Anything else and a resumed session silently diverges.
    #[tokio::test]
    async fn a_resumed_compacted_session_matches_the_live_history() {
        let temp = tempfile::tempdir().unwrap();
        let mut log = SessionLog::create_under(temp.path(), temp.path())
            .await
            .unwrap();
        let path = log.path().to_path_buf();

        // Three exchanges, as the agent loop would record them.
        let mut live: Vec<Message> = Vec::new();
        log.append(SessionEvent::TurnStart).await.unwrap();
        for i in 0..3 {
            let user = format!("question {}", i);
            let reply = format!("answer {}", i);

            log.append(SessionEvent::UserMessage { text: user.clone() })
                .await
                .unwrap();
            live.push(Message::user(&user));

            log.append(SessionEvent::AssistantMessage {
                blocks: vec![ContentPart::Text {
                    text: reply.clone(),
                }],
            })
            .await
            .unwrap();
            live.push(Message::assistant(vec![ContentPart::Text { text: reply }]));
        }

        // Compaction: replace the first four messages, keep the last two verbatim.
        let cut = 4;
        let checkpoint = "CHECKPOINT: earlier turns summarized".to_string();
        log.append(SessionEvent::Compacted {
            checkpoint: checkpoint.clone(),
            replaced: cut,
        })
        .await
        .unwrap();
        live.splice(0..cut, std::iter::once(Message::user(&checkpoint)));

        log.append(SessionEvent::TurnEnd {
            reason: TurnEnd::Complete,
        })
        .await
        .unwrap();
        log.flush().await.unwrap();
        drop(log);

        let restored = resume(&path).await.unwrap().history;

        let rendered = |messages: &[Message]| -> Vec<(String, String)> {
            messages
                .iter()
                .map(|m| (m.role.to_string(), text_of(m).to_string()))
                .collect()
        };
        assert_eq!(
            rendered(&restored),
            rendered(&live),
            "a resumed compacted session must match the live history"
        );
        assert_eq!(restored.len(), 3, "checkpoint plus the retained tail");
    }

    #[tokio::test]
    async fn listing_reports_newest_first_and_ignores_other_files() {
        let temp = tempfile::tempdir().unwrap();
        let first = SessionLog::create_under(temp.path(), temp.path())
            .await
            .unwrap();
        tokio::fs::write(first.path().parent().unwrap().join("notes.txt"), "x")
            .await
            .unwrap();

        let listed = list_under(&session_dir_under(temp.path(), temp.path()))
            .await
            .unwrap();
        assert_eq!(listed.len(), 1, "only .jsonl logs count: {:?}", listed);
        assert_eq!(listed[0].1.id, first.id());
    }

    // Regression guard: create_under must write inside the root it is given. Deriving the
    // directory from `cwd` alone made every test run leave fixtures in the user's real data
    // directory, where they looked like genuine sessions.
    #[tokio::test]
    async fn a_log_stays_inside_the_root_it_was_given() {
        let temp = tempfile::tempdir().unwrap();
        let log = SessionLog::create_under(temp.path(), temp.path())
            .await
            .unwrap();

        assert!(
            log.path().starts_with(temp.path()),
            "{} escaped {}",
            log.path().display(),
            temp.path().display()
        );
        assert!(
            !log.path().starts_with(sessions_root().unwrap()),
            "a test log must not land in the real sessions directory"
        );
    }

    #[test]
    fn the_slug_keeps_paths_filesystem_safe() {
        let s = slug(Path::new("/home/user/My Project (v2)"));
        assert!(
            !s.contains('/') && !s.contains(' ') && !s.contains('('),
            "got {}",
            s
        );
    }

    #[test]
    fn the_slug_does_not_start_with_a_dash() {
        // Otherwise `head <dir>/log.jsonl` and friends read the name as a flag.
        for path in ["/home/user/proj", "/tmp/.tmpXYZ", "///weird"] {
            let s = slug(Path::new(path));
            assert!(!s.starts_with('-'), "{} produced {}", path, s);
        }
    }

    #[test]
    fn an_unnameable_path_still_yields_a_directory() {
        assert_eq!(slug(Path::new("/")), "no-cwd");
    }
}