synaps-core 0.10.2

Foundation types, config, session, auth, protocol — leaf crate for agent-runtime
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
use crate::core::stream_types::SharedMessage;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
    pub id: String,
    pub title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub model: String,
    pub thinking_level: String,
    pub system_prompt: Option<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub total_input_tokens: u64,
    pub total_output_tokens: u64,
    pub session_cost: f64,
    /// Prompt-cache keep-warm spend (task #444), already INCLUDED in
    /// `session_cost`; persisted so a resumed/reloaded session still labels
    /// it. Absent (0) on sessions that never kept warm.
    ///
    /// SNAPSHOT-ONLY: never journaled. The v2 journal's `SessionMeta` is
    /// `deny_unknown_fields`, so a new field there would make an older build
    /// (0.10.1) treat every meta record as a torn tail and truncate the
    /// session; the `.json` snapshot tolerates unknown fields. In journal
    /// mode the label is therefore as of the last snapshot (slightly stale
    /// until the next one); load clamps it to `session_cost`.
    #[serde(default, skip_serializing_if = "is_zero_cost")]
    pub keepwarm_cost: f64,
    /// Keep-warm ping tokens, already INCLUDED in the token totals.
    /// SNAPSHOT-ONLY, like `keepwarm_cost`; clamped on load to the totals
    /// that survive a reload.
    #[serde(default, skip_serializing_if = "KeepwarmTokens::is_zero")]
    pub keepwarm_tokens: KeepwarmTokens,
    /// Persisted listing hint: `api_messages.len()` at save time. Declared
    /// BEFORE `api_messages` so it lands in the header that
    /// `read_session_header` reads without touching the message array.
    /// Not authoritative in memory — use `api_messages.len()`; refreshed by
    /// `session_journal::save_session_in_dir`. Legacy files → 0.
    #[serde(default)]
    pub message_count: usize,
    /// ID of the session this was compacted from (backward link).
    /// Declared before `api_messages` so `read_session_header` sees it (F24).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_session: Option<String>,
    /// ID of the session created by compacting this one (forward link).
    /// Declared before `api_messages` so `read_session_header` sees it (F24).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compacted_into: Option<String>,
    /// Session environment snapshot (names+values, secrets stripped).
    /// Declared before `api_messages` so `read_session_header` sees it.
    /// Belt-and-braces: values for secret keys are scrubbed on save even
    /// if a future client forgets to strip.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub env: Option<Vec<(String, String)>>,
    /// Names of env vars stripped as secrets (T5, names only, never values).
    /// Declared before `api_messages` so `read_session_header` sees it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub env_stripped: Vec<String>,
    pub api_messages: Vec<SharedMessage>,
    /// Legacy: the "ABORT CONTEXT" recap older Synaps saved for an
    /// interrupted turn, to prepend to the next user message. Never written
    /// now (an interrupted turn is real history plus a marker,
    /// `agent_engine::engine::interrupt`) and never injected: a session that
    /// still carries one is migrated when it is loaded (recap dropped,
    /// marker appended).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub abort_context: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt_provenance: Option<crate::prompt::PromptProvenance>,
    /// Typed compaction summary provenance (spec §9.3). Present on sessions
    /// produced by (or updated in place by) a compaction transition.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compaction: Option<crate::compaction::CompactionRecord>,
}

/// Lightweight info for listing sessions without loading full message history
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInfo {
    pub id: String,
    pub title: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub model: String,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub session_cost: f64,
    pub message_count: usize,
}

/// Project canonical user content for display/title/compaction, never for inference.
/// Only top-level text and attachment labels are visible; in particular, tool
/// results are NOT user prompts and their nested content is never traversed.
/// The original message (including attachment sources) is left untouched.
pub fn user_content_for_display(content: &serde_json::Value) -> Option<String> {
    if let Some(text) = content.as_str() {
        return Some(text.to_string());
    }
    let parts: Vec<String> = content
        .as_array()?
        .iter()
        .filter_map(|block| match block["type"].as_str() {
            Some("text") => block["text"].as_str().map(str::to_string),
            Some("image") => Some("[attached image]".to_string()),
            Some("document") => {
                // Canonical title is a filename, not document text. Accept the
                // explicit filename spelling too, but never inspect source.
                // Strip path prefixes and terminal/label control characters.
                let name = block["filename"]
                    .as_str()
                    .or_else(|| block["title"].as_str())
                    .unwrap_or("")
                    .rsplit(['/', '\\'])
                    .next()
                    .unwrap_or("");
                let name: String = name
                    .chars()
                    .filter(|c| {
                        !c.is_control()
                            && !matches!(c, '[' | ']' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
                    })
                    .take(120)
                    .collect();
                let name = name.trim();
                Some(if name.is_empty() {
                    "[attached document]".to_string()
                } else {
                    format!("[attached document: {name}]")
                })
            }
            _ => None,
        })
        .filter(|part| !part.is_empty())
        .collect();
    (!parts.is_empty()).then(|| parts.join("\n"))
}

fn is_zero_cost(v: &f64) -> bool {
    *v == 0.0
}

/// Keep-warm token subtotal persisted in the snapshot (see
/// [`Session::keepwarm_tokens`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeepwarmTokens {
    #[serde(default)]
    pub input: u64,
    #[serde(default)]
    pub output: u64,
    #[serde(default)]
    pub cache_read: u64,
    #[serde(default)]
    pub cache_creation: u64,
}

impl KeepwarmTokens {
    pub fn is_zero(&self) -> bool {
        *self == Self::default()
    }
}

impl Session {
    /// The keep-warm labels are a subset of the totals; a journal replay can
    /// leave them (snapshot-only) ahead of totals that were reset since, so
    /// clamp them back under. Never raises anything.
    pub fn clamp_keepwarm_to_totals(&mut self) {
        if !(self.keepwarm_cost.is_finite() && self.keepwarm_cost > 0.0) {
            self.keepwarm_cost = 0.0;
        }
        self.keepwarm_cost = self.keepwarm_cost.min(self.session_cost.max(0.0));
        self.keepwarm_tokens.input = self.keepwarm_tokens.input.min(self.total_input_tokens);
        self.keepwarm_tokens.output = self.keepwarm_tokens.output.min(self.total_output_tokens);
    }
}

impl Session {
    pub fn new(model: &str, thinking_level: &str, system_prompt: Option<&str>) -> Self {
        let now = Utc::now();
        let id = format!(
            "{}-{}",
            now.format("%Y%m%d-%H%M%S"),
            &uuid::Uuid::new_v4().to_string()[..4]
        );
        Session {
            id,
            title: String::new(),
            name: None,
            model: model.to_string(),
            thinking_level: thinking_level.to_string(),
            system_prompt: system_prompt.map(|s| s.to_string()),
            created_at: now,
            updated_at: now,
            total_input_tokens: 0,
            total_output_tokens: 0,
            session_cost: 0.0,
            keepwarm_cost: 0.0,
            keepwarm_tokens: KeepwarmTokens::default(),
            message_count: 0,
            api_messages: Vec::new(),
            abort_context: None,
            parent_session: None,
            compacted_into: None,
            env: None,
            env_stripped: Vec::new(),
            prompt_provenance: None,
            compaction: None,
        }
    }

    /// Create a successor session from a compaction transition (spec §9.3).
    /// The summary enters context through the canonical sanitized rendering
    /// ([`crate::compaction::compaction_context_messages`]); the parent's
    /// system prompt stays TYPED metadata — the successor's `system_prompt`
    /// field and the provenance record — never plain user text.
    pub fn from_compaction_record(
        parent: &Session,
        summary_text: &str,
        record: crate::compaction::CompactionRecord,
    ) -> Self {
        let now = Utc::now();
        let id = format!(
            "{}-{}",
            now.format("%Y%m%d-%H%M%S"),
            &uuid::Uuid::new_v4().to_string()[..4]
        );
        // Transfer session name from parent — the compacted session is the
        // continuation, so the name should follow. Parent's name will be
        // cleared when the caller saves it with compacted_into set.
        let name = parent.name.clone();
        Session {
            id,
            title: format!(
                "↳ {}",
                if parent.title.is_empty() {
                    &parent.id
                } else {
                    &parent.title
                }
            ),
            name,
            model: parent.model.clone(),
            thinking_level: parent.thinking_level.clone(),
            system_prompt: parent.system_prompt.clone(),
            created_at: now,
            updated_at: now,
            total_input_tokens: 0,
            total_output_tokens: 0,
            session_cost: 0.0,
            keepwarm_cost: 0.0,
            keepwarm_tokens: KeepwarmTokens::default(),
            message_count: 0,
            api_messages: crate::compaction::compaction_context_messages(summary_text),
            abort_context: None,
            parent_session: Some(parent.id.clone()),
            compacted_into: None,
            env: parent.env.clone(),
            env_stripped: parent.env_stripped.clone(),
            prompt_provenance: None,
            compaction: Some(record),
        }
    }

    /// Set title from the first user message if not already set
    pub fn auto_title(&mut self) {
        if !self.title.is_empty() {
            return;
        }
        for msg in &self.api_messages {
            if msg["role"].as_str() == Some("user") {
                if let Some(content) = user_content_for_display(&msg["content"]) {
                    self.title = content.chars().take(80).collect();
                    return;
                }
            }
        }
    }

    /// Persist this session under the configured persistence mode
    /// (`session_persistence` config key; default is the unchanged legacy
    /// JSON path — see Task 35 / `crate::core::session_journal`).
    pub async fn save(&self) -> std::io::Result<()> {
        let dir = sessions_dir();
        let mode = crate::config::load_config().session_persistence;
        let session = self.clone(); // messages are Arc-shared — cheap clone
        let guard = crate::core::session_save_order::acquire(&dir, &session.id).await;
        tokio::task::spawn_blocking(move || {
            let _guard = guard;
            crate::core::session_journal::save_session_in_dir(&dir, &session, mode).map(|_| ())
        })
        .await
        .map_err(std::io::Error::other)?
    }

    /// Publish a full context checkpoint and wait for durable persistence.
    /// Captures the destination and configured mode BEFORE spawning blocking
    /// work. Unlike `save`, journal mode always replaces the snapshot here.
    ///
    /// On success the snapshot file AND its containing directory have been
    /// fsynced (also newly created directory ancestry). Snapshot publication
    /// is the logical commit: errors from directory sync or journal cleanup
    /// can occur AFTER it is visible, and do not imply rollback. Callers must
    /// stop inference on ANY error and reload/retry rather than assume the old
    /// head survived. Dropping this future does not cancel blocking I/O.
    ///
    /// Async saves to the same destination/session are ordered in-process,
    /// including blocking writers whose awaiter was dropped. Callers still own
    /// ordering of logical session mutations; this is not a multi-process
    /// transaction. Durable saves fail closed on non-Unix platforms; fsync
    /// guarantees still depend on the underlying filesystem/device.
    pub async fn save_durable(&self) -> std::io::Result<()> {
        let dir = sessions_dir();
        let mode = crate::config::load_config().session_persistence;
        self.save_durable_to(dir, mode).await
    }

    // Explicit inputs also let synthetic tempdir tests exercise the exact
    // blocking dispatch without mutating process-wide config/environment.
    async fn save_durable_to(
        &self,
        dir: PathBuf,
        mode: crate::core::session_journal::SessionPersistence,
    ) -> std::io::Result<()> {
        let session = self.clone();
        let guard = crate::core::session_save_order::acquire(&dir, &session.id).await;
        tokio::task::spawn_blocking(move || {
            let _guard = guard;
            crate::core::session_journal::save_session_durable_in_dir(&dir, &session, mode)
                .map(|_| ())
        })
        .await
        .map_err(std::io::Error::other)?
    }

    /// Resolve an ambiguous head without racing an older detached writer.
    /// Read and durable re-publication share the same save-order guard. A
    /// successful read alone must not clear a failed directory-sync barrier.
    pub async fn recover_durable(id: &str) -> std::io::Result<Self> {
        let dir = sessions_dir();
        let mode = crate::config::load_config().session_persistence;
        let id = id.to_owned();
        let guard = crate::core::session_save_order::acquire(&dir, &id).await;
        tokio::task::spawn_blocking(move || {
            let _guard = guard;
            let session = Self::load_from_dir(&dir, &id)?;
            crate::core::session_journal::save_session_durable_in_dir(&dir, &session, mode)?;
            Ok(session)
        })
        .await
        .map_err(std::io::Error::other)?
    }

    pub fn load(id: &str) -> std::io::Result<Self> {
        Self::load_from_dir(&sessions_dir(), id)
    }

    /// Canonical backward-compatible host load for a caller-selected sessions
    /// directory. Both legacy snapshots and journal-backed sessions resolve
    /// through the same journal overlay implementation.
    pub fn load_from_dir(dir: &std::path::Path, id: &str) -> std::io::Result<Self> {
        crate::core::session_journal::load_session_in_dir(dir, id)
    }

    pub fn info(&self) -> SessionInfo {
        SessionInfo {
            id: self.id.clone(),
            title: self.title.clone(),
            name: self.name.clone(),
            model: self.model.clone(),
            created_at: self.created_at,
            updated_at: self.updated_at,
            session_cost: self.session_cost,
            message_count: self.api_messages.len(),
        }
    }

    /// Assign a name to this session. Validates name, enforces uniqueness
    /// across sessions, and rejects collisions with existing chain names.
    /// Idempotent: re-applying the current name is a no-op.
    pub fn set_name(&mut self, name: &str) -> std::io::Result<()> {
        validate_name(name).map_err(std::io::Error::other)?;
        if self.name.as_deref() == Some(name) {
            return Ok(());
        }
        let sessions = list_sessions()?;
        for s in &sessions {
            if s.name.as_deref() == Some(name) && s.id != self.id {
                return Err(std::io::Error::other(format!(
                    "name '{}' already used by session {}",
                    name, s.id
                )));
            }
        }
        if crate::core::chain::load_chain(name).is_ok() {
            return Err(std::io::Error::other(format!(
                "name '{}' conflicts with an existing chain name",
                name
            )));
        }
        self.name = Some(name.to_string());
        Ok(())
    }

    pub fn clear_name(&mut self) {
        self.name = None;
    }
}

/// Blocking body of [`Session::save`]: create the sessions dir (0700), then
/// write `<id>.json` atomically via `private_fs` (temp file created with mode
/// 0600 — never create-then-chmod — then renamed; symlink targets refused).
#[cfg(test)]
pub(crate) fn save_json_in_dir(
    dir: &std::path::Path,
    id: &str,
    json: &[u8],
) -> std::io::Result<()> {
    // fix2: the SAME strict no-symlink root resolution and handle-relative
    // atomic write as every journal operation (see `session_journal`).
    crate::core::session_journal::write_json_snapshot(dir, id, json)
}

/// Find a session by full or partial ID match
pub fn find_session(partial_id: &str) -> std::io::Result<Session> {
    let dir = sessions_dir();
    if !dir.exists() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "no sessions directory",
        ));
    }

    // fix2: strict handle-relative enumeration for both match phases.
    let entries = crate::core::session_journal::session_dir_entries(&dir)?;

    // Try exact match first
    if entries
        .iter()
        .any(|e| e.name == format!("{partial_id}.json"))
    {
        return Session::load(partial_id);
    }

    // Partial match — find all that contain the partial ID
    let mut matches: Vec<String> = Vec::new();
    for entry in &entries {
        if entry.name.ends_with(".json") {
            let id = entry.name.trim_end_matches(".json");
            if id.contains(partial_id) {
                matches.push(id.to_string());
            }
        }
    }

    match matches.len() {
        0 => Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("no session matching '{}'", partial_id),
        )),
        1 => Session::load(&matches[0]),
        _ => Err(std::io::Error::other(format!(
            "ambiguous: {} sessions match '{}'",
            matches.len(),
            partial_id
        ))),
    }
}

/// Load the most recently updated session
pub fn latest_session() -> std::io::Result<Session> {
    // Find the most-recently-modified session file by FILE mtime — without
    // reading or JSON-parsing any of them. The previous impl called
    // list_sessions(), which read + serde-tokenized EVERY session file to sort
    // by the in-file `updated_at`; with hundreds of multi-MB sessions (221 files
    // / 76MB here) that made `--continue` boot take ~11s. mtime is a free, exact
    // proxy for "the session I was last in", and we then load ONLY that one.
    let dir = sessions_dir();
    if !dir.exists() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "no sessions found",
        ));
    }
    // fix2: strict handle-relative enumeration — a symlinked ancestor
    // refuses instead of being followed.
    let entries = crate::core::session_journal::session_dir_entries(&dir)?;
    let names: std::collections::HashSet<&str> = entries.iter().map(|e| e.name.as_str()).collect();
    let mut newest: Option<(std::time::SystemTime, String)> = None;
    for entry in &entries {
        // A journal append IS a save of its session (Task 35): attribute the
        // journal's mtime to the sibling snapshot so "latest" stays exact
        // when snapshots lag behind appends.
        let id = if let Some(id) = entry.name.strip_suffix(".json") {
            id
        } else if let Some(id) = entry.name.strip_suffix(".journal") {
            if !names.contains(format!("{id}.json").as_str()) {
                continue; // orphan journal — not loadable
            }
            id
        } else {
            continue;
        };
        if let Some(mtime) = entry.mtime {
            if newest.as_ref().map_or(true, |(t, _)| mtime > *t) {
                newest = Some((mtime, id.to_string()));
            }
        }
    }
    let id = newest
        .map(|(_, id)| id)
        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no sessions found"))?;
    Session::load(&id)
}

/// List all sessions, sorted by most recently updated.
///
/// Reads only the metadata HEADER of each session file (see
/// [`read_session_header`]) — never the message history. Used by the session
/// resolvers (by name/id). For the capped `/sessions` display prefer
/// [`list_recent_sessions`], which reads only the N most-recent headers.
pub fn list_sessions() -> std::io::Result<Vec<SessionInfo>> {
    let dir = sessions_dir();
    if !dir.exists() {
        return Ok(Vec::new());
    }
    let mut sessions: Vec<SessionInfo> = Vec::new();
    for entry in crate::core::session_journal::session_dir_entries(&dir)? {
        if entry.name.ends_with(".json") {
            if let Some(info) = parse_session_header(&dir, &entry.name) {
                sessions.push(info);
            }
        }
    }
    sessions.sort_by_key(|b| std::cmp::Reverse(b.updated_at));
    Ok(sessions)
}

/// The `limit` most-recently-modified sessions (by file mtime), most-recent
/// first. Sorts the directory entries by mtime WITHOUT parsing, then reads only
/// the top `limit` headers — so `/sessions` is O(limit) reads instead of
/// O(#sessions). mtime is an exact proxy for `updated_at` (the file is rewritten
/// on every save).
pub fn list_recent_sessions(limit: usize) -> std::io::Result<Vec<SessionInfo>> {
    let dir = sessions_dir();
    if !dir.exists() {
        return Ok(Vec::new());
    }
    // fix2: strict handle-relative enumeration.
    let entries = crate::core::session_journal::session_dir_entries(&dir)?;
    let names: std::collections::HashSet<&str> = entries.iter().map(|e| e.name.as_str()).collect();
    let mut by_snapshot: std::collections::HashMap<String, std::time::SystemTime> =
        std::collections::HashMap::new();
    for entry in &entries {
        // Journal mtimes attribute to their session snapshot (Task 35).
        let id = if let Some(id) = entry.name.strip_suffix(".json") {
            id
        } else if let Some(id) = entry.name.strip_suffix(".journal") {
            if !names.contains(format!("{id}.json").as_str()) {
                continue;
            }
            id
        } else {
            continue;
        };
        if let Some(mtime) = entry.mtime {
            let slot = by_snapshot
                .entry(id.to_string())
                .or_insert(std::time::SystemTime::UNIX_EPOCH);
            if mtime > *slot {
                *slot = mtime;
            }
        }
    }
    let mut files: Vec<(std::time::SystemTime, String)> =
        by_snapshot.into_iter().map(|(id, t)| (t, id)).collect();
    files.sort_by_key(|(t, _)| std::cmp::Reverse(*t));
    files.truncate(limit);
    let mut sessions: Vec<SessionInfo> = Vec::new();
    for (_, id) in files {
        if let Some(info) = parse_session_header(&dir, &format!("{id}.json")) {
            sessions.push(info);
        }
    }
    Ok(sessions)
}

/// Read + parse just the metadata header of one session file into a
/// [`SessionInfo`] (no message history). `message_count` comes from the
/// persisted header field (written at save time); legacy files without it
/// report 0.
fn parse_session_header(dir: &std::path::Path, file_name: &str) -> Option<SessionInfo> {
    #[derive(Deserialize)]
    struct SessionMetadata {
        #[serde(default)]
        _journal_generation: Option<String>,
        id: String,
        #[serde(default)]
        title: String,
        #[serde(default)]
        name: Option<String>,
        model: String,
        created_at: DateTime<Utc>,
        updated_at: DateTime<Utc>,
        #[serde(default)]
        session_cost: f64,
        #[serde(default)]
        message_count: usize,
    }
    let header = read_session_header(dir, file_name)?;
    let meta: SessionMetadata = serde_json::from_str(&header).ok()?;
    let mut info = SessionInfo {
        id: meta.id,
        title: meta.title,
        name: meta.name,
        model: meta.model,
        created_at: meta.created_at,
        updated_at: meta.updated_at,
        session_cost: meta.session_cost,
        message_count: meta.message_count,
    };
    // Journal freshness overlay (Task 35): when an opt-in journal exists,
    // its bounded meta tail is newer than the (possibly lagging) snapshot
    // header. Legacy sessions have no journal — zero extra I/O.
    if let Some(tail) = crate::core::session_journal::journal_meta_tail_for_generation(
        dir,
        &info.id,
        meta._journal_generation.as_deref(),
    ) {
        if tail.updated_at > info.updated_at {
            info.updated_at = tail.updated_at;
            info.session_cost = tail.session_cost;
            if let Some(count) = tail.message_count {
                info.message_count = count;
            }
        }
    }
    Some(info)
}

/// Read just the metadata header of a session file — everything BEFORE the
/// (potentially multi-MB) `"api_messages"` array — and return it as a complete,
/// parseable JSON object string. Reads in bounded chunks and STOPS as soon as
/// the `api_messages` key is found, so it never reads or tokenizes the message
/// history. Falls back to the whole file if the key isn't found (small/new
/// sessions). This is what keeps `list_sessions()` O(#sessions) instead of
/// O(total bytes on disk).
fn read_session_header(dir: &std::path::Path, file_name: &str) -> Option<String> {
    let file = crate::core::session_journal::confined_open(dir, file_name).ok()??;
    read_session_header_from_file(file)
}

/// Shared with generation checks; callers provide an already-confined handle.
pub(crate) fn read_session_header_from_file(mut file: std::fs::File) -> Option<String> {
    use std::io::Read;
    const KEY: &[u8] = b"\"api_messages\"";
    const MAX_HEADER: usize = 256 * 1024; // safety cap if the key is never found

    // fix2: confined strict open — same root resolution as every other
    // session read; a symlinked ancestor or artifact yields None, never
    // foreign bytes.
    let mut buf: Vec<u8> = Vec::with_capacity(64 * 1024);
    let mut chunk = [0u8; 16 * 1024];
    let mut cut: Option<usize> = None;
    while buf.len() <= MAX_HEADER {
        let n = file.read(&mut chunk).ok()?;
        if n == 0 {
            break;
        }
        buf.extend_from_slice(&chunk[..n]);
        if let Some(pos) = buf.windows(KEY.len()).position(|w| w == KEY) {
            cut = Some(pos);
            break;
        }
    }

    let end = cut.unwrap_or(buf.len());
    let trimmed = String::from_utf8_lossy(&buf[..end]);
    let mut s = trimmed.trim_end().to_string();
    if s.ends_with(',') {
        s.pop();
    }
    if !s.ends_with('}') {
        s.push('}');
    }
    Some(s)
}

fn sessions_dir() -> PathBuf {
    crate::config::get_active_config_dir().join("sessions")
}

/// Remove a persisted session file (compaction-transition rollback) AND its
/// journal, when one exists (Task 35) — a session and its journal live and
/// die together. A missing file is not an error — rollback must be idempotent.
pub fn delete_session_file(id: &str) -> std::io::Result<()> {
    crate::core::session_journal::delete_session_files_in_dir(&sessions_dir(), id)
}

/// Validate a session or chain name: [a-z0-9-]{1,40}.
pub fn validate_name(name: &str) -> Result<(), String> {
    if name.is_empty() {
        return Err("name cannot be empty".into());
    }
    if name.len() > 40 {
        return Err(format!("invalid name '{}': must be 40 chars or less", name));
    }
    if !name
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
    {
        return Err(format!(
            "invalid name '{}': allowed characters are lowercase letters, digits, and '-'",
            name
        ));
    }
    Ok(())
}

/// Find a session by its assigned name (not partial ID).
/// Iterates session headers one file at a time and returns on first match,
/// avoiding a full directory scan when the named session appears early.
pub fn find_session_by_name(name: &str) -> std::io::Result<Session> {
    let dir = sessions_dir();
    for entry in crate::core::session_journal::session_dir_entries(&dir)? {
        if !entry.name.ends_with(".json") {
            continue;
        }
        if let Some(info) = parse_session_header(&dir, &entry.name) {
            if info.name.as_deref() == Some(name) {
                return Session::load(&info.id);
            }
        }
    }
    Err(std::io::Error::new(
        std::io::ErrorKind::NotFound,
        format!("no session named '{}'", name),
    ))
}

/// Result of resolving a session that may have been compacted into a successor.
#[derive(Debug)]
pub struct ResolvedSession {
    pub session: Session,
    /// If the originally matched session had `compacted_into` set, this
    /// contains a human-readable notice like
    /// `"<old> was compacted into <new> — continuing there"`.
    pub compaction_notice: Option<String>,
}

/// Maximum number of `compacted_into` hops before we bail (cycle guard).
const MAX_COMPACTION_HOPS: usize = 32;

/// Follow the `compacted_into` chain from `session` to its final successor.
/// Returns the final session and a notice if any hops were taken.
/// Errors on cycles, missing successors, or exceeding the hop limit.
pub fn follow_compaction_chain(session: Session) -> std::io::Result<ResolvedSession> {
    if session.compacted_into.is_none() {
        return Ok(ResolvedSession {
            session,
            compaction_notice: None,
        });
    }

    let original_id = session.id.clone();
    let mut current = session;
    let mut visited = std::collections::HashSet::new();
    visited.insert(current.id.clone());

    while let Some(ref successor_id) = current.compacted_into {
        let succ_id = successor_id.clone();
        if !visited.insert(succ_id.clone()) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "compaction cycle detected: session {} loops back to {}",
                    current.id, succ_id
                ),
            ));
        }
        if visited.len() > MAX_COMPACTION_HOPS {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "compaction chain too long (>{} hops) starting from {}",
                    MAX_COMPACTION_HOPS, original_id
                ),
            ));
        }
        current = Session::load(&succ_id).map_err(|e| {
            std::io::Error::new(
                e.kind(),
                format!(
                    "session {} was compacted into {}, but the successor failed to load: {}",
                    current.id, succ_id, e
                ),
            )
        })?;
    }

    let notice = format!(
        "{} was compacted into {} \u{2014} continuing there",
        original_id, current.id
    );
    tracing::info!("{}", notice);
    Ok(ResolvedSession {
        session: current,
        compaction_notice: Some(notice),
    })
}

/// Read only the `compacted_into` field from a session's header on disk,
/// without loading the full message history.
pub fn read_compacted_into(id: &str) -> std::io::Result<Option<String>> {
    read_compacted_into_in_dir(&sessions_dir(), id)
}

/// Like [`read_compacted_into`] but for a caller-selected sessions directory.
pub fn read_compacted_into_in_dir(dir: &std::path::Path, id: &str) -> std::io::Result<Option<String>> {
    let file_name = format!("{}.json", id);
    let header = read_session_header(dir, &file_name).ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("no session file for '{}'", id),
        )
    })?;
    #[derive(serde::Deserialize)]
    struct Hdr {
        #[serde(default)]
        compacted_into: Option<String>,
    }
    let hdr: Hdr = serde_json::from_str(&header).map_err(|e| {
        std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string())
    })?;
    Ok(hdr.compacted_into)
}

/// Resolve a query string to a Session. Resolution order:
/// 1. Chain name  2. Session name  3. Partial session ID
pub fn resolve_session(query: &str) -> std::io::Result<Session> {
    if let Ok(ptr) = crate::core::chain::load_chain(query) {
        match Session::load(&ptr.head) {
            Ok(s) => {
                tracing::info!("resolved '{}' via chain → session {}", query, ptr.head);
                return Ok(s);
            }
            Err(e) => {
                return Err(std::io::Error::new(
                    e.kind(),
                    format!(
                        "chain '{}' points to session '{}' which failed to load: {} (try /chain unname {})",
                        query, ptr.head, e, query
                    ),
                ));
            }
        }
    }
    if let Ok(s) = find_session_by_name(query) {
        tracing::info!("resolved '{}' via session name → {}", query, s.id);
        return Ok(s);
    }
    find_session(query)
}

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

    /// Minimal typed provenance for constructor tests.
    fn test_record(parent: &Session) -> crate::compaction::CompactionRecord {
        crate::compaction::CompactionRecord {
            schema_version: crate::compaction::COMPACTION_SUMMARY_SCHEMA_VERSION,
            source_session: parent.id.clone(),
            source_message_count: parent.api_messages.len(),
            source_range_digest: crate::compaction::message_range_digest(&parent.api_messages),
            summary_provider: "anthropic".into(),
            summary_model: "claude-sonnet-4-6".into(),
            created_at: Utc::now(),
            prompt_stack_digest: crate::compaction::prompt_stack_digest(&["test"]),
            included_classes: crate::compaction::ContentClass::ALL.to_vec(),
            excluded_classes: Vec::new(),
            redaction_policy: crate::compaction::RedactionPolicy::TruncationOnly,
            prior_system_prompt: parent.system_prompt.clone(),
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn durable_dispatch_checkpoints_json_and_journal_without_global_config() {
        use crate::core::session_journal::{save_session_in_dir, SessionPersistence};
        for mode in [SessionPersistence::Json, SessionPersistence::Journal] {
            let tmp = tempfile::TempDir::new().unwrap();
            let dir = tmp
                .path()
                .canonicalize()
                .unwrap()
                .join("profile/nested/sessions");
            let mut session = Session::new("m", "medium", None);
            session.api_messages.push(std::sync::Arc::new(
                json!({"role":"user","content":"checkpoint"}),
            ));
            session.save_durable_to(dir.clone(), mode).await.unwrap();
            let loaded = Session::load_from_dir(&dir, &session.id).unwrap();
            assert_eq!(loaded.api_messages, session.api_messages);
            // Force a later checkpoint after a journal-only append; both
            // durable modes must contain the whole candidate in the snapshot.
            session.api_messages.push(std::sync::Arc::new(
                json!({"role":"assistant","content":"old tail"}),
            ));
            save_session_in_dir(&dir, &session, SessionPersistence::Journal).unwrap();
            session.api_messages.truncate(1);
            session.save_durable_to(dir.clone(), mode).await.unwrap();
            assert_eq!(
                Session::load_from_dir(&dir, &session.id)
                    .unwrap()
                    .api_messages,
                session.api_messages
            );
            let snapshot: Session = serde_json::from_slice(
                &std::fs::read(dir.join(format!("{}.json", session.id))).unwrap(),
            )
            .unwrap();
            assert_eq!(snapshot.api_messages, session.api_messages);
            assert_eq!(
                dir.join(format!("{}.journal", session.id)).exists(),
                mode == SessionPersistence::Journal
            );
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn durable_dispatch_returns_io_errors_and_refuses_symlinks() {
        use crate::core::session_journal::SessionPersistence;
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().canonicalize().unwrap();
        let victim = root.join("victim");
        std::fs::write(&victim, b"unchanged").unwrap();
        let dir = root.join("sessions");
        std::fs::create_dir(&dir).unwrap();
        let session = Session::new("m", "medium", None);
        std::os::unix::fs::symlink(&victim, dir.join(format!("{}.json", session.id))).unwrap();
        for mode in [SessionPersistence::Json, SessionPersistence::Journal] {
            assert!(session.save_durable_to(dir.clone(), mode).await.is_err());
        }
        assert_eq!(std::fs::read(&victim).unwrap(), b"unchanged");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn durable_dispatch_reports_post_commit_cleanup_error() {
        use crate::core::session_journal::SessionPersistence;
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().canonicalize().unwrap();
        let mut session = Session::new("m", "medium", None);
        session
            .save_durable_to(dir.clone(), SessionPersistence::Journal)
            .await
            .unwrap();
        session.title = "published candidate".into();
        std::fs::create_dir(dir.join(format!("{}.journal.tmp", session.id))).unwrap();
        assert!(session
            .save_durable_to(dir.clone(), SessionPersistence::Journal)
            .await
            .is_err());
        // The receipt must be an error, even though rename already committed.
        assert_eq!(
            Session::load_from_dir(&dir, &session.id).unwrap().title,
            session.title
        );
    }

    #[test]
    fn test_session_new() {
        let session = Session::new("gpt-4", "brief", Some("test prompt"));

        // Check model and thinking_level are set correctly
        assert_eq!(session.model, "gpt-4");
        assert_eq!(session.thinking_level, "brief");
        assert_eq!(session.system_prompt, Some("test prompt".to_string()));

        // Check ID is non-empty
        assert!(!session.id.is_empty());

        // Check title starts empty
        assert_eq!(session.title, "");

        // Check tokens are 0
        assert_eq!(session.total_input_tokens, 0);
        assert_eq!(session.total_output_tokens, 0);

        // Check cost is 0
        assert_eq!(session.session_cost, 0.0);

        // Check api_messages is empty
        assert!(session.api_messages.is_empty());

        // Test without system prompt
        let session_no_prompt = Session::new("gpt-3.5-turbo", "normal", None);
        assert_eq!(session_no_prompt.model, "gpt-3.5-turbo");
        assert_eq!(session_no_prompt.thinking_level, "normal");
        assert_eq!(session_no_prompt.system_prompt, None);
    }

    #[test]
    fn test_session_auto_title() {
        let mut session = Session::new("gpt-4", "brief", None);

        // Add a user message
        session.api_messages.push(std::sync::Arc::new(json!({
            "role": "user",
            "content": "hello world"
        })));

        // Call auto_title
        session.auto_title();

        // Check title is set to message content
        assert_eq!(session.title, "hello world");

        // Test it doesn't overwrite existing title
        session.title = "existing title".to_string();
        session.auto_title();
        assert_eq!(session.title, "existing title");

        // Test with empty session (no messages)
        let mut empty_session = Session::new("gpt-4", "brief", None);
        empty_session.auto_title();
        assert_eq!(empty_session.title, "");

        // Test with non-user message
        let mut session_no_user = Session::new("gpt-4", "brief", None);
        session_no_user
            .api_messages
            .push(std::sync::Arc::new(json!({
                "role": "assistant",
                "content": "response"
            })));
        session_no_user.auto_title();
        assert_eq!(session_no_user.title, "");

        // Test with long content (should truncate to 80 chars)
        let mut session_long = Session::new("gpt-4", "brief", None);
        let long_content = "a".repeat(100);
        session_long.api_messages.push(std::sync::Arc::new(json!({
            "role": "user",
            "content": long_content
        })));
        session_long.auto_title();
        assert_eq!(session_long.title.len(), 80);
        assert_eq!(session_long.title, "a".repeat(80));
    }

    #[test]
    fn attachment_projection_and_auto_title_never_read_sources_or_tool_results() {
        let content = json!([
            {"type": "text", "text": "Review"},
            {"type": "image", "source": {"type": "base64", "data": "IMAGE_SENTINEL"}},
            {"type": "document", "title": "a.txt",
             "source": {"type": "text", "data": "DOCUMENT_TEXT_SENTINEL"}},
            {"type": "document", "title": "b.pdf",
             "source": {"type": "base64", "data": "PDF_SENTINEL"}},
            {"type": "text", "text": "Then compare"},
            {"type": "tool_result", "tool_use_id": "t1", "content": [
                {"type": "text", "text": "TOOL_TEXT_SENTINEL"},
                {"type": "document", "title": "TOOL_TITLE_SENTINEL",
                 "source": {"type": "text", "data": "NESTED_DOCUMENT_SENTINEL"}}
            ]}
        ]);
        let original = content.clone();
        let projected = user_content_for_display(&content).unwrap();
        assert_eq!(projected, "Review\n[attached image]\n[attached document: a.txt]\n[attached document: b.pdf]\nThen compare");
        assert!(!projected.contains("SENTINEL"));
        assert_eq!(
            content, original,
            "projection must not mutate canonical data"
        );

        let tool_only = json!([content[5].clone()]);
        assert!(user_content_for_display(&tool_only).is_none());
        let mut session = Session::new("m", "low", None);
        session.api_messages.push(std::sync::Arc::new(json!({
            "role": "user", "content": tool_only
        })));
        session.api_messages.push(std::sync::Arc::new(json!({
            "role": "user", "content": content
        })));
        session.auto_title();
        assert_eq!(
            session.title,
            projected.chars().take(80).collect::<String>()
        );
        assert!(!session.title.contains("SENTINEL"));
    }

    #[test]
    fn attachment_only_titles_and_safe_filename_labels() {
        let content = json!([
            {"type": "document", "title": "/private/path/[report]\u{1b}\n.txt",
             "source": {"type": "text", "data": "DO_NOT_DISPLAY"}},
            {"type": "document", "filename": "C:\\private\\note.txt"},
            {"type": "document", "source": {"data": "NO_FILENAME"}}
        ]);
        assert_eq!(
            user_content_for_display(&content).unwrap(),
            "[attached document: report.txt]\n[attached document: note.txt]\n[attached document]"
        );
        for (block, title) in [
            (
                json!({"type": "image", "source": {"data": "IMAGE_SENTINEL"}}),
                "[attached image]",
            ),
            (
                json!({"type": "document", "title": "notes.txt",
                    "source": {"type": "text", "data": "TEXT_SENTINEL"}}),
                "[attached document: notes.txt]",
            ),
        ] {
            let mut session = Session::new("m", "low", None);
            session.api_messages.push(std::sync::Arc::new(json!({
                "role": "user", "content": [block]
            })));
            session.auto_title();
            assert_eq!(session.title, title);
        }
        assert!(user_content_for_display(&json!([])).is_none());
        assert!(
            user_content_for_display(&json!([{"type": "unknown", "text": "hidden"}])).is_none()
        );
        assert_eq!(
            user_content_for_display(&json!("plain text")).as_deref(),
            Some("plain text")
        );
    }

    #[test]
    fn test_session_info() {
        let mut session = Session::new("gpt-4", "brief", Some("system prompt"));

        // Add some messages to test message count
        session.api_messages.push(std::sync::Arc::new(json!({
            "role": "user",
            "content": "test message"
        })));
        session.api_messages.push(std::sync::Arc::new(json!({
            "role": "assistant",
            "content": "test response"
        })));

        session.title = "Test Title".to_string();
        session.session_cost = 0.05;

        let info = session.info();

        assert_eq!(info.id, session.id);
        assert_eq!(info.title, "Test Title");
        assert_eq!(info.model, "gpt-4");
        assert_eq!(info.created_at, session.created_at);
        assert_eq!(info.updated_at, session.updated_at);
        assert_eq!(info.session_cost, 0.05);
        assert_eq!(info.message_count, 2);
    }

    #[test]
    fn test_session_info_struct() {
        let now = Utc::now();

        let session_info = SessionInfo {
            id: "test-id".to_string(),
            title: "Test Title".to_string(),
            name: None,
            model: "gpt-4".to_string(),
            created_at: now,
            updated_at: now,
            session_cost: 1.23,
            message_count: 5,
        };

        // Verify all fields are accessible
        assert_eq!(session_info.id, "test-id");
        assert_eq!(session_info.title, "Test Title");
        assert_eq!(session_info.model, "gpt-4");
        assert_eq!(session_info.created_at, now);
        assert_eq!(session_info.updated_at, now);
        assert_eq!(session_info.session_cost, 1.23);
        assert_eq!(session_info.message_count, 5);
    }

    #[test]
    fn test_session_serialization_round_trip() {
        let mut session = Session::new(
            "gpt-4-turbo",
            "detailed",
            Some("You are a helpful assistant"),
        );
        session.title = "Test Session".to_string();
        session.api_messages.push(std::sync::Arc::new(
            json!({"role": "user", "content": "test"}),
        ));
        session.total_input_tokens = 100;
        session.total_output_tokens = 200;
        session.session_cost = 0.15;

        // Serialize to JSON string
        let json_str = serde_json::to_string(&session).expect("Failed to serialize session");

        // Deserialize back from JSON string
        let deserialized: Session =
            serde_json::from_str(&json_str).expect("Failed to deserialize session");

        // Verify all fields match
        assert_eq!(deserialized.id, session.id);
        assert_eq!(deserialized.title, session.title);
        assert_eq!(deserialized.model, session.model);
        assert_eq!(deserialized.thinking_level, session.thinking_level);
        assert_eq!(deserialized.system_prompt, session.system_prompt);
        assert_eq!(deserialized.created_at, session.created_at);
        assert_eq!(deserialized.updated_at, session.updated_at);
        assert_eq!(deserialized.total_input_tokens, session.total_input_tokens);
        assert_eq!(
            deserialized.total_output_tokens,
            session.total_output_tokens
        );
        assert_eq!(deserialized.session_cost, session.session_cost);
        assert_eq!(deserialized.api_messages.len(), session.api_messages.len());
        assert_eq!(deserialized.api_messages[0], session.api_messages[0]);
    }

    #[test]
    fn codex_ultra_round_trips_and_compaction_preserves_logical_mode() {
        let parent = Session::new("openai-codex/gpt-5.6-sol", "ultra", None);
        let encoded = serde_json::to_string(&parent).expect("serialize Ultra session");
        let persisted: serde_json::Value =
            serde_json::from_str(&encoded).expect("inspect persisted session");
        assert_eq!(persisted["thinking_level"], "ultra");
        let restored: Session = serde_json::from_str(&encoded).expect("restore Ultra session");
        assert_eq!(restored.model, "openai-codex/gpt-5.6-sol");
        assert_eq!(restored.thinking_level, "ultra");

        let compacted =
            Session::from_compaction_record(&restored, "summary", test_record(&restored));
        assert_eq!(compacted.model, restored.model);
        assert_eq!(compacted.thinking_level, "ultra");
        assert_eq!(
            compacted.parent_session.as_deref(),
            Some(restored.id.as_str())
        );
    }

    #[test]
    fn codex_max_round_trips_without_becoming_ultra_or_xhigh() {
        let session = Session::new("openai-codex/gpt-5.6-luna", "max", None);
        let encoded = serde_json::to_string(&session).expect("serialize Max session");
        let restored: Session = serde_json::from_str(&encoded).expect("restore Max session");
        assert_eq!(restored.thinking_level, "max");
        assert_ne!(restored.thinking_level, "ultra");
        assert_ne!(restored.thinking_level, "xhigh");
    }

    #[test]
    fn test_session_serialization_preserves_all_fields() {
        let mut session = Session::new(
            "claude-3-opus",
            "comprehensive",
            Some("Custom system prompt"),
        );
        session.title = "Complex Session".to_string();

        // Add multiple messages
        session.api_messages.push(std::sync::Arc::new(
            json!({"role": "user", "content": "First message"}),
        ));
        session.api_messages.push(std::sync::Arc::new(
            json!({"role": "assistant", "content": "First response"}),
        ));
        session.api_messages.push(std::sync::Arc::new(
            json!({"role": "user", "content": "Second message"}),
        ));

        // Set token counts and cost
        session.total_input_tokens = 1500;
        session.total_output_tokens = 2500;
        session.session_cost = 0.75;

        // Serialize and deserialize
        let json_str = serde_json::to_string(&session).unwrap();
        let restored: Session = serde_json::from_str(&json_str).unwrap();

        // Verify every field is preserved
        assert_eq!(restored.id, session.id);
        assert_eq!(restored.title, "Complex Session");
        assert_eq!(restored.model, "claude-3-opus");
        assert_eq!(restored.thinking_level, "comprehensive");
        assert_eq!(
            restored.system_prompt.as_ref().unwrap(),
            "Custom system prompt"
        );
        assert_eq!(restored.created_at, session.created_at);
        assert_eq!(restored.updated_at, session.updated_at);
        assert_eq!(restored.total_input_tokens, 1500);
        assert_eq!(restored.total_output_tokens, 2500);
        assert_eq!(restored.session_cost, 0.75);
        assert_eq!(restored.api_messages.len(), 3);
        assert_eq!(restored.api_messages[0]["role"], "user");
        assert_eq!(restored.api_messages[0]["content"], "First message");
        assert_eq!(restored.api_messages[1]["role"], "assistant");
        assert_eq!(restored.api_messages[2]["content"], "Second message");
    }

    #[test]
    fn test_session_info_from_session_with_messages() {
        let mut session = Session::new("gpt-3.5-turbo", "normal", None);

        // Add exactly 3 messages
        session.api_messages.push(std::sync::Arc::new(
            json!({"role": "user", "content": "message 1"}),
        ));
        session.api_messages.push(std::sync::Arc::new(
            json!({"role": "assistant", "content": "response 1"}),
        ));
        session.api_messages.push(std::sync::Arc::new(
            json!({"role": "user", "content": "message 2"}),
        ));

        let info = session.info();

        // Verify message count is exactly 3
        assert_eq!(info.message_count, 3);
        assert_eq!(info.id, session.id);
        assert_eq!(info.model, "gpt-3.5-turbo");
    }

    #[test]
    fn test_session_auto_title_truncation() {
        let mut session = Session::new("gpt-4", "brief", None);

        // Create a user message with exactly 200 characters
        let long_content = "a".repeat(200);
        session.api_messages.push(std::sync::Arc::new(json!({
            "role": "user",
            "content": long_content
        })));

        session.auto_title();

        // Verify title is exactly 80 characters
        assert_eq!(session.title.len(), 80);
        assert_eq!(session.title, "a".repeat(80));
    }

    #[test]
    fn test_session_auto_title_skips_non_user_messages() {
        let mut session = Session::new("gpt-4", "brief", None);

        // Push only an assistant message (no user messages)
        session.api_messages.push(std::sync::Arc::new(json!({
            "role": "assistant",
            "content": "This should be ignored for auto title"
        })));

        session.auto_title();

        // Verify title stays empty since there are no user messages
        assert_eq!(session.title, "");

        // Test with system message too
        session.api_messages.push(std::sync::Arc::new(json!({
            "role": "system",
            "content": "System message should also be ignored"
        })));

        session.auto_title();
        assert_eq!(session.title, "");
    }

    #[test]
    fn test_session_new_generates_unique_ids() {
        let session1 = Session::new("gpt-4", "brief", None);
        let session2 = Session::new("gpt-4", "brief", None);

        // Verify IDs are different
        assert_ne!(session1.id, session2.id);
        assert!(!session1.id.is_empty());
        assert!(!session2.id.is_empty());
    }

    #[test]
    fn test_session_new_timestamps() {
        let before = Utc::now();
        let session = Session::new("gpt-4", "brief", None);
        let after = Utc::now();

        // Verify created_at and updated_at are close to now (within 2 seconds)
        let created_diff = (session.created_at - before).num_seconds().abs();
        let updated_diff = (session.updated_at - before).num_seconds().abs();

        assert!(
            created_diff <= 2,
            "created_at should be within 2 seconds of now"
        );
        assert!(
            updated_diff <= 2,
            "updated_at should be within 2 seconds of now"
        );

        // Verify both timestamps are the same for new sessions
        assert_eq!(session.created_at, session.updated_at);

        // Verify timestamps are not in the future
        assert!(session.created_at <= after);
        assert!(session.updated_at <= after);
    }

    #[test]
    fn test_validate_name() {
        assert!(validate_name("work").is_ok());
        assert!(validate_name("my-project-2").is_ok());
        assert!(validate_name("a").is_ok());
        assert!(validate_name(&"a".repeat(40)).is_ok());

        assert!(validate_name("").is_err());
        assert!(validate_name(&"a".repeat(41)).is_err());
        assert!(validate_name("UPPER").is_err());
        assert!(validate_name("has space").is_err());
        assert!(validate_name("under_score").is_err());
        assert!(validate_name("dots.bad").is_err());

        let err = validate_name("Bad").unwrap_err();
        assert!(err.contains("Bad"));
        assert!(err.contains("lowercase") || err.contains("a-z") || err.contains("allowed"));
    }

    #[test]
    fn test_clear_name() {
        let mut s = Session::new("m", "brief", None);
        s.name = Some("foo".into());
        s.clear_name();
        assert_eq!(s.name, None);
    }

    #[test]
    fn ultracode_serialization_and_compaction_roundtrip_is_distinct() {
        let original = Session::new("anthropic/claude-fable-5", "ultracode", None);
        let json = serde_json::to_string(&original).unwrap();
        let restored: Session = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.thinking_level, "ultracode");
        for other in ["ultra", "max", "xhigh"] {
            assert_ne!(restored.thinking_level, other);
        }
        let compacted =
            Session::from_compaction_record(&restored, "summary", test_record(&restored));
        let resumed: Session =
            serde_json::from_str(&serde_json::to_string(&compacted).unwrap()).unwrap();
        assert_eq!(resumed.thinking_level, "ultracode");
        assert_eq!(
            resumed.parent_session.as_deref(),
            Some(original.id.as_str())
        );
    }

    /// Private-mode tests (spec §5.4). Umask isolation: `#[serial(umask)]`
    /// serializes umask-mutating tests crate-wide; `UmaskGuard` restores the
    /// previous mask on drop (panic-safe). These exercise the blocking body
    /// of `Session::save` directly with a temp dir — no env mutation.
    #[cfg(unix)]
    mod private_modes {
        use super::*;
        use crate::core::private_fs::test_support::UmaskGuard;
        use serial_test::serial;
        use std::os::unix::fs::PermissionsExt;

        fn mode_of(path: &std::path::Path) -> u32 {
            std::fs::metadata(path).unwrap().permissions().mode() & 0o777
        }

        #[test]
        #[serial(umask)]
        fn save_creates_0600_session_file_and_0700_dir_under_permissive_umask() {
            let _umask = UmaskGuard::set(0);
            let tmp = tempfile::TempDir::new().unwrap();
            let dir = tmp.path().join("sessions");
            save_json_in_dir(&dir, "sess-1", b"{}").unwrap();
            assert_eq!(mode_of(&dir), 0o700, "sessions dir must be 0700");
            assert_eq!(
                mode_of(&dir.join("sess-1.json")),
                0o600,
                "session file must be 0600"
            );
        }

        #[test]
        fn save_refuses_symlink_target() {
            let tmp = tempfile::TempDir::new().unwrap();
            let dir = tmp.path().join("sessions");
            std::fs::create_dir_all(&dir).unwrap();
            let victim = tmp.path().join("victim.json");
            std::fs::write(&victim, "original").unwrap();
            std::os::unix::fs::symlink(&victim, dir.join("sess-1.json")).unwrap();
            let res = save_json_in_dir(&dir, "sess-1", b"{}");
            assert!(res.is_err(), "save onto a symlink must fail");
            assert_eq!(
                std::fs::read_to_string(&victim).unwrap(),
                "original",
                "no bytes may be written through the planted symlink"
            );
        }
    }

    mod header_message_count {
        use super::*;
        use crate::core::session_journal::{save_session_in_dir, SessionPersistence};
        use std::sync::Arc;

        fn session_with(n: usize) -> Session {
            let mut s = Session::new("claude-sonnet-4-6", "medium", None);
            for i in 0..n {
                let role = if i % 2 == 0 { "user" } else { "assistant" };
                s.api_messages.push(Arc::new(
                    serde_json::json!({"role": role, "content": format!("m{i}")}),
                ));
            }
            s
        }

        /// save → header reader round-trip: the count is persisted in the
        /// header (before `api_messages`), so the truncating reader sees it.
        #[test]
        fn json_save_persists_count_in_header() {
            let tmp = tempfile::TempDir::new().unwrap();
            let dir = tmp.path().join("sessions");
            let s = session_with(7);
            save_session_in_dir(&dir, &s, SessionPersistence::Json).unwrap();
            let header = read_session_header(&dir, &format!("{}.json", s.id)).unwrap();
            assert!(
                !header.contains("\"api_messages\""),
                "header must stop before the message array"
            );
            let info = parse_session_header(&dir, &format!("{}.json", s.id)).unwrap();
            assert_eq!(info.message_count, 7);
        }

        /// Journal mode: appended messages update the count via the meta tail.
        #[test]
        fn journal_append_updates_count() {
            let tmp = tempfile::TempDir::new().unwrap();
            let dir = tmp.path().join("sessions");
            let mut s = session_with(2);
            save_session_in_dir(&dir, &s, SessionPersistence::Journal).unwrap();
            s.api_messages.push(Arc::new(
                serde_json::json!({"role": "user", "content": "more"}),
            ));
            s.updated_at = Utc::now();
            save_session_in_dir(&dir, &s, SessionPersistence::Journal).unwrap();
            let info = parse_session_header(&dir, &format!("{}.json", s.id)).unwrap();
            assert_eq!(info.message_count, 3);
        }

        #[test]
        fn listing_does_not_overlay_stale_generation_metadata() {
            let tmp = tempfile::TempDir::new().unwrap();
            let dir = tmp.path().canonicalize().unwrap().join("sessions");
            let mut s = session_with(2);
            save_session_in_dir(&dir, &s, SessionPersistence::Journal).unwrap();
            s.api_messages
                .push(Arc::new(serde_json::json!({"role":"user","content":"old"})));
            s.session_cost = 999.0;
            s.updated_at += chrono::Duration::hours(1);
            save_session_in_dir(&dir, &s, SessionPersistence::Journal).unwrap();
            let journal_path = dir.join(format!("{}.journal", s.id));
            let stale = std::fs::read(&journal_path).unwrap();
            s.api_messages.truncate(1);
            s.session_cost = 1.0;
            s.updated_at -= chrono::Duration::hours(2);
            save_session_in_dir(&dir, &s, SessionPersistence::Journal).unwrap();
            std::fs::write(journal_path, stale).unwrap();
            let info = parse_session_header(&dir, &format!("{}.json", s.id)).unwrap();
            assert_eq!(info.message_count, 1);
            assert_eq!(info.session_cost, 1.0);
            assert_eq!(info.updated_at, s.updated_at);
        }

        /// Legacy files without the field report 0, never fail to parse.
        #[test]
        fn legacy_header_defaults_to_zero() {
            let tmp = tempfile::TempDir::new().unwrap();
            let dir = tmp.path().join("sessions");
            let s = session_with(3);
            // Strip the field textually to keep declaration order (a
            // `to_value` round-trip would re-sort keys alphabetically).
            let json = serde_json::to_string(&s).unwrap();
            assert!(json.contains("\"message_count\":0,"));
            let legacy = json.replace("\"message_count\":0,", "");
            save_json_in_dir(&dir, &s.id, legacy.as_bytes()).unwrap();
            let info = parse_session_header(&dir, &format!("{}.json", s.id)).unwrap();
            assert_eq!(info.message_count, 0);
        }
    }

    // ─── follow_compaction_chain tests ─────────────────────────────

    use serial_test::serial;

    fn save_test_session(dir: &std::path::Path, session: &Session) {
        crate::core::session_journal::save_session_in_dir(
            dir,
            session,
            crate::core::session_journal::SessionPersistence::default(),
        )
        .unwrap();
    }

    /// Sets `SYNAPS_BASE_DIR` for one test and restores it on drop. `base_dir()`
    /// reads it BEFORE `HOME`, so a value left behind silently redirects every
    /// later config read/write in this test process — which made
    /// `config::tests::write_config_value_*` fail whenever a `follow_chain_*`
    /// test happened to run first (order-dependent CI flake).
    struct BaseDirGuard(Option<String>);

    impl BaseDirGuard {
        fn set(path: &std::path::Path) -> Self {
            let old = std::env::var("SYNAPS_BASE_DIR").ok();
            std::env::set_var("SYNAPS_BASE_DIR", path);
            Self(old)
        }
    }

    impl Drop for BaseDirGuard {
        fn drop(&mut self) {
            match self.0.take() {
                Some(value) => std::env::set_var("SYNAPS_BASE_DIR", value),
                None => std::env::remove_var("SYNAPS_BASE_DIR"),
            }
        }
    }

    #[test]
    #[serial]
    fn follow_chain_no_compaction_is_identity() {
        let dir = tempfile::tempdir().unwrap();
        let _base_dir = BaseDirGuard::set(&dir.path().join(".synaps-cli"));
        std::fs::create_dir_all(dir.path().join(".synaps-cli/sessions")).unwrap();
        let s = Session::new("m", "brief", None);
        save_test_session(&dir.path().join(".synaps-cli/sessions"), &s);
        let resolved = follow_compaction_chain(s.clone()).unwrap();
        assert_eq!(resolved.session.id, s.id);
        assert!(resolved.compaction_notice.is_none());
    }

    #[test]
    #[serial]
    fn follow_chain_of_three() {
        let dir = tempfile::tempdir().unwrap();
        let sessions_dir = dir.path().join(".synaps-cli/sessions");
        let _base_dir = BaseDirGuard::set(&dir.path().join(".synaps-cli"));
        std::fs::create_dir_all(&sessions_dir).unwrap();

        let mut a = Session::new("m", "brief", None);
        a.id = "aaa".into();
        let mut b = Session::new("m", "brief", None);
        b.id = "bbb".into();
        b.parent_session = Some("aaa".into());
        let mut c = Session::new("m", "brief", None);
        c.id = "ccc".into();
        c.parent_session = Some("bbb".into());

        a.compacted_into = Some("bbb".into());
        b.compacted_into = Some("ccc".into());
        // c has no compacted_into — it's the end

        save_test_session(&sessions_dir, &a);
        save_test_session(&sessions_dir, &b);
        save_test_session(&sessions_dir, &c);

        let resolved = follow_compaction_chain(a).unwrap();
        assert_eq!(resolved.session.id, "ccc");
        let notice = resolved.compaction_notice.unwrap();
        assert!(notice.contains("aaa"), "notice mentions original: {notice}");
        assert!(notice.contains("ccc"), "notice mentions final: {notice}");
    }

    #[test]
    #[serial]
    fn follow_chain_cycle_guard() {
        let dir = tempfile::tempdir().unwrap();
        let sessions_dir = dir.path().join(".synaps-cli/sessions");
        let _base_dir = BaseDirGuard::set(&dir.path().join(".synaps-cli"));
        std::fs::create_dir_all(&sessions_dir).unwrap();

        let mut a = Session::new("m", "brief", None);
        a.id = "aaa".into();
        let mut b = Session::new("m", "brief", None);
        b.id = "bbb".into();

        a.compacted_into = Some("bbb".into());
        b.compacted_into = Some("aaa".into()); // cycle!

        save_test_session(&sessions_dir, &a);
        save_test_session(&sessions_dir, &b);

        let err = follow_compaction_chain(a).unwrap_err();
        assert!(
            err.to_string().contains("cycle"),
            "error mentions cycle: {}",
            err
        );
    }

    #[test]
    #[serial]
    fn follow_chain_missing_successor_error() {
        let dir = tempfile::tempdir().unwrap();
        let sessions_dir = dir.path().join(".synaps-cli/sessions");
        let _base_dir = BaseDirGuard::set(&dir.path().join(".synaps-cli"));
        std::fs::create_dir_all(&sessions_dir).unwrap();

        let mut a = Session::new("m", "brief", None);
        a.id = "aaa".into();
        a.compacted_into = Some("nonexistent".into());

        save_test_session(&sessions_dir, &a);

        let err = follow_compaction_chain(a).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("compacted into nonexistent") && msg.contains("failed to load"),
            "error names the missing successor: {msg}"
        );
    }

}