atm-core 0.2.3

Core domain types for ATM - Claude Code agent management
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
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
//! Session domain entities and value objects.

use crate::lifecycle::{LifecycleEvent, NeedsInputReason, NotificationKind};
use crate::{AgentType, ContextUsage, Model, Money, TokenCount};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::collections::VecDeque;
use std::fmt;
use std::path::{Path, PathBuf};
use tracing::debug;

// ============================================================================
// Type-Safe Identifiers
// ============================================================================

/// Unique identifier for a Claude Code session.
///
/// Wraps a UUID string (e.g., "8e11bfb5-7dc2-432b-9206-928fa5c35731").
/// Obtained from Claude Code's status line JSON `session_id` field.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SessionId(String);

/// Prefix used for pending session IDs (sessions discovered before their real ID is known).
pub const PENDING_SESSION_PREFIX: &str = "pending-";

impl SessionId {
    /// Creates a new SessionId from a string.
    ///
    /// Note: This does not validate UUID format. Claude Code provides
    /// the session_id, so we trust its format.
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Creates a pending session ID from a process ID.
    ///
    /// Used when a Claude process is discovered but no transcript exists yet
    /// (e.g., session just started, no conversation has occurred).
    /// The pending session will be upgraded to the real session ID when
    /// it arrives via hook event or status line.
    pub fn pending_from_pid(pid: u32) -> Self {
        Self(format!("{PENDING_SESSION_PREFIX}{pid}"))
    }

    /// Checks if this is a pending session ID (not yet associated with real session).
    #[must_use]
    pub fn is_pending(&self) -> bool {
        self.0.starts_with(PENDING_SESSION_PREFIX)
    }

    /// Extracts the PID from a pending session ID.
    ///
    /// Returns `None` if this is not a pending session ID or the PID cannot be parsed.
    pub fn pending_pid(&self) -> Option<u32> {
        if !self.is_pending() {
            return None;
        }
        self.0
            .strip_prefix(PENDING_SESSION_PREFIX)
            .and_then(|s| s.parse().ok())
    }

    /// Returns the underlying string reference.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns a shortened display form (first 8 characters).
    ///
    /// Useful for compact TUI display.
    #[must_use]
    pub fn short(&self) -> &str {
        self.0.get(..8).unwrap_or(&self.0)
    }
}

impl fmt::Display for SessionId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for SessionId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for SessionId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

impl AsRef<str> for SessionId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Unique identifier for a tool invocation.
///
/// Format: "toolu_..." (e.g., "toolu_01ABC123XYZ")
/// Provided by Claude Code in hook events.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ToolUseId(String);

impl ToolUseId {
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ToolUseId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<String> for ToolUseId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

/// Path to a session's transcript JSONL file.
///
/// Example: "/home/user/.claude/projects/.../session.jsonl"
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct TranscriptPath(PathBuf);

impl TranscriptPath {
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self(path.into())
    }

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

    /// Returns the filename portion of the path.
    pub fn filename(&self) -> Option<&str> {
        self.0.file_name().and_then(|n| n.to_str())
    }
}

impl fmt::Display for TranscriptPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0.display())
    }
}

impl AsRef<Path> for TranscriptPath {
    fn as_ref(&self) -> &Path {
        &self.0
    }
}

// ============================================================================
// Session Status (3-State Model)
// ============================================================================

/// Current operational status of a session.
///
/// Three fundamental states based on user action requirements:
/// - **Idle**: Nothing happening - Claude finished, waiting for user
/// - **Working**: Claude is actively processing - user just waits
/// - **AttentionNeeded**: User must act for session to proceed
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionStatus {
    /// Session is idle - Claude finished, waiting for user's next action.
    /// User can take their time, no urgency.
    #[default]
    Idle,

    /// Claude is actively processing - user just waits.
    /// Work is happening, no user action needed.
    Working,

    /// User must take action for the session to proceed.
    /// Something is blocked waiting for user input.
    AttentionNeeded,
}

impl SessionStatus {
    /// Returns the display label for this status.
    #[must_use]
    pub fn label(&self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Working => "working",
            Self::AttentionNeeded => "needs input",
        }
    }

    /// Returns the ASCII icon for this status.
    #[must_use]
    pub fn icon(&self) -> &'static str {
        match self {
            Self::Idle => "-",
            Self::Working => ">",
            Self::AttentionNeeded => "!",
        }
    }

    /// Returns true if this status should blink in the UI.
    #[must_use]
    pub fn should_blink(&self) -> bool {
        matches!(self, Self::AttentionNeeded)
    }

    /// Returns true if the session is actively processing.
    #[must_use]
    pub fn is_active(&self) -> bool {
        matches!(self, Self::Working)
    }

    /// Returns true if user action is needed.
    #[must_use]
    pub fn needs_attention(&self) -> bool {
        matches!(self, Self::AttentionNeeded)
    }
}

impl fmt::Display for SessionStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Idle => write!(f, "Idle"),
            Self::Working => write!(f, "Working"),
            Self::AttentionNeeded => write!(f, "Needs Input"),
        }
    }
}

// ============================================================================
// Activity Detail
// ============================================================================

/// Detailed information about current session activity.
///
/// Provides structured details alongside the simple SessionStatus enum.
/// This separates "what state are we in" from "what specifically is happening".
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActivityDetail {
    /// Tool name if running/waiting on a tool
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_name: Option<String>,
    /// When the current activity started
    pub started_at: DateTime<Utc>,
    /// Additional context (e.g., "Compacting", "Setup", "Thinking")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<String>,
}

impl ActivityDetail {
    /// Creates a new ActivityDetail for a tool operation.
    pub fn new(tool_name: &str) -> Self {
        Self {
            tool_name: Some(tool_name.to_string()),
            started_at: Utc::now(),
            context: None,
        }
    }

    /// Creates an ActivityDetail with context but no specific tool.
    pub fn with_context(context: &str) -> Self {
        Self {
            tool_name: None,
            started_at: Utc::now(),
            context: Some(context.to_string()),
        }
    }

    /// Creates an ActivityDetail for "thinking" state.
    pub fn thinking() -> Self {
        Self::with_context("Thinking")
    }

    /// Returns how long this activity has been running.
    pub fn duration(&self) -> chrono::Duration {
        Utc::now().signed_duration_since(self.started_at)
    }

    /// Returns a display string for this activity.
    ///
    /// Returns a `Cow<str>` for zero-copy access when possible.
    #[must_use]
    pub fn display(&self) -> Cow<'_, str> {
        if let Some(ref tool) = self.tool_name {
            Cow::Borrowed(tool)
        } else if let Some(ref ctx) = self.context {
            Cow::Borrowed(ctx)
        } else {
            Cow::Borrowed("Unknown")
        }
    }
}

impl Default for ActivityDetail {
    fn default() -> Self {
        Self::thinking()
    }
}

// ============================================================================
// Value Objects
// ============================================================================

/// Duration tracking for a session.
///
/// Based on Claude Code status line `cost.total_duration_ms`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct SessionDuration {
    /// Total duration in milliseconds
    total_ms: u64,
    /// API call duration in milliseconds (time spent waiting for Claude)
    api_ms: u64,
}

impl SessionDuration {
    /// Creates a new SessionDuration.
    pub fn new(total_ms: u64, api_ms: u64) -> Self {
        Self { total_ms, api_ms }
    }

    /// Creates from total duration only.
    pub fn from_total_ms(total_ms: u64) -> Self {
        Self {
            total_ms,
            api_ms: 0,
        }
    }

    /// Returns total duration in milliseconds.
    pub fn total_ms(&self) -> u64 {
        self.total_ms
    }

    /// Returns API duration in milliseconds.
    pub fn api_ms(&self) -> u64 {
        self.api_ms
    }

    /// Returns total duration as seconds (float).
    pub fn total_seconds(&self) -> f64 {
        self.total_ms as f64 / 1000.0
    }

    /// Returns the overhead time (total - API).
    pub fn overhead_ms(&self) -> u64 {
        self.total_ms.saturating_sub(self.api_ms)
    }

    /// Formats duration for display.
    ///
    /// Returns format like "35s", "2m 15s", "1h 30m"
    pub fn format(&self) -> String {
        let secs = self.total_ms / 1000;
        if secs < 60 {
            format!("{secs}s")
        } else if secs < 3600 {
            let mins = secs / 60;
            let remaining_secs = secs % 60;
            if remaining_secs == 0 {
                format!("{mins}m")
            } else {
                format!("{mins}m {remaining_secs}s")
            }
        } else {
            let hours = secs / 3600;
            let remaining_mins = (secs % 3600) / 60;
            if remaining_mins == 0 {
                format!("{hours}h")
            } else {
                format!("{hours}h {remaining_mins}m")
            }
        }
    }

    /// Formats duration compactly.
    pub fn format_compact(&self) -> String {
        let secs = self.total_ms / 1000;
        if secs < 60 {
            format!("{secs}s")
        } else if secs < 3600 {
            let mins = secs / 60;
            format!("{mins}m")
        } else {
            let hours = secs / 3600;
            format!("{hours}h")
        }
    }
}

impl fmt::Display for SessionDuration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.format())
    }
}

/// Tracks lines added and removed in a session.
///
/// Based on Claude Code status line `cost.total_lines_added/removed`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct LinesChanged {
    /// Lines added
    pub added: u64,
    /// Lines removed
    pub removed: u64,
}

impl LinesChanged {
    /// Creates new LinesChanged.
    pub fn new(added: u64, removed: u64) -> Self {
        Self { added, removed }
    }

    /// Returns net change (added - removed).
    pub fn net(&self) -> i64 {
        self.added as i64 - self.removed as i64
    }

    /// Returns total churn (added + removed).
    pub fn churn(&self) -> u64 {
        self.added.saturating_add(self.removed)
    }

    /// Returns true if no changes have been made.
    pub fn is_empty(&self) -> bool {
        self.added == 0 && self.removed == 0
    }

    /// Formats for display (e.g., "+150 -30").
    pub fn format(&self) -> String {
        format!("+{} -{}", self.added, self.removed)
    }

    /// Formats net change with sign.
    pub fn format_net(&self) -> String {
        let net = self.net();
        if net >= 0 {
            format!("+{net}")
        } else {
            format!("{net}")
        }
    }
}

impl fmt::Display for LinesChanged {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.format())
    }
}

// ============================================================================
// Status Line Data Transfer Object
// ============================================================================

/// Data extracted from Claude Code's status line JSON.
///
/// This struct consolidates the many parameters previously passed to
/// `SessionDomain::from_status_line()` and `update_from_status_line()`,
/// providing named fields for clarity and reducing error-prone parameter ordering.
#[derive(Debug, Clone, Default)]
pub struct StatusLineData {
    /// Session ID from Claude Code
    pub session_id: String,
    /// Model ID (e.g., "claude-sonnet-4-20250514")
    pub model_id: String,
    /// Display name from the provider (e.g., "Claude Opus 4.6"), if provided
    pub model_display_name: Option<String>,
    /// Total cost in USD
    pub cost_usd: f64,
    /// Total session duration in milliseconds
    pub total_duration_ms: u64,
    /// Time spent waiting for API responses in milliseconds
    pub api_duration_ms: u64,
    /// Lines of code added
    pub lines_added: u64,
    /// Lines of code removed
    pub lines_removed: u64,
    /// Total input tokens across all requests
    pub total_input_tokens: u64,
    /// Total output tokens across all responses
    pub total_output_tokens: u64,
    /// Context window size for the model
    pub context_window_size: u32,
    /// Input tokens in current context
    pub current_input_tokens: u64,
    /// Output tokens in current context
    pub current_output_tokens: u64,
    /// Tokens used for cache creation
    pub cache_creation_tokens: u64,
    /// Tokens read from cache
    pub cache_read_tokens: u64,
    /// Current working directory
    pub cwd: Option<String>,
    /// Claude Code version
    pub version: Option<String>,
}

// ============================================================================
// Domain Entity
// ============================================================================

/// Core domain model for a Claude Code session.
///
/// Contains pure business logic and state. Does NOT include
/// infrastructure concerns (PIDs, sockets, file paths).
///
/// Consistent with CONCURRENCY_MODEL.md RegistryActor ownership.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionDomain {
    /// Unique session identifier
    pub id: SessionId,

    /// Type of agent (main, subagent, etc.)
    pub agent_type: AgentType,

    /// Which coding-agent harness drives this session (Claude Code,
    /// pi, future). Distinct from `agent_type` (which today encodes
    /// Claude subagent role) — see `crate::harness::Harness`.
    #[serde(default)]
    pub harness: crate::Harness,

    /// Claude model being used
    pub model: Model,

    /// Display name override for unknown/non-Anthropic models.
    /// When `model` is `Unknown`, this holds the raw model ID or
    /// the provider-supplied display name for UI rendering.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_display_override: Option<String>,

    /// Current session status (3-state model)
    pub status: SessionStatus,

    /// Current activity details (tool name, context, timing)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub current_activity: Option<ActivityDetail>,

    /// Context window usage
    pub context: ContextUsage,

    /// Accumulated cost
    pub cost: Money,

    /// Session duration tracking
    pub duration: SessionDuration,

    /// Lines of code changed
    pub lines_changed: LinesChanged,

    /// When the session started
    pub started_at: DateTime<Utc>,

    /// Last activity timestamp
    pub last_activity: DateTime<Utc>,

    /// Working directory (project root)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub working_directory: Option<String>,

    /// Claude Code version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub claude_code_version: Option<String>,

    /// Tmux pane ID (e.g., "%5") if session is running in tmux
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tmux_pane: Option<String>,

    /// Git project root (resolved from working_directory).
    /// Shared across all worktrees of the same repo.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project_root: Option<String>,

    /// Git worktree path (specific checkout directory).
    /// For the main checkout, this equals project_root.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub worktree_path: Option<String>,

    /// Git branch name for this worktree.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub worktree_branch: Option<String>,

    /// Parent session ID (set when this session is a subagent).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_session_id: Option<SessionId>,

    /// Child subagent session IDs spawned by this session.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub child_session_ids: Vec<SessionId>,

    /// First user prompt (captured from the first UserPromptSubmit hook event).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first_prompt: Option<String>,
}

impl SessionDomain {
    /// Creates a new SessionDomain with required fields.
    pub fn new(id: SessionId, agent_type: AgentType, model: Model) -> Self {
        let now = Utc::now();
        Self {
            id,
            agent_type,
            harness: crate::Harness::default(),
            model,
            model_display_override: None,
            status: SessionStatus::Idle,
            current_activity: None,
            context: ContextUsage::new(model.context_window_size()),
            cost: Money::zero(),
            duration: SessionDuration::default(),
            lines_changed: LinesChanged::default(),
            started_at: now,
            last_activity: now,
            working_directory: None,
            claude_code_version: None,
            tmux_pane: None,
            project_root: None,
            worktree_path: None,
            worktree_branch: None,
            parent_session_id: None,
            child_session_ids: Vec::new(),
            first_prompt: None,
        }
    }

    /// Creates a SessionDomain from Claude Code status line data.
    pub fn from_status_line(data: &StatusLineData) -> Self {
        use crate::model::derive_display_name;

        let model = Model::from_id(&data.model_id);

        let mut session = Self::new(
            SessionId::new(&data.session_id),
            AgentType::GeneralPurpose, // Default, may be updated by hook events
            model,
        );
        // Status-line input is only emitted by Claude Code today.
        session.harness = crate::Harness::ClaudeCode;

        // For unknown models, store a display name fallback:
        // prefer provider-supplied display_name, then derive from raw ID
        if model.is_unknown() && !data.model_id.is_empty() {
            session.model_display_override = Some(
                data.model_display_name
                    .clone()
                    .unwrap_or_else(|| derive_display_name(&data.model_id)),
            );
        }

        session.cost = Money::from_usd(data.cost_usd);
        session.duration = SessionDuration::new(data.total_duration_ms, data.api_duration_ms);
        session.lines_changed = LinesChanged::new(data.lines_added, data.lines_removed);
        session.context = ContextUsage {
            total_input_tokens: TokenCount::new(data.total_input_tokens),
            total_output_tokens: TokenCount::new(data.total_output_tokens),
            context_window_size: data.context_window_size,
            current_input_tokens: TokenCount::new(data.current_input_tokens),
            current_output_tokens: TokenCount::new(data.current_output_tokens),
            cache_creation_tokens: TokenCount::new(data.cache_creation_tokens),
            cache_read_tokens: TokenCount::new(data.cache_read_tokens),
        };
        session.working_directory = data.cwd.clone();
        session.claude_code_version = data.version.clone();
        session.last_activity = Utc::now();

        session
    }

    /// Updates the session with new status line data.
    ///
    /// When `current_usage` is null in Claude's status line, all current_* values
    /// will be 0, which correctly resets context percentage to 0%.
    ///
    /// Returns `true` if the working directory changed (caller should re-resolve git info).
    pub fn update_from_status_line(&mut self, data: &StatusLineData) -> bool {
        self.cost = Money::from_usd(data.cost_usd);
        self.duration = SessionDuration::new(data.total_duration_ms, data.api_duration_ms);
        self.lines_changed = LinesChanged::new(data.lines_added, data.lines_removed);
        self.context.total_input_tokens = TokenCount::new(data.total_input_tokens);
        self.context.total_output_tokens = TokenCount::new(data.total_output_tokens);
        self.context.current_input_tokens = TokenCount::new(data.current_input_tokens);
        self.context.current_output_tokens = TokenCount::new(data.current_output_tokens);
        self.context.cache_creation_tokens = TokenCount::new(data.cache_creation_tokens);
        self.context.cache_read_tokens = TokenCount::new(data.cache_read_tokens);
        self.last_activity = Utc::now();

        // Status line update means Claude is working
        // Don't override AttentionNeeded (permission wait)
        if self.status != SessionStatus::AttentionNeeded {
            self.status = SessionStatus::Working;
        }

        // Detect working directory change
        let cwd_changed = match (&data.cwd, &self.working_directory) {
            (Some(new_cwd), Some(old_cwd)) => new_cwd != old_cwd,
            (Some(_), None) => true,
            _ => false,
        };
        if cwd_changed {
            self.working_directory = data.cwd.clone();
        }
        cwd_changed
    }

    /// Updates status from a vendor-neutral lifecycle event.
    ///
    /// Single source of truth for session-state transitions. Every
    /// adapter (Claude, pi, future) funnels through this method.
    pub fn apply_lifecycle_event(&mut self, event: &LifecycleEvent) {
        self.last_activity = Utc::now();

        match event {
            LifecycleEvent::SessionStart { .. } => {
                self.status = SessionStatus::Idle;
                self.current_activity = None;
            }
            LifecycleEvent::SessionEnd { .. } => {
                // Registry removes the session; this status is rarely
                // observed, but keep it consistent.
                self.status = SessionStatus::Idle;
                self.current_activity = None;
            }
            LifecycleEvent::WorkingStart => {
                self.status = SessionStatus::Working;
                self.current_activity = None;
            }
            LifecycleEvent::WorkingEnd | LifecycleEvent::Idle => {
                self.status = SessionStatus::Idle;
                self.current_activity = None;
            }
            LifecycleEvent::PromptSubmit { .. } => {
                self.status = SessionStatus::Working;
                self.current_activity = None;
                // first_prompt is set separately via set_first_prompt()
            }
            LifecycleEvent::NeedsInput { reason } => {
                self.status = SessionStatus::AttentionNeeded;
                self.current_activity = Some(activity_for_needs_input(reason));
            }
            LifecycleEvent::ToolCallStart { name, .. } => {
                self.status = SessionStatus::Working;
                self.current_activity = Some(ActivityDetail::new(name.as_str()));
            }
            LifecycleEvent::ToolCallEnd { .. } => {
                self.status = SessionStatus::Working;
                self.current_activity = Some(ActivityDetail::thinking());
            }
            LifecycleEvent::ContextCompactStart { .. } => {
                self.status = SessionStatus::Working;
                self.current_activity = Some(ActivityDetail::with_context("Compacting"));
            }
            LifecycleEvent::ContextUpdate { tokens, cost_usd } => {
                // Pi (and future vendors) emit cumulative cost/tokens
                // through this variant — there's no "status line"
                // periodic update like Claude. Fold the values into
                // the same `Session.cost` / `Session.context` fields
                // the Claude path uses, so the TUI displays them
                // identically regardless of vendor.
                if let Some(c) = cost_usd {
                    self.cost = Money::from_usd(*c);
                }
                if let Some(t) = tokens {
                    // Pi reports cumulative total tokens for the
                    // session. The TUI's percentage display reads
                    // `context_tokens()` which sums Claude's
                    // current_input + cache_read + cache_creation —
                    // none of which pi populates. To make pi sessions
                    // surface a non-zero context bar, mirror pi's
                    // cumulative figure into `current_input_tokens`
                    // (the largest summand of `context_tokens()`).
                    // Also keep `total_input_tokens` set for the
                    // detail-panel "total tokens" display, even though
                    // it doesn't affect the percentage.
                    let count = TokenCount::new(*t);
                    self.context.current_input_tokens = count;
                    self.context.total_input_tokens = count;
                }
                // Status unchanged: cost/token updates don't
                // imply a state transition.
            }
            LifecycleEvent::ProviderModelChange { model, .. } => {
                // Pi's `model_select` event fires when the user picks a
                // provider/model in pi's UI. Update Session so the TUI
                // stops showing `[pi] Unknown` once the user has chosen.
                //
                // Strategy: try to map the raw id onto our Claude-shaped
                // `Model` enum first (in case it's a Claude model pi is
                // talking to); fall back to `Model::Unknown` and stash
                // the raw id in `model_display_override` for rendering.
                if let Some(id) = model {
                    let parsed = Model::from_id(id);
                    self.model = parsed;
                    self.model_display_override = if parsed.is_unknown() {
                        Some(crate::model::derive_display_name(id))
                    } else {
                        None
                    };
                }
                // Status unchanged: model selection is metadata only.
            }
            LifecycleEvent::Notification { kind, .. } => {
                if matches!(kind, Some(NotificationKind::Setup)) {
                    self.status = SessionStatus::Working;
                    self.current_activity = Some(ActivityDetail::with_context("Setup"));
                }
                // Other notifications: no status change. Permission /
                // elicitation prompts arrive as `NeedsInput`, not
                // `Notification`, after translation.
            }
            LifecycleEvent::ChildSessionStart { .. } | LifecycleEvent::ChildSessionEnd { .. } => {
                // Child-session correlation is tracked by the registry
                // (subagent pending-list); status remains Working.
                self.status = SessionStatus::Working;
            }
        }
    }

    /// Stores the first user prompt if not already set.
    pub fn set_first_prompt_from_event(&mut self, event: &LifecycleEvent) {
        if let LifecycleEvent::PromptSubmit { prompt: Some(text) } = event {
            if !text.is_empty() {
                self.set_first_prompt(text);
            }
        }
    }

    /// Stores the first user prompt if not already set.
    pub fn set_first_prompt(&mut self, prompt: &str) {
        if self.first_prompt.is_none() && !prompt.is_empty() {
            self.first_prompt = Some(prompt.to_string());
        }
    }

    /// Returns the session age (time since started).
    pub fn age(&self) -> chrono::Duration {
        Utc::now().signed_duration_since(self.started_at)
    }

    /// Returns time since last activity.
    pub fn time_since_activity(&self) -> chrono::Duration {
        Utc::now().signed_duration_since(self.last_activity)
    }

    /// Returns true if context usage needs attention.
    pub fn needs_context_attention(&self) -> bool {
        self.context.is_warning() || self.context.is_critical()
    }
}

impl Default for SessionDomain {
    fn default() -> Self {
        Self::new(
            SessionId::new("unknown"),
            AgentType::default(),
            Model::default(),
        )
    }
}

// ============================================================================
// Infrastructure Entity
// ============================================================================

/// Record of a tool invocation.
#[derive(Debug, Clone)]
pub struct ToolUsageRecord {
    /// Name of the tool (e.g., "Bash", "Read", "Write")
    pub tool_name: String,
    /// Unique ID for this tool invocation
    pub tool_use_id: Option<ToolUseId>,
    /// When the tool was invoked
    pub timestamp: DateTime<Utc>,
}

/// Infrastructure-level data for a session.
///
/// Contains OS/system concerns that don't belong in the domain model.
/// Owned by RegistryActor alongside SessionDomain.
#[derive(Debug, Clone)]
pub struct SessionInfrastructure {
    /// Process ID of the Claude Code process (if known)
    pub pid: Option<u32>,

    /// Process start time in clock ticks (from /proc/{pid}/stat field 22).
    /// Used to detect PID reuse - if the start time changes, it's a different process.
    pub process_start_time: Option<u64>,

    /// Path to the Unix socket for this session (if applicable)
    pub socket_path: Option<PathBuf>,

    /// Path to the transcript JSONL file
    pub transcript_path: Option<TranscriptPath>,

    /// Recent tool usage history (bounded FIFO queue)
    pub recent_tools: VecDeque<ToolUsageRecord>,

    /// Number of status updates received
    pub update_count: u64,

    /// Number of hook events received
    pub hook_event_count: u64,

    /// Last error encountered (for debugging)
    pub last_error: Option<String>,
}

impl SessionInfrastructure {
    /// Maximum number of tool records to keep.
    const MAX_TOOL_HISTORY: usize = 50;

    /// Creates new SessionInfrastructure.
    pub fn new() -> Self {
        Self {
            pid: None,
            process_start_time: None,
            socket_path: None,
            transcript_path: None,
            recent_tools: VecDeque::with_capacity(Self::MAX_TOOL_HISTORY),
            update_count: 0,
            hook_event_count: 0,
            last_error: None,
        }
    }

    /// Sets the process ID and captures the process start time for PID reuse detection.
    ///
    /// The start time is read from `/proc/{pid}/stat` field 22 (starttime in clock ticks).
    /// If the PID is already set with the same value, this is a no-op.
    ///
    /// # Validation
    ///
    /// The PID is only stored if:
    /// - It's non-zero (PID 0 is invalid)
    /// - We can successfully read its start time from `/proc/{pid}/stat`
    ///
    /// This prevents storing invalid PIDs that would cause incorrect liveness checks.
    pub fn set_pid(&mut self, pid: u32) {
        // PID 0 is invalid
        if pid == 0 {
            return;
        }

        // Only update if PID changed or wasn't set
        if self.pid == Some(pid) {
            return;
        }

        // Only store PID if we can read and validate its start time
        // This ensures the PID is valid and gives us PID reuse protection
        if let Some(start_time) = read_process_start_time(pid) {
            self.pid = Some(pid);
            self.process_start_time = Some(start_time);
        } else {
            debug!(
                pid = pid,
                "PID validation failed - process may have exited or is inaccessible"
            );
        }
    }

    /// Checks if the tracked process is still alive.
    ///
    /// Returns `true` if:
    /// - No PID is tracked (can't determine liveness)
    /// - The process exists and has the same start time
    ///
    /// Returns `false` if:
    /// - The process no longer exists
    /// - The PID has been reused by a different process (start time mismatch)
    pub fn is_process_alive(&self) -> bool {
        let Some(pid) = self.pid else {
            // No PID tracked - assume alive (can't determine)
            debug!(pid = ?self.pid, "is_process_alive: no PID tracked, assuming alive");
            return true;
        };

        let Some(expected_start_time) = self.process_start_time else {
            // No start time recorded - just check if process exists via procfs
            let exists = procfs::process::Process::new(pid as i32).is_ok();
            debug!(
                pid,
                exists, "is_process_alive: no start_time, checking procfs only"
            );
            return exists;
        };

        // Check if process exists and has same start time
        match read_process_start_time(pid) {
            Some(current_start_time) => {
                let alive = current_start_time == expected_start_time;
                if !alive {
                    debug!(
                        pid,
                        expected_start_time,
                        current_start_time,
                        "is_process_alive: start time MISMATCH - PID reused?"
                    );
                }
                alive
            }
            None => {
                debug!(
                    pid,
                    expected_start_time, "is_process_alive: process NOT FOUND in /proc"
                );
                false
            }
        }
    }

    /// Records a tool usage.
    pub fn record_tool_use(&mut self, tool_name: &str, tool_use_id: Option<ToolUseId>) {
        let record = ToolUsageRecord {
            tool_name: tool_name.to_string(),
            tool_use_id,
            timestamp: Utc::now(),
        };

        self.recent_tools.push_back(record);

        // Maintain bounded size using safe VecDeque operations
        while self.recent_tools.len() > Self::MAX_TOOL_HISTORY {
            self.recent_tools.pop_front();
        }

        self.hook_event_count += 1;
    }

    /// Increments the update count.
    pub fn record_update(&mut self) {
        self.update_count += 1;
    }

    /// Records an error.
    pub fn record_error(&mut self, error: &str) {
        self.last_error = Some(error.to_string());
    }

    /// Returns the most recent tool used.
    pub fn last_tool(&self) -> Option<&ToolUsageRecord> {
        self.recent_tools.back()
    }

    /// Returns recent tools (most recent first).
    pub fn recent_tools_iter(&self) -> impl Iterator<Item = &ToolUsageRecord> {
        self.recent_tools.iter().rev()
    }
}

/// Activity-detail string for an `AttentionNeeded` state.
fn activity_for_needs_input(reason: &NeedsInputReason) -> ActivityDetail {
    match reason {
        NeedsInputReason::InteractiveTool { tool } | NeedsInputReason::PermissionGate { tool } => {
            ActivityDetail::new(tool.as_str())
        }
        NeedsInputReason::Notification { kind, label } => {
            // When the vendor-supplied label is present (e.g. pi
            // forwards the dialog title from `ctx.ui.select`), prefer
            // it over the kind-derived static string — it tells the
            // user what's actually being asked.
            if let Some(text) = label.as_deref() {
                return ActivityDetail::with_context(text);
            }
            match kind {
                NotificationKind::PermissionPrompt => ActivityDetail::with_context("Permission"),
                NotificationKind::ElicitationDialog => ActivityDetail::with_context("MCP Input"),
                other => ActivityDetail::with_context(other.as_str()),
            }
        }
    }
}

/// Reads the process start time using the procfs crate.
///
/// The start time (in clock ticks since boot) is stable for the lifetime
/// of a process and unique enough to detect PID reuse.
///
/// Returns `None` if the process doesn't exist or can't be read.
fn read_process_start_time(pid: u32) -> Option<u64> {
    let process = procfs::process::Process::new(pid as i32).ok()?;
    let stat = process.stat().ok()?;
    Some(stat.starttime)
}

impl Default for SessionInfrastructure {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Application Layer DTO
// ============================================================================

/// Read-only view of a session for TUI display.
///
/// Immutable snapshot created from SessionDomain.
/// Implements Clone for easy distribution to multiple UI components.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionView {
    /// Session identifier
    pub id: SessionId,

    /// Short ID for display (first 8 chars)
    pub id_short: String,

    /// Agent type label
    pub agent_type: String,

    /// Coding-agent harness short tag (`"claude"`, `"pi"`, `"?"`).
    /// Drives the vendor badge in the TUI.
    #[serde(default)]
    pub harness: String,

    /// Model display name
    pub model: String,

    /// Current status (3-state model)
    pub status: SessionStatus,

    /// Status label for display
    pub status_label: String,

    /// Activity detail (tool name or context)
    pub activity_detail: Option<String>,

    /// Whether this status should blink
    pub should_blink: bool,

    /// Status icon
    pub status_icon: String,

    /// Context usage percentage
    pub context_percentage: f64,

    /// Context usage formatted string
    pub context_display: String,

    /// Whether context is in warning state
    pub context_warning: bool,

    /// Whether context is in critical state
    pub context_critical: bool,

    /// Cost formatted string
    pub cost_display: String,

    /// Cost in USD (for sorting)
    pub cost_usd: f64,

    /// Duration formatted string
    pub duration_display: String,

    /// Duration in seconds (for sorting)
    pub duration_seconds: f64,

    /// Lines changed formatted string
    pub lines_display: String,

    /// Working directory (shortened for display)
    pub working_directory: Option<String>,

    /// Whether session needs attention (permission wait, high context)
    pub needs_attention: bool,

    /// Time since last activity (formatted)
    pub last_activity_display: String,

    /// Session age (formatted)
    pub age_display: String,

    /// Session start time (ISO 8601)
    pub started_at: String,

    /// Last activity time (ISO 8601)
    pub last_activity: String,

    /// Tmux pane ID (e.g., "%5") if session is running in tmux
    pub tmux_pane: Option<String>,

    /// Git project root (for grouping in tree view)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project_root: Option<String>,

    /// Git worktree path
    #[serde(skip_serializing_if = "Option::is_none")]
    pub worktree_path: Option<String>,

    /// Git branch name for this worktree
    #[serde(skip_serializing_if = "Option::is_none")]
    pub worktree_branch: Option<String>,

    /// Parent session ID (if this is a subagent)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parent_session_id: Option<SessionId>,

    /// Child subagent session IDs
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub child_session_ids: Vec<SessionId>,

    /// First user prompt (for preview summary)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first_prompt: Option<String>,
}

impl SessionView {
    /// Creates a SessionView from a SessionDomain.
    pub fn from_domain(session: &SessionDomain) -> Self {
        let now = Utc::now();
        let since_activity = now.signed_duration_since(session.last_activity);
        let age = now.signed_duration_since(session.started_at);

        Self {
            id: session.id.clone(),
            id_short: session.id.short().to_string(),
            agent_type: session.agent_type.short_name().to_string(),
            harness: session.harness.short_tag().to_string(),
            model: if session.model.is_unknown() {
                session
                    .model_display_override
                    .clone()
                    .unwrap_or_else(|| session.model.display_name().to_string())
            } else {
                session.model.display_name().to_string()
            },
            status: session.status,
            status_label: session.status.label().to_string(),
            activity_detail: session
                .current_activity
                .as_ref()
                .map(|a| a.display().into_owned()),
            should_blink: session.status.should_blink(),
            status_icon: session.status.icon().to_string(),
            context_percentage: session.context.usage_percentage(),
            context_display: session.context.format(),
            context_warning: session.context.is_warning(),
            context_critical: session.context.is_critical(),
            cost_display: session.cost.format(),
            cost_usd: session.cost.as_usd(),
            duration_display: session.duration.format(),
            duration_seconds: session.duration.total_seconds(),
            lines_display: session.lines_changed.format(),
            working_directory: session.working_directory.clone().map(|p| {
                // Shorten path for display
                if p.len() > 30 {
                    format!("...{}", &p[p.len().saturating_sub(27)..])
                } else {
                    p
                }
            }),
            needs_attention: session.status.needs_attention() || session.needs_context_attention(),
            last_activity_display: format_duration(since_activity),
            age_display: format_duration(age),
            started_at: session.started_at.to_rfc3339(),
            last_activity: session.last_activity.to_rfc3339(),
            tmux_pane: session.tmux_pane.clone(),
            project_root: session.project_root.clone(),
            worktree_path: session.worktree_path.clone(),
            worktree_branch: session.worktree_branch.clone(),
            parent_session_id: session.parent_session_id.clone(),
            child_session_ids: session.child_session_ids.clone(),
            first_prompt: session.first_prompt.clone(),
        }
    }
}

impl From<&SessionDomain> for SessionView {
    fn from(session: &SessionDomain) -> Self {
        Self::from_domain(session)
    }
}

/// Formats a duration for human-readable display.
fn format_duration(duration: chrono::Duration) -> String {
    let secs = duration.num_seconds();
    if secs < 0 {
        return "now".to_string();
    }
    if secs < 60 {
        format!("{secs}s ago")
    } else if secs < 3600 {
        let mins = secs / 60;
        format!("{mins}m ago")
    } else if secs < 86400 {
        let hours = secs / 3600;
        format!("{hours}h ago")
    } else {
        let days = secs / 86400;
        format!("{days}d ago")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tool::Tool;

    /// Creates a test session with default values.
    fn create_test_session(id: &str) -> SessionDomain {
        SessionDomain::new(SessionId::new(id), AgentType::GeneralPurpose, Model::Opus45)
    }

    #[test]
    fn test_session_id_short() {
        let id = SessionId::new("8e11bfb5-7dc2-432b-9206-928fa5c35731");
        assert_eq!(id.short(), "8e11bfb5");
    }

    #[test]
    fn test_session_id_short_short_id() {
        let id = SessionId::new("abc");
        assert_eq!(id.short(), "abc");
    }

    #[test]
    fn test_session_status_display() {
        let status = SessionStatus::Working;
        assert_eq!(format!("{status}"), "Working");
    }

    #[test]
    fn test_session_domain_creation() {
        let session = SessionDomain::new(
            SessionId::new("test-123"),
            AgentType::GeneralPurpose,
            Model::Opus45,
        );
        assert_eq!(session.id.as_str(), "test-123");
        assert_eq!(session.model, Model::Opus45);
        assert!(session.cost.is_zero());
    }

    #[test]
    fn test_session_view_from_domain() {
        let session = SessionDomain::new(
            SessionId::new("8e11bfb5-7dc2-432b-9206-928fa5c35731"),
            AgentType::Explore,
            Model::Sonnet4,
        );
        let view = SessionView::from_domain(&session);

        assert_eq!(view.id_short, "8e11bfb5");
        assert_eq!(view.agent_type, "explore");
        assert_eq!(view.model, "Sonnet 4");
    }

    #[test]
    fn test_session_view_unknown_model_with_override() {
        let mut session = SessionDomain::new(
            SessionId::new("test-override"),
            AgentType::GeneralPurpose,
            Model::Unknown,
        );
        session.model_display_override = Some("GPT-4o".to_string());

        let view = SessionView::from_domain(&session);
        assert_eq!(view.model, "GPT-4o");
    }

    #[test]
    fn test_session_view_unknown_model_without_override() {
        let session = SessionDomain::new(
            SessionId::new("test-no-override"),
            AgentType::GeneralPurpose,
            Model::Unknown,
        );

        let view = SessionView::from_domain(&session);
        assert_eq!(view.model, "Unknown");
    }

    #[test]
    fn test_session_view_known_model_ignores_override() {
        let mut session = SessionDomain::new(
            SessionId::new("test-known"),
            AgentType::GeneralPurpose,
            Model::Opus46,
        );
        // Even if override is set, known models use their display_name
        session.model_display_override = Some("something else".to_string());

        let view = SessionView::from_domain(&session);
        assert_eq!(view.model, "Opus 4.6");
    }

    #[test]
    fn test_lines_changed() {
        let lines = LinesChanged::new(150, 30);
        assert_eq!(lines.net(), 120);
        assert_eq!(lines.churn(), 180);
        assert_eq!(lines.format(), "+150 -30");
        assert_eq!(lines.format_net(), "+120");
    }

    #[test]
    fn test_session_duration_formatting() {
        assert_eq!(SessionDuration::from_total_ms(35_000).format(), "35s");
        assert_eq!(SessionDuration::from_total_ms(135_000).format(), "2m 15s");
        assert_eq!(SessionDuration::from_total_ms(5_400_000).format(), "1h 30m");
    }

    #[test]
    fn test_session_id_pending_from_pid() {
        let id = SessionId::pending_from_pid(12345);
        assert_eq!(id.as_str(), "pending-12345");
        assert!(id.is_pending());
        assert_eq!(id.pending_pid(), Some(12345));
    }

    #[test]
    fn test_session_id_is_pending_true() {
        let id = SessionId::new("pending-99999");
        assert!(id.is_pending());
    }

    #[test]
    fn test_session_id_is_pending_false() {
        let id = SessionId::new("8e11bfb5-7dc2-432b-9206-928fa5c35731");
        assert!(!id.is_pending());
    }

    #[test]
    fn test_session_id_pending_pid_returns_none_for_regular_id() {
        let id = SessionId::new("8e11bfb5-7dc2-432b-9206-928fa5c35731");
        assert_eq!(id.pending_pid(), None);
    }

    #[test]
    fn test_session_id_pending_pid_returns_none_for_invalid_pid() {
        let id = SessionId::new("pending-not-a-number");
        assert_eq!(id.pending_pid(), None);
    }

    #[test]
    fn lifecycle_provider_model_change_known_claude_id() {
        // A pi session targeting a Claude model should map onto the
        // existing Model variant; no override needed.
        let mut session = create_test_session("test-pmc-known");
        session.model = Model::Unknown;
        session.model_display_override = Some("stale".to_string());

        session.apply_lifecycle_event(&LifecycleEvent::ProviderModelChange {
            provider: Some("anthropic".to_string()),
            model: Some("claude-sonnet-4-5-20250929".to_string()),
        });

        assert_eq!(session.model, Model::Sonnet45);
        assert!(
            session.model_display_override.is_none(),
            "override must be cleared when the id maps to a known model"
        );
    }

    #[test]
    fn lifecycle_provider_model_change_unknown_id() {
        // A pi session pointed at a non-Claude provider should land
        // as Unknown with the raw id surfaced via the override field
        // so the TUI shows something meaningful instead of "Unknown".
        let mut session = create_test_session("test-pmc-unknown");
        session.model = Model::Unknown;
        session.model_display_override = None;

        session.apply_lifecycle_event(&LifecycleEvent::ProviderModelChange {
            provider: Some("openai".to_string()),
            model: Some("gpt-4o".to_string()),
        });

        assert_eq!(session.model, Model::Unknown);
        assert_eq!(session.model_display_override.as_deref(), Some("gpt-4o"));
    }

    #[test]
    fn lifecycle_provider_model_change_no_model_is_noop() {
        let mut session = create_test_session("test-pmc-none");
        session.model = Model::Sonnet4;
        session.model_display_override = None;

        session.apply_lifecycle_event(&LifecycleEvent::ProviderModelChange {
            provider: Some("anthropic".to_string()),
            model: None,
        });

        assert_eq!(session.model, Model::Sonnet4);
        assert!(session.model_display_override.is_none());
    }

    #[test]
    fn lifecycle_needs_input_for_interactive_tool() {
        let mut session = create_test_session("test-interactive");

        session.apply_lifecycle_event(&LifecycleEvent::NeedsInput {
            reason: NeedsInputReason::InteractiveTool {
                tool: Tool::AskUserQuestion,
            },
        });
        assert_eq!(session.status, SessionStatus::AttentionNeeded);
        assert_eq!(
            session
                .current_activity
                .as_ref()
                .map(|a| a.display())
                .as_deref(),
            Some("AskUserQuestion")
        );

        session.apply_lifecycle_event(&LifecycleEvent::ToolCallEnd {
            name: Tool::AskUserQuestion,
            tool_use_id: None,
            is_error: false,
        });
        assert_eq!(session.status, SessionStatus::Working);
    }

    #[test]
    fn lifecycle_needs_input_for_enter_plan_mode() {
        let mut session = create_test_session("test-plan");

        session.apply_lifecycle_event(&LifecycleEvent::NeedsInput {
            reason: NeedsInputReason::InteractiveTool {
                tool: Tool::EnterPlanMode,
            },
        });
        assert_eq!(session.status, SessionStatus::AttentionNeeded);
        assert_eq!(
            session
                .current_activity
                .as_ref()
                .map(|a| a.display())
                .as_deref(),
            Some("EnterPlanMode")
        );
    }

    #[test]
    fn lifecycle_needs_input_notification_uses_label_when_present() {
        // The `label` plumbing exists so the TUI shows *what* permission
        // is being asked (the dialog title forwarded by pi-atm's
        // `ctx.ui.select` wrapper) instead of a generic kind string.
        let mut session = create_test_session("test-label");

        session.apply_lifecycle_event(&LifecycleEvent::NeedsInput {
            reason: NeedsInputReason::Notification {
                kind: NotificationKind::PermissionPrompt,
                label: Some("Allow `rm -rf /tmp/cache`?".into()),
            },
        });
        assert_eq!(session.status, SessionStatus::AttentionNeeded);
        assert_eq!(
            session
                .current_activity
                .as_ref()
                .map(|a| a.display())
                .as_deref(),
            Some("Allow `rm -rf /tmp/cache`?")
        );
    }

    #[test]
    fn lifecycle_needs_input_notification_falls_back_to_kind_when_label_absent() {
        // Claude `Notification(permission_prompt)` events don't carry a
        // per-prompt label — only a kind tag. Verify the fallback
        // rendering still resolves to the kind-derived string.
        let mut session = create_test_session("test-no-label");

        session.apply_lifecycle_event(&LifecycleEvent::NeedsInput {
            reason: NeedsInputReason::Notification {
                kind: NotificationKind::PermissionPrompt,
                label: None,
            },
        });
        assert_eq!(session.status, SessionStatus::AttentionNeeded);
        assert_eq!(
            session
                .current_activity
                .as_ref()
                .map(|a| a.display())
                .as_deref(),
            Some("Permission")
        );

        session.apply_lifecycle_event(&LifecycleEvent::NeedsInput {
            reason: NeedsInputReason::Notification {
                kind: NotificationKind::ElicitationDialog,
                label: None,
            },
        });
        assert_eq!(
            session
                .current_activity
                .as_ref()
                .map(|a| a.display())
                .as_deref(),
            Some("MCP Input")
        );
    }

    #[test]
    fn lifecycle_tool_call_start_for_standard_tool() {
        let mut session = create_test_session("test-standard");

        session.apply_lifecycle_event(&LifecycleEvent::ToolCallStart {
            name: Tool::Bash,
            tool_use_id: None,
            input: None,
        });
        assert_eq!(session.status, SessionStatus::Working);
        assert_eq!(
            session
                .current_activity
                .as_ref()
                .map(|a| a.display())
                .as_deref(),
            Some("Bash")
        );

        session.apply_lifecycle_event(&LifecycleEvent::ToolCallEnd {
            name: Tool::Bash,
            tool_use_id: None,
            is_error: false,
        });
        assert_eq!(session.status, SessionStatus::Working);
    }

    #[test]
    fn lifecycle_unknown_tool_lands_in_other_and_keeps_name() {
        // The empty/unknown case used to be "standard tool with empty name".
        // After typing, the same input becomes Tool::Other("") — the session
        // still treats it as a working tool call without crashing on missing data.
        let mut session = create_test_session("test-other");

        session.apply_lifecycle_event(&LifecycleEvent::ToolCallStart {
            name: Tool::Other("custom_pi_tool".into()),
            tool_use_id: None,
            input: None,
        });
        assert_eq!(session.status, SessionStatus::Working);
        assert_eq!(
            session
                .current_activity
                .as_ref()
                .map(|a| a.display())
                .as_deref(),
            Some("custom_pi_tool")
        );
    }

    #[test]
    fn test_activity_detail_creation() {
        let detail = ActivityDetail::new("Bash");
        assert_eq!(detail.tool_name.as_deref(), Some("Bash"));
        assert!(detail.started_at <= Utc::now());
        assert!(detail.context.is_none());
    }

    #[test]
    fn test_activity_detail_with_context() {
        let detail = ActivityDetail::with_context("Compacting");
        assert!(detail.tool_name.is_none());
        assert_eq!(detail.context.as_deref(), Some("Compacting"));
    }

    #[test]
    fn test_activity_detail_display() {
        let detail = ActivityDetail::new("Read");
        assert_eq!(detail.display(), "Read");

        let context_detail = ActivityDetail::with_context("Setup");
        assert_eq!(context_detail.display(), "Setup");
    }

    #[test]
    fn test_new_session_status_variants() {
        // All three states should exist
        let idle = SessionStatus::Idle;
        let working = SessionStatus::Working;
        let attention = SessionStatus::AttentionNeeded;

        assert_eq!(idle.label(), "idle");
        assert_eq!(working.label(), "working");
        assert_eq!(attention.label(), "needs input");
    }

    #[test]
    fn test_session_status_should_blink() {
        assert!(!SessionStatus::Idle.should_blink());
        assert!(!SessionStatus::Working.should_blink());
        assert!(SessionStatus::AttentionNeeded.should_blink());
    }

    #[test]
    fn test_session_status_icons() {
        assert_eq!(SessionStatus::Idle.icon(), "-");
        assert_eq!(SessionStatus::Working.icon(), ">");
        assert_eq!(SessionStatus::AttentionNeeded.icon(), "!");
    }

    #[test]
    fn test_session_domain_new_fields_default() {
        let session = create_test_session("test-defaults");
        assert!(session.project_root.is_none());
        assert!(session.worktree_path.is_none());
        assert!(session.worktree_branch.is_none());
        assert!(session.parent_session_id.is_none());
        assert!(session.child_session_ids.is_empty());
    }

    #[test]
    fn test_session_view_includes_new_fields() {
        let mut session = create_test_session("test-view-fields");
        session.project_root = Some("/home/user/project".to_string());
        session.worktree_path = Some("/home/user/worktree".to_string());
        session.worktree_branch = Some("feature-x".to_string());
        session.parent_session_id = Some(SessionId::new("parent-123"));
        session.child_session_ids = vec![SessionId::new("child-1"), SessionId::new("child-2")];

        let view = SessionView::from_domain(&session);

        assert_eq!(view.project_root, Some("/home/user/project".to_string()));
        assert_eq!(view.worktree_path, Some("/home/user/worktree".to_string()));
        assert_eq!(view.worktree_branch, Some("feature-x".to_string()));
        assert_eq!(view.parent_session_id, Some(SessionId::new("parent-123")));
        assert_eq!(view.child_session_ids.len(), 2);
        assert_eq!(view.child_session_ids[0].as_str(), "child-1");
        assert_eq!(view.child_session_ids[1].as_str(), "child-2");
    }

    // ========================================================================
    // update_from_status_line cwd change detection
    // ========================================================================

    fn make_status_data(cwd: Option<&str>) -> StatusLineData {
        StatusLineData {
            session_id: "test".to_string(),
            model_id: "claude-sonnet-4-20250514".to_string(),
            model_display_name: None,
            cost_usd: 0.10,
            total_duration_ms: 1000,
            api_duration_ms: 500,
            lines_added: 10,
            lines_removed: 5,
            total_input_tokens: 1000,
            total_output_tokens: 500,
            context_window_size: 200_000,
            current_input_tokens: 800,
            current_output_tokens: 400,
            cache_creation_tokens: 0,
            cache_read_tokens: 0,
            cwd: cwd.map(|s| s.to_string()),
            version: None,
        }
    }

    #[test]
    fn test_update_from_status_line_cwd_changed() {
        let mut session = SessionDomain::new(
            SessionId::new("test"),
            AgentType::GeneralPurpose,
            Model::Sonnet4,
        );
        session.working_directory = Some("/home/user/repo-a".to_string());

        let data = make_status_data(Some("/home/user/repo-b"));
        let changed = session.update_from_status_line(&data);

        assert!(changed, "should return true when cwd changes");
        assert_eq!(
            session.working_directory.as_deref(),
            Some("/home/user/repo-b"),
            "working_directory should be updated"
        );
    }

    #[test]
    fn test_update_from_status_line_cwd_same() {
        let mut session = SessionDomain::new(
            SessionId::new("test"),
            AgentType::GeneralPurpose,
            Model::Sonnet4,
        );
        session.working_directory = Some("/home/user/repo".to_string());

        let data = make_status_data(Some("/home/user/repo"));
        let changed = session.update_from_status_line(&data);

        assert!(!changed, "should return false when cwd is the same");
    }

    #[test]
    fn test_update_from_status_line_cwd_none_to_some() {
        let mut session = SessionDomain::new(
            SessionId::new("test"),
            AgentType::GeneralPurpose,
            Model::Sonnet4,
        );
        // working_directory starts as None

        let data = make_status_data(Some("/home/user/repo"));
        let changed = session.update_from_status_line(&data);

        assert!(
            changed,
            "should return true when cwd goes from None to Some"
        );
        assert_eq!(
            session.working_directory.as_deref(),
            Some("/home/user/repo")
        );
    }

    #[test]
    fn test_update_from_status_line_cwd_some_to_none() {
        let mut session = SessionDomain::new(
            SessionId::new("test"),
            AgentType::GeneralPurpose,
            Model::Sonnet4,
        );
        session.working_directory = Some("/home/user/repo".to_string());

        let data = make_status_data(None);
        let changed = session.update_from_status_line(&data);

        assert!(
            !changed,
            "should return false when incoming cwd is None (partial update)"
        );
        assert_eq!(
            session.working_directory.as_deref(),
            Some("/home/user/repo"),
            "should preserve existing cwd when incoming is None"
        );
    }
}