treeship-core 0.24.0

Portable trust receipts for agent workflows - core library
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
//! Session Receipt composer.
//!
//! Builds the canonical Session Receipt JSON from session events,
//! artifact store, and Merkle tree. The receipt is the composed
//! package-level artifact that unifies an entire session.

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::merkle::{InclusionProof, MerkleTree};

use super::event::SessionEvent;
use super::graph::AgentGraph;
use super::manifest::{
    HostInfo, LifecycleMode, Participants, RoomInfo, SessionManifest, SessionStatus, ToolInfo,
};
use super::render::RenderConfig;
use super::side_effects::SideEffects;

/// Receipt type identifier.
pub const RECEIPT_TYPE: &str = "treeship/session-receipt/v1";

/// Current receipt schema version. Receipts without this field are treated
/// as schema "0" and verified under legacy rules (pre-v0.9.0 shape).
pub const RECEIPT_SCHEMA_VERSION: &str = "1";

// ── Top-level receipt ────────────────────────────────────────────────

/// The complete Session Receipt.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionReceipt {
    /// Always "treeship/session-receipt/v1".
    #[serde(rename = "type")]
    pub type_: String,

    /// Schema version. Absent on pre-v0.9.0 receipts (treated as "0").
    /// Set to "1" for v0.9.0+ receipts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub schema_version: Option<String>,

    pub session: SessionSection,
    pub participants: Participants,
    pub hosts: Vec<HostInfo>,
    pub tools: Vec<ToolInfo>,
    pub agent_graph: AgentGraph,
    pub timeline: Vec<TimelineEntry>,
    pub side_effects: SideEffects,
    pub artifacts: Vec<ArtifactEntry>,
    pub proofs: ProofsSection,
    pub merkle: MerkleSection,
    pub render: RenderConfig,
    /// Tool usage summary: declared vs actual tools used during the session.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_usage: Option<ToolUsage>,

    /// What each action/v2 in this session was authorized to do, and whether it
    /// stayed inside that.
    ///
    /// Absent when the session contained no action/v2 receipts, which keeps
    /// older receipts byte-identical. Present-but-empty never happens: a
    /// session with nothing to say about authority says nothing, rather than
    /// showing an empty band that reads like a clean bill.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub authority: Option<AuthoritySection>,

    /// Who actually held the signing key, when that is not the actor.
    ///
    /// Absent means self-custody -- the actor signed for itself, which is the
    /// default and the strong case. Present means a service signed on the
    /// actor's behalf, which is a materially weaker claim and has to be
    /// legible as such rather than inferred from context.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub custody: Option<Custody>,
}

/// Who signed, when that is not the actor itself.
///
/// This is a **separate axis from `attestation_class`**, and keeping them
/// separate is the point. `attestation_class` grades how evidence was
/// *captured* (self / runtime / countersigned). Custody grades who held the
/// *key*. They vary independently: a service-mediated room can have excellent
/// runtime-captured evidence and still be custodially signed, and an agent
/// signing for itself can have nothing but its own word.
///
/// Collapsing them is the same error `EffectConfidence` and `EffectFinality`
/// exist to avoid -- one label carrying two unrelated questions, where a
/// reader cannot tell which one a value is answering.
///
/// The distinction is not cosmetic. Under self-custody, forging a
/// participant's action requires that participant's key. Under delegated
/// custody, a compromised service can mint any history it likes for every
/// actor it signs for. Same receipt shape, different threat model, so the
/// receipt says which.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Custody {
    /// Custody mode. Only `delegated` is ever serialized -- self-custody is
    /// represented by the whole section being absent, so existing receipts
    /// stay byte-identical and "no custody block" cannot be misread as
    /// "custody unknown".
    pub mode: CustodyMode,

    /// The identity whose key actually produced the signature, e.g.
    /// `svc://gateway-rooms`. This is who a verifier is really trusting.
    pub signer: String,

    /// The actor the signature is claimed to be *for*, e.g. `agent://fizz`.
    /// A verifier can confirm `signer` signed; it cannot confirm this actor
    /// agreed, and must not present it as though it could.
    pub on_behalf_of: String,

    /// Optional human-readable reason the actor did not sign for itself
    /// (e.g. "browser-mediated room; participants hold no local key").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// How the signature relates to the actor it speaks for.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CustodyMode {
    /// A service signed on the actor's behalf. The actor may hold no key at
    /// all. Upgrade path: the actor registers its own key and joins via
    /// `session invite` / `join` / `countersign`, which produces a
    /// two-signature participant event no service can forge.
    Delegated,
}

impl Custody {
    /// A service signing for an actor that holds no key of its own.
    pub fn delegated(signer: impl Into<String>, on_behalf_of: impl Into<String>) -> Self {
        Self {
            mode: CustodyMode::Delegated,
            signer: signer.into(),
            on_behalf_of: on_behalf_of.into(),
            reason: None,
        }
    }

    /// Attach the reason the actor did not sign for itself.
    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }
}

/// Per-action authority for a session.
///
/// The signature layer answers "was this receipt tampered with". This answers
/// the question underneath it: was the action allowed, by whom, and what could
/// we not check. A session receipt that reports only the former reads as
/// complete while omitting the half a counterparty is actually deciding on.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuthoritySection {
    pub actions: Vec<AuthorityEntry>,
    /// How many action/v2 receipts were judged.
    pub checked: u32,
    /// Actions that fell outside their grant. Any non-zero value is the
    /// headline.
    pub violations: u32,
    /// Actions where some layer could not be checked. Not violations, and not
    /// clean either -- counted separately so neither can hide in the other.
    pub unverified: u32,
    /// Actions run under a grant naming no holder, spendable by anyone who
    /// obtained it.
    pub bearer: u32,
}

/// One action's authority record.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AuthorityEntry {
    pub artifact_id: String,
    /// The action label, e.g. `payments.charge`.
    pub action: String,
    /// `pass` | `unverified` | `fail`.
    pub verdict: String,
    /// Why, in the verifier's own words. Empty on a clean pass.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reasons: Vec<String>,
    /// What the grant admitted.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scope: Vec<String>,
    pub audience: String,
    pub grant_id: String,
    /// Whether the grant named the key entitled to exercise it. `false` means
    /// bearer, and the surface must say so rather than leave it blank.
    pub holder_bound: bool,
    /// `not_claimed` | `holds` | `widened` | `unresolvable`.
    pub delegation: String,
    /// Hops in the resolved chain, when one was claimed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub delegation_hops: Option<u32>,
    /// How far the state change got: `not_attempted` | `initiated` |
    /// `finalized` | `failed` | `indeterminate`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub effect_finality: Option<String>,
    /// Whether anything is still owed: `resolved` | `indefinite` | `pending` |
    /// `breached` | `bad_deadline`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolution: Option<String>,
}

/// Tool authorization and usage summary for the session.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ToolUsage {
    /// Tools declared as authorized (from declaration.json).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub declared: Vec<String>,
    /// Tools actually called during the session with invocation counts.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub actual: Vec<ToolUsageEntry>,
    /// Tools called that were NOT in the declared list.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unauthorized: Vec<String>,
}

/// A single tool's usage count.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolUsageEntry {
    pub tool_name: String,
    pub count: u32,
}

/// Session metadata section of the receipt.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionSection {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    pub mode: LifecycleMode,
    pub started_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ended_at: Option<String>,
    pub status: SessionStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<u64>,
    /// Ship ID this session ran under, parsed from the manifest actor URI
    /// (`ship://<ship_id>`). Absent on pre-v0.9.0 receipts or when the actor
    /// URI was not a ship:// URI (e.g. human://alice for a human-led session).
    /// Cross-verification uses this to check that a receipt and a presented
    /// Agent Certificate reference the same ship.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ship_id: Option<String>,
    /// Structured narrative for human review. All fields optional.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub narrative: Option<Narrative>,
    /// Cumulative input tokens across all agents.
    #[serde(default)]
    pub total_tokens_in: u64,
    /// Cumulative output tokens across all agents.
    #[serde(default)]
    pub total_tokens_out: u64,
    /// Room this session hosted, mirrored from the manifest. Carried here so
    /// `invitation_authority` sits inside the DSSE-signed payload instead of
    /// only in unsigned `session.json` -- see `RoomInfo`'s doc comment for
    /// why an unsigned authority field is a wire-controllable-dispatch-field
    /// risk. Absent for ordinary (non-room) sessions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub room: Option<RoomInfo>,
}

/// Structured narrative for the session summary.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Narrative {
    /// One-line headline: "Verifier refactor completed."
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub headline: Option<String>,
    /// Multi-sentence summary of what happened.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
    /// What should be reviewed before trusting the output.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub review: Option<String>,
}

/// A single timeline entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimelineEntry {
    pub sequence_no: u64,
    pub timestamp: String,
    pub event_id: String,
    pub event_type: String,
    pub agent_instance_id: String,
    pub agent_name: String,
    pub host_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
}

/// An artifact referenced in the session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArtifactEntry {
    pub artifact_id: String,
    pub payload_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub digest: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signed_at: Option<String>,
}

/// Proofs section of the receipt.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProofsSection {
    #[serde(default)]
    pub signature_count: u32,
    #[serde(default)]
    pub signatures_valid: bool,
    #[serde(default)]
    pub merkle_root_valid: bool,
    #[serde(default)]
    pub inclusion_proofs_count: u32,
    #[serde(default)]
    pub zk_proofs_present: bool,
    /// Count of events.jsonl lines that were skipped during read_all
    /// because they failed to deserialize. Set by session::close from
    /// EventLog::read_all_with_stats. Codex adversarial review finding #8:
    /// without this in-band signal, a receipt sealed after malformed
    /// events were silently dropped looks complete to a verifier even
    /// when it isn't. `treeship package verify` surfaces this as a WARN
    /// when nonzero. Defaults to 0; absent on pre-v0.9.6 receipts so
    /// they still verify byte-identical.
    #[serde(default, skip_serializing_if = "is_zero_u32")]
    pub event_log_skipped: u32,
    #[serde(default, skip_serializing_if = "is_zero_u32")]
    pub reconcile_untracked_truncated: u32,
    #[serde(default, skip_serializing_if = "is_zero_u32")]
    pub reconcile_untracked_cap: u32,
    /// AUD-07: the git-diff backstop was unavailable at close even though git
    /// worked at session start (start_commit_sha was captured). A file could
    /// have changed via a non-AgentWroteFile channel and the only backstop
    /// that would have caught it was disabled (`.git` removed, corrupt index,
    /// PATH-poisoned git), so the "Files changed" ledger may be incomplete.
    /// `package verify` WARNs on this. Absent on receipts sealed before this
    /// field so they stay byte-identical.
    #[serde(default, skip_serializing_if = "is_false")]
    pub reconcile_degraded: bool,
}

fn is_zero_u32(n: &u32) -> bool {
    *n == 0
}
fn is_false(b: &bool) -> bool {
    !*b
}

/// Merkle section of the receipt.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MerkleSection {
    pub leaf_count: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub root: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub checkpoint_id: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub inclusion_proofs: Vec<InclusionProofEntry>,
    /// Merkle format version byte. Drives the leaf/internal hash dispatch
    /// at verify time. Absent on pre-v0.10.3 receipts — defaults to `1`
    /// (no domain separation) so v0.10.2 receipts continue to verify.
    /// New receipts always serialize `2` (RFC 9162 domain separation).
    #[serde(default = "crate::merkle::tree::default_merkle_version_v1")]
    pub merkle_version: u8,
}

impl Default for MerkleSection {
    fn default() -> Self {
        // Default newly-constructed sections to v2 — the in-the-wild
        // "default = v1" behavior only triggers when serde fills the
        // field for a JSON that omitted it (legacy receipts).
        Self {
            leaf_count: 0,
            root: None,
            checkpoint_id: None,
            inclusion_proofs: Vec::new(),
            merkle_version: crate::merkle::tree::MERKLE_VERSION_V2,
        }
    }
}

/// A Merkle inclusion proof entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InclusionProofEntry {
    pub artifact_id: String,
    pub leaf_index: usize,
    pub proof: InclusionProof,
}

// ── Composer ─────────────────────────────────────────────────────────

/// Composes a Session Receipt from events and artifacts.
pub struct ReceiptComposer;

impl ReceiptComposer {
    /// Compose a receipt from a session manifest, events, and optional artifact entries.
    pub fn compose(
        manifest: &SessionManifest,
        events: &[SessionEvent],
        artifact_entries: Vec<ArtifactEntry>,
    ) -> SessionReceipt {
        Self::compose_with_custody(manifest, events, artifact_entries, None)
    }

    /// Compose a receipt for a session whose actor did NOT hold the signing
    /// key -- a service signing on its behalf.
    ///
    /// Use this from any surface that mediates for actors who hold no key of
    /// their own (a browser-based room being the motivating case). Passing
    /// `None` is identical to [`compose`]: self-custody is the absence of the
    /// block, so nothing is added to the signed bytes and existing receipts
    /// stay byte-identical.
    ///
    /// Recording it is not optional politeness. A receipt naming
    /// `agent://fizz` when a service actually signed is a lie of omission, and
    /// it is the kind that surfaces in someone else's security review rather
    /// than ours.
    pub fn compose_with_custody(
        manifest: &SessionManifest,
        events: &[SessionEvent],
        artifact_entries: Vec<ArtifactEntry>,
        custody: Option<Custody>,
    ) -> SessionReceipt {
        // Build agent graph
        let agent_graph = AgentGraph::from_events(events);

        // Build side effects
        let side_effects = SideEffects::from_events(events);

        // Build timeline from all events
        let mut timeline: Vec<TimelineEntry> = events
            .iter()
            .map(|e| TimelineEntry {
                sequence_no: e.sequence_no,
                timestamp: e.timestamp.clone(),
                event_id: e.event_id.clone(),
                event_type: event_type_label(&e.event_type),
                agent_instance_id: e.agent_instance_id.clone(),
                agent_name: e.agent_name.clone(),
                host_id: e.host_id.clone(),
                summary: event_summary(&e.event_type),
            })
            .collect();

        // Sort by (timestamp, sequence_no, event_id) for determinism
        timeline.sort_by(|a, b| {
            a.timestamp
                .cmp(&b.timestamp)
                .then(a.sequence_no.cmp(&b.sequence_no))
                .then(a.event_id.cmp(&b.event_id))
        });

        // Compute participants from graph
        let participants = compute_participants(&agent_graph, manifest);

        // Compute hosts and tools from events
        let hosts = compute_hosts(events, &manifest.hosts);
        let tools = compute_tools(events, &manifest.tools);

        // Compute duration from the session close event if present
        let duration_ms = events.iter().find_map(|e| {
            if let super::event::EventType::SessionClosed { duration_ms, .. } = &e.event_type {
                *duration_ms
            } else {
                None
            }
        });

        // Build Merkle tree from artifact IDs
        let (merkle_section, merkle_tree) = build_merkle(&artifact_entries);

        // Proofs section. zk_proofs_present defaults to false here;
        // the CLI caller sets it to true after compose if proof files
        // exist in the session directory.
        let proofs = ProofsSection {
            signature_count: artifact_entries.len() as u32,
            // AUD-01: compose does NOT run a signature-verification pass over
            // the artifacts, so this must not claim signatures were verified.
            // A `true` here was a self-asserted "valid" flag baked into the
            // signed receipt that a consumer could mistake for an independent
            // verification result. It stays false unless a real verify pass
            // sets it.
            signatures_valid: false,
            merkle_root_valid: merkle_tree.is_some(),
            inclusion_proofs_count: merkle_section.inclusion_proofs.len() as u32,
            zk_proofs_present: false,
            event_log_skipped: 0, // Set by caller after compose (Codex #8)
            reconcile_untracked_truncated: 0,
            reconcile_untracked_cap: 0,
            reconcile_degraded: false, // Set by caller after compose (AUD-07)
        };

        // Compute cost/token totals from agent graph
        // Cost is deliberately not aggregated. See event.rs comment.
        let total_tokens_in: u64 = agent_graph.nodes.iter().map(|n| n.tokens_in).sum();
        let total_tokens_out: u64 = agent_graph.nodes.iter().map(|n| n.tokens_out).sum();

        // Session section
        let session = SessionSection {
            id: manifest.session_id.clone(),
            name: manifest.name.clone(),
            mode: manifest.mode.clone(),
            started_at: manifest.started_at.clone(),
            ended_at: manifest.closed_at.clone(),
            status: manifest.status.clone(),
            duration_ms,
            ship_id: parse_ship_id_from_actor(&manifest.actor),
            narrative: manifest.summary.as_ref().map(|s| Narrative {
                headline: manifest.name.clone(),
                summary: Some(s.clone()),
                review: None,
            }),
            total_tokens_in,
            total_tokens_out,
            room: manifest.room.clone(),
        };

        // Render config
        let render = RenderConfig {
            title: manifest.name.clone(),
            theme: None,
            sections: RenderConfig::default_sections(),
            generate_preview: true,
        };

        // Derive tool usage from side effects + manifest authorized_tools
        let tool_usage = derive_tool_usage(&side_effects, &manifest.authorized_tools);

        SessionReceipt {
            type_: RECEIPT_TYPE.into(),
            schema_version: Some(RECEIPT_SCHEMA_VERSION.into()),
            session,
            participants,
            hosts,
            tools,
            agent_graph,
            timeline,
            side_effects,
            artifacts: artifact_entries,
            proofs,
            merkle: merkle_section,
            render,
            tool_usage,
            // Composed from storage by the caller, which is the layer that can
            // load envelopes and run the verifier. The composer sees only
            // manifest + events + artifact metadata.
            authority: None,
            custody,
        }
    }

    /// Produce deterministic canonical JSON bytes from a receipt.
    ///
    /// Uses serde's field-declaration-order serialization for determinism.
    /// The resulting bytes are suitable for hashing.
    pub fn to_canonical_json(receipt: &SessionReceipt) -> Result<Vec<u8>, serde_json::Error> {
        serde_json::to_vec(receipt)
    }

    /// Compute SHA-256 digest of the canonical receipt JSON.
    pub fn digest(receipt: &SessionReceipt) -> Result<String, serde_json::Error> {
        let bytes = Self::to_canonical_json(receipt)?;
        let hash = Sha256::digest(&bytes);
        Ok(format!("sha256:{}", hex::encode(hash)))
    }
}

// ── Helpers ──────────────────────────────────────────────────────────

fn compute_participants(graph: &AgentGraph, manifest: &SessionManifest) -> Participants {
    use std::collections::BTreeSet;

    let mut tool_runtimes: BTreeSet<String> = BTreeSet::new();
    // Count unique agents
    let total_agents = graph.nodes.len() as u32;
    let spawned_subagents = graph.spawn_count();
    let handoffs = graph.handoff_count();
    let max_depth = graph.max_depth();
    let host_ids = graph.host_ids();

    // Collect tool runtimes from events in manifest
    for tool in &manifest.tools {
        if let Some(ref rt) = tool.tool_runtime_id {
            tool_runtimes.insert(rt.clone());
        }
    }

    // Find root agent (depth 0, first started)
    let root = graph
        .nodes
        .iter()
        .filter(|n| n.depth == 0)
        .min_by_key(|n| n.started_at.as_deref().unwrap_or(""))
        .map(|n| n.agent_instance_id.clone());

    // Find final output agent (last completed at max depth or last completed overall)
    let final_output = graph
        .nodes
        .iter()
        .filter(|n| n.completed_at.is_some())
        .max_by_key(|n| n.completed_at.as_deref().unwrap_or(""))
        .map(|n| n.agent_instance_id.clone());

    Participants {
        root_agent_instance_id: root.or(manifest.participants.root_agent_instance_id.clone()),
        final_output_agent_instance_id: final_output
            .or(manifest.participants.final_output_agent_instance_id.clone()),
        total_agents,
        spawned_subagents,
        handoffs,
        max_depth,
        hosts: host_ids.len() as u32,
        tool_runtimes: tool_runtimes.len() as u32,
    }
}

fn compute_hosts(events: &[SessionEvent], manifest_hosts: &[HostInfo]) -> Vec<HostInfo> {
    use std::collections::BTreeMap;

    let mut hosts: BTreeMap<String, HostInfo> = BTreeMap::new();

    // Seed from manifest
    for h in manifest_hosts {
        hosts.insert(h.host_id.clone(), h.clone());
    }

    // Discover from events
    for e in events {
        hosts.entry(e.host_id.clone()).or_insert_with(|| HostInfo {
            host_id: e.host_id.clone(),
            hostname: None,
            os: None,
            arch: None,
        });
    }

    hosts.into_values().collect()
}

fn compute_tools(events: &[SessionEvent], manifest_tools: &[ToolInfo]) -> Vec<ToolInfo> {
    use std::collections::BTreeMap;

    let mut tools: BTreeMap<String, ToolInfo> = BTreeMap::new();

    // Seed from manifest
    for t in manifest_tools {
        tools.insert(t.tool_id.clone(), t.clone());
    }

    // Count tool invocations from events
    for e in events {
        if let super::event::EventType::AgentCalledTool { ref tool_name, .. } = e.event_type {
            let entry = tools.entry(tool_name.clone()).or_insert_with(|| ToolInfo {
                tool_id: tool_name.clone(),
                tool_name: tool_name.clone(),
                tool_runtime_id: e.tool_runtime_id.clone(),
                invocation_count: 0,
            });
            entry.invocation_count += 1;
        }
    }

    tools.into_values().collect()
}

fn build_merkle(artifacts: &[ArtifactEntry]) -> (MerkleSection, Option<MerkleTree>) {
    if artifacts.is_empty() {
        return (MerkleSection::default(), None);
    }

    let mut tree = MerkleTree::new();
    for art in artifacts {
        tree.append(&art.artifact_id);
    }

    let root = tree.root().map(|r| format!("mroot_{}", hex::encode(r)));

    // Build inclusion proofs for each artifact
    let inclusion_proofs: Vec<InclusionProofEntry> = artifacts
        .iter()
        .enumerate()
        .filter_map(|(i, art)| {
            tree.inclusion_proof(i).map(|proof| InclusionProofEntry {
                artifact_id: art.artifact_id.clone(),
                leaf_index: i,
                proof,
            })
        })
        .collect();

    let section = MerkleSection {
        leaf_count: artifacts.len(),
        root,
        checkpoint_id: None,
        inclusion_proofs,
        merkle_version: tree.version(),
    };

    (section, Some(tree))
}

/// Extract the ship_id from an actor URI of the form `ship://<id>`.
/// Returns None for other URI schemes (human://, agent://) or malformed values.
pub fn parse_ship_id_from_actor(actor: &str) -> Option<String> {
    let rest = actor.strip_prefix("ship://")?;
    // Strip any trailing path segment so `ship://ship_abc/foo` -> `ship_abc`.
    let id = rest.split('/').next().unwrap_or(rest);
    if id.is_empty() {
        None
    } else {
        Some(id.to_string())
    }
}

/// Extract a human-readable label from an EventType.
/// Derive tool usage from side effects and the declared authorized tools list.
///
/// Bug Codex caught in adversarial review: previously this function counted
/// only `side_effects.tool_invocations` (built from `EventType::AgentCalledTool`).
/// But Claude Code's PostToolUse hook emits SPECIALIZED events for built-in
/// tools (`agent.wrote_file` for Write/Edit, `agent.completed_process` for
/// Bash, `agent.read_file` for Read, etc) -- those events never landed in
/// `tool_invocations`, so a certificate that omitted "Bash" or "Write"
/// passed cross-verification cleanly even when the agent ran them.
///
/// The fix: also count side effects from specialized event types under
/// canonical tool names that match what an operator would declare in
/// `bounded_actions`. Naming follows Claude Code conventions (Read, Write,
/// Bash, WebFetch) since those are the tools users actually declare. A
/// cert that uses an alternate naming scheme (e.g. `files.write`) needs
/// to declare both for now -- a future TODO is canonical mapping at the
/// cert layer.
/// Side-effect canonical mapping for tool authorization.
///
/// Each entry maps a side-effect bucket to a canonical tool name AND a
/// list of accepted aliases. The canonical name is what gets recorded
/// in `tool_usage.actual`. Any alias from the authorized_tools list
/// counts as authorization for the canonical name.
///
/// Codex round-2 caught two bugs in the round-1 fix:
///
/// 1. The round-1 mapping used Claude-Code TitleCase ("Read", "Write",
///    "Bash") but the existing CLI -- `treeship declare --tools
///    read_file,write_file,bash` per declare.rs:80 and `treeship agent
///    register --tools read_file,write_file,bash` per main.rs:226 --
///    teaches users lowercase snake_case names. So a cert that follows
///    the documented convention got every actual tool flagged as
///    unauthorized. Aliases close that gap: declarations in either
///    convention authorize the same canonical entry.
///
/// 2. The round-1 logic counted side effects regardless of provenance.
///    `git-reconcile` synthetic writes (the backstop layer) registered
///    as tool use even though no actual tool was directly attributed
///    for them. A build script that touched a file made the receipt
///    say "Write tool was used", and the cert had to authorize Write
///    or fail cross-verify -- even though the agent never invoked any
///    Write tool. Below, only direct-attribution sources (`hook`,
///    `mcp`, `shell-wrap`, `session-event-cli`, and untagged legacy
///    events) count toward tool usage. Backstop sources (`git-reconcile`,
///    `daemon-atime`) surface in the receipt's "Files changed" section
///    so the reader sees the change, but they do NOT claim that an
///    agent tool was the proximate cause. See source_attributes_a_tool
///    below for the authoritative allow list.
const TOOL_ALIASES: &[(&str, &[&str])] = &[
    // Canonical first; rest are accepted aliases.
    ("read_file", &["read_file", "Read"]),
    (
        "write_file",
        &[
            "write_file",
            "Write",
            "Edit",
            "MultiEdit",
            "NotebookEdit",
            "edit_file",
        ],
    ),
    ("bash", &["bash", "Bash", "shell"]),
    ("web_fetch", &["web_fetch", "WebFetch", "webfetch"]),
];

/// Returns true iff `source` represents a direct tool attribution that
/// should count toward `tool_usage.actual`.
///
/// Direct attribution sources -- a real tool fired and the channel
/// captured it:
///   - `hook`              integration hook saw the tool fire
///   - `mcp`               promoted from MCP-bridge agent.called_tool
///   - `shell-wrap`        `treeship wrap` captured a shell command
///   - `session-event-cli` `treeship session event` from a hook script.
///                         The Claude Code plugin's PostToolUse hook
///                         calls `treeship session event --type
///                         agent.wrote_file --file X`, and the CLI
///                         tags those as "session-event-cli" -- so
///                         excluding this label would make every
///                         claude-code-plugin event invisible to
///                         cross-verify.
///   - None                legacy untagged event (back-compat)
///
/// Backstop / inference sources -- a file changed but no tool was
/// directly attributed. Surface in the receipt's "Files changed"
/// section so the reader sees the change but they must NOT inflate
/// tool_usage:
///   - `git-reconcile`     git diff at session close
///   - `daemon-atime`      atime-based file detection
fn source_attributes_a_tool(source: Option<&str>) -> bool {
    matches!(
        source,
        None | Some("hook") | Some("mcp") | Some("shell-wrap") | Some("session-event-cli"),
    )
}

/// Counts side effects by canonical tool name, filtering out
/// non-attribution sources (git-reconcile, daemon-atime).
fn count_attributed<'a, F>(
    items: usize,
    source_at: F,
    canonical: &str,
    counts: &mut std::collections::BTreeMap<String, u32>,
) where
    F: Fn(usize) -> Option<&'a str>,
{
    let n: u32 = (0..items)
        .filter(|i| source_attributes_a_tool(source_at(*i)))
        .count() as u32;
    if n > 0 {
        *counts.entry(canonical.to_string()).or_insert(0) += n;
    }
}

fn derive_tool_usage(side_effects: &SideEffects, authorized_tools: &[String]) -> Option<ToolUsage> {
    use std::collections::BTreeMap;

    let total_specialized = side_effects.files_read.len()
        + side_effects.files_written.len()
        + side_effects.processes.len()
        + side_effects.network_connections.len();

    if side_effects.tool_invocations.is_empty()
        && total_specialized == 0
        && authorized_tools.is_empty()
    {
        return None;
    }

    let mut counts: BTreeMap<String, u32> = BTreeMap::new();

    // Generic agent.called_tool events use the tool's actual name.
    // The MCP bridge writes meta.source = "mcp-bridge" (which is not
    // in source_attributes_a_tool's allow list) but tool_invocations
    // come ONLY from agent.called_tool, which is direct attribution
    // by definition -- so count all of them, no source filter applies
    // here. (The bridge tool name is the source.)
    for inv in &side_effects.tool_invocations {
        *counts.entry(inv.tool_name.clone()).or_insert(0) += 1;
    }

    // Specialized side effects, source-filtered: only direct
    // attribution (hook / mcp / shell-wrap / untagged-legacy) counts.
    // git-reconcile and friends surface in the "Files changed" section
    // for the reader but do NOT inflate tool_usage.
    let fr = &side_effects.files_read;
    count_attributed(
        fr.len(),
        |i| fr[i].source.as_deref(),
        "read_file",
        &mut counts,
    );
    let fw = &side_effects.files_written;
    count_attributed(
        fw.len(),
        |i| fw[i].source.as_deref(),
        "write_file",
        &mut counts,
    );
    let pr = &side_effects.processes;
    count_attributed(pr.len(), |i| pr[i].source.as_deref(), "bash", &mut counts);
    // network_connections has no source field today; treat all as
    // attributed (this matches the round-1 behavior since there's no
    // backstop layer producing network entries).
    if !side_effects.network_connections.is_empty() {
        *counts.entry("web_fetch".to_string()).or_insert(0) +=
            side_effects.network_connections.len() as u32;
    }

    let actual: Vec<ToolUsageEntry> = counts
        .iter()
        .map(|(name, &count)| ToolUsageEntry {
            tool_name: name.clone(),
            count,
        })
        .collect();

    // Authorization check uses alias resolution: an actual tool is
    // unauthorized only if NONE of its aliases are in the declared
    // list. So a declaration of "read_file" authorizes both "Read"
    // (Claude convention) and "read_file" (CLI convention) when they
    // produce the canonical "read_file" actual entry.
    let unauthorized = if authorized_tools.is_empty() {
        Vec::new()
    } else {
        let declared_set: std::collections::BTreeSet<&str> =
            authorized_tools.iter().map(|s| s.as_str()).collect();
        counts
            .keys()
            .filter(|actual_name| !is_authorized(actual_name, &declared_set))
            .cloned()
            .collect()
    };

    Some(ToolUsage {
        declared: authorized_tools.to_vec(),
        actual,
        unauthorized,
    })
}

/// Returns true if `actual_name` (or any of its declared aliases) is
/// in the declared set. Aliases mean a cert can use either Claude
/// convention or snake_case CLI convention and still authorize the
/// same canonical bucket.
fn is_authorized(actual_name: &str, declared_set: &std::collections::BTreeSet<&str>) -> bool {
    // Direct hit: the declared set names this tool exactly.
    if declared_set.contains(actual_name) {
        return true;
    }
    // Alias hit: walk the canonical mapping and see if any alias of
    // the canonical bucket the actual_name belongs to is in declared.
    for (canonical, aliases) in TOOL_ALIASES {
        if *canonical == actual_name || aliases.contains(&actual_name) {
            for alias in *aliases {
                if declared_set.contains(*alias) {
                    return true;
                }
            }
            return false;
        }
    }
    false
}

fn event_type_label(et: &super::event::EventType) -> String {
    use super::event::EventType::*;
    match et {
        SessionStarted => "session.started",
        SessionClosed { .. } => "session.closed",
        AgentStarted { .. } => "agent.started",
        AgentSpawned { .. } => "agent.spawned",
        AgentHandoff { .. } => "agent.handoff",
        AgentCollaborated { .. } => "agent.collaborated",
        AgentReturned { .. } => "agent.returned",
        AgentCompleted { .. } => "agent.completed",
        AgentFailed { .. } => "agent.failed",
        AgentCalledTool { .. } => "agent.called_tool",
        AgentReadFile { .. } => "agent.read_file",
        AgentWroteFile { .. } => "agent.wrote_file",
        AgentOpenedPort { .. } => "agent.opened_port",
        AgentConnectedNetwork { .. } => "agent.connected_network",
        AgentStartedProcess { .. } => "agent.started_process",
        AgentCompletedProcess { .. } => "agent.completed_process",
        AgentDecision { .. } => "agent.decision",
    }
    .into()
}

/// Optional human-readable summary from an EventType.
fn event_summary(et: &super::event::EventType) -> Option<String> {
    use super::event::EventType::*;
    match et {
        SessionStarted => Some("Session started".into()),
        SessionClosed { summary, .. } => summary.clone().or(Some("Session closed".into())),
        AgentSpawned { reason, .. } => reason.clone(),
        AgentHandoff {
            from_agent_instance_id,
            to_agent_instance_id,
            ..
        } => Some(format!(
            "{from_agent_instance_id} -> {to_agent_instance_id}"
        )),
        AgentCalledTool { tool_name, .. } => Some(format!("Called {tool_name}")),
        AgentReadFile { file_path, .. } => Some(format!("Read {file_path}")),
        AgentWroteFile { file_path, .. } => Some(format!("Wrote {file_path}")),
        AgentOpenedPort { port, .. } => Some(format!("Opened port {port}")),
        AgentConnectedNetwork { destination, .. } => Some(format!("Connected to {destination}")),
        AgentStartedProcess { process_name, .. } => Some(format!("Started {process_name}")),
        AgentCompletedProcess {
            process_name,
            exit_code,
            ..
        } => Some(format!(
            "Completed {process_name} (exit {})",
            exit_code.unwrap_or(-1)
        )),
        AgentCompleted { termination_reason } => termination_reason
            .clone()
            .or(Some("Agent completed".into())),
        AgentFailed { reason } => reason.clone().or(Some("Agent failed".into())),
        AgentDecision {
            model,
            summary,
            provider,
            ..
        } => {
            let mut parts = Vec::new();
            if let Some(s) = summary {
                parts.push(s.clone());
            }
            if let Some(m) = model {
                parts.push(format!("model: {m}"));
            }
            if let Some(p) = provider {
                parts.push(format!("via {p}"));
            }
            if parts.is_empty() {
                Some("LLM decision".into())
            } else {
                Some(parts.join(" | "))
            }
        }
        _ => None,
    }
}

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

    fn make_manifest() -> SessionManifest {
        SessionManifest::new(
            "ssn_001".into(),
            "agent://test".into(),
            "2026-04-05T08:00:00Z".into(),
            1743843600000,
        )
    }

    /// Module-level event constructor so the tool-authorization regression
    /// tests below can reuse it without each redefining the closure.
    fn mk(seq: u64, inst: &str, et: EventType) -> SessionEvent {
        SessionEvent {
            session_id: "ssn_001".into(),
            event_id: format!("evt_{:016x}", seq),
            timestamp: format!("2026-04-05T08:{:02}:00Z", seq),
            sequence_no: seq,
            trace_id: "trace_1".into(),
            span_id: format!("span_{seq}"),
            parent_span_id: None,
            agent_id: format!("agent://{inst}"),
            agent_instance_id: inst.into(),
            agent_name: inst.into(),
            agent_role: None,
            host_id: "host_1".into(),
            tool_runtime_id: None,
            event_type: et,
            artifact_ref: None,
            meta: None,
        }
    }

    fn make_events() -> Vec<SessionEvent> {
        vec![
            mk(0, "root", EventType::SessionStarted),
            mk(
                1,
                "root",
                EventType::AgentStarted {
                    parent_agent_instance_id: None,
                },
            ),
            mk(
                2,
                "worker",
                EventType::AgentSpawned {
                    spawned_by_agent_instance_id: "root".into(),
                    reason: Some("review".into()),
                },
            ),
            mk(
                3,
                "worker",
                EventType::AgentCalledTool {
                    tool_name: "read_file".into(),
                    tool_input_digest: None,
                    tool_output_digest: None,
                    duration_ms: Some(5),
                },
            ),
            mk(
                4,
                "worker",
                EventType::AgentWroteFile {
                    file_path: "src/fix.rs".into(),
                    digest: None,
                    operation: None,
                    additions: None,
                    deletions: None,
                },
            ),
            mk(
                5,
                "worker",
                EventType::AgentCompleted {
                    termination_reason: None,
                },
            ),
            mk(
                6,
                "root",
                EventType::SessionClosed {
                    summary: Some("Done".into()),
                    duration_ms: Some(360000),
                },
            ),
        ]
    }

    #[test]
    fn compose_receipt() {
        let manifest = make_manifest();
        let events = make_events();
        let artifacts = vec![
            ArtifactEntry {
                artifact_id: "art_001".into(),
                payload_type: "action".into(),
                digest: None,
                signed_at: None,
            },
            ArtifactEntry {
                artifact_id: "art_002".into(),
                payload_type: "action".into(),
                digest: None,
                signed_at: None,
            },
        ];

        let receipt = ReceiptComposer::compose(&manifest, &events, artifacts);

        assert_eq!(receipt.type_, RECEIPT_TYPE);
        assert_eq!(receipt.session.id, "ssn_001");
        assert_eq!(receipt.timeline.len(), 7);
        assert_eq!(receipt.agent_graph.nodes.len(), 2); // root + worker
        assert_eq!(receipt.side_effects.files_written.len(), 1);
        assert_eq!(receipt.merkle.leaf_count, 2);
        assert!(receipt.merkle.root.is_some());
    }

    #[test]
    fn new_receipts_carry_schema_version() {
        let manifest = make_manifest();
        let events = make_events();
        let artifacts = vec![ArtifactEntry {
            artifact_id: "art_001".into(),
            payload_type: "action".into(),
            digest: None,
            signed_at: None,
        }];
        let receipt = ReceiptComposer::compose(&manifest, &events, artifacts);
        assert_eq!(
            receipt.schema_version.as_deref(),
            Some(RECEIPT_SCHEMA_VERSION)
        );
        // And it shows up in canonical JSON.
        let json =
            String::from_utf8(ReceiptComposer::to_canonical_json(&receipt).unwrap()).unwrap();
        assert!(
            json.contains(r#""schema_version":"1""#),
            "missing schema_version: {json}"
        );
    }

    #[test]
    fn legacy_receipt_without_schema_version_round_trips_byte_identical() {
        // Simulate a pre-v0.9.0 receipt by composing one and stripping the
        // schema_version field. Re-serializing must produce byte-identical
        // output so the package-level determinism check keeps passing for
        // old receipts that nobody can re-sign.
        let manifest = make_manifest();
        let events = make_events();
        let artifacts = vec![ArtifactEntry {
            artifact_id: "art_001".into(),
            payload_type: "action".into(),
            digest: None,
            signed_at: None,
        }];
        let mut receipt = ReceiptComposer::compose(&manifest, &events, artifacts);
        receipt.schema_version = None; // mimic a legacy receipt

        let original = ReceiptComposer::to_canonical_json(&receipt).unwrap();
        // Verify the field is omitted, not serialized as null.
        let original_str = std::str::from_utf8(&original).unwrap();
        assert!(
            !original_str.contains("schema_version"),
            "schema_version must be skipped when None"
        );

        let parsed: SessionReceipt = serde_json::from_slice(&original).unwrap();
        assert!(
            parsed.schema_version.is_none(),
            "legacy receipts must parse with schema_version=None"
        );

        let reserialized = ReceiptComposer::to_canonical_json(&parsed).unwrap();
        assert_eq!(
            original, reserialized,
            "legacy receipt must round-trip byte-identical so package determinism check passes"
        );
    }

    #[test]
    fn canonical_json_is_deterministic() {
        let manifest = make_manifest();
        let events = make_events();
        let artifacts = vec![ArtifactEntry {
            artifact_id: "art_001".into(),
            payload_type: "action".into(),
            digest: None,
            signed_at: None,
        }];

        let r1 = ReceiptComposer::compose(&manifest, &events, artifacts.clone());
        let r2 = ReceiptComposer::compose(&manifest, &events, artifacts);

        let j1 = ReceiptComposer::to_canonical_json(&r1).unwrap();
        let j2 = ReceiptComposer::to_canonical_json(&r2).unwrap();
        assert_eq!(j1, j2);

        let d1 = ReceiptComposer::digest(&r1).unwrap();
        let d2 = ReceiptComposer::digest(&r2).unwrap();
        assert_eq!(d1, d2);
    }

    // ── Tool authorization regression tests (Codex finding #1) ──
    //
    // Specialized event types (agent.wrote_file, agent.completed_process,
    // agent.read_file) must contribute to tool_usage.actual so that a
    // certificate's bounded_actions list can correctly flag unauthorized
    // built-in tool usage. Before this fix, only agent.called_tool fed
    // tool_usage.actual, so a cert that omitted "Bash" still passed even
    // when the agent ran Bash via Claude Code's built-in.

    fn manifest_with_authorized(tools: Vec<&str>) -> SessionManifest {
        let mut m = make_manifest();
        m.authorized_tools = tools.into_iter().map(String::from).collect();
        m
    }

    #[test]
    fn cert_omitting_bash_flags_unauthorized_when_session_runs_bash() {
        // Cert uses CLI-documented snake_case names (declare.rs:80,
        // main.rs:226). Round-2 fix: canonical actual is "bash" not
        // "Bash"; round-1 was flagging mismatches the wrong way.
        let manifest = manifest_with_authorized(vec!["read_file", "write_file"]); // NO bash
        let events = vec![
            mk(0, "root", EventType::SessionStarted),
            mk(
                1,
                "agent",
                EventType::AgentCompletedProcess {
                    process_name: "rm -rf /".into(),
                    exit_code: Some(0),
                    duration_ms: Some(50),
                    command: Some("rm -rf /".into()),
                },
            ),
            mk(
                2,
                "root",
                EventType::SessionClosed {
                    summary: None,
                    duration_ms: Some(1000),
                },
            ),
        ];
        let receipt = ReceiptComposer::compose(&manifest, &events, vec![]);
        let tu = receipt.tool_usage.expect("tool_usage must be populated");
        assert!(
            tu.unauthorized.iter().any(|t| t == "bash"),
            "bash must be flagged as unauthorized when cert omits it; got unauthorized={:?}, actual={:?}",
            tu.unauthorized, tu.actual,
        );
    }

    #[test]
    fn cert_omitting_write_flags_unauthorized_when_session_writes_file() {
        let manifest = manifest_with_authorized(vec!["read_file", "bash"]); // NO write_file
        let events = vec![
            mk(0, "root", EventType::SessionStarted),
            mk(
                1,
                "agent",
                EventType::AgentWroteFile {
                    file_path: "src/secret.rs".into(),
                    digest: None,
                    operation: Some("modified".into()),
                    additions: Some(10),
                    deletions: Some(0),
                },
            ),
            mk(
                2,
                "root",
                EventType::SessionClosed {
                    summary: None,
                    duration_ms: Some(1000),
                },
            ),
        ];
        let receipt = ReceiptComposer::compose(&manifest, &events, vec![]);
        let tu = receipt.tool_usage.expect("tool_usage must be populated");
        assert!(
            tu.unauthorized.iter().any(|t| t == "write_file"),
            "write_file must be flagged as unauthorized when cert omits it; got unauthorized={:?}, actual={:?}",
            tu.unauthorized, tu.actual,
        );
    }

    #[test]
    fn cert_includes_read_write_bash_passes_clean_when_all_used() {
        let manifest = manifest_with_authorized(vec!["read_file", "write_file", "bash"]);
        let events = vec![
            mk(0, "root", EventType::SessionStarted),
            mk(
                1,
                "agent",
                EventType::AgentReadFile {
                    file_path: "package.json".into(),
                    digest: None,
                },
            ),
            mk(
                2,
                "agent",
                EventType::AgentWroteFile {
                    file_path: "src/lib.rs".into(),
                    digest: None,
                    operation: Some("modified".into()),
                    additions: Some(5),
                    deletions: Some(2),
                },
            ),
            mk(
                3,
                "agent",
                EventType::AgentCompletedProcess {
                    process_name: "bun test".into(),
                    exit_code: Some(0),
                    duration_ms: Some(2000),
                    command: Some("bun test".into()),
                },
            ),
            mk(
                4,
                "root",
                EventType::SessionClosed {
                    summary: None,
                    duration_ms: Some(5000),
                },
            ),
        ];
        let receipt = ReceiptComposer::compose(&manifest, &events, vec![]);
        let tu = receipt.tool_usage.expect("tool_usage must be populated");
        assert!(
            tu.unauthorized.is_empty(),
            "all tools declared in cert should pass clean; got unauthorized={:?}",
            tu.unauthorized,
        );
        // The actual list uses canonical lowercase names that match what
        // `treeship declare --tools` and `treeship agent register --tools`
        // teach (declare.rs:80, main.rs:226).
        let actual_names: std::collections::BTreeSet<String> =
            tu.actual.iter().map(|e| e.tool_name.clone()).collect();
        assert!(actual_names.contains("read_file"));
        assert!(actual_names.contains("write_file"));
        assert!(actual_names.contains("bash"));
    }

    #[test]
    fn webfetch_unauthorized_flagged_when_cert_omits_it() {
        let manifest = manifest_with_authorized(vec!["read_file", "write_file", "bash"]); // NO web_fetch
        let events = vec![
            mk(0, "root", EventType::SessionStarted),
            mk(
                1,
                "agent",
                EventType::AgentConnectedNetwork {
                    destination: "evil.example.com".into(),
                    port: Some(443),
                },
            ),
            mk(
                2,
                "root",
                EventType::SessionClosed {
                    summary: None,
                    duration_ms: Some(1000),
                },
            ),
        ];
        let receipt = ReceiptComposer::compose(&manifest, &events, vec![]);
        let tu = receipt.tool_usage.expect("tool_usage must be populated");
        assert!(
            tu.unauthorized.iter().any(|t| t == "web_fetch"),
            "web_fetch must be flagged as unauthorized when cert omits it; got unauthorized={:?}",
            tu.unauthorized,
        );
    }

    // ── Round-2 fix tests: alias matching + source filtering ──

    fn evt_with_source(event_type: EventType, source: &str) -> SessionEvent {
        let mut e = mk(99, "agent", event_type);
        e.meta = Some(serde_json::json!({"source": source}));
        e
    }

    #[test]
    fn titlecase_cert_authorizes_canonical_snake_actuals_via_alias() {
        // Operator declares Claude convention. Aliases map "Read" to
        // canonical "read_file", "Write" to "write_file", etc.
        let manifest = manifest_with_authorized(vec!["Read", "Write", "Bash"]);
        let events = vec![
            mk(0, "root", EventType::SessionStarted),
            mk(
                1,
                "agent",
                EventType::AgentReadFile {
                    file_path: "x".into(),
                    digest: None,
                },
            ),
            mk(
                2,
                "agent",
                EventType::AgentWroteFile {
                    file_path: "y".into(),
                    digest: None,
                    operation: None,
                    additions: None,
                    deletions: None,
                },
            ),
            mk(
                3,
                "agent",
                EventType::AgentCompletedProcess {
                    process_name: "z".into(),
                    exit_code: Some(0),
                    duration_ms: Some(1),
                    command: None,
                },
            ),
            mk(
                4,
                "root",
                EventType::SessionClosed {
                    summary: None,
                    duration_ms: Some(1000),
                },
            ),
        ];
        let tu = ReceiptComposer::compose(&manifest, &events, vec![])
            .tool_usage
            .unwrap();
        assert!(
            tu.unauthorized.is_empty(),
            "TitleCase declarations must authorize canonical snake_case actuals via aliases; \
             got unauthorized={:?}",
            tu.unauthorized,
        );
    }

    #[test]
    fn edit_alias_authorizes_specialized_wrote_file() {
        // Operator declares "Edit" specifically. post-tool-use.sh
        // emits agent.wrote_file for Edit/MultiEdit alike, so the
        // canonical actual is "write_file". Edit is in the write_file
        // alias list, so the cert authorizes.
        let manifest = manifest_with_authorized(vec!["Edit"]);
        let events = vec![
            mk(0, "root", EventType::SessionStarted),
            mk(
                1,
                "agent",
                EventType::AgentWroteFile {
                    file_path: "x".into(),
                    digest: None,
                    operation: None,
                    additions: None,
                    deletions: None,
                },
            ),
            mk(
                2,
                "root",
                EventType::SessionClosed {
                    summary: None,
                    duration_ms: Some(1000),
                },
            ),
        ];
        let tu = ReceiptComposer::compose(&manifest, &events, vec![])
            .tool_usage
            .unwrap();
        assert!(
            tu.unauthorized.is_empty(),
            "Edit alias must authorize write_file"
        );
    }

    #[test]
    fn git_reconcile_writes_dont_count_toward_tool_usage() {
        // Backstop evidence -- not direct tool attribution.
        // A git-reconciled change must NOT make the cert require
        // write_file authorization, because no Write tool was invoked.
        let manifest = manifest_with_authorized(vec!["read_file"]);
        let events = vec![
            mk(0, "root", EventType::SessionStarted),
            evt_with_source(
                EventType::AgentWroteFile {
                    file_path: "CHANGELOG.md".into(),
                    digest: None,
                    operation: Some("modified".into()),
                    additions: Some(7),
                    deletions: Some(2),
                },
                "git-reconcile",
            ),
            mk(
                2,
                "root",
                EventType::SessionClosed {
                    summary: None,
                    duration_ms: Some(1000),
                },
            ),
        ];
        let tu = ReceiptComposer::compose(&manifest, &events, vec![])
            .tool_usage
            .unwrap();
        assert!(
            !tu.unauthorized.iter().any(|t| t == "write_file"),
            "git-reconcile entries must NOT count toward tool_usage; \
             got unauthorized={:?}, actual={:?}",
            tu.unauthorized,
            tu.actual,
        );
        let actual_names: std::collections::BTreeSet<String> =
            tu.actual.iter().map(|e| e.tool_name.clone()).collect();
        assert!(
            !actual_names.contains("write_file"),
            "actual must not include backstop-only writes"
        );
    }

    // session-event-cli is a direct-attribution source -- the standard
    // label the CLI stamps on events emitted by claude-code-plugin's
    // PostToolUse hook. So it counts toward tool_usage.actual just like
    // hook/mcp/shell-wrap do. The end-to-end test for this lives in
    // the targeted acceptance suite (T1) rather than as a unit test
    // here, because it requires the full event-emission + receipt-
    // composition pipeline running through `treeship session event`.

    #[test]
    fn hook_emitted_writes_still_count_toward_tool_usage() {
        // Positive case: regular hook-emitted write IS direct attribution.
        let manifest = manifest_with_authorized(vec!["read_file"]); // NO write_file
        let events = vec![
            mk(0, "root", EventType::SessionStarted),
            evt_with_source(
                EventType::AgentWroteFile {
                    file_path: "src/x.rs".into(),
                    digest: None,
                    operation: None,
                    additions: None,
                    deletions: None,
                },
                "hook",
            ),
            mk(
                2,
                "root",
                EventType::SessionClosed {
                    summary: None,
                    duration_ms: Some(1000),
                },
            ),
        ];
        let tu = ReceiptComposer::compose(&manifest, &events, vec![])
            .tool_usage
            .unwrap();
        assert!(
            tu.unauthorized.iter().any(|t| t == "write_file"),
            "hook-emitted writes MUST count toward tool_usage; got unauthorized={:?}",
            tu.unauthorized,
        );
    }

    #[test]
    fn legacy_untagged_writes_count_for_back_compat() {
        // Pre-v0.9.6 events have no source tag. Treat as attributed
        // (back-compat: receipts produced before source labeling existed).
        let manifest = manifest_with_authorized(vec!["read_file"]); // NO write_file
        let events = vec![
            mk(0, "root", EventType::SessionStarted),
            mk(
                1,
                "agent",
                EventType::AgentWroteFile {
                    file_path: "x".into(),
                    digest: None,
                    operation: None,
                    additions: None,
                    deletions: None,
                },
            ),
            mk(
                2,
                "root",
                EventType::SessionClosed {
                    summary: None,
                    duration_ms: Some(1000),
                },
            ),
        ];
        let tu = ReceiptComposer::compose(&manifest, &events, vec![])
            .tool_usage
            .unwrap();
        assert!(
            tu.unauthorized.iter().any(|t| t == "write_file"),
            "legacy untagged writes must count for back-compat",
        );
    }
}

#[cfg(test)]
mod custody_tests {
    use super::*;

    /// Self-custody is absence, not a value. Existing receipts must stay
    /// byte-identical, and a missing block must not read as "unknown".
    #[test]
    fn self_custody_serializes_to_nothing() {
        let c: Option<Custody> = None;
        let json = serde_json::to_string(&serde_json::json!({ "custody": c })).unwrap();
        assert_eq!(json, r#"{"custody":null}"#);
        // ...and on the real struct the field is skipped entirely:
        #[derive(Serialize)]
        struct Holder {
            #[serde(default, skip_serializing_if = "Option::is_none")]
            custody: Option<Custody>,
        }
        let s = serde_json::to_string(&Holder { custody: None }).unwrap();
        assert_eq!(s, "{}", "self-custody must add no bytes");
    }

    /// A delegated receipt must name BOTH parties. Recording only the actor
    /// would present a service signature as the actor's own; recording only
    /// the signer would lose who the claim is about.
    #[test]
    fn delegated_custody_names_signer_and_subject() {
        let c = Custody::delegated("svc://gateway-rooms", "agent://fizz")
            .with_reason("browser-mediated room; participants hold no local key");
        let v = serde_json::to_value(&c).unwrap();
        assert_eq!(v["mode"], "delegated");
        assert_eq!(v["signer"], "svc://gateway-rooms");
        assert_eq!(v["on_behalf_of"], "agent://fizz");
        assert!(v["reason"].as_str().unwrap().contains("no local key"));
    }

    #[test]
    fn reason_is_optional_and_omitted_when_unset() {
        let c = Custody::delegated("svc://x", "agent://y");
        let v = serde_json::to_value(&c).unwrap();
        assert!(v.get("reason").is_none(), "unset reason must not serialize");
    }

    /// Round-trips through JSON unchanged -- this rides inside signed bytes,
    /// so a lossy field would break verification, not just display.
    #[test]
    fn custody_round_trips() {
        let c = Custody::delegated("svc://gateway-rooms", "agent://fizz").with_reason("r");
        let back: Custody = serde_json::from_str(&serde_json::to_string(&c).unwrap()).unwrap();
        assert_eq!(c, back);
    }

    /// Custody and attestation_class are independent axes. A service-signed
    /// receipt can carry runtime-captured evidence -- good evidence, delegated
    /// key -- and the two labels must not be inferred from each other.
    #[test]
    fn custody_is_orthogonal_to_evidence_capture() {
        let receipt = serde_json::json!({
            "attestation_class": "runtime",
            "custody": Custody::delegated("svc://gateway-rooms", "agent://fizz"),
        });
        assert_eq!(receipt["attestation_class"], "runtime");
        assert_eq!(receipt["custody"]["mode"], "delegated");
    }
}

#[cfg(test)]
mod custody_wiring_tests {
    use super::*;

    /// The schema is the gate: `validate("session.v1", ..)` runs fail-closed
    /// before anything is signed, so a custody block the schema rejects would
    /// mean a service literally cannot emit an honest receipt. That is the
    /// state this test exists to prevent -- the type existed for a while with
    /// no schema entry, which made it decorative.
    #[test]
    fn a_delegated_receipt_passes_predicate_validation() {
        let payload = serde_json::json!({
            "session_id": "ssn_room_demo",
            "actor": "agent://fizz",
            "outcome": "completed",
            "started_at": "2026-08-10T10:00:00Z",
            "closed_at": "2026-08-10T10:30:00Z",
            "attestation_class": "runtime",
            "receipt_digest": format!("sha256:{}", "a".repeat(64)),
            "custody": {
                "mode": "delegated",
                "signer": "svc://gateway-rooms",
                "on_behalf_of": "agent://fizz",
                "reason": "browser-mediated room; participants hold no local key"
            }
        });
        crate::predicates::validate("session.v1", Some(&payload))
            .expect("a delegated-custody receipt must validate");
    }

    /// Self-custody stays byte-identical: no block, no schema objection.
    #[test]
    fn a_self_custody_receipt_still_validates() {
        let payload = serde_json::json!({
            "session_id": "ssn_plain",
            "actor": "ship://local",
            "outcome": "completed",
            "started_at": "2026-08-10T10:00:00Z",
            "closed_at": "2026-08-10T10:30:00Z",
            "attestation_class": "self",
            "receipt_digest": format!("sha256:{}", "b".repeat(64)),
        });
        crate::predicates::validate("session.v1", Some(&payload))
            .expect("a self-custody receipt must validate");
    }

    /// A custody block missing `signer` names no one -- recording "delegated"
    /// without saying delegated to WHOM is worse than omitting it, because it
    /// tells a reader the actor did not sign while withholding who did.
    ///
    /// Core's validator does NOT catch this: it is documented as "a small,
    /// dependency-free structural check" over TOP-LEVEL required fields and
    /// does not recurse into nested objects. The `required` list inside the
    /// custody schema is therefore documentation for consumers running a full
    /// JSON Schema validator, not something core enforces.
    ///
    /// What actually holds the invariant is the Rust type: `signer` and
    /// `on_behalf_of` are `String`, not `Option<String>`, so a `Custody`
    /// cannot be constructed without them. This test pins that, and pins the
    /// validator's limit so nobody assumes a guarantee that is not there.
    #[test]
    fn custody_requires_a_signer_by_type_not_by_validator() {
        // The type will not let you omit it.
        let c = Custody::delegated("svc://gateway-rooms", "agent://fizz");
        assert!(!c.signer.is_empty());
        assert!(!c.on_behalf_of.is_empty());

        // And core's validator, by design, does not police nested shape --
        // asserting otherwise would encode a guarantee we do not offer.
        let payload = serde_json::json!({
            "session_id": "ssn_bad",
            "actor": "agent://fizz",
            "outcome": "completed",
            "started_at": "2026-08-10T10:00:00Z",
            "closed_at": "2026-08-10T10:30:00Z",
            "attestation_class": "self",
            "receipt_digest": format!("sha256:{}", "c".repeat(64)),
            "custody": { "mode": "delegated", "on_behalf_of": "agent://fizz" }
        });
        assert!(
            crate::predicates::validate("session.v1", Some(&payload)).is_ok(),
            "core validates top-level fields only; if this starts failing the \
             validator gained nested checking and the doc comment above is stale"
        );
    }

    /// `compose_with_custody(.., None)` must be indistinguishable from
    /// `compose` -- otherwise adding the parameter silently changed every
    /// existing receipt.
    #[test]
    fn none_custody_composes_identically() {
        let m = SessionManifest::new(
            "ssn_x".into(),
            "ship://local".into(),
            "2026-08-10T10:00:00Z".into(),
            1_760_000_000_000,
        );
        let a = ReceiptComposer::compose(&m, &[], Vec::new());
        let b = ReceiptComposer::compose_with_custody(&m, &[], Vec::new(), None);
        assert_eq!(
            serde_json::to_string(&a).unwrap(),
            serde_json::to_string(&b).unwrap()
        );
    }

    #[test]
    fn delegated_custody_reaches_the_composed_receipt() {
        let m = SessionManifest::new(
            "ssn_y".into(),
            "agent://fizz".into(),
            "2026-08-10T10:00:00Z".into(),
            1_760_000_000_000,
        );
        let r = ReceiptComposer::compose_with_custody(
            &m,
            &[],
            Vec::new(),
            Some(Custody::delegated("svc://gateway-rooms", "agent://fizz")),
        );
        let v = serde_json::to_value(&r).unwrap();
        assert_eq!(v["custody"]["signer"], "svc://gateway-rooms");
        assert_eq!(v["custody"]["on_behalf_of"], "agent://fizz");
    }
}