kiss-coding 0.0.24

Coding harness: sessions, tools, compaction, settings, skills
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
//! SessionManager: append-only JSONL tree with leaf tracking, branching,
//! context building, and pi-compatible on-disk layout.

use super::entry::{
    EntryBase, SESSION_VERSION, SessionEntry, SessionHeader, iso_now, new_entry_id,
};
use anyhow::{Context as _, Result};
use kiss_agent::{AgentMessage, BranchSummaryMessage, CompactionSummaryMessage, CustomMessage};
use kiss_ai::{Model, ThinkingLevel, Usage};
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};

pub struct SessionManager {
    header: SessionHeader,
    entries: Vec<SessionEntry>,
    index: HashMap<String, usize>,
    leaf_id: Option<String>,
    context_revision: u64,
    file: Option<PathBuf>,
    append_file: Option<File>,
    session_dir: PathBuf,
    cwd: PathBuf,
}

/// Slug a working directory the way pi does: `/a/b` -> `--a-b--`.
pub fn cwd_slug(cwd: &Path) -> String {
    let s = cwd.display().to_string().replace(['/', '\\', ':'], "-");
    format!("-{s}-")
}

pub fn default_session_dir() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".kiss/agent/sessions")
}

#[derive(Debug, Clone)]
pub struct SessionListing {
    pub path: PathBuf,
    pub id: String,
    pub name: Option<String>,
    pub first_message: Option<String>,
    pub cwd: String,
    pub modified: std::time::SystemTime,
    pub entry_count: usize,
}

impl SessionManager {
    // ----- creation -----------------------------------------------------

    pub fn create(cwd: &Path, session_dir: Option<PathBuf>) -> Result<Self> {
        let session_dir = session_dir.unwrap_or_else(default_session_dir);
        let mut manager = Self::in_memory(cwd);
        manager.session_dir = session_dir;
        manager.assign_new_file()?;
        Ok(manager)
    }

    pub fn in_memory(cwd: &Path) -> Self {
        SessionManager {
            header: SessionHeader {
                entry_type: "session".into(),
                version: SESSION_VERSION,
                id: uuid::Uuid::new_v4().to_string(),
                timestamp: iso_now(),
                cwd: cwd.display().to_string(),
                parent_session: None,
                extra: Map::new(),
            },
            entries: Vec::new(),
            index: HashMap::new(),
            leaf_id: None,
            context_revision: 0,
            file: None,
            append_file: None,
            session_dir: default_session_dir(),
            cwd: cwd.to_path_buf(),
        }
    }

    /// Restore an in-memory session from entries managed by an SDK caller.
    pub fn in_memory_with_entries(cwd: &Path, entries: Vec<SessionEntry>) -> Self {
        let mut manager = Self::in_memory(cwd);
        for entry in entries {
            manager.insert_entry(entry);
        }
        manager.leaf_id = manager.entries.last().map(|entry| entry.id().to_string());
        manager
    }

    pub fn open(path: &Path) -> Result<Self> {
        let text = std::fs::read_to_string(path)
            .with_context(|| format!("open session {}", path.display()))?;
        let needs_trailing_newline = !text.is_empty() && !text.ends_with('\n');
        let mut lines = text.lines().filter(|l| !l.trim().is_empty());
        let header_line = lines.next().context("empty session file")?;
        let header: SessionHeader =
            serde_json::from_str(header_line).context("parse session header")?;
        let cwd = PathBuf::from(&header.cwd);
        let mut manager = SessionManager {
            header,
            entries: Vec::new(),
            index: HashMap::new(),
            leaf_id: None,
            context_revision: 0,
            file: Some(path.to_path_buf()),
            append_file: None,
            session_dir: path
                .parent()
                .and_then(|p| p.parent())
                .map(|p| p.to_path_buf())
                .unwrap_or_else(default_session_dir),
            cwd,
        };
        let mut all_entries_valid = true;
        for line in lines {
            match serde_json::from_str::<SessionEntry>(line) {
                Ok(entry) => manager.insert_entry(entry),
                Err(err) => {
                    all_entries_valid = false;
                    eprintln!("warning: skipping malformed session line: {err}");
                }
            }
        }
        manager.leaf_id = manager.entries.last().map(|e| e.id().to_string());
        if needs_trailing_newline && all_entries_valid {
            let mut file = std::fs::OpenOptions::new().append(true).open(path)?;
            file.write_all(b"\n")?;
        }
        manager.reopen_append_file()?;
        Ok(manager)
    }

    pub fn continue_recent(cwd: &Path, session_dir: Option<PathBuf>) -> Result<Self> {
        let dir = session_dir.clone().unwrap_or_else(default_session_dir);
        let listings = Self::list(cwd, &dir)?;
        match listings.first() {
            Some(listing) => Self::open(&listing.path),
            None => Self::create(cwd, session_dir),
        }
    }

    pub fn create_sibling(&self) -> Result<Self> {
        if self.is_persisted() {
            Self::create(&self.cwd, Some(self.session_dir.clone()))
        } else {
            let mut manager = Self::in_memory(&self.cwd);
            manager.session_dir = self.session_dir.clone();
            Ok(manager)
        }
    }

    /// Create a child session in the same working directory and session store.
    pub fn create_child(&self) -> Result<Self> {
        let mut manager = self.create_sibling()?;
        manager.header.parent_session = Some(
            self.file
                .as_ref()
                .map(|path| path.display().to_string())
                .unwrap_or_else(|| format!("session:{}", self.header.id)),
        );
        Ok(manager)
    }

    /// Fork: copy the source session's entries into a new file for `cwd`.
    pub fn fork_from(source: &Path, cwd: &Path, session_dir: Option<PathBuf>) -> Result<Self> {
        let origin = Self::open(source)?;
        let mut manager = Self::create(cwd, session_dir)?;
        manager.header.parent_session = Some(source.display().to_string());
        for entry in &origin.entries {
            manager.insert_entry(entry.clone());
        }
        manager.leaf_id = origin.leaf_id.clone();
        manager.rewrite_file()?;
        Ok(manager)
    }

    /// Copy one active branch into a new session file.
    ///
    /// `through` selects the last entry to inspect. When `include_through` is
    /// false, the new session ends at that entry's parent. This lets an
    /// interactive caller put a selected user message back in the editor.
    pub fn fork_active_branch(&self, through: Option<&str>, include_through: bool) -> Result<Self> {
        if let Some(entry_id) = through
            && self.get_entry(entry_id).is_none()
        {
            anyhow::bail!("unknown entry id {entry_id}");
        }

        let mut branch = self.branch_entries(through);
        if !include_through && through.is_some() {
            branch.pop();
        }

        let mut manager = self.create_sibling()?;
        manager.header.parent_session = self.file.as_ref().map(|path| path.display().to_string());
        manager.entries.clear();
        manager.index.clear();
        manager.leaf_id = None;
        for entry in branch {
            let entry = entry.clone();
            manager.leaf_id = Some(entry.id().to_string());
            manager.insert_entry(entry);
        }
        manager.rewrite_file()?;
        Ok(manager)
    }

    // ----- listing ------------------------------------------------------

    pub fn list(cwd: &Path, session_dir: &Path) -> Result<Vec<SessionListing>> {
        let dir = session_dir.join(cwd_slug(cwd));
        let mut out = Self::list_dir(&dir)?;
        out.sort_by_key(|listing| std::cmp::Reverse(listing.modified));
        Ok(out)
    }

    pub fn list_all(session_dir: &Path) -> Result<Vec<SessionListing>> {
        let mut out = Vec::new();
        if let Ok(entries) = std::fs::read_dir(session_dir) {
            for entry in entries.flatten() {
                if entry.path().is_dir() {
                    out.extend(Self::list_dir(&entry.path())?);
                }
            }
        }
        out.sort_by_key(|listing| std::cmp::Reverse(listing.modified));
        Ok(out)
    }

    fn list_dir(dir: &Path) -> Result<Vec<SessionListing>> {
        let mut out = Vec::new();
        let Ok(entries) = std::fs::read_dir(dir) else {
            return Ok(out);
        };
        for file in entries.flatten() {
            let path = file.path();
            if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
                continue;
            }
            if let Some(listing) = Self::peek(&path) {
                out.push(listing);
            }
        }
        Ok(out)
    }

    /// Cheap listing: header + scan for name/first user message.
    fn peek(path: &Path) -> Option<SessionListing> {
        let mut reader = BufReader::new(File::open(path).ok()?);
        let mut line = String::new();
        loop {
            line.clear();
            if reader.read_line(&mut line).ok()? == 0 {
                return None;
            }
            if !line.trim().is_empty() {
                break;
            }
        }
        let header: SessionHeader = serde_json::from_str(&line).ok()?;
        let mut name = None;
        let mut first_message = None;
        let mut entry_count = 0usize;
        loop {
            line.clear();
            if reader.read_line(&mut line).ok()? == 0 {
                break;
            }
            if line.trim().is_empty() {
                continue;
            }
            entry_count += 1;
            if name.is_none()
                && line.contains("\"session_info\"")
                && let Ok(v) = serde_json::from_str::<Value>(&line)
                && v["type"] == "session_info"
            {
                name = v["name"].as_str().map(String::from);
            }
            if first_message.is_none()
                && line.contains("\"message\"")
                && let Ok(v) = serde_json::from_str::<Value>(&line)
                && v["type"] == "message"
                && v["message"]["role"] == "user"
            {
                let content = &v["message"]["content"];
                let text = content.as_str().map(String::from).or_else(|| {
                    content
                        .as_array()
                        .and_then(|a| a.iter().find(|b| b["type"] == "text"))
                        .and_then(|b| b["text"].as_str().map(String::from))
                });
                first_message = text.map(|t| t.chars().take(120).collect());
            }
        }
        if entry_count == 0 {
            return None;
        }
        let modified = std::fs::metadata(path).and_then(|m| m.modified()).ok()?;
        Some(SessionListing {
            path: path.to_path_buf(),
            id: header.id,
            name,
            first_message,
            cwd: header.cwd,
            modified,
            entry_count,
        })
    }

    /// Find a session file by partial UUID across all projects.
    pub fn find_by_id(session_dir: &Path, partial: &str) -> Result<Option<PathBuf>> {
        for listing in Self::list_all(session_dir)? {
            if listing.id.starts_with(partial) {
                return Ok(Some(listing.path));
            }
        }
        Ok(None)
    }

    // ----- appends ------------------------------------------------------

    fn make_base(&self) -> EntryBase {
        EntryBase {
            id: new_entry_id(),
            parent_id: self.leaf_id.clone(),
            timestamp: iso_now(),
        }
    }

    pub fn append_message(&mut self, message: AgentMessage) -> Result<String> {
        self.append_entry(|base| SessionEntry::Message {
            base,
            message,
            extra: Map::new(),
        })
    }

    pub fn append_messages_with_session_info<I>(&mut self, messages: I, name: &str) -> Result<()>
    where
        I: IntoIterator<Item = AgentMessage>,
    {
        let mut parent_id = self.leaf_id.clone();
        let mut entries = Vec::new();
        for message in messages {
            let entry = SessionEntry::Message {
                base: EntryBase {
                    id: new_entry_id(),
                    parent_id: parent_id.clone(),
                    timestamp: iso_now(),
                },
                message,
                extra: Map::new(),
            };
            parent_id = Some(entry.id().to_string());
            entries.push(entry);
        }
        entries.push(SessionEntry::SessionInfo {
            base: EntryBase {
                id: new_entry_id(),
                parent_id,
                timestamp: iso_now(),
            },
            name: Some(name.to_string()),
            extra: Map::new(),
        });
        self.append_entries(entries)
    }

    fn append_entries(&mut self, entries: Vec<SessionEntry>) -> Result<()> {
        let mut lines = String::new();
        for entry in &entries {
            lines.push_str(&serde_json::to_string(&entry)?);
            lines.push('\n');
        }
        if !lines.is_empty() {
            self.append_lines(&lines)?;
        }
        for entry in entries {
            self.leaf_id = Some(entry.id().to_string());
            self.insert_entry(entry);
        }
        Ok(())
    }

    pub fn append_model_change(&mut self, provider: &str, model_id: &str) -> Result<String> {
        let (provider, model_id) = (provider.to_string(), model_id.to_string());
        self.append_entry(|base| SessionEntry::ModelChange {
            base,
            provider,
            model_id,
            extra: Map::new(),
        })
    }

    pub fn append_thinking_level_change(&mut self, level: ThinkingLevel) -> Result<String> {
        self.append_entry(|base| SessionEntry::ThinkingLevelChange {
            base,
            thinking_level: level,
            extra: Map::new(),
        })
    }

    pub fn append_usage(
        &mut self,
        kind: &str,
        provider: &str,
        model: &str,
        usage: Usage,
        note: Option<String>,
    ) -> Result<String> {
        let (kind, provider, model) = (kind.to_string(), provider.to_string(), model.to_string());
        self.append_entry(|base| SessionEntry::Usage {
            base,
            kind,
            provider,
            model,
            usage,
            note,
            extra: Map::new(),
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub fn append_compaction(
        &mut self,
        summary: String,
        tokens_before: u64,
        retained_tail: Vec<AgentMessage>,
        usage: Option<Usage>,
        details: Option<Value>,
    ) -> Result<String> {
        self.append_entry(|base| SessionEntry::Compaction {
            base,
            summary,
            tokens_before,
            first_kept_entry_id: None,
            retained_tail: Some(retained_tail),
            usage,
            details,
            extra: Map::new(),
        })
    }

    pub fn append_session_info(&mut self, name: &str) -> Result<String> {
        let name = name.to_string();
        self.append_entry(|base| SessionEntry::SessionInfo {
            base,
            name: Some(name),
            extra: Map::new(),
        })
    }

    pub fn append_label(&mut self, target_id: &str, label: Option<String>) -> Result<String> {
        let target_id = target_id.to_string();
        self.append_entry(|base| SessionEntry::Label {
            base,
            target_id,
            label,
            extra: Map::new(),
        })
    }

    pub fn append_custom(&mut self, custom_type: &str, data: Option<Value>) -> Result<String> {
        let custom_type = custom_type.to_string();
        self.append_entry(|base| SessionEntry::Custom {
            base,
            custom_type,
            data,
            extra: Map::new(),
        })
    }

    fn append_entry(&mut self, make: impl FnOnce(EntryBase) -> SessionEntry) -> Result<String> {
        let entry = make(self.make_base());
        let id = entry.id().to_string();
        self.append_entries(vec![entry])?;
        Ok(id)
    }

    fn insert_entry(&mut self, entry: SessionEntry) {
        self.index
            .insert(entry.id().to_string(), self.entries.len());
        self.entries.push(entry);
        self.context_revision = self.context_revision.wrapping_add(1);
    }

    fn append_lines(&mut self, lines: &str) -> Result<()> {
        if self.file.is_none() {
            return Ok(());
        }
        if self.append_file.is_none() {
            let path = self.file.as_ref().expect("a persisted session has a path");
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            let is_new = !path.exists();
            let mut file = std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(path)?;
            if is_new {
                writeln!(file, "{}", serde_json::to_string(&self.header)?)?;
            }
            self.append_file = Some(file);
        }
        let file = self
            .append_file
            .as_mut()
            .expect("a persisted session has an append file");
        file.write_all(lines.as_bytes())?;
        file.flush()?;
        file.sync_data()?;
        Ok(())
    }

    fn reopen_append_file(&mut self) -> Result<()> {
        self.append_file = match &self.file {
            Some(path) => Some(std::fs::OpenOptions::new().append(true).open(path)?),
            None => None,
        };
        Ok(())
    }

    fn assign_new_file(&mut self) -> Result<()> {
        let dir = self.session_dir.join(cwd_slug(&self.cwd));
        let stamp = chrono::Utc::now().format("%Y-%m-%d-%H-%M-%S");
        let path = dir.join(format!("{stamp}_{}.jsonl", self.header.id));
        self.file = Some(path);
        Ok(())
    }

    /// Rewrite the whole file (header + entries). Used at creation and fork.
    fn rewrite_file(&mut self) -> Result<()> {
        let Some(path) = self.file.clone() else {
            return Ok(());
        };
        if self.entries.is_empty() && !path.exists() {
            return Ok(());
        }
        self.append_file = None;
        let mut out = serde_json::to_string(&self.header)?;
        out.push('\n');
        for entry in &self.entries {
            out.push_str(&serde_json::to_string(entry)?);
            out.push('\n');
        }
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let parent = path
            .parent()
            .context("session file has no parent directory")?;
        let mut temporary = tempfile::NamedTempFile::new_in(parent)?;
        temporary.write_all(out.as_bytes())?;
        temporary.as_file().sync_all()?;
        temporary.persist(&path).map_err(|error| error.error)?;
        self.reopen_append_file()?;
        Ok(())
    }

    // ----- tree ---------------------------------------------------------

    pub fn get_entry(&self, id: &str) -> Option<&SessionEntry> {
        self.index.get(id).map(|&i| &self.entries[i])
    }

    pub fn entries(&self) -> &[SessionEntry] {
        &self.entries
    }

    pub fn leaf_id(&self) -> Option<&str> {
        self.leaf_id.as_deref()
    }

    /// Monotonic value for cache invalidation after context or tree changes.
    pub fn context_revision(&self) -> u64 {
        self.context_revision
    }

    /// Move the leaf to an earlier entry (in-place branching).
    pub fn branch(&mut self, entry_id: &str) -> Result<()> {
        if self.get_entry(entry_id).is_none() {
            anyhow::bail!("unknown entry id {entry_id}");
        }
        self.leaf_id = Some(entry_id.to_string());
        self.context_revision = self.context_revision.wrapping_add(1);
        Ok(())
    }

    /// Reset the leaf to before any entries.
    pub fn reset_leaf(&mut self) {
        self.leaf_id = None;
        self.context_revision = self.context_revision.wrapping_add(1);
    }

    /// Branch to `entry_id` and record a summary of the abandoned path.
    pub fn branch_with_summary(
        &mut self,
        entry_id: Option<&str>,
        from_id: &str,
        summary: String,
        usage: Option<Usage>,
        details: Option<Value>,
    ) -> Result<String> {
        if let Some(entry_id) = entry_id {
            self.branch(entry_id)?;
        } else {
            self.reset_leaf();
        }
        let from_id = from_id.to_string();
        self.append_entry(|base| SessionEntry::BranchSummary {
            base,
            from_id,
            summary,
            usage,
            details,
            extra: Map::new(),
        })
    }

    pub fn children(&self, parent_id: Option<&str>) -> Vec<&SessionEntry> {
        self.entries
            .iter()
            .filter(|e| e.parent_id() == parent_id)
            .collect()
    }

    /// Walk leaf -> root. Returns entries in root-first order.
    pub fn branch_entries(&self, from: Option<&str>) -> Vec<&SessionEntry> {
        let mut out = Vec::new();
        let mut cursor = from.or(self.leaf_id.as_deref()).map(String::from);
        while let Some(id) = cursor {
            let Some(entry) = self.get_entry(&id) else {
                break;
            };
            out.push(entry);
            cursor = entry.parent_id().map(String::from);
        }
        out.reverse();
        out
    }

    /// LLM messages on one branch after an optional common ancestor.
    pub fn branch_messages_after(&self, from: &str, ancestor: Option<&str>) -> Vec<AgentMessage> {
        let path = self.branch_entries(Some(from));
        let start = ancestor
            .and_then(|ancestor| path.iter().position(|entry| entry.id() == ancestor))
            .map_or(0, |position| position + 1);
        let mut messages = Vec::new();
        for entry in &path[start..] {
            match entry {
                SessionEntry::Message { message, .. } => messages.push(message.clone()),
                SessionEntry::Compaction {
                    summary,
                    tokens_before,
                    base,
                    ..
                } => messages.push(AgentMessage::CompactionSummary(CompactionSummaryMessage {
                    summary: summary.clone(),
                    tokens_before: *tokens_before,
                    timestamp: chrono::DateTime::parse_from_rfc3339(&base.timestamp)
                        .map(|time| time.timestamp_millis())
                        .unwrap_or_else(|_| kiss_ai::now_ms()),
                })),
                SessionEntry::BranchSummary {
                    summary,
                    from_id,
                    base,
                    ..
                } => messages.push(AgentMessage::BranchSummary(BranchSummaryMessage {
                    summary: summary.clone(),
                    from_id: from_id.clone(),
                    timestamp: chrono::DateTime::parse_from_rfc3339(&base.timestamp)
                        .map(|time| time.timestamp_millis())
                        .unwrap_or_else(|_| kiss_ai::now_ms()),
                })),
                SessionEntry::CustomMessage {
                    custom_type,
                    content,
                    display,
                    details,
                    base,
                    ..
                } => messages.push(AgentMessage::Custom(CustomMessage {
                    custom_type: custom_type.clone(),
                    content: content.clone(),
                    display: *display,
                    details: details.clone(),
                    timestamp: chrono::DateTime::parse_from_rfc3339(&base.timestamp)
                        .map(|time| time.timestamp_millis())
                        .unwrap_or_else(|_| kiss_ai::now_ms()),
                })),
                _ => {}
            }
        }
        messages
    }

    /// Latest session name on the active path.
    pub fn session_name(&self) -> Option<String> {
        self.branch_entries(None)
            .iter()
            .rev()
            .find_map(|e| match e {
                SessionEntry::SessionInfo { name, .. } => name.clone(),
                _ => None,
            })
    }

    pub fn label_of(&self, target: &str) -> Option<String> {
        // Labels apply tree-wide. Last write wins.
        self.entries
            .iter()
            .rev()
            .find_map(|e| match e {
                SessionEntry::Label {
                    target_id, label, ..
                } if target_id == target => Some(label.clone()),
                _ => None,
            })
            .flatten()
    }

    // ----- context building --------------------------------------------

    /// Active-branch entries with compaction applied: on a compaction with a
    /// retained tail, the checkpoint replaces everything before it.
    pub fn build_context_entries(&self) -> Vec<&SessionEntry> {
        let path = self.branch_entries(None);
        let compaction_pos = path
            .iter()
            .rposition(|e| matches!(e, SessionEntry::Compaction { .. }));
        match compaction_pos {
            Some(pos) => {
                let SessionEntry::Compaction {
                    retained_tail,
                    first_kept_entry_id,
                    ..
                } = path[pos]
                else {
                    unreachable!()
                };
                let mut out: Vec<&SessionEntry> = Vec::new();
                out.push(path[pos]);
                if retained_tail.is_none() {
                    // Legacy: include entries from firstKeptEntryId up to the
                    // compaction entry.
                    if let Some(first_kept) = first_kept_entry_id
                        && let Some(start) = path.iter().position(|e| e.id() == first_kept)
                    {
                        for e in &path[start..pos] {
                            out.push(e);
                        }
                    }
                }
                for e in &path[pos + 1..] {
                    out.push(e);
                }
                out
            }
            None => path,
        }
    }

    /// Messages + model + thinking level for the next LLM call.
    pub fn build_session_context(&self) -> SessionContext {
        // Model/thinking come from the full active path.
        let path = self.branch_entries(None);
        let mut model: Option<(String, String)> = None;
        let mut thinking: Option<ThinkingLevel> = None;
        for entry in &path {
            match entry {
                SessionEntry::ModelChange {
                    provider, model_id, ..
                } => {
                    model = Some((provider.clone(), model_id.clone()));
                }
                SessionEntry::ThinkingLevelChange { thinking_level, .. } => {
                    thinking = Some(*thinking_level)
                }
                _ => {}
            }
        }

        let mut messages: Vec<AgentMessage> = Vec::new();
        for entry in self.build_context_entries() {
            match entry {
                SessionEntry::Message { message, .. } => messages.push(message.clone()),
                SessionEntry::Compaction {
                    summary,
                    tokens_before,
                    retained_tail,
                    base,
                    ..
                } => {
                    if !summary.is_empty() {
                        messages.push(AgentMessage::CompactionSummary(CompactionSummaryMessage {
                            summary: summary.clone(),
                            tokens_before: *tokens_before,
                            timestamp: chrono::DateTime::parse_from_rfc3339(&base.timestamp)
                                .map(|t| t.timestamp_millis())
                                .unwrap_or_else(|_| kiss_ai::now_ms()),
                        }));
                    }
                    if let Some(tail) = retained_tail {
                        messages.extend(tail.iter().cloned());
                    }
                }
                SessionEntry::BranchSummary {
                    summary,
                    from_id,
                    base,
                    ..
                } => {
                    messages.push(AgentMessage::BranchSummary(BranchSummaryMessage {
                        summary: summary.clone(),
                        from_id: from_id.clone(),
                        timestamp: chrono::DateTime::parse_from_rfc3339(&base.timestamp)
                            .map(|t| t.timestamp_millis())
                            .unwrap_or_else(|_| kiss_ai::now_ms()),
                    }));
                }
                SessionEntry::CustomMessage {
                    custom_type,
                    content,
                    display,
                    details,
                    base,
                    ..
                } => {
                    messages.push(AgentMessage::Custom(CustomMessage {
                        custom_type: custom_type.clone(),
                        content: content.clone(),
                        display: *display,
                        details: details.clone(),
                        timestamp: chrono::DateTime::parse_from_rfc3339(&base.timestamp)
                            .map(|t| t.timestamp_millis())
                            .unwrap_or_else(|_| kiss_ai::now_ms()),
                    }));
                }
                _ => {}
            }
        }
        SessionContext {
            messages,
            model,
            thinking_level: thinking,
        }
    }

    /// Restore provider-native OpenAI history from the latest compaction on
    /// the active branch. Completed turns from another model are excluded.
    pub fn build_openai_compaction_context(
        &self,
        model: &Model,
    ) -> Option<OpenAICompactionContext> {
        let path = self.branch_entries(None);
        let compaction_pos = path
            .iter()
            .rposition(|entry| matches!(entry, SessionEntry::Compaction { .. }))?;
        let SessionEntry::Compaction {
            details: Some(details),
            ..
        } = path[compaction_pos]
        else {
            return None;
        };
        let remote = details.get("remoteCompaction")?.as_object()?;
        if remote.get("version")?.as_u64()? != 2
            || remote.get("provider")?.as_str()? != "openai-responses-compaction"
            || remote.get("modelKey")?.as_str()?
                != kiss_ai::api::openai_compaction::model_key(model)
        {
            return None;
        }
        let replacement_history = remote
            .get("replacementHistory")?
            .as_array()?
            .iter()
            .filter(|item| item.get("type").and_then(Value::as_str).is_some())
            .cloned()
            .collect::<Vec<_>>();
        if replacement_history.is_empty()
            || !replacement_history
                .iter()
                .any(|item| item["type"] == "compaction")
        {
            return None;
        }

        let mut messages = Vec::new();
        let mut pending = Vec::new();
        for entry in &path[compaction_pos + 1..] {
            let Some(message) = context_message_from_entry(entry) else {
                continue;
            };
            match &message {
                AgentMessage::Assistant(assistant) => {
                    if assistant.provider == model.provider && assistant.model == model.id {
                        messages.append(&mut pending);
                        messages.push(message);
                    } else {
                        pending.clear();
                    }
                }
                _ => pending.push(message),
            }
        }
        // Pending messages are the current unfinished turn. They have not yet
        // received an assistant completion from a possibly different model.
        messages.append(&mut pending);
        Some(OpenAICompactionContext {
            replacement_history,
            messages,
        })
    }

    // ----- info ---------------------------------------------------------

    pub fn header(&self) -> &SessionHeader {
        &self.header
    }

    pub fn session_id(&self) -> &str {
        &self.header.id
    }

    pub fn session_file(&self) -> Option<&Path> {
        self.file.as_deref()
    }

    pub fn cwd(&self) -> &Path {
        &self.cwd
    }

    pub fn session_dir(&self) -> &Path {
        &self.session_dir
    }

    pub fn is_persisted(&self) -> bool {
        self.file.is_some()
    }

    /// Sum every provider operation recorded in this append-only session.
    pub fn usage_totals(&self) -> Usage {
        let mut totals = Usage::default();
        for entry in &self.entries {
            match entry {
                SessionEntry::Message {
                    message: AgentMessage::Assistant(assistant),
                    ..
                } => totals.add(&assistant.usage),
                SessionEntry::Compaction {
                    usage: Some(usage), ..
                }
                | SessionEntry::BranchSummary {
                    usage: Some(usage), ..
                }
                | SessionEntry::Usage { usage, .. } => totals.add(usage),
                _ => {}
            }
        }
        totals
    }

    /// Serialize the full append-only session file format.
    pub fn to_jsonl(&self) -> Result<String> {
        let mut output = serde_json::to_string(&self.header)?;
        output.push('\n');
        for entry in &self.entries {
            output.push_str(&serde_json::to_string(entry)?);
            output.push('\n');
        }
        Ok(output)
    }
}

#[derive(Debug, Clone)]
pub struct SessionContext {
    pub messages: Vec<AgentMessage>,
    pub model: Option<(String, String)>,
    pub thinking_level: Option<ThinkingLevel>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct OpenAICompactionContext {
    pub replacement_history: Vec<Value>,
    pub messages: Vec<AgentMessage>,
}

fn context_message_from_entry(entry: &SessionEntry) -> Option<AgentMessage> {
    match entry {
        SessionEntry::Message { message, .. } => Some(message.clone()),
        SessionEntry::BranchSummary {
            summary,
            from_id,
            base,
            ..
        } => Some(AgentMessage::BranchSummary(BranchSummaryMessage {
            summary: summary.clone(),
            from_id: from_id.clone(),
            timestamp: entry_timestamp(base),
        })),
        SessionEntry::CustomMessage {
            custom_type,
            content,
            display,
            details,
            base,
            ..
        } => Some(AgentMessage::Custom(CustomMessage {
            custom_type: custom_type.clone(),
            content: content.clone(),
            display: *display,
            details: details.clone(),
            timestamp: entry_timestamp(base),
        })),
        _ => None,
    }
}

fn entry_timestamp(base: &EntryBase) -> i64 {
    chrono::DateTime::parse_from_rfc3339(&base.timestamp)
        .map(|time| time.timestamp_millis())
        .unwrap_or_else(|_| kiss_ai::now_ms())
}

#[cfg(test)]
mod tests {
    use super::*;
    use kiss_ai::{AssistantMessage, ContentBlock, ModelCost, StopReason};
    use std::collections::BTreeMap;

    fn manager() -> SessionManager {
        SessionManager::in_memory(Path::new("/tmp/project"))
    }

    fn openai_model() -> Model {
        Model {
            id: "gpt-test".into(),
            name: "GPT test".into(),
            api: "openai-responses".into(),
            provider: "openai".into(),
            base_url: "https://api.openai.com/v1".into(),
            reasoning: true,
            input: vec!["text".into()],
            cost: ModelCost::default(),
            prompt_cache: None,
            context_window: 100_000,
            max_tokens: 1_000,
            compat: None,
            thinking_level_map: BTreeMap::new(),
            headers: BTreeMap::new(),
            sampling_params: Default::default(),
        }
    }

    fn assistant(provider: &str, model: &str, text: &str) -> AgentMessage {
        let mut message = AssistantMessage::empty("openai-responses", provider, model);
        message.content.push(ContentBlock::text(text));
        message.stop_reason = StopReason::Stop;
        AgentMessage::Assistant(message)
    }

    fn remote_details(model: &Model) -> Value {
        kiss_ai::api::openai_compaction::build_remote_compaction_details(
            model,
            &kiss_ai::api::openai_compaction::RemoteCompactionResult {
                replacement_history: vec![
                    serde_json::json!({
                        "type": "message",
                        "role": "user",
                        "content": [{"type": "input_text", "text": "old request"}]
                    }),
                    serde_json::json!({
                        "type": "compaction",
                        "encrypted_content": "opaque"
                    }),
                ],
                usage: None,
            },
        )
    }

    #[test]
    fn linear_appends_build_context() {
        let mut m = manager();
        m.append_message(AgentMessage::user("one")).unwrap();
        m.append_message(AgentMessage::user("two")).unwrap();
        let ctx = m.build_session_context();
        assert_eq!(ctx.messages.len(), 2);
    }

    #[test]
    fn usage_totals_include_saved_provider_operations() {
        let mut manager = manager();
        let mut answer = AssistantMessage::empty("openai-responses", "openai", "gpt-test");
        answer.usage = Usage {
            input: 20,
            cache_read: 80,
            cache_read_available: true,
            ..Default::default()
        };
        manager
            .append_message(AgentMessage::Assistant(answer))
            .unwrap();
        manager
            .append_compaction(
                "summary".into(),
                100,
                Vec::new(),
                Some(Usage {
                    input: 10,
                    ..Default::default()
                }),
                None,
            )
            .unwrap();

        let totals = manager.usage_totals();
        assert_eq!(totals.input, 30);
        assert_eq!(totals.cache_read, 80);
        assert!(totals.cache_read_available);
    }

    #[test]
    fn batched_messages_with_info_persist_as_one_branch() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().join("project");
        let mut m = SessionManager::create(&cwd, Some(dir.path().join("sessions"))).unwrap();
        m.append_messages_with_session_info(
            [AgentMessage::user("one"), assistant("test", "test", "two")],
            "imported",
        )
        .unwrap();

        let reopened = SessionManager::open(m.session_file().unwrap()).unwrap();
        assert_eq!(reopened.entries().len(), 3);
        assert_eq!(reopened.branch_entries(None).len(), 3);
        assert_eq!(reopened.session_name().as_deref(), Some("imported"));
    }

    #[test]
    fn branching_moves_leaf() {
        let mut m = manager();
        let a = m.append_message(AgentMessage::user("a")).unwrap();
        let _b = m.append_message(AgentMessage::user("b")).unwrap();
        m.branch(&a).unwrap();
        let c = m.append_message(AgentMessage::user("c")).unwrap();
        let path: Vec<String> = m
            .branch_entries(None)
            .iter()
            .map(|e| e.id().to_string())
            .collect();
        assert_eq!(path, vec![a, c]);
        assert_eq!(m.children(path.first().map(String::as_str)).len(), 2);
    }

    #[test]
    fn branch_summary_can_move_to_root() {
        let mut m = manager();
        let first = m.append_message(AgentMessage::user("first")).unwrap();
        let second = m.append_message(AgentMessage::user("second")).unwrap();
        let messages = m.branch_messages_after(&second, Some(&first));
        assert!(matches!(
            messages.as_slice(),
            [AgentMessage::User(user)] if user.content.as_text() == "second"
        ));

        let summary = m
            .branch_with_summary(None, &second, "old work".into(), None, None)
            .unwrap();
        assert_eq!(m.leaf_id(), Some(summary.as_str()));
        assert_eq!(m.get_entry(&summary).unwrap().parent_id(), None);
    }

    #[test]
    fn compaction_with_retained_tail_replaces_history() {
        let mut m = manager();
        m.append_message(AgentMessage::user("old1")).unwrap();
        m.append_message(AgentMessage::user("old2")).unwrap();
        m.append_compaction(
            "summary of old".into(),
            5000,
            vec![AgentMessage::user("kept")],
            None,
            None,
        )
        .unwrap();
        m.append_message(AgentMessage::user("new")).unwrap();
        let ctx = m.build_session_context();
        let texts: Vec<String> = ctx
            .messages
            .iter()
            .map(|msg| match msg {
                AgentMessage::User(u) => u.content.as_text(),
                AgentMessage::CompactionSummary(c) => format!("summary:{}", c.summary),
                other => other.role().to_string(),
            })
            .collect();
        assert_eq!(texts, vec!["summary:summary of old", "kept", "new"]);
    }

    #[test]
    fn empty_summary_checkpoint_replays_only_verbatim_history() {
        let mut manager = manager();
        manager
            .append_message(AgentMessage::user("discarded"))
            .unwrap();
        let retained = vec![AgentMessage::user("verbatim")];
        manager
            .append_compaction(String::new(), 100, retained.clone(), None, None)
            .unwrap();

        assert_eq!(manager.build_session_context().messages, retained);
    }

    #[test]
    fn matching_openai_model_restores_remote_history_and_trailing_turns() {
        let model = openai_model();
        let mut manager = manager();
        manager.append_message(AgentMessage::user("old")).unwrap();
        manager
            .append_compaction(
                "portable summary".into(),
                2_000,
                vec![AgentMessage::user("local tail")],
                None,
                Some(remote_details(&model)),
            )
            .unwrap();
        manager
            .append_message(AgentMessage::user("after compaction"))
            .unwrap();
        manager
            .append_message(assistant("openai", "gpt-test", "continued"))
            .unwrap();

        let restored = manager.build_openai_compaction_context(&model).unwrap();
        assert_eq!(restored.replacement_history.len(), 2);
        assert_eq!(restored.replacement_history[1]["type"], "compaction");
        assert_eq!(restored.messages.len(), 2);
        assert!(matches!(
            &restored.messages[0],
            AgentMessage::User(user) if user.content.as_text() == "after compaction"
        ));
    }

    #[test]
    fn remote_history_drops_other_model_turns_but_keeps_current_prompt() {
        let model = openai_model();
        let mut manager = manager();
        manager
            .append_compaction(
                "portable summary".into(),
                2_000,
                vec![],
                None,
                Some(remote_details(&model)),
            )
            .unwrap();
        manager
            .append_message(AgentMessage::user("question for Claude"))
            .unwrap();
        manager
            .append_message(assistant("anthropic", "claude-test", "Claude answer"))
            .unwrap();
        manager
            .append_message(AgentMessage::user("back to OpenAI"))
            .unwrap();

        let restored = manager.build_openai_compaction_context(&model).unwrap();
        assert_eq!(restored.messages.len(), 1);
        assert!(matches!(
            &restored.messages[0],
            AgentMessage::User(user) if user.content.as_text() == "back to OpenAI"
        ));

        let mut other_model = model.clone();
        other_model.id = "gpt-other".into();
        assert!(
            manager
                .build_openai_compaction_context(&other_model)
                .is_none()
        );
    }

    #[test]
    fn persist_and_reopen_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().join("proj");
        std::fs::create_dir_all(&cwd).unwrap();
        let mut m = SessionManager::create(&cwd, Some(dir.path().join("sessions"))).unwrap();
        m.append_message(AgentMessage::user("persisted")).unwrap();
        m.append_session_info("my task").unwrap();
        let path = m.session_file().unwrap().to_path_buf();

        let reopened = SessionManager::open(&path).unwrap();
        assert_eq!(reopened.entries().len(), 2);
        assert_eq!(reopened.session_name().as_deref(), Some("my task"));
        let listings = SessionManager::list(&cwd, &dir.path().join("sessions")).unwrap();
        assert_eq!(listings.len(), 1);
        assert_eq!(listings[0].name.as_deref(), Some("my task"));
    }

    #[test]
    fn empty_session_is_lazy_and_header_only_files_are_hidden() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().join("project");
        let sessions = dir.path().join("sessions");
        let mut manager = SessionManager::create(&cwd, Some(sessions.clone())).unwrap();
        let path = manager.session_file().unwrap().to_path_buf();
        assert!(!path.exists());

        let legacy = path.with_file_name("legacy.jsonl");
        std::fs::create_dir_all(legacy.parent().unwrap()).unwrap();
        std::fs::write(
            &legacy,
            format!("{}\n", serde_json::to_string(manager.header()).unwrap()),
        )
        .unwrap();
        assert!(SessionManager::list(&cwd, &sessions).unwrap().is_empty());

        manager
            .append_message(AgentMessage::user("first message"))
            .unwrap();
        assert!(path.exists());
        assert_eq!(SessionManager::list(&cwd, &sessions).unwrap().len(), 1);
    }

    #[test]
    fn child_session_records_its_parent() {
        let parent = manager();
        let child = parent.create_child().unwrap();
        assert_eq!(
            child.header().parent_session.as_deref(),
            Some(format!("session:{}", parent.session_id()).as_str())
        );

        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().join("project");
        std::fs::create_dir_all(&cwd).unwrap();
        let parent = SessionManager::create(&cwd, Some(dir.path().join("sessions"))).unwrap();
        let parent_file = parent.session_file().unwrap().display().to_string();
        let mut child = parent.create_child().unwrap();
        assert!(!child.session_file().unwrap().exists());
        child
            .append_message(AgentMessage::user("child work"))
            .unwrap();
        let reopened = SessionManager::open(child.session_file().unwrap()).unwrap();
        assert_eq!(
            reopened.header().parent_session.as_deref(),
            Some(parent_file.as_str())
        );
    }

    #[test]
    fn model_and_thinking_tracked() {
        let mut m = manager();
        m.append_model_change("anthropic", "claude-sonnet-4-5")
            .unwrap();
        m.append_thinking_level_change(ThinkingLevel::High).unwrap();
        let ctx = m.build_session_context();
        assert_eq!(
            ctx.model,
            Some(("anthropic".into(), "claude-sonnet-4-5".into()))
        );
        assert_eq!(ctx.thinking_level, Some(ThinkingLevel::High));
        assert!(ctx.messages.is_empty());
    }

    #[test]
    fn active_branch_fork_excludes_selected_user_message_for_editing() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().join("project");
        std::fs::create_dir_all(&cwd).unwrap();
        let mut source = SessionManager::create(&cwd, Some(dir.path().join("sessions"))).unwrap();
        let first = source.append_message(AgentMessage::user("first")).unwrap();
        let selected = source
            .append_message(AgentMessage::user("selected"))
            .unwrap();
        source
            .append_message(AgentMessage::user("abandoned"))
            .unwrap();

        let fork = source.fork_active_branch(Some(&selected), false).unwrap();
        assert_eq!(fork.leaf_id(), Some(first.as_str()));
        assert_eq!(fork.entries().len(), 1);
        assert_ne!(fork.session_id(), source.session_id());
        assert_eq!(
            fork.header().parent_session.as_deref(),
            source
                .session_file()
                .map(|path| path.to_string_lossy())
                .as_deref()
        );
    }

    #[test]
    fn jsonl_serialization_reopens() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("session.jsonl");
        let mut source = manager();
        source
            .append_message(AgentMessage::user("portable"))
            .unwrap();
        std::fs::write(&target, source.to_jsonl().unwrap()).unwrap();
        let reopened = SessionManager::open(&target).unwrap();
        assert_eq!(reopened.entries().len(), 1);
    }

    #[test]
    fn in_memory_session_restores_external_entries() {
        let mut original = SessionManager::in_memory(Path::new("/work"));
        original
            .append_message(AgentMessage::user("restored"))
            .unwrap();
        let restored =
            SessionManager::in_memory_with_entries(Path::new("/work"), original.entries().to_vec());
        assert_eq!(
            restored.build_session_context().messages,
            original.build_session_context().messages
        );
        assert_eq!(restored.leaf_id(), original.leaf_id());
        assert!(!restored.is_persisted());
    }

    #[test]
    fn open_repairs_missing_final_newline_before_append() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().join("project");
        std::fs::create_dir_all(&cwd).unwrap();
        let mut source = SessionManager::create(&cwd, Some(dir.path().join("sessions"))).unwrap();
        source
            .append_message(AgentMessage::user("before repair"))
            .unwrap();
        let path = source.session_file().unwrap().to_path_buf();
        drop(source);

        let mut text = std::fs::read_to_string(&path).unwrap();
        assert_eq!(text.pop(), Some('\n'));
        std::fs::write(&path, text).unwrap();

        let mut reopened = SessionManager::open(&path).unwrap();
        reopened
            .append_message(AgentMessage::user("after repair"))
            .unwrap();
        drop(reopened);

        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.ends_with('\n'));
        assert_eq!(text.lines().count(), 3);
        for line in text.lines() {
            let _: Value = serde_json::from_str(line).unwrap();
        }
        assert_eq!(SessionManager::open(&path).unwrap().entries().len(), 2);
    }

    #[test]
    fn sibling_of_in_memory_session_stays_in_memory() {
        let source = manager();
        let sibling = source.create_sibling().unwrap();
        assert!(!sibling.is_persisted());
    }

    #[test]
    #[ignore = "release-mode performance benchmark"]
    fn benchmark_performance_session_append() {
        let dir = tempfile::tempdir().unwrap();
        let cwd = dir.path().join("project");
        std::fs::create_dir_all(&cwd).unwrap();
        let session_dir = dir.path().join("sessions");
        kiss_bench::measure(
            "session_append_500",
            11,
            1,
            "500_persisted_user_messages",
            || {
                let mut manager = SessionManager::create(&cwd, Some(session_dir.clone())).unwrap();
                for index in 0..500 {
                    manager
                        .append_message(AgentMessage::user(format!(
                            "message {index}: deterministic session append benchmark"
                        )))
                        .unwrap();
                }
                manager.entries().len()
            },
        );
    }
}