canwu-sim 0.11.1

Deterministic simulation runtime, scheduling, persistence, replay, and plugins for Canwu
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
use super::{
    ArmyId, BoundaryReceipt, BoundaryRequest, CanwuError, CauseRef, CommandAttemptId, CommandId,
    CommandPolicyContext, CommandRequestId, CommandTransactionCheckpoint, Deserialize, EntityRef,
    ErrorCode, EventId, IngressId, IngressTransactionCheckpoint, InteractionPolicy, LetterId,
    PayloadSchema, PersonId, RejectionTransactionCheckpoint, Serialize, SimDuration, SimTime,
    Simulation, SystemCadence, TerritoryId, Value, canonical_hash, claim_counter,
    invalid_snapshot_error, is_expected_command_rejection, resolve_command_authority,
    runtime_entity_exists, runtime_entity_identity_exists, runtime_has_unqueued_command_history,
    validate_command_ingress_policy, validate_runtime_cause,
};
use std::cmp::Reverse;

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", content = "id", rename_all = "snake_case")]
pub enum Issuer {
    Actor(PersonId),
    Human(String),
    Ai(String),
    Institution(String),
    Replay(String),
    Experiment(String),
    Debug,
    System(String),
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CommandIngress {
    LegacyDirect,
    LiveRequest,
    FrozenReplay,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum DecisionOrigin {
    Actor {
        actor: PersonId,
    },
    Institution {
        institution: EntityRef,
        responsible_actor: Option<PersonId>,
    },
    Council {
        council_id: String,
    },
    NoResponsibleActor {
        reason: String,
    },
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CommandAuthority {
    pub decision_origin: DecisionOrigin,
    pub seat_id: Option<String>,
    pub permission_profile_id: Option<String>,
    pub command_subject: Option<EntityRef>,
}

impl CommandAuthority {
    #[must_use]
    pub const fn for_actor(actor: PersonId) -> Self {
        Self {
            decision_origin: DecisionOrigin::Actor { actor },
            seat_id: None,
            permission_profile_id: None,
            command_subject: None,
        }
    }

    #[must_use]
    pub fn no_responsible_actor(reason: impl Into<String>) -> Self {
        Self {
            decision_origin: DecisionOrigin::NoResponsibleActor {
                reason: reason.into(),
            },
            seat_id: None,
            permission_profile_id: None,
            command_subject: None,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CommandContext {
    pub issuer: Issuer,
    pub authority: CommandAuthority,
    /// Present only when the engine admitted this command as the selected
    /// action of a validated `DecisionTicket` controller.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decision_controller_id: Option<String>,
    pub run_policy: CommandPolicyContext,
    pub ingress: CommandIngress,
    pub attempt_id: Option<CommandAttemptId>,
    pub command_id: CommandId,
    pub request_id: Option<CommandRequestId>,
    pub revision: u64,
    pub simulation_time: SimTime,
    pub expected_revision: Option<u64>,
    pub expected_time: Option<SimTime>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Command {
    OrderMovement {
        subject: EntityRef,
        destination: TerritoryId,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        cargo: Vec<LetterId>,
    },
    DebugSetArmyMorale {
        army: ArmyId,
        morale: u16,
    },
    Plugin {
        plugin: String,
        command: String,
        payload: Value,
    },
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct CommandEnvelope {
    pub issuer: Issuer,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub authority: Option<CommandAuthority>,
    pub command: Command,
    pub expected_time: Option<SimTime>,
}

impl CommandEnvelope {
    #[must_use]
    pub const fn new(issuer: Issuer, command: Command) -> Self {
        Self {
            issuer,
            authority: None,
            command,
            expected_time: None,
        }
    }

    #[must_use]
    pub const fn at_time(mut self, expected_time: SimTime) -> Self {
        self.expected_time = Some(expected_time);
        self
    }

    #[must_use]
    pub fn with_authority(mut self, authority: CommandAuthority) -> Self {
        self.authority = Some(authority);
        self
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct CommandRequest {
    pub request_id: CommandRequestId,
    /// Must equal the persisted authoritative revision at command admission.
    ///
    /// Accepted commands, persisted expected rejections, and completed
    /// settlement boundaries advance the revision. Bare clock movement does
    /// not, so declared external commands also carry `envelope.expected_time`.
    pub expected_revision: u64,
    pub envelope: CommandEnvelope,
}

impl CommandRequest {
    #[must_use]
    pub const fn new(
        request_id: CommandRequestId,
        expected_revision: u64,
        envelope: CommandEnvelope,
    ) -> Self {
        Self {
            request_id,
            expected_revision,
            envelope,
        }
    }
}

#[derive(Clone, Copy)]
pub(super) struct CommandAdmission {
    pub(super) request_id: Option<CommandRequestId>,
    pub(super) expected_revision: Option<u64>,
    pub(super) expected_time: Option<SimTime>,
    pub(super) revision_before: u64,
    pub(super) ingress: CommandIngress,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct CommandRecord {
    pub id: CommandId,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attempt_id: Option<CommandAttemptId>,
    pub accepted_at: SimTime,
    pub envelope: CommandEnvelope,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub emitted_events: Vec<EventId>,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CommandReceipt {
    pub attempt_id: Option<CommandAttemptId>,
    pub command_id: CommandId,
    pub request_id: Option<CommandRequestId>,
    /// Authoritative revision after the accepted command commits.
    pub revision: u64,
    pub accepted_at: SimTime,
    pub emitted_events: Vec<EventId>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct CommandRejection {
    pub attempt_id: Option<CommandAttemptId>,
    pub request_id: Option<CommandRequestId>,
    /// Authoritative revision after persisted rejection evidence commits.
    /// Non-persisted conflicts retain the already committed current revision.
    pub retained_revision: u64,
    pub rejected_at: SimTime,
    pub error: CanwuError,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "decision", rename_all = "snake_case")]
pub enum CommandOutcome {
    Accepted { receipt: CommandReceipt },
    Rejected { rejection: CommandRejection },
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "decision", rename_all = "snake_case")]
pub enum CommandAttemptOutcome {
    Accepted { command_id: CommandId },
    Rejected { error: CanwuError },
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct CommandAttemptRecord {
    pub id: CommandAttemptId,
    pub at: SimTime,
    /// Authoritative revision immediately before this attempt transaction.
    pub revision_before: u64,
    pub ingress: CommandIngress,
    pub request_id: Option<CommandRequestId>,
    pub expected_revision: Option<u64>,
    pub envelope: CommandEnvelope,
    pub outcome: CommandAttemptOutcome,
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum IngressClass {
    Command,
    Communication,
    Acknowledgement,
    Information,
    Decision,
    ScheduledSystem,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct PluginIngressDescriptor {
    pub name: String,
    pub description: String,
    pub class: IngressClass,
    pub payload_schema: PayloadSchema,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct PluginIngressRequest {
    pub plugin: String,
    pub packet_type: String,
    pub due_at: SimTime,
    pub priority: i32,
    pub payload: Value,
    pub affected_entities: Vec<EntityRef>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cause: Option<CauseRef>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub archive_retention: Vec<PluginArchiveRetention>,
}

#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PluginArchiveRetention {
    pub namespace: String,
    pub object_id: String,
}

/// Opaque capability issued only while a plugin registers a kernel-internal
/// ingress type. Hosts can pass the capability back but cannot construct or
/// alter it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PluginIngressPermit {
    pub(super) plugin: String,
    pub(super) packet_type: String,
    pub(super) semantic_hash: String,
    pub(super) token: String,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "maintenance", rename_all = "snake_case")]
pub enum MaintenanceIngressRequest {
    DecisionArchive {
        commit: super::VerifiedDecisionArchiveCommit,
    },
    OwnerAuthorized {
        commit: super::VerifiedOwnerAuthorizedMaintenanceCommit,
    },
}

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MaintenanceDisposition {
    Applied,
    RejectedStale,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MaintenanceRejectionReceipt {
    pub token: String,
    pub expected_source_root: String,
    pub observed_source_root: String,
    pub reason: String,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct MaintenanceChangeRecord {
    pub kind: String,
    pub token: String,
    pub disposition: MaintenanceDisposition,
    pub source_root: String,
    pub target_root: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rejection: Option<MaintenanceRejectionReceipt>,
}

impl PluginIngressRequest {
    #[must_use]
    pub fn new(
        plugin: impl Into<String>,
        packet_type: impl Into<String>,
        due_at: SimTime,
        payload: Value,
    ) -> Self {
        Self {
            plugin: plugin.into(),
            packet_type: packet_type.into(),
            due_at,
            priority: 0,
            payload,
            affected_entities: Vec::new(),
            cause: None,
            archive_retention: Vec::new(),
        }
    }

    #[must_use]
    pub const fn with_priority(mut self, priority: i32) -> Self {
        self.priority = priority;
        self
    }

    #[must_use]
    pub fn with_entity(mut self, entity: EntityRef) -> Self {
        self.affected_entities.push(entity);
        self
    }

    #[must_use]
    pub fn caused_by(mut self, cause: CauseRef) -> Self {
        self.cause = Some(cause);
        self
    }

    #[must_use]
    pub fn with_archive_retention(
        mut self,
        retention: impl IntoIterator<Item = PluginArchiveRetention>,
    ) -> Self {
        self.archive_retention.extend(retention);
        self
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum IngressPayload {
    Command {
        request: Box<CommandRequest>,
    },
    Plugin {
        plugin: String,
        packet_type: String,
        payload: Value,
        affected_entities: Vec<EntityRef>,
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        archive_retention: Vec<PluginArchiveRetention>,
    },
    Calendar {
        cadences: Vec<SystemCadence>,
    },
    Decision {
        request: Box<super::DecisionIngressRequest>,
    },
    Maintenance {
        request: Box<MaintenanceIngressRequest>,
    },
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct IngressRecord {
    pub id: IngressId,
    pub issued_at: SimTime,
    #[serde(default, skip_serializing_if = "is_zero")]
    pub eligible_boundary_count: u64,
    pub due_at: SimTime,
    pub class: IngressClass,
    pub priority: i32,
    pub payload: IngressPayload,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cause: Option<CauseRef>,
}

#[allow(clippy::trivially_copy_pass_by_ref)]
const fn is_zero(value: &u64) -> bool {
    *value == 0
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct IngressReceipt {
    pub ingress_id: IngressId,
    pub issued_at: SimTime,
    pub due_at: SimTime,
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct IngressQueueKey {
    pub due_at: SimTime,
    pub class: IngressClass,
    pub priority: Reverse<i32>,
    pub issued_at: SimTime,
    pub id: IngressId,
}

impl IngressQueueKey {
    #[must_use]
    pub(crate) const fn from_record(record: &IngressRecord) -> Self {
        Self {
            due_at: record.due_at,
            class: record.class,
            priority: Reverse(record.priority),
            issued_at: record.issued_at,
            id: record.id,
        }
    }
}

impl Simulation {
    pub fn submit(&mut self, envelope: CommandEnvelope) -> Result<CommandReceipt, CanwuError> {
        match self.admit_command(
            None,
            None,
            envelope,
            CommandIngress::LegacyDirect,
            None,
            false,
        )? {
            CommandOutcome::Accepted { receipt } => Ok(receipt),
            CommandOutcome::Rejected { rejection } => Err(rejection.error),
        }
    }

    pub fn enqueue_command(
        &mut self,
        due_at: SimTime,
        priority: i32,
        request: CommandRequest,
    ) -> Result<IngressReceipt, CanwuError> {
        self.ensure_runtime_ready()?;
        self.ensure_canonical_ingress_can_start()?;
        self.ensure_command_ingress_family(CommandIngress::LiveRequest)?;
        if let Some(existing) = self
            .state
            .evidence
            .archived_ingress_requests
            .get(&request.request_id)
        {
            let input_hash = canonical_hash(
                "canwu.archive.ingress.command.v1",
                &(due_at, priority, &request),
            )?;
            if existing.input_hash == input_hash {
                return Ok(existing.receipt.clone());
            }
            return Err(CanwuError::new(
                ErrorCode::IdempotencyConflict,
                format!(
                    "command request {} is already queued with different ingress content",
                    request.request_id
                ),
            ));
        }
        for record in &self.state.evidence.ingress {
            let IngressPayload::Command { request: existing } = &record.payload else {
                continue;
            };
            if existing.request_id != request.request_id {
                continue;
            }
            if existing.as_ref() == &request
                && record.due_at == due_at
                && record.priority == priority
            {
                return Ok(IngressReceipt {
                    ingress_id: record.id,
                    issued_at: record.issued_at,
                    due_at: record.due_at,
                });
            }
            return Err(CanwuError::new(
                ErrorCode::IdempotencyConflict,
                format!(
                    "command request {} is already queued with different ingress content",
                    request.request_id
                ),
            ));
        }
        if self.command_request_id_is_in_use(request.request_id) {
            return Err(CanwuError::new(
                ErrorCode::IdempotencyConflict,
                format!(
                    "command request {} is already reserved or processed",
                    request.request_id
                ),
            ));
        }
        if request
            .envelope
            .expected_time
            .is_some_and(|expected| expected != due_at)
        {
            return Err(CanwuError::new(
                ErrorCode::SimulationTimeConflict,
                "queued command expected time must equal its due simulation time",
            ));
        }
        self.append_ingress(
            due_at,
            IngressClass::Command,
            priority,
            IngressPayload::Command {
                request: Box::new(request),
            },
            None,
            false,
        )
    }

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

    /// Queues a plugin-owned internal ingress through an opaque capability
    /// returned by [`super::plugins::PluginRegistrar::register_internal_ingress`].
    pub fn enqueue_permitted_plugin_ingress(
        &mut self,
        request: PluginIngressRequest,
        permit: &PluginIngressPermit,
    ) -> Result<IngressReceipt, CanwuError> {
        self.enqueue_plugin_ingress_inner(request, Some(permit), false)
    }

    pub(super) fn replay_plugin_ingress(
        &mut self,
        request: PluginIngressRequest,
    ) -> Result<IngressReceipt, CanwuError> {
        self.enqueue_plugin_ingress_inner(request, None, true)
    }

    fn enqueue_plugin_ingress_inner(
        &mut self,
        mut request: PluginIngressRequest,
        permit: Option<&PluginIngressPermit>,
        replay: bool,
    ) -> Result<IngressReceipt, CanwuError> {
        self.ensure_runtime_ready()?;
        self.ensure_canonical_ingress_can_start()?;
        if !replay
            && self
                .state
                .metadata
                .run_configuration
                .declared()
                .is_some_and(|configuration| {
                    configuration.interaction == InteractionPolicy::ReadOnly
                })
        {
            return Err(CanwuError::new(
                ErrorCode::InteractionReadOnly,
                "the run interaction policy rejects newly authored plugin ingress",
            ));
        }
        let key = (request.plugin.clone(), request.packet_type.clone());
        let descriptor = self.plugins.ingress.get(&key).ok_or_else(|| {
            CanwuError::new(
                ErrorCode::InvalidPayload,
                format!(
                    "plugin ingress type {}.{} is not registered",
                    request.plugin, request.packet_type
                ),
            )
        })?;
        let internal = self.plugins.internal_ingress.contains(&key);
        if internal && !replay {
            let semantic_hash = self
                .plugins
                .descriptors
                .get(&request.plugin)
                .map(|descriptor| descriptor.semantic_hash.as_str())
                .ok_or_else(|| {
                    CanwuError::new(
                        ErrorCode::PluginNotActive,
                        "internal plugin ingress owner is unavailable",
                    )
                })?;
            let expected_token = super::canonical_hash(
                "canwu.plugin.internal-ingress-permit.v1",
                &(&request.plugin, &request.packet_type, semantic_hash),
            )?;
            if permit.is_none_or(|permit| {
                permit.plugin != request.plugin
                    || permit.packet_type != request.packet_type
                    || permit.semantic_hash != semantic_hash
                    || permit.token != expected_token
            }) {
                return Err(CanwuError::new(
                    ErrorCode::InvalidAuthority,
                    "plugin-owned internal ingress requires its opaque registration permit",
                ));
            }
        }
        if !request.archive_retention.is_empty() && !internal && !replay {
            return Err(CanwuError::new(
                ErrorCode::InvalidAuthority,
                "archive retention may be attached only to plugin-owned internal ingress",
            ));
        }
        request.archive_retention.sort();
        request.archive_retention.dedup();
        if request.archive_retention.len() > 32_768
            || request.archive_retention.iter().any(|retention| {
                retention.namespace.is_empty()
                    || retention.namespace.len() > 128
                    || retention.object_id.is_empty()
                    || retention.object_id.len() > 256
                    || !retention.namespace.bytes().all(|byte| {
                        byte.is_ascii_lowercase()
                            || byte.is_ascii_digit()
                            || matches!(byte, b'.' | b'-' | b'_')
                    })
                    || !retention.object_id.is_ascii()
            })
        {
            return Err(CanwuError::new(
                ErrorCode::InvalidPayload,
                "plugin ingress archive retention is malformed or exceeds its hard limit",
            ));
        }
        self.plugins.validate_archive_retention(
            &request.plugin,
            &request.packet_type,
            &request.payload,
            &request.archive_retention,
        )?;
        descriptor.payload_schema.validate(&request.payload)?;
        request.affected_entities.sort();
        request.affected_entities.dedup();
        if request
            .affected_entities
            .iter()
            .any(|entity| !runtime_entity_identity_exists(&self.state, entity))
        {
            return Err(CanwuError::new(
                ErrorCode::EntityNotFound,
                "plugin ingress references an unknown entity identity",
            ));
        }
        if let Some(cause) = &request.cause {
            if matches!(
                cause,
                CauseRef::Boundary(_) | CauseRef::Command(_) | CauseRef::Event(_)
            ) {
                return Err(CanwuError::new(
                    ErrorCode::InvalidPayload,
                    "boundary, command, and event causes are reserved for plugin-generated ingress",
                ));
            }
            validate_runtime_cause(&self.state, cause)?;
        }
        self.append_ingress(
            request.due_at,
            descriptor.class,
            request.priority,
            IngressPayload::Plugin {
                plugin: request.plugin,
                packet_type: request.packet_type,
                payload: request.payload,
                affected_entities: request.affected_entities,
                archive_retention: request.archive_retention,
            },
            request.cause,
            false,
        )
    }

    pub fn schedule_calendar_boundary(
        &mut self,
        due_at: SimTime,
        mut cadences: Vec<SystemCadence>,
    ) -> Result<IngressReceipt, CanwuError> {
        self.ensure_runtime_ready()?;
        self.ensure_canonical_ingress_can_start()?;
        if cadences.contains(&SystemCadence::EventDriven) {
            return Err(CanwuError::new(
                ErrorCode::InvalidBoundary,
                "calendar ingress cannot declare event-driven cadence",
            ));
        }
        cadences.sort();
        cadences.dedup();
        if cadences.is_empty() {
            return Err(CanwuError::new(
                ErrorCode::InvalidBoundary,
                "calendar ingress requires at least one scheduled cadence",
            ));
        }
        self.append_ingress(
            due_at,
            IngressClass::ScheduledSystem,
            0,
            IngressPayload::Calendar { cadences },
            Some(CauseRef::System("canwu.core.calendar".to_owned())),
            false,
        )
    }

    pub(super) fn append_ingress(
        &mut self,
        due_at: SimTime,
        class: IngressClass,
        priority: i32,
        payload: IngressPayload,
        cause: Option<CauseRef>,
        after_current_boundary: bool,
    ) -> Result<IngressReceipt, CanwuError> {
        if due_at < self.state.scheduler.now {
            return Err(CanwuError::new(
                ErrorCode::LateIngress,
                format!(
                    "ingress due at {due_at} cannot be queued after committed time {}",
                    self.state.scheduler.now
                ),
            ));
        }
        let transaction = IngressTransactionCheckpoint::capture(&self.state);
        let (id, next_id) = claim_counter(self.state.counters.next_ingress_id, "ingress ID")?;
        let boundary_count = self
            .state
            .evidence
            .archived
            .boundary_count
            .checked_add(
                u64::try_from(self.state.evidence.boundaries.len()).map_err(|_| {
                    CanwuError::new(
                        ErrorCode::IdentifierExhausted,
                        "boundary count exceeds the ingress journal range",
                    )
                })?,
            )
            .ok_or_else(|| {
                CanwuError::new(
                    ErrorCode::IdentifierExhausted,
                    "boundary count exceeds the ingress journal range",
                )
            })?;
        let eligible_boundary_count = if after_current_boundary {
            boundary_count.checked_add(1).ok_or_else(|| {
                CanwuError::new(
                    ErrorCode::IdentifierExhausted,
                    "ingress boundary eligibility exceeds the journal range",
                )
            })?
        } else {
            boundary_count
        };
        let record = IngressRecord {
            id: IngressId::new(id),
            issued_at: self.state.scheduler.now,
            eligible_boundary_count,
            due_at,
            class,
            priority,
            payload,
            cause,
        };
        let queue_key = IngressQueueKey::from_record(&record);
        self.state.counters.next_ingress_id = next_id;
        self.state.scheduler.pending_ingress.insert(queue_key);
        self.state.evidence.ingress.push(record.clone());
        self.state.metadata.plugin_registration_closed = true;
        if let Err(error) = self.refresh_checkpoint_hash() {
            transaction.restore(&mut self.state, &queue_key);
            return Err(error);
        }
        Ok(IngressReceipt {
            ingress_id: record.id,
            issued_at: record.issued_at,
            due_at: record.due_at,
        })
    }

    pub fn process_command(
        &mut self,
        request: CommandRequest,
    ) -> Result<CommandOutcome, CanwuError> {
        self.ensure_runtime_ready()?;
        if self.state.evidence.archived.ingress_count != 0
            || !self.state.evidence.ingress.is_empty()
        {
            return Err(CanwuError::new(
                ErrorCode::MixedCommandIngress,
                "direct command requests cannot bypass an active canonical ingress journal",
            ));
        }
        self.admit_command(
            Some(request.request_id),
            Some(request.expected_revision),
            request.envelope,
            CommandIngress::LiveRequest,
            None,
            true,
        )
    }

    pub(super) fn admit_command(
        &mut self,
        request_id: Option<CommandRequestId>,
        expected_revision: Option<u64>,
        envelope: CommandEnvelope,
        ingress: CommandIngress,
        decision_controller_id: Option<String>,
        record_attempt: bool,
    ) -> Result<CommandOutcome, CanwuError> {
        self.ensure_runtime_ready()?;
        self.ensure_command_ingress_family(ingress)?;
        if let Some(cached) =
            self.cached_command_outcome(request_id, expected_revision, &envelope)?
        {
            return Ok(cached);
        }

        let revision_before = self.revision();
        let admission = CommandAdmission {
            request_id,
            expected_revision,
            expected_time: envelope.expected_time,
            revision_before,
            ingress,
        };
        let attempt_id = if record_attempt {
            let (value, _) = claim_counter(
                self.state.counters.next_command_attempt_id,
                "command attempt ID",
            )?;
            CommandAttemptId::new(value)
        } else {
            CommandAttemptId::default()
        };
        let authority = match resolve_command_authority(&envelope) {
            Ok(authority) => authority,
            Err(error) if is_expected_command_rejection(&error.code) && record_attempt => {
                return self.record_command_rejection(attempt_id, admission, envelope, error);
            }
            Err(error) => return Err(error),
        };
        if let Err(error) = self.validate_command_ingress(&envelope.issuer, &authority, admission) {
            if is_expected_command_rejection(&error.code) && record_attempt {
                return self.record_command_rejection(attempt_id, admission, envelope, error);
            }
            return Err(error);
        }
        if let Some(expected_time) = envelope.expected_time
            && expected_time != self.state.scheduler.now
        {
            let error = CanwuError::new(
                ErrorCode::SimulationTimeConflict,
                format!(
                    "command expected time {expected_time}, but simulation is at {}",
                    self.state.scheduler.now
                ),
            );
            if record_attempt {
                return self.record_command_rejection(attempt_id, admission, envelope, error);
            }
            return Err(error);
        }

        let (command_id_value, next_command_id) =
            claim_counter(self.state.counters.next_command_id, "command ID")?;
        let (correlation_id, next_correlation_id) =
            claim_counter(self.state.counters.next_correlation_id, "correlation ID")?;
        let command_id = CommandId::new(command_id_value);
        let context = CommandContext {
            issuer: envelope.issuer.clone(),
            authority,
            decision_controller_id,
            run_policy: self.state.metadata.run_configuration.command_policy(),
            ingress: admission.ingress,
            attempt_id: record_attempt.then_some(attempt_id),
            command_id,
            request_id: admission.request_id,
            revision: admission.revision_before,
            simulation_time: self.state.scheduler.now,
            expected_revision: admission.expected_revision,
            expected_time: envelope.expected_time,
        };
        let prepared = match self.prepare_command(&envelope, &context) {
            Ok(prepared) => prepared,
            Err(error) if is_expected_command_rejection(&error.code) && record_attempt => {
                return self.record_command_rejection(attempt_id, admission, envelope, error);
            }
            Err(error) => return Err(error),
        };
        let next_attempt_id = if record_attempt {
            let (claimed_id, next_attempt_id) = claim_counter(
                self.state.counters.next_command_attempt_id,
                "command attempt ID",
            )?;
            if claimed_id != attempt_id.get() {
                return Err(CanwuError::new(
                    ErrorCode::InvalidSnapshot,
                    "command attempt allocation changed during application",
                ));
            }
            Some(next_attempt_id)
        } else {
            None
        };
        let revision = self.next_state_revision()?;
        let transaction = CommandTransactionCheckpoint::capture(&self.state);
        let event_start = self.state.evidence.events.len();
        self.state.counters.next_command_id = next_command_id;
        self.state.counters.next_correlation_id = next_correlation_id;
        self.invalidate_commitments(prepared.commitment_invalidation());

        if let Err(error) = self.apply_prepared(prepared, command_id, correlation_id) {
            transaction.restore(&mut self.state);
            if is_expected_command_rejection(&error.code) && record_attempt {
                return self.record_command_rejection(attempt_id, admission, envelope, error);
            }
            return Err(error);
        }
        let emitted_events: Vec<_> = self.state.evidence.events[event_start..]
            .iter()
            .map(|event| event.id)
            .collect();
        self.state.metadata.plugin_registration_closed = true;
        self.state.evidence.commands.push(CommandRecord {
            id: command_id,
            attempt_id: record_attempt.then_some(attempt_id),
            accepted_at: self.state.scheduler.now,
            envelope: envelope.clone(),
            emitted_events: if record_attempt {
                emitted_events.clone()
            } else {
                Vec::new()
            },
        });
        if let Some(next_attempt_id) = next_attempt_id {
            self.state.counters.next_command_attempt_id = next_attempt_id;
            self.state
                .evidence
                .command_attempts
                .push(CommandAttemptRecord {
                    id: attempt_id,
                    at: self.state.scheduler.now,
                    revision_before: admission.revision_before,
                    ingress: admission.ingress,
                    request_id: admission.request_id,
                    expected_revision: admission.expected_revision,
                    envelope,
                    outcome: CommandAttemptOutcome::Accepted { command_id },
                });
        }
        self.state.counters.state_revision = revision;
        if let Err(error) = self.refresh_checkpoint_hash() {
            transaction.restore(&mut self.state);
            return Err(error);
        }

        Ok(CommandOutcome::Accepted {
            receipt: CommandReceipt {
                attempt_id: record_attempt.then_some(attempt_id),
                command_id,
                request_id: admission.request_id,
                revision,
                accepted_at: self.state.scheduler.now,
                emitted_events,
            },
        })
    }

    fn ensure_command_ingress_family(&self, ingress: CommandIngress) -> Result<(), CanwuError> {
        let has_legacy_commands = self.state.evidence.archived_legacy_commands
            || self
                .state
                .evidence
                .commands
                .iter()
                .any(|record| record.attempt_id.is_none());
        let has_tracked_attempts = self.state.evidence.archived_tracked_attempts
            || !self.state.evidence.command_attempts.is_empty()
            || !self.state.evidence.ingress.is_empty();
        if (ingress == CommandIngress::LegacyDirect && has_tracked_attempts)
            || (ingress != CommandIngress::LegacyDirect && has_legacy_commands)
        {
            return Err(CanwuError::new(
                ErrorCode::MixedCommandIngress,
                "legacy-direct commands and tracked request/replay attempts cannot coexist in one run",
            ));
        }
        Ok(())
    }

    pub(super) fn ensure_canonical_ingress_can_start(&self) -> Result<(), CanwuError> {
        if runtime_has_unqueued_command_history(&self.state) {
            return Err(CanwuError::new(
                ErrorCode::MixedCommandIngress,
                "canonical ingress cannot be added after direct command history",
            ));
        }
        Ok(())
    }

    fn cached_command_outcome(
        &self,
        request_id: Option<CommandRequestId>,
        expected_revision: Option<u64>,
        envelope: &CommandEnvelope,
    ) -> Result<Option<CommandOutcome>, CanwuError> {
        let Some(request_id) = request_id else {
            return Ok(None);
        };
        if let Some(cached) = self
            .state
            .evidence
            .archived_command_requests
            .get(&request_id)
        {
            let input_hash = canonical_hash(
                "canwu.archive.command.request.v1",
                &(expected_revision, envelope),
            )?;
            if cached.input_hash != input_hash {
                return Ok(Some(CommandOutcome::Rejected {
                    rejection: CommandRejection {
                        attempt_id: None,
                        request_id: Some(request_id),
                        retained_revision: self.revision(),
                        rejected_at: self.state.scheduler.now,
                        error: CanwuError::new(
                            ErrorCode::IdempotencyConflict,
                            "this command request ID was already used for different input",
                        ),
                    },
                }));
            }
            return Ok(Some(cached.outcome.clone()));
        }
        let Some(attempt) = self
            .state
            .evidence
            .command_attempts
            .iter()
            .find(|attempt| attempt.request_id == Some(request_id))
        else {
            return Ok(None);
        };
        if attempt.expected_revision != expected_revision || &attempt.envelope != envelope {
            return Ok(Some(CommandOutcome::Rejected {
                rejection: CommandRejection {
                    attempt_id: None,
                    request_id: Some(request_id),
                    retained_revision: self.revision(),
                    rejected_at: self.state.scheduler.now,
                    error: CanwuError::new(
                        ErrorCode::IdempotencyConflict,
                        "this command request ID was already used for different input",
                    ),
                },
            }));
        }
        Ok(Some(self.command_outcome_from_attempt(attempt)?))
    }

    pub(super) fn command_outcome_from_attempt(
        &self,
        attempt: &CommandAttemptRecord,
    ) -> Result<CommandOutcome, CanwuError> {
        let request_id = attempt.request_id.ok_or_else(|| {
            invalid_snapshot_error("tracked command attempt is missing its request ID")
        })?;
        let committed_revision = attempt.revision_before.checked_add(1).ok_or_else(|| {
            invalid_snapshot_error("cached command attempt revision is exhausted")
        })?;
        match &attempt.outcome {
            CommandAttemptOutcome::Accepted { command_id } => {
                let retained_number = command_id
                    .get()
                    .checked_sub(self.state.evidence.archived.command_count)
                    .and_then(|value| value.checked_sub(1))
                    .ok_or_else(|| {
                        invalid_snapshot_error(
                            "accepted command attempt references archived command evidence",
                        )
                    })?;
                let index = usize::try_from(retained_number).map_err(|_| {
                    invalid_snapshot_error(
                        "accepted command attempt exceeds the retained command index space",
                    )
                })?;
                let record = self
                    .state
                    .evidence
                    .commands
                    .get(index)
                    .filter(|record| record.id == *command_id)
                    .ok_or_else(|| {
                        invalid_snapshot_error(
                            "accepted command attempt references a missing command",
                        )
                    })?;
                Ok(CommandOutcome::Accepted {
                    receipt: CommandReceipt {
                        attempt_id: Some(attempt.id),
                        command_id: *command_id,
                        request_id: Some(request_id),
                        revision: committed_revision,
                        accepted_at: record.accepted_at,
                        emitted_events: record.emitted_events.clone(),
                    },
                })
            }
            CommandAttemptOutcome::Rejected { error } => Ok(CommandOutcome::Rejected {
                rejection: CommandRejection {
                    attempt_id: Some(attempt.id),
                    request_id: Some(request_id),
                    retained_revision: committed_revision,
                    rejected_at: attempt.at,
                    error: error.clone(),
                },
            }),
        }
    }

    fn record_command_rejection(
        &mut self,
        attempt_id: CommandAttemptId,
        admission: CommandAdmission,
        envelope: CommandEnvelope,
        error: CanwuError,
    ) -> Result<CommandOutcome, CanwuError> {
        let (claimed_id, next_attempt_id) = claim_counter(
            self.state.counters.next_command_attempt_id,
            "command attempt ID",
        )?;
        if claimed_id != attempt_id.get() {
            return Err(CanwuError::new(
                ErrorCode::InvalidSnapshot,
                "command attempt allocation changed during rejection",
            ));
        }
        let revision = self.next_state_revision()?;
        let attempt = CommandAttemptRecord {
            id: attempt_id,
            at: self.state.scheduler.now,
            revision_before: admission.revision_before,
            ingress: admission.ingress,
            request_id: admission.request_id,
            expected_revision: admission.expected_revision,
            envelope,
            outcome: CommandAttemptOutcome::Rejected {
                error: error.clone(),
            },
        };
        let transaction = RejectionTransactionCheckpoint::capture(&self.state);
        self.state.counters.next_command_attempt_id = next_attempt_id;
        self.state.counters.state_revision = revision;
        self.state.metadata.plugin_registration_closed = true;
        self.state.evidence.command_attempts.push(attempt);
        if let Err(hash_error) = self.refresh_checkpoint_hash() {
            transaction.restore(&mut self.state);
            return Err(hash_error);
        }
        Ok(CommandOutcome::Rejected {
            rejection: CommandRejection {
                attempt_id: Some(attempt_id),
                request_id: admission.request_id,
                retained_revision: revision,
                rejected_at: self.state.scheduler.now,
                error,
            },
        })
    }

    fn validate_command_ingress(
        &self,
        issuer: &Issuer,
        authority: &CommandAuthority,
        admission: CommandAdmission,
    ) -> Result<(), CanwuError> {
        validate_command_ingress_policy(
            &self.state.metadata.run_configuration,
            issuer,
            authority,
            admission,
            &|entity| runtime_entity_exists(&self.state, entity),
        )
    }

    pub fn advance_canonical(
        &mut self,
        duration: SimDuration,
    ) -> Result<Vec<BoundaryReceipt>, CanwuError> {
        self.ensure_runtime_ready()?;
        if duration.is_negative() {
            return Err(CanwuError::new(
                ErrorCode::InvalidDuration,
                "canonical simulation time cannot advance by a negative duration",
            ));
        }
        let target = self
            .state
            .scheduler
            .now
            .checked_add(duration)
            .ok_or_else(|| {
                CanwuError::new(
                    ErrorCode::InvalidDuration,
                    "canonical simulation target time exceeds the supported range",
                )
            })?;
        let mut receipts = Vec::new();
        while let Some(next_due) = self.next_canonical_due_time()
            && next_due <= target
        {
            let at = next_due.max(self.state.scheduler.now);
            receipts.push(self.settle_boundary(BoundaryRequest::at(at))?);
        }
        if self.state.scheduler.now < target {
            self.advance_to(target)?;
        }
        Ok(receipts)
    }

    pub fn step_canonical(&mut self) -> Result<Option<BoundaryReceipt>, CanwuError> {
        self.ensure_runtime_ready()?;
        let Some(next_due) = self.next_canonical_due_time() else {
            return Ok(None);
        };
        self.settle_boundary(BoundaryRequest::at(next_due.max(self.state.scheduler.now)))
            .map(Some)
    }

    fn next_canonical_due_time(&self) -> Option<SimTime> {
        let scheduled = self.state.scheduler.actions.keys().next().map(|key| key.at);
        let ingress = self
            .state
            .scheduler
            .pending_ingress
            .first()
            .map(|key| key.due_at);
        match (scheduled, ingress) {
            (Some(left), Some(right)) => Some(left.min(right)),
            (Some(value), None) | (None, Some(value)) => Some(value),
            (None, None) => None,
        }
    }

    pub(super) fn take_due_ingress(&mut self, at: SimTime) -> Vec<IngressId> {
        let mut admitted = Vec::new();
        while self
            .state
            .scheduler
            .pending_ingress
            .first()
            .is_some_and(|key| key.due_at <= at)
        {
            let key = self
                .state
                .scheduler
                .pending_ingress
                .pop_first()
                .expect("pending ingress was checked as non-empty");
            admitted.push(key.id);
        }
        admitted
    }
}