axioval-engine 0.3.0

Trusted capability compiler and deterministic source-neutral validation runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
//! Trusted capability compilation and deterministic runtime.
#![forbid(unsafe_code)]
#![allow(missing_docs, clippy::missing_errors_doc)]

use std::{
    collections::{BTreeMap, BTreeSet},
    sync::Arc,
};

pub use axioval_ir::NotEvaluatedReason;
use axioval_ir::contract as schema;
use axioval_ir::{
    Finding, Location, NotEvaluated, ObjectId, Project, Report, ReportTable, RuleId, RuleSummary,
    Scope, SourceId,
};
use thiserror::Error;

mod session;

/// Errors while compiling untrusted declarations into a trusted execution plan.
#[derive(Debug, Error, PartialEq, Eq)]
pub enum EngineError {
    /// A package declares a schema version this compiler does not implement.
    #[error(
        "unsupported schema version `{version}` for {package_kind} `{package_id}`; supported: {supported}"
    )]
    UnsupportedSchemaVersion {
        package_kind: &'static str,
        package_id: String,
        version: String,
        supported: &'static str,
    },
    /// Multiple supplied definition packages declared the same package identity.
    #[error("duplicate definition package `{0}`")]
    DuplicateDefinitionPackage(String),
    /// A capability was not registered by the host.
    #[error("unknown capability `{0}`")]
    UnknownCapability(String),
    /// Two trusted implementations claimed an ID.
    #[error("duplicate capability `{0}`")]
    DuplicateCapability(String),
    /// A package supplied a non-declared parameter.
    #[error("capability `{capability}` does not declare parameter `{parameter}`")]
    UnknownParameter {
        capability: String,
        parameter: String,
    },
    /// A required parameter was absent.
    #[error("capability `{capability}` requires parameter `{parameter}`")]
    MissingParameter {
        capability: String,
        parameter: String,
    },
    /// A binding type did not conform to its descriptor.
    #[error("capability `{capability}` parameter `{parameter}` has invalid type")]
    InvalidParameterType {
        capability: String,
        parameter: String,
    },
    /// A row of a table-valued binding does not fit the declared columns.
    #[error("capability `{capability}` parameter `{parameter}` row {row}: {detail}")]
    InvalidTableRow {
        capability: String,
        parameter: String,
        /// Zero-based row index.
        row: usize,
        detail: String,
    },
    /// A rule binds a parameter more than once.
    #[error("rule has duplicate parameter binding `{0}`")]
    DuplicateBinding(String),
    /// A rule ID violates the engine identity contract.
    #[error("invalid rule id `{0}`")]
    InvalidRuleId(String),
    /// A rule references no loaded definition.
    #[error("unknown rule definition `{0}`")]
    UnknownDefinition(String),
    /// A ruleset references a definition package that was not supplied.
    #[error("missing definition package `{0}`")]
    MissingDefinitionPackage(String),
    /// A trusted capability descriptor conflicts with its portable definition.
    #[error("definition `{definition}` conflicts with capability `{capability}`: {detail}")]
    CapabilityContract {
        definition: String,
        capability: String,
        detail: String,
    },
    /// Rule IDs must be unique throughout the recursive folder tree.
    #[error("duplicate rule id `{0}`")]
    DuplicateRule(String),
    /// Two rulesets compiled together share a package ID.
    #[error("duplicate ruleset package `{0}`")]
    DuplicateRuleSet(String),
    /// No ruleset was given to compile.
    #[error("no ruleset to compile")]
    NoRuleSet,
    /// Two loaded definition packages declare the same concept identity.
    #[error("duplicate concept `{0}` across definition packages")]
    DuplicateConcept(String),
    /// A rule names a concept no loaded definition package declares.
    #[error("rule `{rule}` references unknown {kind} concept `{concept}`")]
    UnknownConcept {
        rule: String,
        kind: String,
        concept: String,
    },
    /// One rule reported two tables of one name.
    #[error("rule `{rule}` reported table `{table}` twice")]
    DuplicateReportTable { rule: String, table: String },
    /// A rule refines its outcomes in a way the package or the capability
    /// cannot support, such as severity bands on a capability that reports
    /// no deviation.
    #[error("rule `{rule}`: {detail}")]
    InvalidRefinement { rule: String, detail: String },
    /// The host asked the runtime to refine every outcome (locate it) and
    /// registered no outcome refiner to do so.
    #[error("{0} needs an outcome refiner, and the host registered none")]
    MissingRefiner(&'static str),
    /// A rule's gate or `ruleOutcome` selector names no rule of its
    /// ruleset, a cycle of rules depends on itself, or the host registered
    /// no outcome refiner to read another rule's selection.
    #[error("rule `{rule}`: {detail}")]
    InvalidDependency { rule: String, detail: String },
    /// A classification the ruleset derives is malformed, reads a rule's
    /// outcome, depends on itself through other classifications, is declared
    /// twice with different rows, or the host registered no outcome refiner
    /// to evaluate its rows.
    #[error("classification `{classification}`: {detail}")]
    InvalidClassification {
        classification: String,
        detail: String,
    },
}

pub use schema::ColumnKind;

/// One trusted column of a table parameter.
///
/// A definition's columns must match the descriptor's by ID, kind and
/// requirement, in any order; their names and descriptions are presentation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TableColumn {
    pub id: &'static str,
    pub kind: ColumnKind,
    pub required: bool,
}
impl TableColumn {
    /// A column every row must fill.
    #[must_use]
    pub const fn required(id: &'static str, kind: ColumnKind) -> Self {
        Self {
            id,
            kind,
            required: true,
        }
    }
    /// A column a row may leave empty.
    #[must_use]
    pub const fn optional(id: &'static str, kind: ColumnKind) -> Self {
        Self {
            id,
            kind,
            required: false,
        }
    }
}

/// Supported declarative parameter types.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ParameterType {
    Boolean,
    Integer,
    Number,
    String,
    Quantity,
    Enum,
    /// An ISO 8601 calendar date, validated when the package is read.
    Date,
    /// An ISO 8601 date-time with a UTC offset, validated when the package
    /// is read.
    DateTime,
    Reference,
    ObjectTypeReference,
    PropertyReference,
    Selector,
    StringList,
    ReferenceList,
    /// Rows of typed cells in the given columns.
    Table(&'static [TableColumn]),
}
impl ParameterType {
    /// The kind's spelling in a definition package.
    #[must_use]
    pub fn package_kind(self) -> &'static str {
        match self {
            Self::Boolean => "boolean",
            Self::Integer => "integer",
            Self::Number => "number",
            Self::String => "string",
            Self::Quantity => "quantity",
            Self::Enum => "enum",
            Self::Date => "date",
            Self::DateTime => "dateTime",
            Self::Reference => "reference",
            Self::ObjectTypeReference => "objectTypeReference",
            Self::PropertyReference => "propertyReference",
            Self::Selector => "selector",
            Self::StringList => "stringList",
            Self::ReferenceList => "referenceList",
            Self::Table(_) => "table",
        }
    }
    fn accepts(self, value: &schema::ParameterValue) -> bool {
        matches!(
            (self, value),
            (Self::Boolean, schema::ParameterValue::Boolean { .. })
                | (Self::Integer, schema::ParameterValue::Integer { .. })
                | (Self::Number, schema::ParameterValue::Number { .. })
                | (Self::String, schema::ParameterValue::String { .. })
                | (Self::Quantity, schema::ParameterValue::Quantity { .. })
                | (Self::Enum, schema::ParameterValue::Enum { .. })
                | (Self::Date, schema::ParameterValue::Date { .. })
                | (Self::DateTime, schema::ParameterValue::DateTime { .. })
                | (Self::Reference, schema::ParameterValue::Reference { .. })
                | (
                    Self::ObjectTypeReference,
                    schema::ParameterValue::ObjectTypeReference { .. }
                )
                | (
                    Self::PropertyReference,
                    schema::ParameterValue::PropertyReference { .. }
                )
                | (Self::Selector, schema::ParameterValue::Selector { .. })
                | (Self::StringList, schema::ParameterValue::StringList { .. })
                | (
                    Self::ReferenceList,
                    schema::ParameterValue::ReferenceList { .. }
                )
                | (Self::Table(_), schema::ParameterValue::Table { .. })
        )
    }
}
/// Trusted capability parameter descriptor.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParameterDescriptor {
    pub name: String,
    pub parameter_type: ParameterType,
    pub required: bool,
}
impl ParameterDescriptor {
    /// Required parameter descriptor.
    pub fn required(name: impl Into<String>, parameter_type: ParameterType) -> Self {
        Self {
            name: name.into(),
            parameter_type,
            required: true,
        }
    }
    /// Optional parameter descriptor.
    pub fn optional(name: impl Into<String>, parameter_type: ParameterType) -> Self {
        Self {
            name: name.into(),
            parameter_type,
            required: false,
        }
    }
}

/// One validated portable rule bound to trusted executable capability code.
#[derive(Clone, Debug, PartialEq)]
pub struct CompiledRule {
    /// Package-local stable rule ID.
    pub id: RuleId,
    /// Registered capability ID.
    pub capability: String,
    /// Rule severity.
    pub severity: schema::Severity,
    /// Source-neutral applicability selector.
    pub selector: schema::Selector,
    /// Strictly validated parameter bindings.
    pub parameters: BTreeMap<String, schema::ParameterValue>,
}

/// Source-neutral data and typed host services visible during one rule evaluation.
pub struct RuleContext<'a> {
    /// Immutable composed project view.
    pub project: &'a Project,
    /// Adapter-provided semantic and computational capabilities.
    pub services: &'a ServiceRegistry,
}

/// Fail-closed output from one trusted capability evaluation.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CapabilityEvaluation {
    findings: Vec<Finding>,
    not_evaluated: Vec<CapabilityNotEvaluated>,
    tables: Vec<ReportTable>,
    /// The deviation of each graded finding, by its index in `findings`.
    graded: Vec<(usize, Deviation)>,
}
/// A not-evaluated outcome before the runtime binds its compiled rule ID.
#[derive(Clone, Debug, PartialEq)]
pub struct CapabilityNotEvaluated {
    scope: Scope,
    reason: NotEvaluatedReason,
    message: String,
    location: Option<Location>,
}
impl CapabilityNotEvaluated {
    /// The object that could not be evaluated, if the outcome is about one.
    #[must_use]
    pub fn object_id(&self) -> Option<&ObjectId> {
        self.scope.object()
    }
    /// What could not be evaluated: an object, a source, or the whole rule.
    #[must_use]
    pub fn scope(&self) -> &Scope {
        &self.scope
    }
    #[must_use]
    pub fn reason(&self) -> &NotEvaluatedReason {
        &self.reason
    }
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
    /// Where the outcome's object lies, once an [`OutcomeRefiner`] located
    /// it.
    #[must_use]
    pub fn location(&self) -> Option<&Location> {
        self.location.as_ref()
    }
    /// Locates the outcome; for an [`OutcomeRefiner`].
    pub fn set_location(&mut self, location: Location) {
        self.location = Some(location);
    }
}

impl CapabilityEvaluation {
    /// Conclusive findings emitted by this capability.
    #[must_use]
    pub fn findings(&self) -> &[Finding] {
        &self.findings
    }
    /// Explicit fail-closed outcomes emitted by this capability.
    #[must_use]
    pub fn not_evaluated_outcomes(&self) -> &[CapabilityNotEvaluated] {
        &self.not_evaluated
    }
    /// Tables of measured values emitted by this capability.
    #[must_use]
    pub fn tables(&self) -> &[ReportTable] {
        &self.tables
    }
    /// Creates a conclusive evaluation from zero or more findings.
    #[must_use]
    pub fn evaluated(findings: Vec<Finding>) -> Self {
        Self {
            findings,
            ..Self::default()
        }
    }
    /// Adds a table of measured values, reported beside the findings.
    ///
    /// A table without rows is dropped: it measured nothing, and the
    /// not-evaluated outcomes already say why. Tables are informative only;
    /// they never stand in for a finding or a not-evaluated outcome.
    pub fn push_table(&mut self, table: ReportTable) {
        if !table.is_empty() {
            self.tables.push(table);
        }
    }
    /// Creates a rule-level not-evaluated outcome.
    #[must_use]
    pub fn not_evaluated(reason: NotEvaluatedReason, message: impl Into<String>) -> Self {
        let mut outcome = Self::default();
        outcome.push_not_evaluated(reason, message);
        outcome
    }
    /// Adds a conclusive finding, about an object, a source or the project
    /// as its [`Scope`] says.
    pub fn push_finding(&mut self, finding: Finding) {
        self.findings.push(finding);
    }
    /// Adds a finding of a value missing its bound by `deviation`, so a rule
    /// declaring severity bands grades it. The finding keeps its own
    /// severity otherwise; the deviation is never reported.
    pub fn push_graded_finding(&mut self, finding: Finding, deviation: Deviation) {
        self.graded.push((self.findings.len(), deviation));
        self.findings.push(finding);
    }
    /// Adds a finding, graded when `deviation` is known.
    pub fn push_finding_deviating(&mut self, finding: Finding, deviation: Option<Deviation>) {
        match deviation {
            Some(deviation) => self.push_graded_finding(finding, deviation),
            None => self.push_finding(finding),
        }
    }
    /// The deviation a graded finding was pushed with, by its index in
    /// [`Self::findings`]; `None` for an ungraded one.
    #[must_use]
    pub fn deviation(&self, finding: usize) -> Option<Deviation> {
        self.graded
            .iter()
            .find(|(index, _)| *index == finding)
            .map(|(_, deviation)| *deviation)
    }
    /// Grades every graded finding's severity by `bands`, the finding's own
    /// severity standing beyond the last band.
    fn grade(&mut self, bands: &[schema::SeverityBand]) {
        for (index, deviation) in std::mem::take(&mut self.graded) {
            let finding = &mut self.findings[index];
            let (severity, mixed) = refinement::grade(bands, &finding.severity, deviation);
            if mixed {
                use std::fmt::Write as _;
                let _ = write!(
                    finding.message,
                    "; deviation between {} and {}, graded {} by its most severe band",
                    percent(deviation.lower()),
                    percent(deviation.upper()),
                    refinement::label(&severity)
                );
            }
            finding.severity = severity;
        }
    }
    /// Findings, for an [`OutcomeRefiner`] to refine in place.
    pub fn findings_mut(&mut self) -> &mut [Finding] {
        &mut self.findings
    }
    /// Not-evaluated outcomes, for an [`OutcomeRefiner`] to locate.
    pub fn not_evaluated_outcomes_mut(&mut self) -> &mut [CapabilityNotEvaluated] {
        &mut self.not_evaluated
    }
    /// Removes and returns every finding, for an [`OutcomeRefiner`] to put
    /// back refined; deviations are dropped with them.
    pub fn take_findings(&mut self) -> Vec<Finding> {
        self.graded.clear();
        std::mem::take(&mut self.findings)
    }
    /// Adds a not-evaluated outcome about `scope`: an object, a source, or
    /// the rule as a whole.
    pub fn push_not_evaluated_about(
        &mut self,
        scope: Scope,
        reason: NotEvaluatedReason,
        message: impl Into<String>,
    ) {
        self.push_unavailable(scope, reason, message);
    }
    /// Adds a rule-level not-evaluated outcome.
    pub fn push_not_evaluated(&mut self, reason: NotEvaluatedReason, message: impl Into<String>) {
        self.push_unavailable(Scope::Project, reason, message);
    }
    /// Adds a not-evaluated outcome about one source as a whole, such as a
    /// count over that source that undecided objects could still change.
    pub fn push_source_not_evaluated(
        &mut self,
        source: SourceId,
        reason: NotEvaluatedReason,
        message: impl Into<String>,
    ) {
        self.push_unavailable(Scope::Source(source), reason, message);
    }
    /// Adds an object-specific not-evaluated outcome.
    pub fn push_object_not_evaluated(
        &mut self,
        object_id: ObjectId,
        reason: NotEvaluatedReason,
        message: impl Into<String>,
    ) {
        self.push_unavailable(Scope::Object(object_id), reason, message);
    }
    fn push_unavailable(
        &mut self,
        scope: Scope,
        reason: NotEvaluatedReason,
        message: impl Into<String>,
    ) {
        self.not_evaluated.push(CapabilityNotEvaluated {
            scope,
            reason,
            message: message.into(),
            location: None,
        });
    }
}

/// A relative deviation as a reviewer reads it, `12.5 %`.
fn percent(value: f64) -> String {
    if value.is_finite() {
        format!("{} %", (value * 1e4).round() / 1e2)
    } else {
        "unbounded".to_owned()
    }
}

/// Trusted code selected by a package capability ID; packages never supply executable code.
pub trait RuleCapability: Send + Sync {
    /// Stable trusted capability ID.
    fn id(&self) -> &'static str;
    /// Strict accepted parameters.
    fn parameters(&self) -> Vec<ParameterDescriptor>;
    /// Whether findings report how far a value misses its bound
    /// ([`CapabilityEvaluation::push_graded_finding`]), so a rule may grade
    /// them with severity bands. A rule declaring bands on a capability that
    /// answers `false` fails compilation.
    fn grades_deviation(&self) -> bool {
        false
    }
    /// Evaluates an already-validated rule request.
    fn evaluate(&self, context: &RuleContext<'_>, rule: &CompiledRule) -> CapabilityEvaluation;
}

/// Host-controlled registry of trusted capabilities.
#[derive(Clone, Default)]
pub struct CapabilityRegistry {
    capabilities: BTreeMap<String, Arc<dyn RuleCapability>>,
    refiner: Option<Arc<dyn OutcomeRefiner>>,
}
impl CapabilityRegistry {
    /// Creates an empty registry.
    pub fn new() -> Self {
        Self::default()
    }
    /// Registers a capability; duplicate IDs are rejected.
    pub fn register<C: RuleCapability + 'static>(
        mut self,
        capability: C,
    ) -> Result<Self, EngineError> {
        let id = capability.id().to_owned();
        if self
            .capabilities
            .insert(id.clone(), Arc::new(capability))
            .is_some()
        {
            return Err(EngineError::DuplicateCapability(id));
        }
        Ok(self)
    }
    /// Gets trusted code by exact ID.
    pub fn get(&self, id: &str) -> Option<&Arc<dyn RuleCapability>> {
        self.capabilities.get(id)
    }
    /// Installs the trusted code that applies rule refinements reading the
    /// model, replacing any installed before.
    #[must_use]
    pub fn with_refiner<R: OutcomeRefiner + 'static>(mut self, refiner: R) -> Self {
        self.refiner = Some(Arc::new(refiner));
        self
    }
    /// The installed outcome refiner, if any.
    pub fn refiner(&self) -> Option<&Arc<dyn OutcomeRefiner>> {
        self.refiner.as_ref()
    }
}

/// A compiled rule the engine cannot execute as authored.
///
/// Carried in the plan so every run reports it as not evaluated; dropping it
/// would make an unexecuted requirement indistinguishable from a satisfied one.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeferredRule {
    /// Package-local stable rule ID.
    pub id: RuleId,
    /// Registered capability ID.
    pub capability: String,
    /// Why the rule cannot run as authored.
    pub reason: String,
}

/// Validated, deterministic request plan.
#[derive(Clone, Debug)]
pub struct ExecutionPlan {
    rules: Vec<CompiledRule>,
    deferred: Vec<DeferredRule>,
    concepts: Arc<ConceptCatalog>,
    refinements: BTreeMap<RuleId, RuleRefinement>,
    /// Whole-rule gates: each gated rule's parents and conditions.
    gates: BTreeMap<RuleId, Vec<(RuleId, schema::GateCondition)>>,
    /// Rules whose selection a dependent reads per object.
    recorded: BTreeSet<RuleId>,
    /// Rules reported only through the rules that read them.
    auxiliary: BTreeSet<RuleId>,
    /// Classifications to derive before any rule runs, each after those
    /// its rows read.
    classifications: Vec<schema::ClassificationDefinition>,
}
impl ExecutionPlan {
    /// Rules in execution order: every rule after the rules its gates and
    /// `ruleOutcome` selectors read, and otherwise by stable rule ID.
    pub fn rules(&self) -> &[CompiledRule] {
        &self.rules
    }
    /// Rules compiled but not executable as authored, ordered by rule ID.
    pub fn deferred(&self) -> &[DeferredRule] {
        &self.deferred
    }
    /// Canonical concepts declared by the ruleset's definition packages.
    pub fn concepts(&self) -> &ConceptCatalog {
        &self.concepts
    }
    /// How `rule` refines its outcomes; `None` when it declares nothing.
    pub fn refinement(&self, rule: &RuleId) -> Option<&RuleRefinement> {
        self.refinements.get(rule)
    }
    /// The classifications the plan derives, in the order they are derived.
    pub fn classifications(&self) -> &[schema::ClassificationDefinition] {
        &self.classifications
    }
    /// The whole-rule gates of `rule`: each parent rule and the condition
    /// on its outcome. Empty for an ungated rule.
    pub fn gates(&self, rule: &RuleId) -> &[(RuleId, schema::GateCondition)] {
        self.gates.get(rule).map_or(&[], Vec::as_slice)
    }
    /// Whether `rule` is auxiliary: run for the rules that read its
    /// outcome, and never reported itself.
    pub fn is_auxiliary(&self, rule: &RuleId) -> bool {
        self.auxiliary.contains(rule)
    }
}

mod boundary_coverage;
mod circulation;
mod classifications;
mod compiler;
mod concepts;
mod contact;
mod coordinate_system;
mod corridor_end;
mod coverage;
mod derived;
mod derived_relationships;
mod discipline_map;
mod door_leaves;
mod envelope_membership;
mod facade_area;
mod federation;
mod free_space;
mod guard;
mod integrity;
mod linear_quantity;
mod measured;
mod metric_routing;
mod object_frame;
mod pairwise;
mod path;
mod plan_area;
mod plan_region;
mod plan_span;
mod properties;
mod proximity;
mod refinement;
mod relationships;
mod resources;
mod rule_outcomes;
mod services;
mod side_distance;
mod sight;
mod source_metadata;
mod space;
mod topology;
mod triangle_count;
mod vertical_extent;
mod walkability;
mod walking_surface;
pub use boundary_coverage::{
    BoundaryCoverage, BoundaryCoverageError, BoundaryCoverageRequest, BoundaryCoverageService,
    BoundaryCoverageServiceHandle, BoundaryOverlap, BoundaryPlacement, CoverageAreas,
    MeasuredBoundary, ShareInterval, SurfaceAreaInterval,
};
pub use circulation::{
    CirculationContact, CirculationMap, CirculationNode, CirculationNodeKind, CirculationRequest,
};
pub use classifications::{
    ClassificationAssignment, ClassificationError, ClassificationService,
    ClassificationServiceHandle,
};
pub use compiler::{QUALIFIED_RULE_SEPARATOR, SUPPORTED_SCHEMA_VERSION, compile, compile_rulesets};
pub use concepts::{
    BindingError, ConceptBindings, ConceptCatalog, ConceptKind, TypeHierarchyError,
    TypeHierarchyService, TypeHierarchyServiceHandle,
};
pub use contact::{
    ContactError, ContactEvidence, ContactRequest, ContactService, ContactServiceHandle,
    ContactSide, ContactTolerance,
};
pub use coordinate_system::{
    CoordinateFrame, CoordinateSystemError, CoordinateSystemService, CoordinateSystemServiceHandle,
    MapConversion, SourceCoordinateSystem,
};
pub use corridor_end::{CorridorEnd, CorridorEndRequest, CorridorEnds, EndWall, WallContact};
pub use coverage::{CoverageEvidence, CoverageRequest, EffectMeets, EffectReach, Participant};
pub use derived::{ClassOutcome, Classifications};
pub use derived_relationships::{
    AdjacentSide, DERIVED_RELATIONSHIP_PREFIX, Derivation, DerivedRelationshipService,
    DerivedRelationshipServiceHandle, LevelFacts, LevelMatch, adjacent_side,
};
pub use discipline_map::{
    DisciplineMap, DisciplineMapError, DisciplineOrigin, DisciplineRule, UnmappedReason,
    wildcard_regex,
};
pub use door_leaves::{
    DoorLeaf, DoorLeaves, DoorLeavesError, HingeSide, LeafMotion, LeafPosition, PlanRing,
    SWEPT_FLOOR_REACH_METRES, SweptDoor, SwingSector,
};
pub use envelope_membership::{
    EnvelopeDerivation, EnvelopeMembershipError, EnvelopeMembershipEvidence,
    EnvelopeMembershipRequest, EnvelopeMembershipService, EnvelopeMembershipServiceHandle,
};
pub use facade_area::{FacadeArea, FacadeAreaError, FacadeAreaService, FacadeAreaServiceHandle};
pub use free_space::{
    AreaInterval, BoxClearance, ClearanceOutcome, ClearancePlacementEvidence, ClearanceRequest,
    ClearanceShape, CompleteClearanceEvidence, CompletePlacementEvidence, CompleteSupportEvidence,
    ContainmentEvidence, ContainmentOutcome, ContainmentRequest, CylinderClearance, ElevationBand,
    EntranceReach, FrameOffsetPlacement, FreeAreaEvidence, FreeAreaRequest, FreeSpaceError,
    FreeSpaceService, FreeSpaceServiceHandle, MetricDirection, MetricFrame, ObstructionEvidence,
    PlacementDomain, PlacementOrientation, PlacementOutcome, PlacementRequest, PlacementShape,
    SignedDistanceInterval, SupportCoverageEvidence, SupportCoverageOutcome,
    SupportCoverageRequest, SupportedPlacement,
};
pub use guard::{
    ClimbableCandidate, GuardCandidate, GuardEdge, GuardError, GuardEvidence, GuardSearch,
    GuardService, GuardServiceHandle,
};
pub use integrity::{
    IntegrityError, IntegrityIssue, IntegritySeverity, SourceIntegrityService,
    SourceIntegrityServiceHandle,
};
pub use linear_quantity::{
    LinearInterval, LinearQuantityError, LinearQuantityEvidence, LinearQuantityKind,
    LinearQuantityRequest, LinearQuantityService, LinearQuantityServiceHandle, ShelfGeometry,
};
pub use metric_routing::{
    BlockedMetricRouteEvidence, ClimbLength, CompleteMetricEvidence, ConnectorRouting,
    FarthestPointEvidence, FarthestPointOutcome, FarthestPointRequest, ForcedWalkEvidence,
    ForcedWalkOutcome, ForcedWalkRequest, LengthInterval, MetricPoint, MetricRouteEvidence,
    MetricRouteOutcome, MetricRouteRequest, MetricRoutingError, MetricRoutingService,
    MetricRoutingServiceHandle, MobilityProfile, NearestTargetEvidence, NearestTargetOutcome,
    NearestTargetRequest, NeverEnteredEvidence, PathTrace, PathTraceRequest, StairLength,
    ThresholdVerdict, TravelCost, UnreachableRegionEvidence, UnreachableTargetsEvidence,
};
pub use object_frame::{
    ObjectFrame, ObjectFrameError, ObjectFrameService, ObjectFrameServiceHandle, ObjectFront,
};
pub use pairwise::{
    CandidatePair, CandidateSearchError, candidate_pairs, projected_candidate_pairs,
};
pub use path::PathSegment;
pub use plan_area::{
    ElevationCover, ElevationRequest, PlanArea, PlanAreaError, PlanAreaService,
    PlanAreaServiceHandle, PlanBand,
};
pub use plan_region::ConvexPlanRegion;
pub use plan_span::{
    CentrePlacement, PlanCentre, PlanLength, PlanRecess, PlanRecesses, PlanRectangle, PlanSection,
    PlanSpan, PlanSpanError, PlanSpanService, PlanSpanServiceHandle, RectangleOrientation,
};
pub use properties::{
    CompletePropertyAbsenceEvidence, NameMatch, NamePattern, PropertyEnumeration,
    PropertyEnumerationRequest, PropertyRequest, PropertyResolution, PropertyResolutionError,
    PropertyResolutionService, PropertyResolutionServiceHandle, ResolvedProperty, UnreadableValue,
};
pub use proximity::{
    BodyContainment, BodyVolume, Bounds3, CounterpartSurface, FaceClass, FaceDistanceError,
    FaceDistanceEvidence, FaceDistanceRequest, GeometryFidelity, IntersectionVolume, ObjectBounds,
    OverlapAlongEvidence, OverlapAlongRequest, OverlapExtents, ProjectedDistanceEvidence,
    ProximityError, ProximityEvidence, ProximityProjection, ProximityRequest, ProximityService,
    ProximityServiceHandle, RegionDistanceEvidence, RegionDistanceRequest, SubjectSurface,
    VerticalDirection, VerticalSurfaces, VolumeInterval,
};
pub use refinement::{
    Deviation, LocationMethod, LocationPolicy, OutcomeRefiner, Refining, RuleRefinement,
    report_severity,
};
pub use relationships::{
    AbsentEndPolicy, CompleteRelationshipSelection, RelationshipQuery, RelationshipSelectionError,
    RelationshipSelectionRequest, RelationshipSelectionService, RelationshipSelectionServiceHandle,
    SemanticRelationship, TraversalDirection,
};
pub use resources::{
    Reached, ResourceError, ResourceObjects, ResourceRequest, ResourceService,
    ResourceServiceHandle,
};
pub use rule_outcomes::{ObjectVerdict, RuleOutcomes, RuleRecord, RuleVerdict, SelectorVerdict};
pub use services::{ServiceRegistry, ServiceRegistryError};
pub use session::{
    EvidenceSession, EvidenceSessionError, SessionSources, SnapshotBoundService, SourceDisciplines,
    SourceSnapshot,
};
pub use side_distance::{
    RectangleSide, SideDistance, SideDistanceRequest, SideDistances, SidePresence,
};
pub use sight::{
    SightError, SightEvidence, SightOutcome, SightRequest, SightService, SightServiceHandle,
};
pub use source_metadata::{SourceMetadata, SourceMetadataIndex};
pub use space::{
    BoundaryGap, BoundaryRequest, Cap, CapCoverage, CapRequest, ClearHeightEvidence, Containment,
    OverlapRequest, SpaceError, SpaceOverlap, SpaceService, SpaceServiceHandle, SupportCounts,
    UnallocatedRegion,
};
pub use topology::{
    CompleteTopologyEvidence, ConnectivityGraph, RouteOutcome, TopologyError, VerifiedConnection,
};
pub use triangle_count::{
    TriangleCount, TriangleCountError, TriangleCountService, TriangleCountServiceHandle,
};
pub use vertical_extent::{
    DirectionalExtent, ElevationInterval, VerticalExtent, VerticalExtentError,
    VerticalExtentService, VerticalExtentServiceHandle,
};
pub use walkability::{
    PassageAdmission, StretchLimit, VerifiedWalkablePassage, VerticalConnector,
    VerticalConnectorKind, WalkabilityError, WalkabilityRegion, WalkabilityRegionId,
    WalkabilityRequest, WalkabilityRouteOutcome, WalkabilityService, WalkabilityServiceHandle,
    WalkabilitySnapshot, WalkableStretch,
};
pub use walking_surface::{
    ClearWidthEvidence, ClearWidthRequest, ClearanceBelow, ClearanceBelowRequest, HandrailEvidence,
    HandrailRequest, Headroom, HeadroomRequest, Landing, LandingEvidence, LandingExtent,
    LandingRequest, MeasuredInterval, PlanSegment, RailMeasurement, RailSide, RiserClosure,
    SlopedRun, SlopedSurface, StretchPart, Tread, TreadFlight, TreadFlightRequest, WalkingEnd,
    WalkingLine, WalkingLinePlacement, WalkingStretch, WalkingSurfaceError, WalkingSurfaceService,
    WalkingSurfaceServiceHandle, across,
};

/// Binds a rule's outcomes to it, reporting each source-wide cause once.
///
/// An unbound concept depends on the package and the source, an unrecorded
/// fact on the source alone, and a missing service on the run, never on the
/// object, so every object of that source fails identically. Listing each
/// one buries the single cause under thousands of copies. Object-level
/// outcomes with any of these reasons
/// are merged per source, reason and message into one rule-level outcome
/// scoped to that source, naming the count and a few examples. Every other
/// outcome keeps its scope.
fn collapse_source_wide(
    rule_id: &RuleId,
    outcomes: Vec<CapabilityNotEvaluated>,
) -> Vec<NotEvaluated> {
    const EXAMPLES: usize = 3;
    let mut merged: BTreeMap<(axioval_ir::SourceId, NotEvaluatedReason, String), Vec<ObjectId>> =
        BTreeMap::new();
    let mut kept = Vec::new();
    for outcome in outcomes {
        match (outcome.reason, outcome.scope) {
            (
                reason @ (NotEvaluatedReason::UnboundConcept
                | NotEvaluatedReason::NotRecorded
                | NotEvaluatedReason::MissingService),
                Scope::Object(object),
            ) => merged
                .entry((object.source.clone(), reason, outcome.message))
                .or_default()
                .push(object),
            (reason, scope) => kept.push(NotEvaluated {
                rule_id: rule_id.clone(),
                scope,
                reason,
                message: outcome.message,
                location: outcome.location,
            }),
        }
    }
    kept.extend(merged.into_iter().map(|((source, reason, message), mut objects)| {
        objects.sort();
        let examples: Vec<&str> = objects
            .iter()
            .take(EXAMPLES)
            .map(|object| object.local_id.as_str())
            .collect();
        let more = objects.len().saturating_sub(EXAMPLES);
        let tail = if more > 0 {
            format!(", +{more} more")
        } else {
            String::new()
        };
        NotEvaluated {
            rule_id: rule_id.clone(),
            scope: Scope::Source(source.clone()),
            reason,
            message: format!(
                "{message}; {} object(s) of source `{source}` not evaluated (e.g. {}{tail})",
                objects.len(),
                examples.join(", ")
            ),
            location: None,
        }
    }));
    kept
}

/// One rule's counts from its refined outcomes.
fn summarize(rule: &RuleId, checked: usize, evaluation: &CapabilityEvaluation) -> RuleSummary {
    let objects = |scopes: &mut dyn Iterator<Item = &Scope>| {
        scopes
            .filter_map(Scope::object)
            .collect::<std::collections::BTreeSet<_>>()
            .len()
    };
    let failed = objects(&mut evaluation.findings.iter().map(|finding| &finding.scope));
    let open = objects(
        &mut evaluation
            .not_evaluated
            .iter()
            .map(|outcome| &outcome.scope),
    );
    RuleSummary::new(
        rule.clone(),
        checked,
        (failed, !evaluation.findings.is_empty()),
        (open, !evaluation.not_evaluated.is_empty()),
    )
}

/// Deterministic runtime that invokes only registered trusted capabilities.
pub struct Runtime {
    registry: CapabilityRegistry,
    services: ServiceRegistry,
    locations: Option<LocationPolicy>,
    summaries: bool,
}
impl Runtime {
    /// Creates a runtime from a host-controlled registry.
    pub fn new(registry: CapabilityRegistry) -> Self {
        Self {
            registry,
            services: ServiceRegistry::new(),
            locations: None,
            summaries: false,
        }
    }
    /// Reports per-rule counts and status ([`Report::rules`]): how many
    /// objects each rule surely selected, how many it found or left not
    /// evaluated, and whether it passed, failed, was not evaluated or
    /// selected nothing. Off by default, and then reports are unchanged.
    /// Needs the registry's outcome refiner to count selections.
    #[must_use]
    pub fn with_rule_summaries(mut self) -> Self {
        self.summaries = true;
        self
    }
    /// Locates every finding and not-evaluated outcome by storey and space
    /// as `policy` says. Off by default, and then reports carry no
    /// location. Needs the registry's outcome refiner.
    #[must_use]
    pub fn with_locations(mut self, policy: LocationPolicy) -> Self {
        self.locations = Some(policy);
        self
    }
    /// Adds adapter-provided host services to subsequent evaluations.
    #[must_use]
    pub fn with_services(mut self, services: ServiceRegistry) -> Self {
        self.services = services;
        self
    }
    /// Executes a plan and returns deterministically sorted findings.
    ///
    /// Execution fails closed if the host registry no longer contains any capability
    /// that was present when the plan was compiled.
    ///
    /// A bare project carries no source type-system declarations, so package
    /// concepts bind to nothing and concept-based selection is reported as not
    /// evaluated. Hosts that want concept binding run an [`EvidenceSession`].
    pub fn run(&self, project: &Project, plan: ExecutionPlan) -> Result<Report, EngineError> {
        self.run_with_services(
            project,
            &self.services,
            BTreeMap::new(),
            (
                SessionSources::new(project.objects().map(|object| object.id.source.clone())),
                SourceDisciplines::default(),
                SourceMetadataIndex::default(),
            ),
            plan,
        )
    }

    /// Executes a plan against one immutable source/evidence snapshot.
    pub fn run_session(
        &self,
        session: &EvidenceSession,
        plan: ExecutionPlan,
    ) -> Result<Report, EngineError> {
        let type_systems = session
            .snapshots()
            .map(|snapshot| (snapshot.source().clone(), snapshot.type_systems().to_vec()))
            .collect();
        self.run_with_services(
            session.project(),
            session.services(),
            type_systems,
            (
                SessionSources::new(
                    session
                        .snapshots()
                        .map(|snapshot| snapshot.source().clone()),
                ),
                session.source_disciplines(),
                session.metadata_index(),
            ),
            plan,
        )
    }

    /// The registry's outcome refiner, refused missing when the plan or
    /// the host's options need one.
    fn refiner_for(
        &self,
        plan: &ExecutionPlan,
    ) -> Result<Option<&Arc<dyn OutcomeRefiner>>, EngineError> {
        let refiner = self.registry.refiner();
        if refiner.is_some() {
            return Ok(refiner);
        }
        if !plan.recorded.is_empty() {
            return Err(EngineError::MissingRefiner(
                "reading another rule's outcomes per object",
            ));
        }
        if !plan.classifications.is_empty() {
            return Err(EngineError::MissingRefiner("deriving classifications"));
        }
        if self.locations.is_some() {
            return Err(EngineError::MissingRefiner("locating outcomes"));
        }
        if self.summaries {
            return Err(EngineError::MissingRefiner(
                "counting each rule's selection",
            ));
        }
        Ok(None)
    }

    /// Evaluates `rule`, then grades and refines its outcomes.
    fn evaluate(
        &self,
        context: &RuleContext<'_>,
        capability: &dyn RuleCapability,
        rule: &CompiledRule,
        refinement: Option<&RuleRefinement>,
    ) -> CapabilityEvaluation {
        let mut evaluation = capability.evaluate(context, rule);
        if let Some(refinement) = refinement {
            evaluation.grade(&refinement.severity_bands);
        }
        if let Some(refiner) = self.registry.refiner()
            && (refinement.is_some() || self.locations.is_some())
        {
            let unrefined = RuleRefinement::default();
            let refining = Refining {
                refinement: refinement.unwrap_or(&unrefined),
                locations: self.locations.as_ref(),
            };
            refiner.refine(context, rule, &refining, &mut evaluation);
        }
        evaluation
    }

    fn run_with_services(
        &self,
        project: &Project,
        services: &ServiceRegistry,
        type_systems: BTreeMap<axioval_ir::SourceId, Vec<Arc<str>>>,
        (sources, disciplines, metadata): (SessionSources, SourceDisciplines, SourceMetadataIndex),
        plan: ExecutionPlan,
    ) -> Result<Report, EngineError> {
        // Bindings are per run: they join this plan's package concepts to this
        // project's declared type systems, so they cannot be registered once by
        // a host. A host-registered `ConceptBindings` is overridden rather than
        // trusted, because it could bind concepts the packages never declared.
        let mut services = services.clone();
        services.replace(ConceptBindings::new(plan.concepts.clone(), type_systems));
        // Disciplines are the session's declarations; a host-registered copy
        // could claim roles the session never declared.
        services.replace(disciplines);
        // So is what the session knows about each source as a whole.
        services.replace(metadata);
        // So are the sources: a host copy could hide an empty source.
        services.replace(sources);
        // And the resource objects the rules name: a host copy could claim
        // resource objects the session never listed.
        resources::install(&mut services, project, &plan.rules);
        let refiner = self.refiner_for(&plan)?;
        let mut summaries: Vec<RuleSummary> = Vec::new();
        let mut findings = Vec::new();
        let mut tables: Vec<ReportTable> = Vec::new();
        let mut not_evaluated: Vec<NotEvaluated> = plan
            .deferred
            .into_iter()
            .inspect(|rule| {
                if self.summaries {
                    summaries.push(RuleSummary::new(rule.id.clone(), 0, (0, false), (0, true)));
                }
            })
            .map(|rule| NotEvaluated {
                rule_id: rule.id,
                scope: Scope::Project,
                reason: NotEvaluatedReason::InvalidDeclaration,
                message: rule.reason,
                location: None,
            })
            .collect();
        // Measured values are answered through the host's resolver in
        // every run; classifications are derived first when the plan has
        // any.
        if plan.classifications.is_empty()
            && let Some(host) = services.get::<PropertyResolutionServiceHandle>().cloned()
        {
            derived::install(&mut services, Some(&host), Arc::default(), project);
        }
        if let Some(refiner) = refiner.filter(|_| !plan.classifications.is_empty()) {
            derive_classifications(
                refiner.as_ref(),
                project,
                &mut services,
                &plan.classifications,
            );
        }
        // What every completed rule reported, for the rules that read it.
        let mut outcomes = RuleOutcomes::default();
        for rule in plan.rules {
            let capability = self
                .registry
                .get(&rule.capability)
                .ok_or_else(|| EngineError::UnknownCapability(rule.capability.clone()))?;
            let rule_id = rule.id.clone();
            // An auxiliary rule's outcome is recorded for the rules that
            // read it, and reported only through them.
            let reported = !plan.auxiliary.contains(&rule_id);
            // A rule reads the outcomes of the rules the plan ran before it.
            services.replace(outcomes.clone());
            let context = RuleContext {
                project,
                services: &services,
            };
            let gates = plan.gates.get(&rule_id).map_or(&[][..], Vec::as_slice);
            let mut evaluation = match outcomes.gate(gates) {
                rule_outcomes::Gate::Closed => {
                    outcomes.insert(rule_id.clone(), RuleRecord::skipped());
                    if self.summaries && reported {
                        summaries.push(RuleSummary::skipped(rule_id));
                    }
                    continue;
                }
                rule_outcomes::Gate::Undecided(why) => {
                    outcomes.insert(rule_id.clone(), RuleRecord::undecided(&why));
                    CapabilityEvaluation::not_evaluated(NotEvaluatedReason::IncompleteEvidence, why)
                }
                rule_outcomes::Gate::Open => {
                    let evaluation = self.evaluate(
                        &context,
                        capability.as_ref(),
                        &rule,
                        plan.refinements.get(&rule_id),
                    );
                    let selection = refiner
                        .filter(|_| plan.recorded.contains(&rule_id))
                        .map(|refiner| rule_outcomes::selection(refiner.as_ref(), &context, &rule));
                    outcomes.insert(rule_id.clone(), RuleRecord::of(&evaluation, selection));
                    evaluation
                }
            };
            if !reported {
                continue;
            }
            if let Some(refiner) = refiner
                && self.summaries
            {
                summaries.push(summarize(
                    &rule_id,
                    refiner.selected(&context, &rule),
                    &evaluation,
                ));
            }
            findings.extend(std::mem::take(&mut evaluation.findings));
            // The compiled rule is the table's identity, whatever the capability named.
            tables.extend(
                std::mem::take(&mut evaluation.tables)
                    .into_iter()
                    .map(|table| table.with_rule_id(rule_id.clone())),
            );
            not_evaluated.extend(collapse_source_wide(&rule_id, evaluation.not_evaluated));
        }
        assemble(findings, not_evaluated, tables, summaries, &services)
    }
}

/// The resource objects the outcomes name, sorted by identity.
fn named_resources(
    findings: &[Finding],
    not_evaluated: &[NotEvaluated],
    tables: &[ReportTable],
    services: &ServiceRegistry,
) -> Vec<axioval_ir::Object> {
    let Some(resources) = services
        .get::<ResourceObjects>()
        .filter(|resources| !resources.is_empty())
    else {
        return Vec::new();
    };
    let mut named: BTreeSet<&ObjectId> = BTreeSet::new();
    for finding in findings {
        named.extend(finding.object_id());
        named.extend(&finding.related);
    }
    named.extend(not_evaluated.iter().filter_map(NotEvaluated::object_id));
    named.extend(
        tables
            .iter()
            .flat_map(|table| table.rows().iter().filter_map(|row| row.scope().object())),
    );
    named
        .into_iter()
        .filter_map(|id| resources.object(id).cloned())
        .collect()
}

/// Classifies every object by each of `definitions`, in order, and installs
/// the run's property resolver answering the classification set: each
/// classification's rows read the ones derived before it.
fn derive_classifications(
    refiner: &dyn OutcomeRefiner,
    project: &Project,
    services: &mut ServiceRegistry,
    definitions: &[schema::ClassificationDefinition],
) {
    let host = services.get::<PropertyResolutionServiceHandle>().cloned();
    let mut derived = Classifications::default();
    for definition in definitions {
        derived::install(services, host.as_ref(), Arc::new(derived.clone()), project);
        let context = RuleContext { project, services };
        derived.classify(refiner, &context, definition);
    }
    derived::install(services, host.as_ref(), Arc::new(derived), project);
}

/// The report of every rule's outcomes, each part in its deterministic
/// order, with the resource objects of `services` they name; a rule
/// reporting one table name twice fails the run.
fn assemble(
    mut findings: Vec<Finding>,
    mut not_evaluated: Vec<NotEvaluated>,
    mut tables: Vec<ReportTable>,
    mut summaries: Vec<RuleSummary>,
    services: &ServiceRegistry,
) -> Result<Report, EngineError> {
    findings.sort_by(|a, b| {
        a.rule_id
            .cmp(&b.rule_id)
            // Project, then sources, then objects, each by identity.
            .then_with(|| a.scope.cmp(&b.scope))
            .then_with(|| a.message.cmp(&b.message))
    });
    not_evaluated.sort();
    tables.sort_by(|a, b| (a.rule_id(), a.name()).cmp(&(b.rule_id(), b.name())));
    if let Some(pair) = tables
        .windows(2)
        .find(|pair| (pair[0].rule_id(), pair[0].name()) == (pair[1].rule_id(), pair[1].name()))
    {
        return Err(EngineError::DuplicateReportTable {
            rule: pair[0].rule_id().to_string(),
            table: pair[0].name().to_owned(),
        });
    }
    summaries.sort();
    Ok(Report {
        resources: named_resources(&findings, &not_evaluated, &tables, services),
        stale_decisions: Vec::new(),
        findings,
        not_evaluated,
        tables,
        rules: summaries,
    })
}