canwu-api 0.13.0

Public Rust API for the Canwu deterministic historical simulation engine
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
//! Public programmatic, query, semantic-agent, explanation, and debug interfaces.

#![allow(clippy::missing_errors_doc, clippy::module_name_repetitions)]

pub use canwu_core::{
    ArmyId, BoundaryId, CommandAttemptId, CommandId, CommandRequestId, CoreEntityKind,
    DecisionRequestId, DecisionTicketId, DecisionTraceId, DomainEntityKindClass, DomainEntityType,
    DomainKindClass, DomainRecordKind, DomainRecordRef, DomainRecordType, DomainRecordVersionRef,
    DomainRecordVersionSource, DomainValueKindClass, DomainValueType, EntityRef, EvaluationTerm,
    EvaluationTraceRecord, EventId, EvidenceRef, GovernmentId, HolderKnowledgeRecordId, IngressId,
    KnowledgeHolderPolicy, KnowledgeHolderRef, KnowledgeRecordId, KnowledgeRecordKind,
    KnowledgeSchemaId, LetterId, OrganizationId, PersonId, RandomDrawId, ResourceId, RouteId,
    SchemaRegistry, SchemaRegistryError, SimulationGranularity, TerritoryId, TypeSchema,
    TypedDomainRecordRef,
};
pub use canwu_event::{CauseRef, EventAudience, EventKind, EventKindError, SimEvent};
pub use canwu_knowledge::{
    ActorKnowledge, ArmyKnowledge, EstimateRange, KnowledgeCursor, KnowledgeHistoryView,
    KnowledgeOrigin, KnowledgeQuery, KnowledgeQueryError, KnowledgeQueryResult, KnowledgeReadCut,
    KnowledgeRecord, KnowledgeRecordDraft, KnowledgeRecordView, KnowledgeSnapshot, KnowledgeSource,
    KnowledgeSubject, KnowledgeSubjectTarget, MAX_KNOWLEDGE_PAGE_SIZE,
};
pub use canwu_routing::{
    DepartureSlot, DurationSample, PlanningSnapshot, ROUTING_ALGORITHM_VERSION, RouteCost,
    RouteLeg, RoutePlan, RoutingAlgorithm, RoutingCache, RoutingConnection, RoutingConnectionRef,
    RoutingEndpoint, RoutingEndpointKind, RoutingError, RoutingNetwork, RoutingNodeRef,
    RoutingPolicy, RoutingRequest, TransferMode, TraversalModel, plan_route,
};
use canwu_sim::Simulation;
pub use canwu_sim::{
    ADMISSION_CURSOR_FORMAT_VERSION, ArchiveProvider, ArchiveReachabilityManifest, ArchiveStore,
    ArchiveStoreOutcome, ArchivedEvidenceLocator, ArchivedEvidenceReceipt,
    ArchivedPluginIngressProvenance, ArchivedSegmentHeader, Army, ArtifactManifest, BoundaryChange,
    BoundaryContext, BoundaryDirective, BoundaryEmission, BoundaryEmissionKind,
    BoundaryEvaluationTrace, BoundaryIngressGeneration, BoundaryKnowledgeChange,
    BoundaryPersonAvailabilityChange, BoundaryPersonCreation, BoundaryPhase, BoundaryProposal,
    BoundaryReceipt, BoundaryRecord, BoundaryRequest, BoundarySystemContract,
    BoundarySystemHandler, CHECKPOINT_JOURNAL_FORMAT_VERSION, COMMITMENT_FORMAT_VERSION,
    CONTROLLER_AUTHORITY_UNAVAILABLE_REASON, CanwuError, CheckpointJournal, Command,
    CommandAttemptOutcome, CommandAttemptRecord, CommandAuthority, CommandContext, CommandEnvelope,
    CommandIngress, CommandOutcome, CommandPolicyContext, CommandReceipt, CommandRecord,
    CommandRejection, CommandRequest, CommitmentRoots, CompactedSimulation, ControllerDecision,
    ControllerPolicy, CreatedPerson, CustodyState, DECISION_ARCHIVE_BUCKET_PAGE_FORMAT_VERSION,
    DECISION_ARCHIVE_FORMAT_VERSION, DECISION_MAKER_UNAVAILABLE_REASON,
    DECISION_REQUEST_COMMITMENT_DOMAIN, DecisionAction, DecisionArchiveBlob,
    DecisionArchiveBucketPage, DecisionArchiveProvider, DecisionArchiveReceipt,
    DecisionArchiveRecord, DecisionArchiveStore, DecisionArchiveStoreOutcome,
    DecisionAttemptErrorCode, DecisionAttemptOutcome, DecisionAttemptRecord, DecisionAuthority,
    DecisionContext, DecisionController, DecisionControllerBinding, DecisionError,
    DecisionErrorCode, DecisionEvaluation, DecisionExternalEvidence, DecisionFactorContribution,
    DecisionHistoryCursor, DecisionHistoryKey, DecisionHistoryLocation, DecisionHistoryPage,
    DecisionHistoryQueryBudget, DecisionHotState, DecisionIngressRequest,
    DecisionLocatorScaleMetrics, DecisionMutation, DecisionOption, DecisionOptionEvaluation,
    DecisionOptionWeight, DecisionOrigin, DecisionOutcome, DecisionPolicy, DecisionPolicyIdentity,
    DecisionPolicyKind, DecisionRandomEvidence, DecisionRule, DecisionStage, DecisionState,
    DecisionTicket, DecisionTicketDraft, DecisionTicketState, DecisionTrace, DemoIds, DomainRecord,
    DomainRecordChange, DomainRecordClass, DomainRecordCommitmentRoots, DomainRecordDraft,
    DomainRecordLifecycle, DomainRecordMutation, DomainRecordMutationPolicy, DomainRecordOperation,
    DomainRecordPage, DomainRecordPageRoots, DomainRecordSchema, DomainReference,
    DomainReferenceSchema, DomainReferenceTarget, DomainReferenceTargetKind, ENGINE_VERSION,
    ErrorCode, EvaluationLimitsV1, EvidenceArchiveIndex, EvidenceCursor, EvidenceIndexEntry,
    EvidenceItemLocator, EvidenceJournalKind, EvidenceJournalRoots, EvidenceJournalSegment,
    EvidenceNestedLocator, EvidenceSealToken, ExternalDecisionOption, ExternalDecisionRequest,
    ExternalDecisionResponse, ExternalPolicy, Government, GuardedUtilityPolicy,
    HumanDecisionResponse, HumanPolicy, IDENTITY_EVIDENCE_DEPENDENCIES_FIELD,
    IDENTITY_EVIDENCE_DEPENDENCIES_FORMAT_VERSION, IdentityEvidenceDependenciesV1,
    IngressCancellationAuthority, IngressClass, IngressPayload, IngressReceipt, IngressRecord,
    InteractionPolicy, Issuer, KnowledgeLimitsV1, KnowledgeSubjectSchema,
    KnowledgeSubjectTargetKind, KnowledgeWriteGrant, LetterCargo, LetterStatus, LifeState,
    LlmModelIdentity, LlmPolicy, MAX_DECISION_ARCHIVE_BATCH_ENTRIES,
    MAX_DECISION_HISTORY_PAGE_BYTES, MAX_DECISION_HISTORY_PAGE_SIZE,
    MAX_INGRESS_CANCELLATION_REASON_BYTES, MAX_OWNER_AUTHORIZED_MUTATIONS,
    MAX_OWNER_AUTHORIZED_PARTICIPANTS, MAX_STATE_DELTA_PAGES, MAX_STATE_PAGE_BYTES,
    MaintenanceChangeRecord, MaintenanceDependencyResolverDescriptor, MaintenanceDisposition,
    MaintenanceIngressRequest, MaintenanceRejectionReceipt, MapPoint,
    OWNER_AUTHORIZED_MAINTENANCE_FORMAT_VERSION, ObservationPolicy, OrderedRulePolicy, OutboxEntry,
    OwnerAuthorizedMaintenanceDraft, OwnerAuthorizedMaintenanceParticipant,
    OwnerAuthorizedMaintenanceRequest, OwnerAuthorizedMutation, OwnerAuthorizedParticipantDraft,
    OwnerAuthorizedParticipantProposal, OwnerAuthorizedParticipantRole,
    OwnerAuthorizedRecordExpectation, PAGED_CHECKPOINT_FORMAT_VERSION,
    PAYLOAD_REQUIRED_EVIDENCE_CONTINUATION_FIELD,
    PAYLOAD_REQUIRED_EVIDENCE_CONTINUATION_FORMAT_VERSION, PLUGIN_DESCRIPTOR_FORMAT_VERSION,
    PagedSimulationCheckpoint, PatriciaStoreMetrics, PayloadProperty,
    PayloadRequiredEvidenceContinuationV1, PayloadSchema, PayloadValueType,
    PersistentDomainRecordStore, Person, PersonAvailability, PersonDraft, PersonTransitState,
    PluginActionDescriptor, PluginArchiveObjectProvider, PluginArchiveReachabilityParticipant,
    PluginArchiveRetention, PluginCommandHandler, PluginComponentRecord, PluginDescriptor,
    PluginIngressDescriptor, PluginIngressPermit, PluginIngressRequest, PluginIngressTarget,
    PluginKnowledgeSchema, PluginRegistrar, PluginRegistry, PolicyDecision,
    PortablePagedSimulationCheckpoint, PreparedDecisionArchive, PreparedDecisionIngress,
    PreparedEvidenceSeal, PreparedPagedSimulationCheckpoint, PreparedStateDelta,
    QueuedExternalPolicy, QueuedHumanPolicy, QueuedLlmPolicy, RUN_CONFIGURATION_FORMAT_VERSION,
    RUN_MANIFEST_FORMAT_VERSION, RandomAlgorithm, RandomDecisionResolution, RandomDrawAddress,
    RandomDrawOutcome, RandomDrawProducer, RandomDrawRecord, RandomOperationAddressV1,
    RandomOperationTarget, RandomSample, RandomStreamKey, RandomStreamState, ReplayJournal,
    ReservationAllocation, ReservationDisposition, ReservationOffer, ReservationOfferRecord,
    ReservationPoolKey, ReservationRef, ReservationRequest, ReservationRequestRecord, Route,
    RuleChoice, RulePolicy, RunConfiguration, RunConfigurationSnapshot, RunManifest, RunPurpose,
    SNAPSHOT_FORMAT_VERSION, STATE_PAGE_CODEC, STATE_PAGE_FORMAT_VERSION,
    STATE_REVISION_FORMAT_VERSION, Scenario, SeatBinding, SeatPolicy, SimulationCheckpoint,
    SimulationPlugin, SimulationSnapshot, SimulationSystemHandler, SimulationView, StateKey,
    StatePageBlob, StatePageProvider, StatePageRetentionHandle, StatePageRetentionLedger,
    StatePageRetentionPhase, StatePageStore, StateVisibility, SystemCadence, SystemContract,
    SystemDirective, Territory, TracePolicy, TransitState, UtilityEvaluator, UtilityPolicy,
    UtilityProfile, VerifiedDecisionArchiveCommit, VerifiedOwnerAuthorizedMaintenanceCommit,
    WeightedUtilityEvaluator, WeightedUtilityPolicy, WorldSnapshot, canonical_byte_hash,
    canonical_hash, format8_decision_locator_scale_probe, format8_patricia_scale_probe,
    identity_evidence_dependencies_property_v1, payload_required_evidence_continuation_property_v1,
    prepare_state_delta, state_page_id, verify_state_delta,
};
// Transition manifests and their audit (gap G-04).
pub use canwu_sim::{
    MAX_PENDING_TRANSITION_MANIFESTS, MAX_PENDING_TRANSITION_MANIFESTS_PER_COORDINATOR,
    MAX_TRANSITION_EXPECTED_VERSIONS, MAX_TRANSITION_LINEAGE_ID_BYTES, MAX_TRANSITION_PARTICIPANTS,
    MAX_TRANSITION_READY_HORIZON, PendingTransitionManifest, TransitionAuditOutcome,
    TransitionAuditRecord, TransitionManifest, TransitionManifestId, TransitionParticipant,
    TransitionParticipantAudit, TransitionRecordVersion,
};
pub use canwu_time::{SimDuration, SimTime};
pub use canwu_transport::{
    BookingAllocationV1, CAPACITY_BOOKING_ALLOCATION_DIGEST_DOMAIN, CapacityAllocationFailureV1,
    CapacityBooking, CapacityBookingAllocationEvidenceV1, CapacityBookingId,
    CapacityBookingRequestV1, CapacityBookingStatus, DeliveryCompletionRequest, DeliverySaga,
    Handoff, HandoffId, HandoffKind, ItineraryRevision, ItineraryRevisionId,
    ItineraryRevisionReason, LegExecution, LegExecutionId, LegExecutionStatus, MovementInitiative,
    MovementOrder, MovementOrderError, MovementOrderId, MovementSubject, MovementSubjectRole,
    ReconciliationOutcome, SagaState, TRANSPORT_SEMANTIC_VERSION, TransportCapacityPoolV1,
    TransportError, TransportExecution, TransportExecutionId, TransportExecutionState,
    allocate_capacity_bookings, capacity_booking_allocation_operation_key,
    delivery_completion_operation_key,
};
use serde::{Deserialize, Serialize};

/// Main in-process API. All returned world values are detached snapshots.
pub struct Canwu {
    simulation: Simulation,
}

/// Public API for a live runtime whose sealed evidence segments are stored by the caller.
pub struct CompactedCanwu {
    simulation: CompactedSimulation,
}

impl PluginArchiveObjectProvider for Canwu {
    fn load_plugin_archive_object(
        &self,
        namespace: &str,
        object_id: &str,
    ) -> Result<Option<Vec<u8>>, CanwuError> {
        self.plugin_archive_object(namespace, object_id)
    }
}

impl Canwu {
    #[must_use]
    pub const fn version() -> &'static str {
        ENGINE_VERSION
    }

    pub fn new(seed: u64, scenario: Scenario) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::new(seed, scenario)?,
        })
    }

    /// Enters the explicit compact-journal interface without discarding evidence.
    pub fn into_compacted(self) -> Result<CompactedCanwu, CanwuError> {
        Ok(CompactedCanwu {
            simulation: self.simulation.into_compacted()?,
        })
    }

    pub fn new_with_plugins(
        seed: u64,
        scenario: Scenario,
        plugins: &[&dyn SimulationPlugin],
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::new_with_plugins(seed, scenario, plugins)?,
        })
    }

    pub fn new_with_manifest(
        seed: u64,
        scenario: Scenario,
        run_manifest: RunManifest,
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::new_with_manifest(seed, scenario, run_manifest)?,
        })
    }

    pub fn new_with_manifest_and_plugins(
        seed: u64,
        scenario: Scenario,
        run_manifest: RunManifest,
        plugins: &[&dyn SimulationPlugin],
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::new_with_manifest_and_plugins(
                seed,
                scenario,
                run_manifest,
                plugins,
            )?,
        })
    }

    pub fn new_with_run_configuration(
        seed: u64,
        scenario: Scenario,
        run_manifest: RunManifest,
        run_configuration: RunConfiguration,
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::new_with_run_configuration(
                seed,
                scenario,
                run_manifest,
                run_configuration,
            )?,
        })
    }

    pub fn new_with_run_configuration_and_plugins(
        seed: u64,
        scenario: Scenario,
        run_manifest: RunManifest,
        run_configuration: RunConfiguration,
        plugins: &[&dyn SimulationPlugin],
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::new_with_run_configuration_and_plugins(
                seed,
                scenario,
                run_manifest,
                run_configuration,
                plugins,
            )?,
        })
    }

    /// Deprecated compatibility scenario. New hosts should use an integration-owned scenario.
    pub fn demo(seed: u64) -> Result<Self, CanwuError> {
        let (simulation, _) = Simulation::demo(seed)?;
        Ok(Self { simulation })
    }

    /// IDs for the deprecated compatibility scenario.
    #[must_use]
    pub fn demo_ids() -> DemoIds {
        let (_, ids) = canwu_sim::demo_scenario();
        ids
    }

    #[must_use]
    pub const fn time(&self) -> SimTime {
        self.simulation.time()
    }

    #[must_use]
    pub const fn run_manifest(&self) -> &RunManifest {
        self.simulation.run_manifest()
    }

    #[must_use]
    pub const fn run_configuration(&self) -> &RunConfigurationSnapshot {
        self.simulation.run_configuration()
    }

    #[must_use]
    /// Returns the persisted authoritative transaction revision.
    ///
    /// Accepted commands, persisted expected rejections, and completed
    /// settlement boundaries each advance it exactly once. Failed work, exact
    /// retries, bare clock movement, queued but unadmitted ingress, and plugin
    /// setup do not advance it; combine it with command expected-time guards.
    pub fn revision(&self) -> u64 {
        self.simulation.revision()
    }

    #[must_use]
    pub fn run_manifest_hash(&self) -> &str {
        self.simulation.run_manifest_hash()
    }

    #[must_use]
    pub fn checkpoint_hash(&self) -> &str {
        self.simulation.checkpoint_hash()
    }

    pub fn authoritative_state_hash(&self) -> Result<String, CanwuError> {
        self.simulation.authoritative_state_hash()
    }

    pub fn entities(&self) -> impl Iterator<Item = &EntityRef> {
        self.simulation.entities()
    }

    #[must_use]
    pub fn entity_exists(&self, entity: &EntityRef) -> bool {
        self.simulation.entity_exists(entity)
    }

    /// Deprecated detached format-5 compatibility projection.
    #[must_use]
    pub fn world(&self) -> WorldSnapshot {
        self.simulation.world()
    }

    /// Trusted host access to a person's committed life and custody state.
    /// `None` means no change has been committed: the person is alive and free.
    #[must_use]
    pub fn person_availability(&self, person: PersonId) -> Option<&PersonAvailability> {
        self.simulation.person_availability(person)
    }

    /// Trusted host access to every committed person availability, in
    /// person-ID order. Persons without an entry are alive and free.
    pub fn person_availabilities(&self) -> impl Iterator<Item = (&PersonId, &PersonAvailability)> {
        self.simulation.person_availabilities()
    }

    /// Trusted host access to the registered transition manifests whose
    /// ready boundary has not settled, in manifest-ID order. Settled
    /// manifests leave their audit on the boundary record and receipt.
    pub fn pending_transition_manifests(&self) -> impl Iterator<Item = &PendingTransitionManifest> {
        self.simulation.pending_transition_manifests()
    }

    /// Trusted host/admin access to the complete knowledge snapshot.
    ///
    /// Do not expose this public API to player, agent, observer, or remote clients;
    /// use [`Canwu::viewer`] or [`Canwu::viewer_for_actor`] instead.
    #[must_use]
    pub fn knowledge(&self) -> &KnowledgeSnapshot {
        self.simulation.knowledge()
    }

    #[must_use]
    pub fn events(&self) -> &[SimEvent] {
        self.simulation.events()
    }

    #[must_use]
    pub fn commands(&self) -> &[CommandRecord] {
        self.simulation.command_log()
    }

    #[must_use]
    pub fn boundaries(&self) -> &[BoundaryRecord] {
        self.simulation.boundaries()
    }

    #[must_use]
    pub fn command_attempts(&self) -> &[CommandAttemptRecord] {
        self.simulation.command_attempts()
    }

    #[must_use]
    pub fn ingress_log(&self) -> &[IngressRecord] {
        self.simulation.ingress_log()
    }

    #[must_use]
    pub fn domain_record(&self, reference: &DomainRecordRef) -> Option<&DomainRecord> {
        self.simulation.domain_record(reference)
    }

    /// Returns whether an exact domain-record version exists in current or retained evidence.
    #[must_use]
    pub fn domain_record_version_evidence_exists(
        &self,
        reference: &DomainRecordVersionRef,
    ) -> bool {
        self.simulation
            .domain_record_version_evidence_exists(reference)
    }

    /// Returns whether a generic evidence identity is retained or archived.
    #[must_use]
    pub fn evidence_exists(&self, reference: &EvidenceRef) -> bool {
        self.simulation.evidence_exists(reference)
    }

    /// Returns when retained evidence first became authoritative.
    ///
    /// Compacted identity-only receipts return `None`; load the archived
    /// evidence body before making decisions that require temporal ordering.
    #[must_use]
    pub fn evidence_time(&self, reference: &EvidenceRef) -> Option<SimTime> {
        self.simulation.evidence_time(reference)
    }

    /// Resolves the retained record body for one exact domain-record version.
    ///
    /// A compacted archive receipt proves existence but does not expose the
    /// version body through this trusted-host query.
    #[must_use]
    pub fn domain_record_version(
        &self,
        reference: &DomainRecordVersionRef,
    ) -> Option<DomainRecord> {
        self.simulation.domain_record_version(reference)
    }

    /// Returns the retained or archive-resolvable exact identity for the
    /// authoritative current record version. Missing provenance fails closed.
    pub fn current_domain_record_version(
        &self,
        reference: &DomainRecordRef,
    ) -> Result<Option<DomainRecordVersionRef>, CanwuError> {
        self.simulation.current_domain_record_version(reference)
    }

    #[must_use]
    pub fn typed_domain_record<T: DomainRecordType>(
        &self,
        reference: &TypedDomainRecordRef<T>,
    ) -> Option<&DomainRecord> {
        self.simulation.typed_domain_record(reference)
    }

    pub fn domain_records(&self) -> impl Iterator<Item = &DomainRecord> {
        self.simulation.domain_records()
    }

    /// Returns one trusted-host page bound to an authoritative revision.
    ///
    /// Use the returned revision as `expected_revision` on subsequent pages.
    pub fn domain_record_page(
        &self,
        kind: &DomainRecordKind,
        after: Option<&DomainRecordRef>,
        limit: usize,
        expected_revision: Option<u64>,
    ) -> Result<DomainRecordPage, CanwuError> {
        self.simulation
            .domain_record_page(kind, after, limit, expected_revision)
    }

    #[must_use]
    pub fn decision_ticket(&self, id: DecisionTicketId) -> Option<&DecisionTicket> {
        self.simulation.decision_ticket(id)
    }

    #[must_use]
    pub fn decision_controller(&self, id: &str) -> Option<&DecisionControllerBinding> {
        self.simulation.decision_controller(id)
    }

    #[must_use]
    pub fn decision_trace(&self, id: DecisionTraceId) -> Option<&DecisionTrace> {
        self.simulation.decision_trace(id)
    }

    #[must_use]
    pub fn decision_attempt(&self, id: DecisionRequestId) -> Option<&DecisionAttemptRecord> {
        self.simulation.decision_attempt(id)
    }

    #[must_use]
    pub fn decision_hot_state(&self) -> DecisionHotState {
        self.simulation.decision_hot_state()
    }

    #[must_use]
    pub fn decision_history_location(&self, key: &DecisionHistoryKey) -> DecisionHistoryLocation {
        self.simulation.decision_history_location(key)
    }

    pub fn decision_history_location_with_provider(
        &self,
        key: &DecisionHistoryKey,
        provider: &dyn DecisionArchiveProvider,
    ) -> Result<DecisionHistoryLocation, CanwuError> {
        self.simulation
            .decision_history_location_with_provider(key, provider)
    }

    #[must_use]
    pub fn random_draws(&self) -> &[RandomDrawRecord] {
        self.simulation.random_draws()
    }

    #[must_use]
    pub fn boundary_head_hash(&self) -> Option<&str> {
        self.simulation.boundary_head_hash()
    }

    #[must_use]
    pub const fn schema(&self) -> &SchemaRegistry {
        self.simulation.schema()
    }

    pub fn plugin_descriptors(&self) -> impl Iterator<Item = &PluginDescriptor> {
        self.simulation.plugin_descriptors()
    }

    #[must_use]
    pub fn replay_journal(&self) -> ReplayJournal {
        self.simulation.replay_journal()
    }

    pub fn outbox_entries(&self) -> Result<Vec<OutboxEntry>, CanwuError> {
        self.simulation.outbox_entries()
    }

    pub fn evidence_cursor(&self) -> Result<EvidenceCursor, CanwuError> {
        self.simulation.evidence_cursor()
    }

    pub fn checkpoint(&self) -> Result<SimulationCheckpoint, CanwuError> {
        self.simulation.checkpoint()
    }

    pub fn archive_reachability_manifest(
        &self,
        retained_checkpoints: &[SimulationCheckpoint],
        page_retention: &StatePageRetentionLedger,
        decision_provider: &dyn DecisionArchiveProvider,
        plugin_provider: &dyn PluginArchiveObjectProvider,
    ) -> Result<ArchiveReachabilityManifest, CanwuError> {
        self.simulation.archive_reachability_manifest(
            retained_checkpoints,
            page_retention,
            decision_provider,
            plugin_provider,
        )
    }

    pub fn journal_segment_since(
        &self,
        start: EvidenceCursor,
    ) -> Result<EvidenceJournalSegment, CanwuError> {
        self.simulation.journal_segment_since(start)
    }

    pub fn checkpoint_journal(&self) -> Result<CheckpointJournal, CanwuError> {
        self.simulation.checkpoint_journal()
    }

    pub fn checkpoint_journal_json(&self) -> Result<String, CanwuError> {
        self.simulation.checkpoint_journal_json()
    }

    pub fn register_plugin<P: SimulationPlugin + ?Sized>(
        &mut self,
        plugin: &P,
    ) -> Result<(), CanwuError> {
        self.simulation.register_plugin(plugin)
    }

    /// Attaches caller-owned package archive storage for authenticated cold
    /// history resolution during normal admissions, settlement, and queries.
    pub fn set_plugin_archive_object_provider(
        &mut self,
        provider: std::rc::Rc<dyn PluginArchiveObjectProvider>,
    ) {
        self.simulation.set_plugin_archive_object_provider(provider);
    }

    /// Loads one opaque package archive object from the attached provider.
    /// Package integrations authenticate the bytes against their committed
    /// archive roots before use.
    pub fn plugin_archive_object(
        &self,
        namespace: &str,
        object_id: &str,
    ) -> Result<Option<Vec<u8>>, CanwuError> {
        self.simulation.plugin_archive_object(namespace, object_id)
    }

    pub fn submit(&mut self, command: CommandEnvelope) -> Result<CommandReceipt, CanwuError> {
        self.simulation.submit(command)
    }

    pub fn process_command(
        &mut self,
        request: CommandRequest,
    ) -> Result<CommandOutcome, CanwuError> {
        self.simulation.process_command(request)
    }

    pub fn enqueue_command(
        &mut self,
        due_at: SimTime,
        priority: i32,
        request: CommandRequest,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation.enqueue_command(due_at, priority, request)
    }

    pub fn enqueue_plugin_ingress(
        &mut self,
        request: PluginIngressRequest,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation.enqueue_plugin_ingress(request)
    }

    pub fn enqueue_permitted_plugin_ingress(
        &mut self,
        request: PluginIngressRequest,
        permit: &PluginIngressPermit,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation
            .enqueue_permitted_plugin_ingress(request, permit)
    }

    /// Withdraws a still-pending plugin ingress item that the host enqueued
    /// with [`Self::enqueue_plugin_ingress`], strictly before its due time.
    ///
    /// Due, admitted, archived, or already cancelled items fail with
    /// [`ErrorCode::LateIngress`]; items of internal packet types or items a
    /// plugin scheduled inside the engine fail with
    /// [`ErrorCode::InvalidAuthority`]; unknown IDs fail with
    /// [`ErrorCode::EvidenceUnavailable`]; non-plugin targets and reasons that
    /// are empty, untrimmed, or longer than
    /// [`MAX_INGRESS_CANCELLATION_REASON_BYTES`] fail with
    /// [`ErrorCode::InvalidPayload`]; declared read-only runs fail with
    /// [`ErrorCode::InteractionReadOnly`]. The returned receipt names the
    /// terminal [`IngressPayload::PluginCancellation`] journal record. The
    /// withdrawn item is never admitted, never settles, and nothing is rolled
    /// back; snapshots, checkpoint journals, and exact replay preserve the
    /// cancellation.
    pub fn cancel_plugin_ingress(
        &mut self,
        ingress_id: IngressId,
        reason: impl Into<String>,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation.cancel_plugin_ingress(ingress_id, reason)
    }

    /// Withdraws a still-pending item of an internal packet type through the
    /// owning plugin's opaque registration permit. The permit covers
    /// host-enqueued items of that exact type and items the same plugin
    /// scheduled inside the engine; timing rules match
    /// [`Self::cancel_plugin_ingress`].
    pub fn cancel_permitted_plugin_ingress(
        &mut self,
        ingress_id: IngressId,
        permit: &PluginIngressPermit,
        reason: impl Into<String>,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation
            .cancel_permitted_plugin_ingress(ingress_id, permit, reason)
    }

    pub fn prepare_decision(
        &self,
        decision_request_id: DecisionRequestId,
        command_request_id: Option<CommandRequestId>,
        ticket_id: DecisionTicketId,
        policy: &dyn DecisionPolicy,
    ) -> Result<DecisionEvaluation, CanwuError> {
        self.simulation
            .prepare_decision(decision_request_id, command_request_id, ticket_id, policy)
    }

    pub fn prepare_decision_at(
        &self,
        due_at: SimTime,
        decision_request_id: DecisionRequestId,
        command_request_id: Option<CommandRequestId>,
        ticket_id: DecisionTicketId,
        policy: &dyn DecisionPolicy,
    ) -> Result<DecisionEvaluation, CanwuError> {
        self.simulation.prepare_decision_at(
            due_at,
            decision_request_id,
            command_request_id,
            ticket_id,
            policy,
        )
    }

    pub fn enqueue_decision(
        &mut self,
        due_at: SimTime,
        priority: i32,
        request: DecisionIngressRequest,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation.enqueue_decision(due_at, priority, request)
    }

    pub fn drive_decision(
        &mut self,
        due_at: SimTime,
        priority: i32,
        decision_request_id: DecisionRequestId,
        command_request_id: Option<CommandRequestId>,
        ticket_id: DecisionTicketId,
        policy: &dyn DecisionPolicy,
    ) -> Result<DecisionEvaluation, CanwuError> {
        self.simulation.drive_decision(
            due_at,
            priority,
            decision_request_id,
            command_request_id,
            ticket_id,
            policy,
        )
    }

    pub fn schedule_calendar_boundary(
        &mut self,
        due_at: SimTime,
        cadences: Vec<SystemCadence>,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation.schedule_calendar_boundary(due_at, cadences)
    }

    pub fn advance_canonical(
        &mut self,
        duration: SimDuration,
    ) -> Result<Vec<BoundaryReceipt>, CanwuError> {
        self.simulation.advance_canonical(duration)
    }

    pub fn step_canonical(&mut self) -> Result<Option<BoundaryReceipt>, CanwuError> {
        self.simulation.step_canonical()
    }

    pub fn advance(&mut self, duration: SimDuration) -> Result<Vec<SimEvent>, CanwuError> {
        self.simulation.advance(duration)
    }

    pub fn settle_boundary(
        &mut self,
        request: BoundaryRequest,
    ) -> Result<BoundaryReceipt, CanwuError> {
        self.simulation.settle_boundary(request)
    }

    pub fn wait(&mut self, duration: SimDuration) -> Result<Vec<SimEvent>, CanwuError> {
        self.advance(duration)
    }

    pub fn step(&mut self) -> Result<Vec<SimEvent>, CanwuError> {
        self.simulation.step()
    }

    #[must_use]
    pub fn snapshot(&self) -> SimulationSnapshot {
        self.simulation.snapshot()
    }

    pub fn snapshot_json(&self) -> Result<String, CanwuError> {
        self.simulation.snapshot_json()
    }

    pub fn from_snapshot_json(json: &str) -> Result<Self, CanwuError> {
        let simulation = Simulation::from_snapshot_json(json)?;
        Ok(Self { simulation })
    }

    pub fn from_snapshot_json_with_plugins(
        json: &str,
        plugins: &[&dyn SimulationPlugin],
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::from_snapshot_json_with_plugins(json, plugins)?,
        })
    }

    pub fn from_checkpoint_and_journal(
        checkpoint: SimulationCheckpoint,
        segments: Vec<EvidenceJournalSegment>,
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::from_checkpoint_and_journal(checkpoint, segments)?,
        })
    }

    pub fn from_checkpoint_journal(bundle: CheckpointJournal) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::from_checkpoint_journal(bundle)?,
        })
    }

    pub fn from_checkpoint_journal_with_plugins(
        bundle: CheckpointJournal,
        plugins: &[&dyn SimulationPlugin],
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::from_checkpoint_journal_with_plugins(bundle, plugins)?,
        })
    }

    pub fn from_checkpoint_journal_json(json: &str) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::from_checkpoint_journal_json(json)?,
        })
    }

    pub fn from_checkpoint_journal_json_with_plugins(
        json: &str,
        plugins: &[&dyn SimulationPlugin],
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::from_checkpoint_journal_json_with_plugins(json, plugins)?,
        })
    }

    pub fn replay_from_journal(
        plugins: &[&dyn SimulationPlugin],
        journal: &ReplayJournal,
    ) -> Result<Self, CanwuError> {
        let simulation = Simulation::replay_from_journal(plugins, journal)?;
        Ok(Self { simulation })
    }

    /// Replays with package archive storage attached before the first
    /// recorded boundary, so package-owned cold history participates in
    /// ordinary admission and settlement throughout replay.
    pub fn replay_from_journal_with_archive_provider(
        plugins: &[&dyn SimulationPlugin],
        journal: &ReplayJournal,
        archive_provider: std::rc::Rc<dyn PluginArchiveObjectProvider>,
    ) -> Result<Self, CanwuError> {
        let simulation = Simulation::replay_from_journal_with_archive_provider(
            plugins,
            journal,
            archive_provider,
        )?;
        Ok(Self { simulation })
    }

    pub fn replay_from_journal_json(
        plugins: &[&dyn SimulationPlugin],
        json: &str,
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: Simulation::replay_from_journal_json(plugins, json)?,
        })
    }

    #[must_use]
    pub fn fork(&self) -> Self {
        Self {
            simulation: self.simulation.fork(),
        }
    }

    /// Trusted host/admin holder query. Player-facing callers must use a
    /// restricted [`CanwuViewer`].
    pub fn admin_query_knowledge(
        &self,
        holder: KnowledgeHolderRef,
        query: &KnowledgeQuery,
    ) -> Result<KnowledgeQueryResult, CanwuError> {
        self.simulation
            .knowledge()
            .query_current(
                holder,
                query,
                self.simulation.boundaries().last().map(|value| value.id),
            )
            .map_err(map_knowledge_query_error)
    }

    /// Creates the restricted viewer dictated entirely by the persisted run
    /// policy and seat binding.
    pub fn viewer(&self) -> Result<CanwuViewer<'_>, CanwuError> {
        let principal = self.declared_observation_principal()?;
        Ok(CanwuViewer {
            canwu: self,
            context: KnowledgeViewContext { principal },
        })
    }

    /// Character-seat and compatibility convenience. It never upgrades an
    /// institution, public, research, or developer policy to a person.
    pub fn viewer_for_actor(&self, actor: PersonId) -> Result<CanwuViewer<'_>, CanwuError> {
        if !self.entity_exists(&EntityRef::Person(actor)) {
            return Err(CanwuError::new(
                ErrorCode::ActorNotFound,
                format!("actor {actor} was not found"),
            ));
        }
        let principal = match self.run_configuration().declared() {
            Some(configuration)
                if configuration.observation == ObservationPolicy::ActorBound
                    && configuration.seat == SeatPolicy::CharacterBound
                    && configuration
                        .seat_binding
                        .as_ref()
                        .and_then(|binding| binding.actor)
                        == Some(actor) =>
            {
                ObservationPrincipal::Person(actor)
            }
            Some(_) => {
                return Err(CanwuError::new(
                    ErrorCode::InvalidAuthority,
                    "the persisted run policy does not authorize a character viewer",
                ));
            }
            None => ObservationPrincipal::Person(actor),
        };
        Ok(CanwuViewer {
            canwu: self,
            context: KnowledgeViewContext { principal },
        })
    }

    pub fn viewer_context(&self, actor: PersonId) -> Result<ViewerContext, CanwuError> {
        let viewer = self.viewer_for_actor(actor)?;
        Ok(ViewerContext {
            principal: viewer.context.principal.clone(),
            observation: ObservationPolicy::ActorBound,
            checkpoint_hash: self.checkpoint_hash().to_owned(),
        })
    }

    fn declared_observation_principal(&self) -> Result<ObservationPrincipal, CanwuError> {
        let Some(configuration) = self.run_configuration().declared() else {
            return Err(CanwuError::new(
                ErrorCode::InvalidAuthority,
                "legacy runs require viewer_for_actor with an existing character",
            ));
        };
        match configuration.observation {
            ObservationPolicy::ActorBound => match configuration.seat {
                SeatPolicy::CharacterBound => configuration
                    .seat_binding
                    .as_ref()
                    .and_then(|binding| binding.actor)
                    .map(ObservationPrincipal::Person)
                    .ok_or_else(|| {
                        CanwuError::new(
                            ErrorCode::InvalidAuthority,
                            "character-bound observation lacks an actor binding",
                        )
                    }),
                SeatPolicy::InstitutionBound => configuration
                    .seat_binding
                    .as_ref()
                    .and_then(|binding| binding.institution.clone())
                    .map(ObservationPrincipal::Institution)
                    .ok_or_else(|| {
                        CanwuError::new(
                            ErrorCode::InvalidAuthority,
                            "institution-bound observation lacks an institution binding",
                        )
                    }),
                SeatPolicy::ObserverSeat | SeatPolicy::AdvisorSeat | SeatPolicy::None => {
                    Err(CanwuError::new(
                        ErrorCode::InvalidAuthority,
                        "actor-bound observation requires a character or institution seat",
                    ))
                }
            },
            ObservationPolicy::PublicObserver => Ok(ObservationPrincipal::Public),
            ObservationPolicy::ResearchFull => Ok(ObservationPrincipal::Research),
            ObservationPolicy::DeveloperDiagnostic => Ok(ObservationPrincipal::Developer),
        }
    }

    #[must_use]
    pub fn explain(&self, request: &ExplanationRequest) -> Explanation {
        match request {
            ExplanationRequest::Event(event_id) => self.explain_event(*event_id),
            ExplanationRequest::Failure(error) => Explanation {
                summary: error.message.clone(),
                causal_chain: vec![ExplanationStep {
                    label: format!("Validation failed: {:?}", error.code),
                    event: None,
                }],
            },
        }
    }

    fn explain_event(&self, event_id: EventId) -> Explanation {
        let mut chain = Vec::new();
        let events = self.events();
        let mut current = event_by_id(events, event_id);
        while let Some(event) = current {
            chain.push(ExplanationStep {
                label: event.summary.clone(),
                event: Some(event.id),
            });
            current = match &event.cause {
                Some(CauseRef::Boundary(boundary)) => {
                    chain.push(ExplanationStep {
                        label: format!("Committed by boundary {boundary}"),
                        event: None,
                    });
                    None
                }
                Some(CauseRef::Event(parent)) => event_by_id(events, *parent),
                Some(CauseRef::Command(command)) => {
                    chain.push(ExplanationStep {
                        label: format!("Accepted command {command}"),
                        event: None,
                    });
                    None
                }
                Some(CauseRef::System(system)) => {
                    chain.push(ExplanationStep {
                        label: format!("Produced by system {system}"),
                        event: None,
                    });
                    None
                }
                None => None,
            };
        }
        Explanation {
            summary: chain.first().map_or_else(
                || "Event was not found".to_owned(),
                |step| step.label.clone(),
            ),
            causal_chain: chain,
        }
    }
}

fn event_by_id(events: &[SimEvent], event_id: EventId) -> Option<&SimEvent> {
    let index = usize::try_from(event_id.get().checked_sub(1)?).ok()?;
    events.get(index).filter(|event| event.id == event_id)
}

impl CompactedCanwu {
    pub fn from_checkpoint_and_journal(
        checkpoint: SimulationCheckpoint,
        segments: Vec<EvidenceJournalSegment>,
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: CompactedSimulation::from_checkpoint_and_journal(checkpoint, segments)?,
        })
    }

    pub fn from_checkpoint_and_journal_with_plugins(
        checkpoint: SimulationCheckpoint,
        segments: Vec<EvidenceJournalSegment>,
        plugins: &[&dyn SimulationPlugin],
    ) -> Result<Self, CanwuError> {
        Ok(Self {
            simulation: CompactedSimulation::from_checkpoint_and_journal_with_plugins(
                checkpoint, segments, plugins,
            )?,
        })
    }

    pub fn evidence_cursor(&self) -> Result<EvidenceCursor, CanwuError> {
        self.simulation.evidence_cursor()
    }

    pub fn checkpoint(&self) -> Result<SimulationCheckpoint, CanwuError> {
        self.simulation.checkpoint()
    }

    pub fn outbox_entries(&self) -> Result<Vec<OutboxEntry>, CanwuError> {
        self.simulation.outbox_entries()
    }

    pub fn outbox_entries_for_segment(
        &self,
        segment: &EvidenceJournalSegment,
    ) -> Result<Vec<OutboxEntry>, CanwuError> {
        self.simulation.outbox_entries_for_segment(segment)
    }

    #[must_use]
    pub fn archived_evidence_receipt(
        &self,
        reference: &EvidenceRef,
    ) -> Option<&ArchivedEvidenceReceipt> {
        self.simulation.archived_evidence_receipt(reference)
    }

    pub fn load_archived_evidence_segment(
        &self,
        reference: &EvidenceRef,
        provider: &dyn ArchiveProvider,
    ) -> Result<EvidenceJournalSegment, CanwuError> {
        self.simulation
            .load_archived_evidence_segment(reference, provider)
    }

    pub fn seal_evidence(&mut self) -> Result<Option<EvidenceJournalSegment>, CanwuError> {
        self.simulation.seal_evidence()
    }

    pub fn prepare_evidence_seal(&self) -> Result<Option<PreparedEvidenceSeal>, CanwuError> {
        self.simulation.prepare_evidence_seal()
    }

    pub fn commit_evidence_seal(
        &mut self,
        token: &EvidenceSealToken,
        provider: &dyn ArchiveProvider,
    ) -> Result<(), CanwuError> {
        self.simulation.commit_evidence_seal(token, provider)
    }

    pub fn snapshot_with_segments(
        &self,
        segments: Vec<EvidenceJournalSegment>,
    ) -> Result<SimulationSnapshot, CanwuError> {
        self.simulation.snapshot_with_segments(segments)
    }

    pub fn replay_journal_with_segments(
        &self,
        segments: Vec<EvidenceJournalSegment>,
    ) -> Result<ReplayJournal, CanwuError> {
        self.simulation.replay_journal_with_segments(segments)
    }

    #[must_use]
    pub const fn time(&self) -> SimTime {
        self.simulation.time()
    }

    #[must_use]
    pub const fn revision(&self) -> u64 {
        self.simulation.revision()
    }

    #[must_use]
    pub fn checkpoint_hash(&self) -> &str {
        self.simulation.checkpoint_hash()
    }

    #[must_use]
    pub fn boundary_head_hash(&self) -> Option<&str> {
        self.simulation.boundary_head_hash()
    }

    pub fn entities(&self) -> impl Iterator<Item = &EntityRef> {
        self.simulation.entities()
    }

    #[must_use]
    pub fn entity_exists(&self, entity: &EntityRef) -> bool {
        self.simulation.entity_exists(entity)
    }

    /// Deprecated detached format-5 compatibility projection.
    #[must_use]
    pub fn world(&self) -> WorldSnapshot {
        self.simulation.world()
    }

    /// Trusted host access to a person's committed life and custody state.
    /// `None` means no change has been committed: the person is alive and free.
    #[must_use]
    pub fn person_availability(&self, person: PersonId) -> Option<&PersonAvailability> {
        self.simulation.person_availability(person)
    }

    /// Trusted host access to every committed person availability, in
    /// person-ID order. Persons without an entry are alive and free.
    pub fn person_availabilities(&self) -> impl Iterator<Item = (&PersonId, &PersonAvailability)> {
        self.simulation.person_availabilities()
    }

    /// Trusted host access to the registered transition manifests whose
    /// ready boundary has not settled, in manifest-ID order. Settled
    /// manifests leave their audit on the boundary record and receipt.
    pub fn pending_transition_manifests(&self) -> impl Iterator<Item = &PendingTransitionManifest> {
        self.simulation.pending_transition_manifests()
    }

    #[must_use]
    pub fn knowledge(&self) -> &KnowledgeSnapshot {
        self.simulation.knowledge()
    }

    #[must_use]
    pub fn domain_record(&self, reference: &DomainRecordRef) -> Option<&DomainRecord> {
        self.simulation.domain_record(reference)
    }

    #[must_use]
    pub fn typed_domain_record<T: DomainRecordType>(
        &self,
        reference: &TypedDomainRecordRef<T>,
    ) -> Option<&DomainRecord> {
        self.simulation.typed_domain_record(reference)
    }

    #[must_use]
    pub fn decision_ticket(&self, id: DecisionTicketId) -> Option<&DecisionTicket> {
        self.simulation.decision_ticket(id)
    }

    #[must_use]
    pub fn decision_controller(&self, id: &str) -> Option<&DecisionControllerBinding> {
        self.simulation.decision_controller(id)
    }

    #[must_use]
    pub fn decision_trace(&self, id: DecisionTraceId) -> Option<&DecisionTrace> {
        self.simulation.decision_trace(id)
    }

    #[must_use]
    pub fn decision_attempt(&self, id: DecisionRequestId) -> Option<&DecisionAttemptRecord> {
        self.simulation.decision_attempt(id)
    }

    #[must_use]
    pub fn decision_hot_state(&self) -> DecisionHotState {
        self.simulation.decision_hot_state()
    }

    #[must_use]
    pub fn decision_history_location(&self, key: &DecisionHistoryKey) -> DecisionHistoryLocation {
        self.simulation.decision_history_location(key)
    }

    pub fn decision_history_location_with_provider(
        &self,
        key: &DecisionHistoryKey,
        provider: &dyn DecisionArchiveProvider,
    ) -> Result<DecisionHistoryLocation, CanwuError> {
        self.simulation
            .decision_history_location_with_provider(key, provider)
    }

    pub fn submit(&mut self, envelope: CommandEnvelope) -> Result<CommandReceipt, CanwuError> {
        self.simulation.submit(envelope)
    }

    pub fn process_command(
        &mut self,
        request: CommandRequest,
    ) -> Result<CommandOutcome, CanwuError> {
        self.simulation.process_command(request)
    }

    pub fn enqueue_command(
        &mut self,
        due_at: SimTime,
        priority: i32,
        request: CommandRequest,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation.enqueue_command(due_at, priority, request)
    }

    pub fn enqueue_plugin_ingress(
        &mut self,
        request: PluginIngressRequest,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation.enqueue_plugin_ingress(request)
    }

    pub fn enqueue_permitted_plugin_ingress(
        &mut self,
        request: PluginIngressRequest,
        permit: &PluginIngressPermit,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation
            .enqueue_permitted_plugin_ingress(request, permit)
    }

    /// Withdraws a still-pending plugin ingress item that the host enqueued
    /// with [`Self::enqueue_plugin_ingress`], strictly before its due time.
    ///
    /// Due, admitted, archived, or already cancelled items fail with
    /// [`ErrorCode::LateIngress`]; items of internal packet types or items a
    /// plugin scheduled inside the engine fail with
    /// [`ErrorCode::InvalidAuthority`]; unknown IDs fail with
    /// [`ErrorCode::EvidenceUnavailable`]; non-plugin targets and reasons that
    /// are empty, untrimmed, or longer than
    /// [`MAX_INGRESS_CANCELLATION_REASON_BYTES`] fail with
    /// [`ErrorCode::InvalidPayload`]; declared read-only runs fail with
    /// [`ErrorCode::InteractionReadOnly`]. The returned receipt names the
    /// terminal [`IngressPayload::PluginCancellation`] journal record. The
    /// withdrawn item is never admitted, never settles, and nothing is rolled
    /// back; snapshots, checkpoint journals, and exact replay preserve the
    /// cancellation.
    pub fn cancel_plugin_ingress(
        &mut self,
        ingress_id: IngressId,
        reason: impl Into<String>,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation.cancel_plugin_ingress(ingress_id, reason)
    }

    /// Withdraws a still-pending item of an internal packet type through the
    /// owning plugin's opaque registration permit. The permit covers
    /// host-enqueued items of that exact type and items the same plugin
    /// scheduled inside the engine; timing rules match
    /// [`Self::cancel_plugin_ingress`].
    pub fn cancel_permitted_plugin_ingress(
        &mut self,
        ingress_id: IngressId,
        permit: &PluginIngressPermit,
        reason: impl Into<String>,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation
            .cancel_permitted_plugin_ingress(ingress_id, permit, reason)
    }

    pub fn prepare_decision(
        &self,
        decision_request_id: DecisionRequestId,
        command_request_id: Option<CommandRequestId>,
        ticket_id: DecisionTicketId,
        policy: &dyn DecisionPolicy,
    ) -> Result<DecisionEvaluation, CanwuError> {
        self.simulation
            .prepare_decision(decision_request_id, command_request_id, ticket_id, policy)
    }

    pub fn prepare_decision_at(
        &self,
        due_at: SimTime,
        decision_request_id: DecisionRequestId,
        command_request_id: Option<CommandRequestId>,
        ticket_id: DecisionTicketId,
        policy: &dyn DecisionPolicy,
    ) -> Result<DecisionEvaluation, CanwuError> {
        self.simulation.prepare_decision_at(
            due_at,
            decision_request_id,
            command_request_id,
            ticket_id,
            policy,
        )
    }

    pub fn enqueue_decision(
        &mut self,
        due_at: SimTime,
        priority: i32,
        request: DecisionIngressRequest,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation.enqueue_decision(due_at, priority, request)
    }

    pub fn drive_decision(
        &mut self,
        due_at: SimTime,
        priority: i32,
        decision_request_id: DecisionRequestId,
        command_request_id: Option<CommandRequestId>,
        ticket_id: DecisionTicketId,
        policy: &dyn DecisionPolicy,
    ) -> Result<DecisionEvaluation, CanwuError> {
        self.simulation.drive_decision(
            due_at,
            priority,
            decision_request_id,
            command_request_id,
            ticket_id,
            policy,
        )
    }

    pub fn schedule_calendar_boundary(
        &mut self,
        due_at: SimTime,
        cadences: Vec<SystemCadence>,
    ) -> Result<IngressReceipt, CanwuError> {
        self.simulation.schedule_calendar_boundary(due_at, cadences)
    }

    pub fn advance(&mut self, duration: SimDuration) -> Result<Vec<SimEvent>, CanwuError> {
        self.simulation.advance(duration)
    }

    pub fn advance_canonical(
        &mut self,
        duration: SimDuration,
    ) -> Result<Vec<BoundaryReceipt>, CanwuError> {
        self.simulation.advance_canonical(duration)
    }

    pub fn step_canonical(&mut self) -> Result<Option<BoundaryReceipt>, CanwuError> {
        self.simulation.step_canonical()
    }

    pub fn settle_boundary(
        &mut self,
        request: BoundaryRequest,
    ) -> Result<BoundaryReceipt, CanwuError> {
        self.simulation.settle_boundary(request)
    }
}

/// An observation identity authorized by the run's persisted observation
/// policy. This type is intentionally constructed through
/// [`Canwu::viewer_context`] so an observation request cannot self-escalate.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ObservationPrincipal {
    Person(PersonId),
    Institution(EntityRef),
    Public,
    Research,
    Developer,
}

impl ObservationPrincipal {
    const fn person(&self) -> Option<PersonId> {
        match self {
            Self::Person(actor) => Some(*actor),
            Self::Institution(_) | Self::Public | Self::Research | Self::Developer => None,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ViewerContext {
    principal: ObservationPrincipal,
    observation: ObservationPolicy,
    checkpoint_hash: String,
}

impl ViewerContext {
    #[must_use]
    pub const fn principal(&self) -> &ObservationPrincipal {
        &self.principal
    }

    #[must_use]
    pub const fn actor(&self) -> Option<PersonId> {
        self.principal.person()
    }

    #[must_use]
    pub const fn observation(&self) -> ObservationPolicy {
        self.observation
    }
}

#[derive(Clone, Debug)]
struct KnowledgeViewContext {
    principal: ObservationPrincipal,
}

/// Restricted player/agent/observer API. It deliberately exposes no raw
/// snapshot, event, boundary, domain-record, or audit-origin access.
pub struct CanwuViewer<'a> {
    canwu: &'a Canwu,
    context: KnowledgeViewContext,
}

impl CanwuViewer<'_> {
    #[must_use]
    pub const fn principal(&self) -> &ObservationPrincipal {
        &self.context.principal
    }

    /// Queries only the holder selected by a bound person or institution
    /// principal. Public and diagnostic principals must use their separately
    /// named capabilities.
    pub fn query_knowledge(
        &self,
        query: &KnowledgeQuery,
    ) -> Result<KnowledgeQueryResult, CanwuError> {
        let holder = match &self.context.principal {
            ObservationPrincipal::Person(actor) => KnowledgeHolderRef::Person(*actor),
            ObservationPrincipal::Institution(entity) => KnowledgeHolderRef::Entity(entity.clone()),
            ObservationPrincipal::Public => return Err(invalid_knowledge_authority()),
            ObservationPrincipal::Research | ObservationPrincipal::Developer => {
                return Err(CanwuError::new(
                    ErrorCode::InvalidKnowledgeAuthority,
                    "diagnostic viewers must select a holder explicitly",
                ));
            }
        };
        self.canwu.admin_query_knowledge(holder, query)
    }

    /// Selects an existing holder under an explicit research/developer policy.
    /// Returned records remain the origin-free holder projection.
    pub fn query_holder_knowledge(
        &self,
        holder: KnowledgeHolderRef,
        query: &KnowledgeQuery,
    ) -> Result<KnowledgeQueryResult, CanwuError> {
        match self.context.principal {
            ObservationPrincipal::Research | ObservationPrincipal::Developer => {}
            ObservationPrincipal::Person(_)
            | ObservationPrincipal::Institution(_)
            | ObservationPrincipal::Public => return Err(invalid_knowledge_authority()),
        }
        if !knowledge_holder_exists(self.canwu, &holder) {
            return Err(CanwuError::new(
                ErrorCode::InvalidKnowledgeHolder,
                "the requested knowledge holder does not exist",
            ));
        }
        self.canwu.admin_query_knowledge(holder, query)
    }

    /// Returns one audit-bearing stored record only for research/developer
    /// principals. Normal holder queries never expose origin evidence.
    pub fn audit_knowledge_record(
        &self,
        holder: &KnowledgeHolderRef,
        record: HolderKnowledgeRecordId,
    ) -> Result<KnowledgeRecord, CanwuError> {
        match self.context.principal {
            ObservationPrincipal::Research | ObservationPrincipal::Developer => {}
            ObservationPrincipal::Person(_)
            | ObservationPrincipal::Institution(_)
            | ObservationPrincipal::Public => return Err(invalid_knowledge_authority()),
        }
        if !knowledge_holder_exists(self.canwu, holder) {
            return Err(CanwuError::new(
                ErrorCode::InvalidKnowledgeHolder,
                "the requested knowledge holder does not exist",
            ));
        }
        let index = usize::try_from(record.get().saturating_sub(1)).map_err(|_| {
            CanwuError::new(
                ErrorCode::KnowledgeRecordNotFound,
                "holder-relative knowledge record ID is outside the supported range",
            )
        })?;
        self.canwu
            .knowledge()
            .for_holder(holder)
            .and_then(|records| records.values().nth(index))
            .cloned()
            .ok_or_else(|| {
                CanwuError::new(
                    ErrorCode::KnowledgeRecordNotFound,
                    "holder-relative knowledge record was not found",
                )
            })
    }

    #[must_use]
    pub fn visible_changes_since(&self, since: SimTime) -> Vec<VisibleChange> {
        let context = ViewerContext {
            principal: self.context.principal.clone(),
            observation: observation_for_principal(&self.context.principal),
            checkpoint_hash: self.canwu.checkpoint_hash().to_owned(),
        };
        self.canwu
            .events()
            .iter()
            .filter(|event| event.timestamp > since)
            .filter_map(|event| {
                let audience = self.canwu.simulation.event_audience(event);
                visible_change(&context, event, &audience)
            })
            .collect()
    }

    /// Returns the holder-facing projection of the retained rule-evaluation
    /// traces of `subject` that this principal may see, from boundaries after
    /// `after` (every retained boundary when `None`), in boundary and
    /// recording order.
    ///
    /// Visibility follows the holder ledger that [`Self::query_knowledge`]
    /// reads. A person or institution principal sees a trace when the subject
    /// is its own entity, or when a knowledge publication to its ledger that
    /// names the subject (as an entity target or, for a domain entity, as a
    /// domain-record target) was visible before the trace was evaluated: in
    /// an earlier boundary, or as a same-boundary publication in phase 4 of
    /// the same boundary. A holder
    /// therefore never gains the breakdowns of a subject evaluated before it
    /// learned of it. Research and developer principals see every trace; a
    /// public principal cannot read traces, as it cannot read a private
    /// ledger.
    ///
    /// Like holder knowledge views, the projection omits evidence. Term
    /// evidence and the producing plugin and system stay on the trusted
    /// [`BoundaryRecord::evaluation_traces`] read through [`Canwu::boundaries`].
    pub fn evaluation_traces(
        &self,
        subject: &EntityRef,
        after: Option<BoundaryId>,
    ) -> Result<Vec<EvaluationTraceView>, CanwuError> {
        let (own, holder) = match &self.context.principal {
            ObservationPrincipal::Person(actor) => (
                EntityRef::Person(*actor),
                KnowledgeHolderRef::Person(*actor),
            ),
            ObservationPrincipal::Institution(entity) => {
                (entity.clone(), KnowledgeHolderRef::Entity(entity.clone()))
            }
            ObservationPrincipal::Research | ObservationPrincipal::Developer => {
                return Ok(self.canwu.evaluation_trace_views(subject, after, None));
            }
            ObservationPrincipal::Public => return Err(invalid_knowledge_authority()),
        };
        if &own == subject {
            return Ok(self.canwu.evaluation_trace_views(subject, after, None));
        }
        // Every generic ledger record is committed by exactly one boundary
        // knowledge change, so the first change naming the subject is the
        // exact cut at which the holder learned of it. A next-boundary
        // publication becomes known only once its boundary has settled.
        let learned = self.canwu.boundaries().iter().find_map(|boundary| {
            boundary
                .knowledge_changes
                .iter()
                .filter(|change| {
                    change.holder == holder
                        && change
                            .records
                            .iter()
                            .any(|record| knowledge_names_subject(record, subject))
                })
                .map(|change| match change.visibility {
                    StateVisibility::SameBoundary => (boundary.id, change.phase),
                    StateVisibility::NextBoundary => {
                        (boundary.id, BoundaryPhase::SaveReplayAndDiagnosticHashing)
                    }
                })
                .min()
        });
        Ok(learned.map_or_else(Vec::new, |learned| {
            self.canwu
                .evaluation_trace_views(subject, after, Some(learned))
        }))
    }
}

impl Canwu {
    fn evaluation_trace_views(
        &self,
        subject: &EntityRef,
        after: Option<BoundaryId>,
        learned: Option<(BoundaryId, BoundaryPhase)>,
    ) -> Vec<EvaluationTraceView> {
        let boundaries = self.boundaries();
        let start = after.map_or(0, |after| {
            boundaries.partition_point(|boundary| boundary.id <= after)
        });
        boundaries[start..]
            .iter()
            .flat_map(|boundary| {
                boundary
                    .evaluation_traces
                    .iter()
                    .map(move |entry| (boundary.id, entry))
            })
            .filter(|(boundary, entry)| {
                &entry.trace.subject == subject
                    && learned.is_none_or(|learned| learned < (*boundary, entry.phase))
            })
            .map(|(_, entry)| EvaluationTraceView::from(&entry.trace))
            .collect()
    }
}

fn knowledge_names_subject(record: &KnowledgeRecord, subject: &EntityRef) -> bool {
    record.subjects.iter().any(|named| match &named.target {
        KnowledgeSubjectTarget::Entity(entity) => entity == subject,
        KnowledgeSubjectTarget::DomainRecord(reference) => {
            matches!(subject, EntityRef::Domain(domain) if domain == reference)
        }
        KnowledgeSubjectTarget::Event(_) => false,
    })
}

/// Holder-facing projection of one [`EvaluationTraceRecord`], returned by
/// [`CanwuViewer::evaluation_traces`]. It keeps the rule, subject, boundary,
/// result, and each term's contribution, and omits evidence identities.
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct EvaluationTraceView {
    pub rule_id: String,
    pub rule_version: String,
    pub subject: EntityRef,
    pub terms: Vec<EvaluationTermView>,
    pub result: i64,
    pub boundary: BoundaryId,
}

/// One term of an [`EvaluationTraceView`].
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct EvaluationTermView {
    pub term_id: String,
    pub contribution: i64,
}

impl From<&EvaluationTraceRecord> for EvaluationTraceView {
    fn from(record: &EvaluationTraceRecord) -> Self {
        Self {
            rule_id: record.rule_id.clone(),
            rule_version: record.rule_version.clone(),
            subject: record.subject.clone(),
            terms: record
                .terms
                .iter()
                .map(|term| EvaluationTermView {
                    term_id: term.term_id.clone(),
                    contribution: term.contribution,
                })
                .collect(),
            result: record.result,
            boundary: record.boundary,
        }
    }
}

const fn observation_for_principal(principal: &ObservationPrincipal) -> ObservationPolicy {
    match principal {
        ObservationPrincipal::Person(_) | ObservationPrincipal::Institution(_) => {
            ObservationPolicy::ActorBound
        }
        ObservationPrincipal::Public => ObservationPolicy::PublicObserver,
        ObservationPrincipal::Research => ObservationPolicy::ResearchFull,
        ObservationPrincipal::Developer => ObservationPolicy::DeveloperDiagnostic,
    }
}

fn invalid_knowledge_authority() -> CanwuError {
    CanwuError::new(
        ErrorCode::InvalidKnowledgeAuthority,
        "this observation principal cannot read a private knowledge ledger",
    )
}

fn knowledge_holder_exists(canwu: &Canwu, holder: &KnowledgeHolderRef) -> bool {
    match holder {
        KnowledgeHolderRef::Person(actor) => canwu.entity_exists(&EntityRef::Person(*actor)),
        KnowledgeHolderRef::Entity(entity) => canwu.entity_exists(entity),
    }
}

fn map_knowledge_query_error(error: KnowledgeQueryError) -> CanwuError {
    match error {
        KnowledgeQueryError::ReadCutUnavailable => CanwuError::new(
            ErrorCode::KnowledgeReadCutUnavailable,
            "knowledge cursor read cut is no longer available",
        ),
        KnowledgeQueryError::InvalidLimit => CanwuError::new(
            ErrorCode::KnowledgeLimitExceeded,
            "knowledge query page size is outside the supported range",
        ),
        KnowledgeQueryError::InvalidCursor
        | KnowledgeQueryError::InvalidLedger
        | KnowledgeQueryError::Encoding => CanwuError::new(
            ErrorCode::InvalidKnowledgeRecord,
            "knowledge query, cursor, or ledger is invalid",
        ),
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct VisibleChange {
    pub timestamp: SimTime,
    pub summary: String,
    pub source_event: EventId,
}

fn visible_change(
    viewer: &ViewerContext,
    event: &SimEvent,
    plugin_audience: &EventAudience,
) -> Option<VisibleChange> {
    let visible = event_visible_to(viewer, event, plugin_audience);
    visible.then(|| VisibleChange {
        timestamp: event.timestamp,
        summary: event.summary.clone(),
        source_event: event.id,
    })
}

fn event_visible_to(viewer: &ViewerContext, event: &SimEvent, audience: &EventAudience) -> bool {
    if matches!(
        viewer.observation,
        ObservationPolicy::ResearchFull | ObservationPolicy::DeveloperDiagnostic
    ) {
        return true;
    }
    match audience {
        EventAudience::Public => true,
        EventAudience::Actor(actor) => viewer.principal.person() == Some(*actor),
        EventAudience::Actors(actors) => viewer
            .principal
            .person()
            .is_some_and(|actor| actors.binary_search(&actor).is_ok()),
        EventAudience::KnowledgeHolder(holder) => {
            principal_matches_holder(&viewer.principal, holder)
        }
        EventAudience::AffectedActors => viewer
            .principal
            .person()
            .is_some_and(|actor| event.affected_entities.contains(&EntityRef::Person(actor))),
        EventAudience::Private => false,
    }
}

fn principal_matches_holder(principal: &ObservationPrincipal, holder: &KnowledgeHolderRef) -> bool {
    match (principal, holder) {
        (ObservationPrincipal::Person(actor), KnowledgeHolderRef::Person(holder)) => {
            actor == holder
        }
        (ObservationPrincipal::Institution(institution), KnowledgeHolderRef::Entity(holder)) => {
            institution == holder
        }
        (ObservationPrincipal::Research | ObservationPrincipal::Developer, _) => true,
        (
            ObservationPrincipal::Person(_)
            | ObservationPrincipal::Institution(_)
            | ObservationPrincipal::Public,
            _,
        ) => false,
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum ExplanationRequest {
    Event(EventId),
    Failure(CanwuError),
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ExplanationStep {
    pub label: String,
    pub event: Option<EventId>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Explanation {
    pub summary: String,
    pub causal_chain: Vec<ExplanationStep>,
}