recursive-agent 0.8.3

A Rust coding-agent platform: kernel, tools, multi-agent orchestration, HTTP API, MCP, and TUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
//! Session files for production pause/resume.
//!
//! A `SessionFile` captures enough agent state to resume a run that
//! terminated abnormally (budget exceeded, stuck, transcript limit).
//! It stores the goal, model, provider, a hash of the tool registry,
//! the steps consumed so far, and the full transcript.
//!
//! Sessions are written alongside transcripts when `--session-out` is
//! set and the finish reason is non-success. They live under
//! `<workspace>/.recursive/sessions/` by convention.
//!
//! Split into sub-modules during the Goal 221 module refactor:
//! - `serialize` — `TranscriptEntry`, `entry_to_message`
//! - `lifecycle` — `SessionLock`, `truncate_transcript_to_turn`
//! - `orphan`   — `OrphanToolCall`
//! - `reader`   — `SessionReader`
//! - `writer`   — `SessionWriter`, `SessionPersistenceSink`

pub mod lifecycle;
pub mod orphan;
pub mod reader;
pub mod serialize;
pub mod writer;

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

use crate::llm::ToolSpec;
use crate::message::Message;

// Re-exports from sub-modules (keep the 8 `pub use` in lib.rs working)
pub use lifecycle::{truncate_transcript_to_turn, SessionLock, SessionLockBusy, TruncateStats};
pub use orphan::OrphanToolCall;
pub use reader::SessionReader;
pub use serialize::{entry_to_message, LoadedEntry, TranscriptEntry};
pub use writer::{SessionPersistenceSink, SessionWriter};

/// Current schema version for session files.
/// Increment when the format changes in a breaking way.
const SESSION_SCHEMA_VERSION: u32 = 1;

/// Maximum `schema_version` this build of the binary can interpret.
/// `SessionReader::load_meta` rejects anything strictly greater
/// than this. Bump this constant (and the helper below) when
/// making a non-backward-compatible change to `SessionMeta`.
pub(crate) const SUPPORTED_SESSION_SCHEMA_VERSION: u32 = 1;

// ---------------------------------------------------------------------------
// SessionStatus
// ---------------------------------------------------------------------------

/// Status of a session. Persisted as a lowercase string.
///
/// Backward compatibility has THREE complementary mechanisms, all
/// required for this enum to load files written by every prior build:
///
/// 1. **`#[serde(alias = ...)]` on individual variants** — accepts
///    legacy on-disk strings that map to the same semantic state.
///    For example, `Completed` accepts both `"completed"` (current)
///    and `"success"` (the string the pre-Goal-276 writer emitted).
///    Without these aliases, old session files would silently load
///    as `Active` (the `other` catch-all) instead of `Completed`.
///
/// 2. **`#[serde(other)]` on the last variant (`Active`)** — catches
///    any *unknown* string the build does not recognise (e.g.
///    `"stalled"` written by a future version, or a typo). It MUST
///    stay last; serde requires the catch-all at the end.
///
/// 3. **`#[serde(default)]` on the field in `SessionMeta`** (see
///    below) — handles a *missing* `status` field on disk. Without
///    it, a `.meta.json` written before the field existed would
///    fail to load.
///
/// Aliases handle **known** legacy values and preserve semantics;
/// `#[serde(other)]` handles **unknown** values and degrades safely
/// to `Active`; the field-level `#[serde(default)]` handles a
/// **missing** field. They are distinct and not interchangeable.
///
/// New variants added here must:
/// - Provide aliases for any prior string literals mapping to the
///   same semantic state.
/// - Keep `Active` as the LAST variant (the `#[serde(other)]` arm
///   must remain terminal — moving it earlier is a serde error).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SessionStatus {
    /// Session finished its goal successfully.
    /// Legacy alias: `"success"` (written by `cli/resume.rs` and
    /// `main.rs` before Goal 276).
    #[serde(alias = "success")]
    Completed,
    /// Session ended because of an unrecoverable error
    /// (provider crash, panic, transcript-limit hard stop, etc.).
    /// Legacy alias: `"incomplete"` (written by the pre-Goal-276
    /// finish_status mapping for non-`NoMoreToolCalls` outcomes).
    #[serde(alias = "incomplete")]
    Crashed,
    /// Session was cancelled by a shutdown signal (SIGINT/SIGTERM).
    /// Legacy alias: `"cancelled"` (the string `FinishReason::Cancelled`
    /// emits via its `Display` impl; that string was used in
    /// `cli/session.rs` for the `interrupt` path).
    #[serde(alias = "cancelled")]
    Interrupted,
    /// Session is parked for later resume (e.g. via
    /// `recursive pause <id>`).
    Paused,
    /// Session is the live, currently-running state. Also acts as
    /// the catch-all (`#[serde(other)]`) for unknown on-disk
    /// statuses — see the type-level doc comment above.
    ///
    /// MUST remain the last variant. Adding a new variant after
    /// `Active` is a compile error; reorder first.
    ///
    /// `#[default]` makes this the `Default::default()` value,
    /// which `#[serde(default)]` on the field in `SessionMeta`
    /// relies on when a `.meta.json` file omits the `status`
    /// key.  The `#[serde(other)]` arm above is a separate
    /// catch-all for *unknown* string values — see the
    /// type-level doc comment.
    #[serde(other)]
    #[default]
    Active,
}

impl std::fmt::Display for SessionStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // The lowercase string MUST match what serde produces via
        // `#[serde(rename_all = "lowercase")]`. The test
        // `session_status_display_matches_serde` guards against
        // accidental drift between this hand-written impl and the
        // derived serialization.
        match self {
            Self::Completed => write!(f, "completed"),
            Self::Crashed => write!(f, "crashed"),
            Self::Interrupted => write!(f, "interrupted"),
            Self::Paused => write!(f, "paused"),
            Self::Active => write!(f, "active"),
        }
    }
}

impl SessionStatus {
    /// Map a [`FinishReason`] to the canonical `SessionStatus` written
    /// when the writer is finalised.
    ///
    /// The mapping is EXHAUSTIVE: there is no wildcard arm, so
    /// adding a new variant to `FinishReason` becomes a compile error
    /// in this function rather than silently falling back to
    /// `Crashed`. The compiler is the safety net.
    pub fn for_finish(reason: &crate::agent::FinishReason) -> Self {
        use crate::agent::FinishReason;
        match reason {
            FinishReason::NoMoreToolCalls => Self::Completed,
            FinishReason::BudgetExceeded
            | FinishReason::ProviderStop(_)
            | FinishReason::Stuck { .. }
            | FinishReason::TranscriptLimit { .. }
            | FinishReason::PermissionDenialLimit
            | FinishReason::WallClockExceeded { .. } => Self::Crashed,
            FinishReason::Cancelled => Self::Interrupted,
        }
    }
}

// ---------------------------------------------------------------------------
// SessionFile (legacy JSON session format)
// ---------------------------------------------------------------------------

/// A saved session that can be resumed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionFile {
    pub schema_version: u32,
    /// The original goal string.
    pub goal: String,
    /// Model name (e.g. "gpt-4o-mini").
    pub model: String,
    /// Provider identifier (e.g. "openai").
    pub provider: String,
    /// BLAKE3 hash of the tool registry specs at the time of save.
    /// Used to detect tool changes that would make the session invalid.
    pub tool_registry_hash: String,
    /// Number of steps already consumed.
    pub steps_consumed: usize,
    /// The full transcript so far (system prompt + user goal + all exchanges).
    pub transcript: Vec<Message>,
    /// Resolved provider preset id (e.g. "deepseek") at session creation
    /// time. `None` when the user did not configure a preset — kept
    /// optional for back-compat with pre-preset-config session files.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preset: Option<String>,
}

impl SessionFile {
    /// Create a new session file from the agent's current state.
    pub fn new(
        goal: String,
        model: String,
        provider: String,
        tool_specs: &[ToolSpec],
        steps_consumed: usize,
        transcript: Vec<Message>,
    ) -> Self {
        let tool_registry_hash = hash_tool_specs(tool_specs);
        Self {
            schema_version: SESSION_SCHEMA_VERSION,
            goal,
            model,
            provider,
            tool_registry_hash,
            steps_consumed,
            transcript,
            preset: None,
        }
    }

    /// Write the session to a JSON file at `path`.
    pub fn write_to(&self, path: &Path) -> std::io::Result<()> {
        let json = serde_json::to_string_pretty(self)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        crate::atomic::atomic_write(path, json.as_bytes())
    }

    /// Read a session from a JSON file at `path`.
    pub fn read_from(path: &Path) -> std::io::Result<Self> {
        let bytes = std::fs::read(path)?;
        serde_json::from_slice(&bytes)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
    }

    /// Validate that the tool registry hash matches the current tool specs.
    /// Returns `Ok(())` if they match, or an error describing the mismatch.
    pub fn validate_tool_registry(&self, current_specs: &[ToolSpec]) -> Result<(), String> {
        let current_hash = hash_tool_specs(current_specs);
        if self.tool_registry_hash == current_hash {
            Ok(())
        } else {
            Err(format!(
                "tool registry hash mismatch: session has '{}', current is '{}'. \
                 Tools have changed since the session was saved; cannot resume.",
                self.tool_registry_hash, current_hash
            ))
        }
    }

    /// Return the transcript messages.
    pub fn messages(&self) -> &[Message] {
        &self.transcript
    }

    /// Consume self and return the transcript.
    pub fn into_transcript(self) -> Vec<Message> {
        self.transcript
    }
}

// ---------------------------------------------------------------------------
// Tool spec hashing
// ---------------------------------------------------------------------------

/// Compute a BLAKE3 hash of the tool registry specs.
///
/// The hash is computed over a deterministic JSON representation of the
/// specs, sorted by tool name. This ensures that the same set of tools
/// always produces the same hash, regardless of registration order.
///
/// Used by both [`SessionFile`] (legacy `.json` resume) and the
/// JSONL session meta's `tool_registry_hash` field (g151) so that
/// `recursive resume` can refuse to load a session whose tool
/// inventory has drifted.
pub fn hash_tool_specs(specs: &[ToolSpec]) -> String {
    use std::collections::BTreeMap;

    let mut map: BTreeMap<String, serde_json::Value> = BTreeMap::new();
    for spec in specs {
        let value = serde_json::json!({
            "description": spec.description,
            "parameters": spec.parameters,
        });
        map.insert(spec.name.clone(), value);
    }
    // BTreeMap<String, serde_json::Value> is always serializable; the error
    // branch is unreachable in practice. If it is somehow reached, log it and
    // return a sentinel that callers can detect and handle explicitly rather
    // than silently comparing equal to every other hash.
    let canonical = serde_json::to_string(&map).unwrap_or_else(|e| {
        tracing::error!(error = %e, "hash_tool_specs: unreachable serialization failure — drift detection may be compromised");
        String::new()
    });
    let hash = blake3::hash(canonical.as_bytes());
    hash.to_hex().to_string()
}

// ---------------------------------------------------------------------------
// Session path utilities
// ---------------------------------------------------------------------------

/// Default session output path for a given workspace.
/// Returns `~/.recursive/workspaces/<ws-hash>/sessions/<timestamp>-<goal-prefix>.json`.
pub fn default_session_path(workspace: &Path, goal: &str) -> PathBuf {
    let ts = filesystem_safe_timestamp();
    // Sanitise the goal prefix for use in a filename
    let prefix: String = goal
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == '_' || *c == '-')
        .take(40)
        .collect();
    let prefix = if prefix.is_empty() {
        "unnamed".to_string()
    } else {
        prefix
    };
    let dir = crate::paths::user_sessions_dir(workspace)
        .unwrap_or_else(|_| workspace.join(".recursive").join("sessions"));
    dir.join(format!("{}-{}.json", ts, prefix))
}

/// List all session files in a workspace's session directory.
pub fn list_sessions(workspace: &Path) -> std::io::Result<Vec<PathBuf>> {
    let dir = match crate::paths::user_sessions_dir(workspace) {
        Ok(d) => d,
        Err(_) => workspace.join(".recursive").join("sessions"),
    };
    if !dir.is_dir() {
        return Ok(Vec::new());
    }
    let mut sessions = Vec::new();
    for entry in std::fs::read_dir(&dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) == Some("json") {
            sessions.push(path);
        }
    }
    sessions.sort();
    Ok(sessions)
}

// ---------------------------------------------------------------------------
// Timestamp utilities
// ---------------------------------------------------------------------------

/// RFC3339 timestamp safe for use in path components on all platforms.
/// Colons in the time portion are replaced with hyphens (Windows forbids `:`).
pub(crate) fn filesystem_safe_timestamp() -> String {
    chrono_lite_now().replace(':', "-")
}

/// RFC3339 UTC timestamp using `chrono`. Format:
/// "YYYY-MM-DDTHH:MM:SSZ".
pub(crate) fn chrono_lite_now() -> String {
    chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string()
}

pub(crate) fn epoch_day_to_ymd(z: i64) -> (i64, u32, u32) {
    let z = z + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
    let y = if m <= 2 { y + 1 } else { y };
    (y, m, d)
}

// ---------------------------------------------------------------------------
// Workspace slug
// ---------------------------------------------------------------------------

/// Convert an absolute workspace path into a filesystem-safe slug.
///
/// - Replaces `/` with `-`
/// - Strips leading `-` (from the root `/`)
/// - Truncates to 80 characters
pub(crate) fn workspace_slug(workspace: &Path) -> String {
    let abs = if workspace.is_absolute() {
        workspace.to_path_buf()
    } else {
        std::env::current_dir().unwrap_or_default().join(workspace)
    };

    // Only keep characters that are valid in a session_id:
    // ASCII alphanumeric, '-', '_', '.'.  Everything else (path
    // separators, Windows drive colons, 8.3 tildes like RUNNER~1,
    // spaces, non-ASCII) becomes '-'.
    let s: String = abs
        .to_string_lossy()
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' || c == '.' {
                c
            } else {
                '-'
            }
        })
        .collect();
    // Strip leading dashes (from root slash / drive letter)
    let s = s.trim_start_matches('-').to_string();
    // Truncate to 80 chars (safe for multibyte)
    if s.len() > 80 {
        crate::truncate_str(&s, 80).to_string()
    } else {
        s
    }
}

// ---------------------------------------------------------------------------
// UsageMeta — per-message token usage
// ---------------------------------------------------------------------------

/// Token usage for one or more LLM API calls, as reported by the provider.
///
/// Used both per-message (`TranscriptEntry.usage`) and as a cumulative
/// session total stored in `SessionMeta.cost` (g156).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct UsageMeta {
    pub input_tokens: u32,
    pub output_tokens: u32,
    /// Prompt-cache creation tokens (Anthropic / OpenAI).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_creation_tokens: Option<u32>,
    /// Prompt-cache read tokens (Anthropic / OpenAI).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_read_tokens: Option<u32>,
    /// Reasoning/thinking tokens (DeepSeek R1, o1, etc.).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reasoning_tokens: Option<u32>,
}

impl UsageMeta {
    /// Accumulate another `UsageMeta` into self.
    pub fn accumulate(&mut self, other: &UsageMeta) {
        self.input_tokens += other.input_tokens;
        self.output_tokens += other.output_tokens;
        self.cache_creation_tokens = Some(
            self.cache_creation_tokens.unwrap_or(0) + other.cache_creation_tokens.unwrap_or(0),
        );
        self.cache_read_tokens =
            Some(self.cache_read_tokens.unwrap_or(0) + other.cache_read_tokens.unwrap_or(0));
        self.reasoning_tokens =
            Some(self.reasoning_tokens.unwrap_or(0) + other.reasoning_tokens.unwrap_or(0));
    }

    /// Convert from `crate::llm::TokenUsage` (g156 integration point).
    pub fn from_token_usage(tu: &crate::llm::TokenUsage) -> Self {
        UsageMeta {
            input_tokens: tu.prompt_tokens,
            output_tokens: tu.completion_tokens,
            cache_creation_tokens: if tu.cache_miss_tokens > 0 {
                Some(tu.cache_miss_tokens)
            } else {
                None
            },
            cache_read_tokens: if tu.cache_hit_tokens > 0 {
                Some(tu.cache_hit_tokens)
            } else {
                None
            },
            // Goal 273: pass through reasoning tokens so they can be
            // summed into SessionCost and priced (treated as output
            // by `ModelPricing::cost_usd`).
            reasoning_tokens: Some(tu.reasoning_tokens),
        }
    }

    /// Returns true if both `input_tokens` and `output_tokens` are zero.
    pub fn is_zero(&self) -> bool {
        self.input_tokens == 0 && self.output_tokens == 0
    }
}

// ---------------------------------------------------------------------------
// SessionCost — cumulative token cost for a session
// ---------------------------------------------------------------------------

/// Cumulative token cost for a session, stored in `.meta.json`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionCost {
    pub total_input_tokens: u64,
    pub total_output_tokens: u64,
    #[serde(default)]
    pub total_cache_creation_tokens: u64,
    #[serde(default)]
    pub total_cache_read_tokens: u64,
    /// Goal 273: reasoning / thinking tokens summed across the
    /// session. Priced at the model's output rate (see
    /// `ModelPricing::cost_usd`).
    #[serde(default)]
    pub total_reasoning_tokens: u64,
}

impl SessionCost {
    pub fn accumulate(&mut self, usage: &UsageMeta) {
        self.total_input_tokens += usage.input_tokens as u64;
        self.total_output_tokens += usage.output_tokens as u64;
        self.total_cache_creation_tokens += usage.cache_creation_tokens.unwrap_or(0) as u64;
        self.total_cache_read_tokens += usage.cache_read_tokens.unwrap_or(0) as u64;
        self.total_reasoning_tokens += usage.reasoning_tokens.unwrap_or(0) as u64;
    }
}

// ---------------------------------------------------------------------------
// SessionMeta
// ---------------------------------------------------------------------------

/// `schema_version` written into a `SessionMeta` whose on-disk
/// representation predates the field. Pre-Goal-269 session files
/// have no `schema_version`; defaulting to 1 (the current value)
/// keeps them loadable.
fn default_schema_version() -> u32 {
    1
}

/// Metadata for a JSONL session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionMeta {
    /// Schema version of the persisted `SessionMeta`. Bumped
    /// whenever a non-backward-compatible field is added (e.g.
    /// dropping a `#[serde(default)]` attribute). The on-disk
    /// format is read by `SessionReader::load_meta`, which checks
    /// this field and refuses to load a session with a
    /// `schema_version` it does not understand.
    ///
    /// Defaults to `1` for pre-Goal-269 session files (the field
    /// was introduced in Goal 269, 2026-06-11).
    #[serde(default = "default_schema_version")]
    pub schema_version: u32,
    pub session_id: String,
    pub goal: String,
    pub model: String,
    pub provider: String,
    pub created_at: String,
    pub updated_at: String,
    pub message_count: u64,
    /// Lifecycle state of the session. Defaults to `Active` for
    /// `.meta.json` files written before Goal 276 (no `status`
    /// key) and degrades to `Active` for unknown string values
    /// (caught by `SessionStatus::Active`'s `#[serde(other)]` arm).
    #[serde(default)]
    pub status: SessionStatus,
    /// BLAKE3 hash of the tool registry specs at session creation
    /// time. Used by `recursive resume` (g151) to refuse loading a
    /// session whose tool inventory has drifted. `None` for
    /// pre-g151 sessions; resume tolerates the absence with a
    /// warning rather than an abort.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_registry_hash: Option<String>,
    /// First user message in this session, truncated to 200 chars (g157).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_prompt: Option<String>,
    /// Most recent user message, truncated to 200 chars (g157).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_prompt: Option<String>,
    /// Cumulative token usage for this session (g156).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cost: Option<SessionCost>,
    /// Resolved provider preset id (e.g. "deepseek") at session creation
    /// time. `None` for pre-preset-config sessions or when the user did
    /// not configure a preset. Optional + skipped on serialize so old
    /// session files round-trip cleanly.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preset: Option<String>,
    /// Optional human-readable display name for this session, set via `--name`.
    /// Shown in the /resume picker and `sessions list` output.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

// ---------------------------------------------------------------------------
// ExportedTranscript
// ---------------------------------------------------------------------------

/// A portable exported transcript for sharing and analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportedTranscript {
    pub version: u32,
    pub session_id: String,
    pub model: String,
    pub goal: String,
    pub created_at: String,
    /// Status at the moment of export. Mirrors `SessionMeta::status`
    /// — the same enum is used in both structs to keep the
    /// wire shape consistent for external SDK consumers.
    pub status: SessionStatus,
    /// Every persisted message in on-disk order, including those that
    /// were folded into a compaction summary (older `messages.len()` of
    /// these were superseded by the corresponding [`Self::compact_boundaries`]
    /// entry at runtime). Consumers that only want the post-compaction
    /// context should filter messages before the last boundary's index.
    pub messages: Vec<TranscriptEntry>,
    /// Cross-turn compaction boundaries, in order. Each records how many
    /// older messages were folded into the summary that follows it.
    /// Empty for sessions that never compacted.
    #[serde(default)]
    pub compact_boundaries: Vec<ExportedCompactBoundary>,
    /// Count of messages in `messages` (excludes boundary markers).
    pub message_count: u64,
}

/// A compaction boundary exported alongside [`ExportedTranscript::messages`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportedCompactBoundary {
    /// Index into `ExportedTranscript::messages` at the position where the
    /// boundary sits (the summary message immediately follows).
    pub message_index: usize,
    pub turn: Option<u32>,
    /// How many older messages were folded into the summary.
    pub removed: usize,
    pub timestamp: String,
}

impl ExportedTranscript {
    /// Build an ExportedTranscript from a session directory.
    pub fn from_session_dir(session_dir: &Path) -> std::io::Result<Self> {
        let meta = SessionReader::load_meta(session_dir)?;
        let loaded = SessionReader::load_full_history(session_dir)?;
        let mut messages: Vec<TranscriptEntry> = Vec::new();
        let mut compact_boundaries: Vec<ExportedCompactBoundary> = Vec::new();
        for entry in loaded {
            match entry {
                LoadedEntry::Message(m) => messages.push(*m),
                LoadedEntry::CompactBoundary { turn, removed } => {
                    // The boundary marker sits between messages; record the
                    // index of the message that would follow it.
                    let timestamp = messages
                        .last()
                        .map(|m| m.timestamp.clone())
                        .unwrap_or_default();
                    compact_boundaries.push(ExportedCompactBoundary {
                        message_index: messages.len(),
                        turn,
                        removed,
                        timestamp,
                    });
                }
            }
        }
        let message_count = messages.len() as u64;
        Ok(Self {
            version: 1,
            session_id: meta.session_id,
            model: meta.model,
            goal: meta.goal,
            created_at: meta.created_at,
            status: meta.status,
            messages,
            compact_boundaries,
            message_count,
        })
    }
}

// ---------------------------------------------------------------------------
// Tests for mod.rs types
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::{Message, Role};

    #[test]
    fn session_round_trip() {
        let goal = "fix the bug".to_string();
        let model = "gpt-4o-mini".to_string();
        let provider = "openai".to_string();
        let tool_specs = vec![
            ToolSpec {
                name: "Read".into(),
                description: "Read a file".into(),
                parameters: serde_json::json!({"type":"object"}),
            },
            ToolSpec {
                name: "Write".into(),
                description: "Write a file".into(),
                parameters: serde_json::json!({"type":"object"}),
            },
        ];
        let transcript = vec![
            Message::system("You are a helpful assistant.".to_string()),
            Message::user("fix the bug".to_string()),
            Message::assistant("Let me look at the code.".to_string()),
        ];

        let session = SessionFile::new(
            goal.clone(),
            model.clone(),
            provider.clone(),
            &tool_specs,
            2,
            transcript.clone(),
        );

        let tmp = tempfile::NamedTempFile::new().unwrap();
        session.write_to(tmp.path()).unwrap();

        let restored = SessionFile::read_from(tmp.path()).unwrap();
        assert_eq!(restored.schema_version, SESSION_SCHEMA_VERSION);
        assert_eq!(restored.goal, goal);
        assert_eq!(restored.model, model);
        assert_eq!(restored.provider, provider);
        assert_eq!(restored.steps_consumed, 2);
        assert_eq!(restored.transcript.len(), 3);
        assert_eq!(
            restored.transcript[0].content,
            "You are a helpful assistant."
        );
        assert_eq!(restored.transcript[1].content, "fix the bug");
        assert_eq!(restored.transcript[2].content, "Let me look at the code.");
    }

    #[test]
    fn resume_validates_tool_registry_hash() {
        let tool_specs = vec![ToolSpec {
            name: "Read".into(),
            description: "Read a file".into(),
            parameters: serde_json::json!({"type":"object"}),
        }];
        let session = SessionFile::new(
            "test".into(),
            "model".into(),
            "provider".into(),
            &tool_specs,
            0,
            vec![],
        );

        // Same specs should validate
        assert!(session.validate_tool_registry(&tool_specs).is_ok());

        // Different specs should fail
        let different_specs = vec![ToolSpec {
            name: "Write".into(),
            description: "Write a file".into(),
            parameters: serde_json::json!({"type":"object"}),
        }];
        assert!(session.validate_tool_registry(&different_specs).is_err());
    }

    #[test]
    #[cfg_attr(target_os = "windows", ignore)]
    fn session_list_finds_files_in_workspace() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();

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

        // Create a session file
        let session = SessionFile::new(
            "test".into(),
            "model".into(),
            "provider".into(),
            &[],
            0,
            vec![],
        );
        let path = default_session_path(ws, "test");
        session.write_to(&path).unwrap();

        let sessions = list_sessions(ws).unwrap();
        assert_eq!(sessions.len(), 1);
        assert_eq!(
            sessions[0].extension().and_then(|e| e.to_str()),
            Some("json")
        );
    }

    #[test]
    fn resume_continues_from_seeded_transcript() {
        let transcript = vec![
            Message::system("sys".to_string()),
            Message::user("original goal".to_string()),
            Message::assistant("partial work".to_string()),
        ];
        let session = SessionFile::new(
            "original goal".into(),
            "model".into(),
            "provider".into(),
            &[],
            1,
            transcript.clone(),
        );

        // The transcript should be preserved exactly
        assert_eq!(session.messages().len(), 3);
        assert_eq!(session.messages()[0].content, "sys");
        assert_eq!(session.messages()[1].content, "original goal");
        assert_eq!(session.messages()[2].content, "partial work");

        // into_transcript should give back the messages
        let restored = session.into_transcript();
        assert_eq!(restored.len(), 3);
    }

    #[test]
    fn round_trip_with_tool_calls() {
        use crate::llm::ToolCall;

        let tool_calls = vec![
            ToolCall {
                id: "call_001".to_string(),
                name: "Read".to_string(),
                arguments: serde_json::json!({"path": "/tmp/foo.rs"}),
            },
            ToolCall {
                id: "call_002".to_string(),
                name: "Write".to_string(),
                arguments: serde_json::json!({"path": "/tmp/bar.rs", "content": "fn main() {}"}),
            },
        ];

        let transcript = vec![
            Message::system("You are an agent.".to_string()),
            Message::user("refactor the code".to_string()),
            Message::assistant_with_tool_calls(
                "I'll read the file first.".to_string(),
                tool_calls.clone(),
            ),
            Message::tool_result("call_001", "fn main() { println!(\"hello\"); }"),
        ];

        let session = SessionFile::new(
            "refactor".into(),
            "gpt-4o".into(),
            "openai".into(),
            &[],
            3,
            transcript,
        );

        let tmp = tempfile::NamedTempFile::new().unwrap();
        session.write_to(tmp.path()).unwrap();

        let restored = SessionFile::read_from(tmp.path()).unwrap();
        assert_eq!(restored.transcript.len(), 4);

        // Verify the assistant message with tool_calls is preserved
        let assistant_msg = &restored.transcript[2];
        assert_eq!(assistant_msg.role, Role::Assistant);
        assert_eq!(assistant_msg.content, "I'll read the file first.");
        assert_eq!(assistant_msg.tool_calls.len(), 2);
        assert_eq!(assistant_msg.tool_calls[0].id, "call_001");
        assert_eq!(assistant_msg.tool_calls[0].name, "Read");
        assert_eq!(
            assistant_msg.tool_calls[0].arguments,
            serde_json::json!({"path": "/tmp/foo.rs"})
        );
        assert_eq!(assistant_msg.tool_calls[1].id, "call_002");
        assert_eq!(assistant_msg.tool_calls[1].name, "Write");
        assert_eq!(
            assistant_msg.tool_calls[1].arguments,
            serde_json::json!({"path": "/tmp/bar.rs", "content": "fn main() {}"})
        );

        // Verify the tool result message
        let tool_msg = &restored.transcript[3];
        assert_eq!(tool_msg.role, Role::Tool);
        assert_eq!(tool_msg.tool_call_id, Some("call_001".to_string()));
        assert_eq!(tool_msg.content, "fn main() { println!(\"hello\"); }");
    }

    #[test]
    fn read_from_nonexistent_file() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let bogus_path = tmp.path().join("does_not_exist.json");

        let result = SessionFile::read_from(&bogus_path);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
    }

    #[test]
    fn read_from_corrupt_json() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(tmp.path(), "this is not valid json {{{garbage").unwrap();

        let result = SessionFile::read_from(tmp.path());
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
    }

    #[test]
    fn validate_tool_registry_mismatch() {
        let original_specs = vec![
            ToolSpec {
                name: "Read".into(),
                description: "Read a file".into(),
                parameters: serde_json::json!({"type":"object"}),
            },
            ToolSpec {
                name: "Write".into(),
                description: "Write a file".into(),
                parameters: serde_json::json!({"type":"object"}),
            },
        ];

        let session = SessionFile::new(
            "test".into(),
            "model".into(),
            "provider".into(),
            &original_specs,
            0,
            vec![],
        );

        // Validate against a completely different set of tools
        let different_specs = vec![ToolSpec {
            name: "execute_command".into(),
            description: "Run a shell command".into(),
            parameters: serde_json::json!({"type":"object","properties":{"cmd":{"type":"string"}}}),
        }];

        let result = session.validate_tool_registry(&different_specs);
        assert!(result.is_err());
        let err_msg = result.unwrap_err();
        assert!(
            err_msg.contains("mismatch"),
            "Expected error to contain 'mismatch', got: {err_msg}"
        );
    }

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

        // Goal with spaces, slashes, unicode, and other special chars
        let goal = "fix bug/issue #42 — with spëcial chars™ 日本語";
        let path = default_session_path(ws, goal);

        // Extract just the filename (without the .json extension)
        let filename = path.file_stem().unwrap().to_str().unwrap();

        // The filename format is "{timestamp}-{sanitized_goal}".
        // The timestamp is filesystem-safe (colons replaced with hyphens).
        // We verify the goal-derived suffix: strip the timestamp prefix
        // (everything up to and including the "Z-" separator).
        let goal_suffix = filename
            .find("Z-")
            .map(|i| &filename[i + 2..])
            .expect("filename should contain Z- separator between timestamp and goal");

        // The goal suffix should contain only alphanumeric (unicode-aware), underscore, or dash
        for ch in goal_suffix.chars() {
            assert!(
                ch.is_alphanumeric() || ch == '_' || ch == '-',
                "Unexpected character '{}' (U+{:04X}) in goal suffix: {}",
                ch,
                ch as u32,
                goal_suffix
            );
        }

        // Spaces, slashes, #, —, ™ should all be stripped
        assert!(!goal_suffix.contains(' '));
        assert!(!goal_suffix.contains('/'));
        assert!(!goal_suffix.contains('#'));
        assert!(!goal_suffix.contains('â„¢'));
        assert!(!goal_suffix.contains('—'));

        // The path should still end inside a sessions/ directory
        // (now lives under the user data dir, not the workspace).
        let parent = path.parent().expect("session path has parent");
        assert_eq!(
            parent.file_name().and_then(|n| n.to_str()),
            Some("sessions"),
            "expected sessions dir as parent, got {}",
            path.display()
        );
        // And should have .json extension
        assert_eq!(path.extension().and_then(|e| e.to_str()), Some("json"));
    }

    /// Kills: `replace || with && at 306:41` and `replace || with && at 306:54`.
    ///
    /// The filter `c.is_alphanumeric() || *c == '_' || *c == '-'` must preserve
    /// ALL three classes of characters.
    ///
    /// - Mutant at 306:41 (`&&` instead of first `||`): reduces to `*c == '-'` only,
    ///   dropping alphanumeric AND underscore characters.  A goal with only letters
    ///   (no `-`) would produce an empty prefix → "unnamed".
    ///
    /// - Mutant at 306:54 (`&&` instead of second `||`): reduces to `c.is_alphanumeric()` only,
    ///   dropping underscore.  A goal with `_` would lose it from the prefix.
    ///
    /// Using "my_feature" exercises both: the alpha chars kill 306:41 and the `_` kills 306:54.
    #[test]
    fn default_session_path_preserves_underscore_and_alphanumeric() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();
        let path = default_session_path(ws, "my_feature");
        let filename = path.file_stem().unwrap().to_str().unwrap();
        let goal_suffix = filename
            .find("Z-")
            .map(|i| &filename[i + 2..])
            .expect("filename should contain Z- separator");
        assert_eq!(
            goal_suffix, "my_feature",
            "goal prefix must preserve both alphanumeric chars and underscores; got: {goal_suffix}"
        );
    }

    #[test]
    fn default_session_path_empty_goal_uses_unnamed() {
        // Kills: `delete !` on `if prefix.is_empty()` in default_session_path.
        // A goal whose characters are ALL filtered out (e.g. only special symbols)
        // must fall back to "unnamed" as the filename prefix.
        // With the `!` deleted, the then-branch would fire when prefix is non-empty
        // and the else-branch when it IS empty → wrong filename.
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();

        // All chars will be filtered: none is alphanumeric, '_', or '-'.
        let goal = "!@#$%^&*()";
        let path = default_session_path(ws, goal);
        let filename = path.file_stem().unwrap().to_str().unwrap();

        // The format is "{timestamp}-unnamed"; extract the suffix after "Z-".
        let goal_suffix = filename
            .find("Z-")
            .map(|i| &filename[i + 2..])
            .expect("filename should contain Z- separator");
        assert_eq!(
            goal_suffix, "unnamed",
            "empty-goal filter must produce 'unnamed'"
        );
    }

    #[test]
    #[cfg_attr(target_os = "windows", ignore)]
    fn list_sessions_ignores_non_json_files() {
        // Kills: `replace == with !=` on the `Some("json")` comparison in list_sessions.
        // When non-.json files are present in the sessions dir, they must NOT appear.
        // With `!=`, json files would be excluded and non-json files included.
        use std::fs;

        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();

        // Create a session to establish the sessions directory
        let session = SessionFile::new("test".into(), "m".into(), "p".into(), &[], 0, vec![]);
        let json_path = default_session_path(ws, "test");
        session.write_to(&json_path).unwrap();

        // Add a non-json file in the same directory
        let sessions_dir = json_path.parent().unwrap();
        fs::write(sessions_dir.join("README.txt"), b"not a session").unwrap();
        fs::write(sessions_dir.join("tmp.bak"), b"backup").unwrap();

        let sessions = list_sessions(ws).unwrap();

        // Must contain exactly the one .json file
        assert_eq!(
            sessions.len(),
            1,
            "non-json files must be excluded; found: {sessions:?}"
        );
        assert_eq!(
            sessions[0].extension().and_then(|e| e.to_str()),
            Some("json"),
        );
    }

    #[test]
    fn filesystem_safe_timestamp_has_no_colons() {
        let ts = filesystem_safe_timestamp();
        assert!(!ts.contains(':'));
        assert!(ts.ends_with('Z'));
    }

    #[test]
    fn workspace_slug_matches_expected() {
        // Absolute path
        let p = Path::new("/home/user/projects/my-app");
        let slug = workspace_slug(p);
        assert!(!slug.starts_with('-'));
        assert!(slug.contains("home-user-projects-my-app"));
        assert!(slug.len() <= 80);

        // Relative path
        let p = Path::new(".");
        let slug = workspace_slug(p);
        assert!(!slug.is_empty());
        assert!(slug.len() <= 80);
    }

    /// Kills: `replace || with && at 394:54`.
    ///
    /// The filter `c.is_ascii_alphanumeric() || c == '_' || c == '.'` must
    /// preserve all three character classes.  Mutant at 394:54 replaces the
    /// second `||` with `&&`, collapsing the condition to `c.is_ascii_alphanumeric()`
    /// only — both `_` and `.` get replaced with `-`.
    #[test]
    fn workspace_slug_preserves_underscore_and_dot() {
        let p = Path::new("/home/user_name/project.ver");
        let slug = workspace_slug(p);
        assert!(
            slug.contains('_'),
            "workspace_slug must preserve underscore; got: {slug}"
        );
        assert!(
            slug.contains('.'),
            "workspace_slug must preserve dot; got: {slug}"
        );
    }

    #[test]
    fn workspace_slug_truncates_to_80_chars() {
        // Kills: `replace > with >=` on `if s.len() > 80` in workspace_slug.
        // With `>=`, a slug of exactly 80 chars would be truncated to 80 (no change) which
        // is fine for >= case, but a slug of exactly 81 must be truncated to 80.
        // Simpler: use a path that produces a slug > 80 chars and verify it's capped.
        let long_component = "a".repeat(100);
        let p = std::path::PathBuf::from(format!("/home/user/{long_component}"));
        let slug = workspace_slug(&p);
        assert!(
            slug.len() <= 80,
            "slug must be capped at 80 chars; got length {}",
            slug.len()
        );
        // Also verify slug starts without a leading dash
        assert!(!slug.starts_with('-'), "slug must not start with dash");
    }

    // ── chrono_lite_now / epoch_day_to_ymd ──────────────────────────────────

    #[test]
    fn epoch_day_to_ymd_unix_epoch() {
        // Day 0 = 1970-01-01
        assert_eq!(epoch_day_to_ymd(0), (1970, 1, 1));
    }

    #[test]
    fn epoch_day_to_ymd_known_dates() {
        // 2024-01-01 = day 19723 since epoch
        assert_eq!(epoch_day_to_ymd(19723), (2024, 1, 1));
        // 2000-02-29 (leap day) = day 11016
        assert_eq!(epoch_day_to_ymd(11016), (2000, 2, 29));
        // 2100-03-01 (2100 is NOT a leap year, so 2100-02-29 doesn't exist)
        // 2100-01-01 = day 47482
        assert_eq!(epoch_day_to_ymd(47482), (2100, 1, 1));
    }

    /// Kills: `replace + with -` and `replace + with *` at line 360:33,
    ///        `replace - with /` at line 360:47.
    ///
    /// Unix day 47541 is 2100-03-01.  At this day `doe = 36524` exactly
    /// (100 * 365.24 days into era 5), which makes `doe/36524 = 1`.
    /// When the `+doe/36524` correction is removed, negated, or replaced
    /// by a multiply, `yoe` drops to 99 and the month formula produces
    /// the non-existent date 2100-02-29 instead of the correct 2100-03-01.
    #[test]
    fn epoch_day_to_ymd_century_correction_at_doe_36524() {
        // 2100-03-01: first day after the "no leap year in 2100" boundary.
        assert_eq!(epoch_day_to_ymd(47541), (2100, 3, 1));
    }

    /// Kills: `replace - with +` and `replace - with /` at line 358:40.
    ///
    /// Unix day -719528 is year 0, January 1 (proleptic Gregorian; year 0 = 1 BC).
    /// The adjusted epoch value is negative, triggering the `else { z - 146_096 }`
    /// branch in the era calculation.  Both mutations compute era = 0 instead of -1,
    /// which causes a u64 overflow in `doe` and produces a completely wrong date.
    #[test]
    fn epoch_day_to_ymd_negative_epoch_day_pre_ce() {
        // Year 0 Jan 1 = Unix day -719528 (proleptic Gregorian year 0 = 1 BC).
        assert_eq!(epoch_day_to_ymd(-719528), (0, 1, 1));
    }

    #[test]
    fn chrono_lite_now_format() {
        let ts = chrono_lite_now();
        // Must match YYYY-MM-DDTHH:MM:SSZ
        assert_eq!(ts.len(), 20, "unexpected length: {ts}");
        assert_eq!(&ts[4..5], "-", "missing first dash: {ts}");
        assert_eq!(&ts[7..8], "-", "missing second dash: {ts}");
        assert_eq!(&ts[10..11], "T", "missing T separator: {ts}");
        assert_eq!(&ts[13..14], ":", "missing first colon: {ts}");
        assert_eq!(&ts[16..17], ":", "missing second colon: {ts}");
        assert_eq!(&ts[19..20], "Z", "missing Z suffix: {ts}");
        // All digit fields must parse as numbers
        let year: u32 = ts[0..4].parse().expect("year");
        let month: u32 = ts[5..7].parse().expect("month");
        let day: u32 = ts[8..10].parse().expect("day");
        let hour: u32 = ts[11..13].parse().expect("hour");
        let min: u32 = ts[14..16].parse().expect("minute");
        let sec: u32 = ts[17..19].parse().expect("second");
        assert!(year >= 2024, "year looks wrong: {year}");
        assert!((1..=12).contains(&month), "month out of range: {month}");
        assert!((1..=31).contains(&day), "day out of range: {day}");
        assert!(hour < 24, "hour out of range: {hour}");
        assert!(min < 60, "minute out of range: {min}");
        assert!(sec < 60, "second out of range: {sec}");
    }

    // ── Goal 276: SessionStatus enum + backward-compatibility surface ─────

    #[test]
    fn session_status_serializes_lowercase() {
        // The lowercase string is part of the wire contract — external
        // SDK consumers parse `status: "completed"` as a known state.
        // A drift here would silently break their pipelines.
        for (variant, expected) in [
            (SessionStatus::Active, "active"),
            (SessionStatus::Completed, "completed"),
            (SessionStatus::Crashed, "crashed"),
            (SessionStatus::Interrupted, "interrupted"),
            (SessionStatus::Paused, "paused"),
        ] {
            let json = serde_json::to_string(&variant).unwrap();
            assert_eq!(json, format!("\"{expected}\""), "mismatch for {variant:?}");
        }
    }

    #[test]
    fn session_status_display_matches_serde() {
        // The hand-written Display impl is what CLI output and format
        // strings see. The derived serde impl is what the on-disk
        // JSON sees. They must agree — if a future contributor adds
        // a variant or renames one, this test catches the drift.
        for variant in [
            SessionStatus::Active,
            SessionStatus::Completed,
            SessionStatus::Crashed,
            SessionStatus::Interrupted,
            SessionStatus::Paused,
        ] {
            let from_display = format!("{variant}");
            let from_serde = serde_json::to_string(&variant)
                .unwrap()
                .trim_matches('"')
                .to_string();
            assert_eq!(
                from_display, from_serde,
                "Display and serde disagree for {variant:?}"
            );
        }
    }

    #[test]
    fn session_status_legacy_aliases_round_trip() {
        // Pre-Goal-276 writer emitted `"success"` for completed runs and
        // `"incomplete"` for everything else; the migrate path also
        // accepts `"cancelled"`. The aliases must read back as the
        // correct modern variant — silent loss of "success" -> "active"
        // would be a corruption bug visible only after a real
        // production write.
        let cases = [
            ("success", SessionStatus::Completed),
            ("incomplete", SessionStatus::Crashed),
            ("cancelled", SessionStatus::Interrupted),
            ("completed", SessionStatus::Completed),
            ("crashed", SessionStatus::Crashed),
            ("interrupted", SessionStatus::Interrupted),
            ("paused", SessionStatus::Paused),
        ];
        for (legacy_str, expected) in cases {
            let parsed: SessionStatus = serde_json::from_str(&format!("\"{legacy_str}\""))
                .unwrap_or_else(|e| panic!("legacy alias {legacy_str:?} did not deserialize: {e}"));
            assert_eq!(parsed, expected, "wrong mapping for {legacy_str:?}");
        }
    }

    #[test]
    fn session_meta_unknown_status_deserializes_to_active() {
        // Old on-disk `.meta.json` files (or files written by a future
        // build) may contain a `status` value this build doesn't
        // recognise — e.g. `"stalled"` from a future hang-detection
        // feature. The `#[serde(other)]` catch-all on `Active` must
        // convert that to `Active` instead of refusing to load the
        // session.
        let json = serde_json::json!({
            "session_id": "future",
            "goal": "future session",
            "model": "gpt-4o-mini",
            "provider": "openai",
            "created_at": "2099-01-01T00:00:00Z",
            "updated_at": "2099-01-01T00:00:00Z",
            "message_count": 0,
            "status": "stalled"
        });
        let restored: SessionMeta = serde_json::from_value(json)
            .expect("unknown status string must not break SessionMeta deserialization");
        assert_eq!(
            restored.status,
            SessionStatus::Active,
            "unknown status should map to Active via #[serde(other)]"
        );
    }

    #[test]
    fn session_meta_missing_status_field_defaults_to_active() {
        // The `#[serde(default)]` on the `status` field covers the case
        // where the key is absent (e.g. a `.meta.json` written before
        // the field existed). This is distinct from the
        // unknown-string case above (which `#[serde(other)]` handles).
        let json = serde_json::json!({
            "session_id": "missing-status",
            "goal": "no status key",
            "model": "gpt-4o-mini",
            "provider": "openai",
            "created_at": "2099-01-01T00:00:00Z",
            "updated_at": "2099-01-01T00:00:00Z",
            "message_count": 0
            // NB: no `status` key
        });
        let restored: SessionMeta = serde_json::from_value(json)
            .expect("missing status field must not break SessionMeta deserialization");
        assert_eq!(
            restored.status,
            SessionStatus::Active,
            "missing status key should default to Active via #[serde(default)]"
        );
    }

    #[test]
    fn session_meta_status_active_round_trip() {
        // Build a SessionMeta with the new status enum, serialize, then
        // deserialize, and confirm the variant is preserved.
        let meta = SessionMeta {
            status: SessionStatus::Active,
            ..meta_for_test(SUPPORTED_SESSION_SCHEMA_VERSION)
        };
        let json = serde_json::to_string(&meta).expect("serialize SessionMeta");
        let restored: SessionMeta = serde_json::from_str(&json).expect("deserialize SessionMeta");
        assert_eq!(restored.status, SessionStatus::Active);
    }

    #[test]
    fn for_finish_maps_exhaustively() {
        // Every `FinishReason` variant must map to a `SessionStatus`.
        // If a new `FinishReason` is added without updating
        // `SessionStatus::for_finish`, the compiler will surface the
        // non-exhaustive match (no `_` arm) — this test just
        // double-checks the currently-known mapping is correct.
        use crate::agent::FinishReason;
        assert_eq!(
            SessionStatus::for_finish(&FinishReason::NoMoreToolCalls),
            SessionStatus::Completed
        );
        assert_eq!(
            SessionStatus::for_finish(&FinishReason::BudgetExceeded),
            SessionStatus::Crashed
        );
        assert_eq!(
            SessionStatus::for_finish(&FinishReason::ProviderStop("rate_limited".into())),
            SessionStatus::Crashed
        );
        assert_eq!(
            SessionStatus::for_finish(&FinishReason::Stuck {
                repeated_call: "Read".into(),
                repeats: 5
            }),
            SessionStatus::Crashed
        );
        assert_eq!(
            SessionStatus::for_finish(&FinishReason::TranscriptLimit {
                chars: 100_000,
                limit: 80_000
            }),
            SessionStatus::Crashed
        );
        assert_eq!(
            SessionStatus::for_finish(&FinishReason::Cancelled),
            SessionStatus::Interrupted
        );
        assert_eq!(
            SessionStatus::for_finish(&FinishReason::PermissionDenialLimit),
            SessionStatus::Crashed
        );
    }

    // -----------------------------------------------------------------------
    // SessionMeta schema_version tests (Goal 269)
    // -----------------------------------------------------------------------

    /// Build a `SessionMeta` with the minimum required fields populated
    /// for tests that care only about the schema-version behaviour.
    /// `schema_version` is intentionally set via the helper, not
    /// hard-coded, so changing the supported version only requires
    /// updating `SUPPORTED_SESSION_SCHEMA_VERSION` in one place.
    fn meta_for_test(schema_version: u32) -> SessionMeta {
        SessionMeta {
            schema_version,
            session_id: "20260611T120000Z-test".into(),
            goal: "schema version test".into(),
            model: "gpt-4o-mini".into(),
            provider: "openai".into(),
            created_at: "2026-06-11T12:00:00Z".into(),
            updated_at: "2026-06-11T12:00:00Z".into(),
            message_count: 0,
            status: SessionStatus::Active,
            tool_registry_hash: None,
            first_prompt: None,
            last_prompt: None,
            cost: None,
            preset: None,
            name: None,
        }
    }

    #[test]
    fn test_session_meta_round_trip() {
        // Goal 269 — the `schema_version` field is preserved across
        // a serialize/deserialize round-trip.
        let original = meta_for_test(SUPPORTED_SESSION_SCHEMA_VERSION);
        let json = serde_json::to_string(&original).expect("serialize SessionMeta");
        let restored: SessionMeta = serde_json::from_str(&json).expect("deserialize SessionMeta");
        assert_eq!(restored.schema_version, SUPPORTED_SESSION_SCHEMA_VERSION);
        assert_eq!(restored.schema_version, 1);
        assert_eq!(restored.session_id, original.session_id);
        assert_eq!(restored.goal, original.goal);
    }

    #[test]
    fn test_session_meta_default_schema_version() {
        // Goal 269 — pre-Goal-269 `.meta.json` files omit
        // `schema_version`. The `#[serde(default)]` attribute must
        // fill in the current value so they remain loadable.
        let legacy_json = serde_json::json!({
            "session_id": "20260610T120000Z-legacy",
            "goal": "legacy session",
            "model": "gpt-4o-mini",
            "provider": "openai",
            "created_at": "2026-06-10T12:00:00Z",
            "updated_at": "2026-06-10T12:00:00Z",
            "message_count": 0,
            "status": "completed"
        });
        // The key assertion: no `schema_version` key, but deserialization
        // still succeeds and the field is populated by the helper.
        assert!(
            legacy_json.get("schema_version").is_none(),
            "test fixture must omit schema_version to exercise the default"
        );
        let restored: SessionMeta =
            serde_json::from_value(legacy_json).expect("deserialize legacy SessionMeta");
        assert_eq!(restored.schema_version, default_schema_version());
        assert_eq!(restored.schema_version, 1);
    }

    #[test]
    fn test_load_rejects_future_schema_version() {
        // Goal 269 — `SessionReader::load_meta` must refuse to load a
        // session whose `schema_version` is newer than this build
        // supports. The error message must surface both the found
        // and the supported values, so the user can tell which build
        // produced the session.
        let tmp = tempfile::tempdir().expect("tempdir");
        let session_dir = tmp.path();
        std::fs::create_dir_all(session_dir).expect("mkdir session dir");
        let future = serde_json::json!({
            "schema_version": 999,
            "session_id": "2099-01-01T00:00:00Z-future",
            "goal": "future session",
            "model": "gpt-4o-mini",
            "provider": "openai",
            "created_at": "2099-01-01T00:00:00Z",
            "updated_at": "2099-01-01T00:00:00Z",
            "message_count": 0,
            "status": "active"
        });
        let meta_path = session_dir.join(".meta.json");
        std::fs::write(
            &meta_path,
            serde_json::to_string_pretty(&future).expect("serialize future meta"),
        )
        .expect("write future .meta.json");

        let err = SessionReader::load_meta(session_dir)
            .expect_err("load_meta must reject future schema_version");
        let msg = err.to_string();
        // The `crate::error::Error::SchemaTooNew` display format we
        // registered must reach the caller, even after the conversion
        // to `std::io::Error::InvalidData`.
        assert!(
            msg.contains("schema_version=999"),
            "error must include found version; got: {msg}"
        );
        assert!(
            msg.contains("supported up to 1"),
            "error must include supported version; got: {msg}"
        );
    }

    /// Goal 273: SessionCost tracks reasoning tokens across accumulate calls.
    #[test]
    fn session_cost_tracks_reasoning_tokens() {
        let mut cost = SessionCost::default();
        let usage_a = UsageMeta {
            reasoning_tokens: Some(1000),
            ..Default::default()
        };
        let usage_b = UsageMeta {
            reasoning_tokens: Some(500),
            ..Default::default()
        };
        cost.accumulate(&usage_a);
        cost.accumulate(&usage_b);
        assert_eq!(cost.total_reasoning_tokens, 1500);
    }

    // -----------------------------------------------------------------------
    // UsageMeta arithmetic tests
    // -----------------------------------------------------------------------

    #[test]
    fn usage_meta_accumulate_adds_tokens() {
        let mut a = UsageMeta {
            input_tokens: 10,
            output_tokens: 20,
            cache_creation_tokens: Some(5),
            cache_read_tokens: Some(3),
            reasoning_tokens: Some(7),
        };
        let b = UsageMeta {
            input_tokens: 1,
            output_tokens: 2,
            cache_creation_tokens: Some(3),
            cache_read_tokens: Some(4),
            reasoning_tokens: Some(5),
        };
        a.accumulate(&b);
        assert_eq!(a.input_tokens, 11, "input_tokens must add");
        assert_eq!(a.output_tokens, 22, "output_tokens must add");
        assert_eq!(a.cache_creation_tokens, Some(8), "cache_creation must add");
        assert_eq!(a.cache_read_tokens, Some(7), "cache_read must add");
        assert_eq!(a.reasoning_tokens, Some(12), "reasoning must add");
    }

    #[test]
    fn usage_meta_accumulate_with_none_treats_as_zero() {
        let mut a = UsageMeta {
            input_tokens: 5,
            output_tokens: 10,
            cache_creation_tokens: None,
            cache_read_tokens: None,
            reasoning_tokens: None,
        };
        let b = UsageMeta {
            input_tokens: 3,
            output_tokens: 4,
            cache_creation_tokens: Some(2),
            cache_read_tokens: Some(1),
            reasoning_tokens: Some(6),
        };
        a.accumulate(&b);
        assert_eq!(a.input_tokens, 8);
        assert_eq!(a.output_tokens, 14);
        assert_eq!(a.cache_creation_tokens, Some(2), "None + Some(2) = Some(2)");
        assert_eq!(a.cache_read_tokens, Some(1), "None + Some(1) = Some(1)");
        assert_eq!(a.reasoning_tokens, Some(6), "None + Some(6) = Some(6)");
    }

    #[test]
    fn usage_meta_from_token_usage_positive_values() {
        use crate::llm::TokenUsage;
        let tu = TokenUsage {
            prompt_tokens: 100,
            completion_tokens: 50,
            total_tokens: 150,
            cache_miss_tokens: 30,
            cache_hit_tokens: 20,
            reasoning_tokens: 10,
        };
        let meta = UsageMeta::from_token_usage(&tu);
        assert_eq!(meta.input_tokens, 100);
        assert_eq!(meta.output_tokens, 50);
        assert_eq!(meta.cache_creation_tokens, Some(30), "positive miss → Some");
        assert_eq!(meta.cache_read_tokens, Some(20), "positive hit → Some");
        assert_eq!(meta.reasoning_tokens, Some(10));
    }

    #[test]
    fn usage_meta_from_token_usage_zero_cache_is_none() {
        use crate::llm::TokenUsage;
        let tu = TokenUsage {
            prompt_tokens: 5,
            completion_tokens: 5,
            total_tokens: 10,
            cache_miss_tokens: 0,
            cache_hit_tokens: 0,
            reasoning_tokens: 0,
        };
        let meta = UsageMeta::from_token_usage(&tu);
        assert_eq!(
            meta.cache_creation_tokens, None,
            "zero cache_miss must produce None"
        );
        assert_eq!(
            meta.cache_read_tokens, None,
            "zero cache_hit must produce None"
        );
    }

    #[test]
    fn usage_meta_is_zero_both_zero() {
        let meta = UsageMeta {
            input_tokens: 0,
            output_tokens: 0,
            ..Default::default()
        };
        assert!(meta.is_zero(), "both zero → is_zero returns true");
    }

    #[test]
    fn usage_meta_is_zero_input_nonzero() {
        let meta = UsageMeta {
            input_tokens: 1,
            output_tokens: 0,
            ..Default::default()
        };
        assert!(!meta.is_zero(), "nonzero input → is_zero returns false");
    }

    #[test]
    fn usage_meta_is_zero_output_nonzero() {
        let meta = UsageMeta {
            input_tokens: 0,
            output_tokens: 1,
            ..Default::default()
        };
        assert!(!meta.is_zero(), "nonzero output → is_zero returns false");
    }

    // -----------------------------------------------------------------------
    // SessionCost accumulate arithmetic tests
    // -----------------------------------------------------------------------

    #[test]
    fn session_cost_accumulate_all_fields() {
        let mut cost = SessionCost::default();
        let usage = UsageMeta {
            input_tokens: 100,
            output_tokens: 50,
            cache_creation_tokens: Some(20),
            cache_read_tokens: Some(10),
            reasoning_tokens: Some(5),
        };
        cost.accumulate(&usage);
        assert_eq!(cost.total_input_tokens, 100, "input must accumulate");
        assert_eq!(cost.total_output_tokens, 50, "output must accumulate");
        assert_eq!(
            cost.total_cache_creation_tokens, 20,
            "cache creation must accumulate"
        );
        assert_eq!(
            cost.total_cache_read_tokens, 10,
            "cache read must accumulate"
        );
        assert_eq!(cost.total_reasoning_tokens, 5, "reasoning must accumulate");
    }

    #[test]
    fn session_cost_accumulate_twice_sums_correctly() {
        let mut cost = SessionCost::default();
        let u1 = UsageMeta {
            input_tokens: 100,
            output_tokens: 50,
            cache_creation_tokens: None,
            cache_read_tokens: None,
            reasoning_tokens: None,
        };
        let u2 = UsageMeta {
            input_tokens: 200,
            output_tokens: 75,
            cache_creation_tokens: None,
            cache_read_tokens: None,
            reasoning_tokens: None,
        };
        cost.accumulate(&u1);
        cost.accumulate(&u2);
        assert_eq!(cost.total_input_tokens, 300, "300 = 100 + 200");
        assert_eq!(cost.total_output_tokens, 125, "125 = 50 + 75");
    }

    // -----------------------------------------------------------------------
    // hash_tool_specs determinism test
    // -----------------------------------------------------------------------

    #[test]
    fn hash_tool_specs_is_deterministic() {
        let specs = vec![
            ToolSpec {
                name: "Read".into(),
                description: "read a file".into(),
                parameters: serde_json::json!({"type": "object"}),
            },
            ToolSpec {
                name: "Write".into(),
                description: "write a file".into(),
                parameters: serde_json::json!({"type": "object"}),
            },
        ];
        let h1 = hash_tool_specs(&specs);
        let h2 = hash_tool_specs(&specs);
        assert_eq!(h1, h2, "same inputs must produce same hash");
        assert!(!h1.is_empty(), "hash must be non-empty");
    }

    #[test]
    fn hash_tool_specs_differs_for_different_specs() {
        let specs_a = vec![ToolSpec {
            name: "Read".into(),
            description: "read".into(),
            parameters: serde_json::json!({}),
        }];
        let specs_b = vec![ToolSpec {
            name: "Write".into(),
            description: "write".into(),
            parameters: serde_json::json!({}),
        }];
        assert_ne!(
            hash_tool_specs(&specs_a),
            hash_tool_specs(&specs_b),
            "different specs must produce different hashes"
        );
    }

    #[test]
    fn default_schema_version_is_one() {
        assert_eq!(
            default_schema_version(),
            1,
            "default schema version must be 1"
        );
    }

    // Goal: session export must include the full history (messages folded
    // by compaction included) plus the compaction boundaries, so consumers
    // see the whole conversation rather than just the post-compaction tail.
    #[test]
    fn export_includes_full_history_and_compact_boundaries() {
        let tmp = crate::test_util::IsolatedWorkspace::new();
        let ws = tmp.path();
        let mut w = SessionWriter::create(ws, "export test", "model", "openai").unwrap();
        let session_dir = w.session_dir().to_path_buf();

        w.append(&Message::user("folded turn".to_string()), None, None)
            .unwrap();
        w.append(&Message::assistant("folded reply".to_string()), None, None)
            .unwrap();
        // Boundary: 2 messages folded.
        w.write_compact_boundary(1, 2, None).unwrap();
        w.append(&Message::system("summary".to_string()), None, None)
            .unwrap();
        w.append(&Message::user("post turn".to_string()), None, None)
            .unwrap();
        w.finish(SessionStatus::Completed).unwrap();

        let exported = ExportedTranscript::from_session_dir(&session_dir).unwrap();
        // All 4 real messages are present (compaction did not strip them).
        assert_eq!(exported.messages.len(), 4);
        assert_eq!(exported.message_count, 4);
        // One boundary recorded, sitting at the index of the summary that
        // follows it (after the 2 folded messages).
        assert_eq!(exported.compact_boundaries.len(), 1);
        let b = &exported.compact_boundaries[0];
        assert_eq!(b.removed, 2);
        assert_eq!(b.turn, Some(1));
        assert_eq!(b.message_index, 2, "boundary precedes the summary message");
    }
}