pr4xis 0.5.0

Prove your domain is correct — ontology-driven rule enforcement with category theory, logical composition, and runtime state machines
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
/// Generic logical composition: Proposition, AllOf, AnyOf, Not, Implies, Compare, Threshold.
///
/// This is the boolean composition layer for ANY ontology or enforcement engine.
/// Compose rules with AND/OR/NOT to build complex enforcement.
use std::fmt::Debug;

/// A logical proposition that can be evaluated to true/false with a reason.
pub trait Proposition: Debug {
    /// The context needed to evaluate this proposition.
    type Context;

    /// Evaluate the proposition. Returns (satisfied, reason).
    fn evaluate(&self, context: &Self::Context) -> Evaluation;

    /// Human-readable description of what this proposition checks.
    fn describe(&self) -> String;
}

/// Result of evaluating a proposition.
#[derive(Debug, Clone, PartialEq)]
pub enum Evaluation {
    Satisfied { reason: String },
    Violated { reason: String },
}

impl Evaluation {
    pub fn is_satisfied(&self) -> bool {
        matches!(self, Evaluation::Satisfied { .. })
    }

    pub fn reason(&self) -> &str {
        match self {
            Evaluation::Satisfied { reason } => reason,
            Evaluation::Violated { reason } => reason,
        }
    }
}

/// Logical AND: all propositions must be satisfied.
/// Uses trait objects so you can mix different proposition types.
pub struct AllOf<Ctx> {
    pub propositions: Vec<Box<dyn Proposition<Context = Ctx>>>,
}

impl<Ctx: Debug> AllOf<Ctx> {
    pub fn new(propositions: Vec<Box<dyn Proposition<Context = Ctx>>>) -> Self {
        Self { propositions }
    }
}

impl<Ctx: Debug> Debug for AllOf<Ctx> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "AllOf({} props)", self.propositions.len())
    }
}

impl<Ctx: Debug> Proposition for AllOf<Ctx> {
    type Context = Ctx;

    fn evaluate(&self, context: &Self::Context) -> Evaluation {
        for prop in &self.propositions {
            let result = prop.evaluate(context);
            if let Evaluation::Violated { reason } = result {
                return Evaluation::Violated {
                    reason: format!("AllOf failed: {}{}", prop.describe(), reason),
                };
            }
        }
        Evaluation::Satisfied {
            reason: format!("all {} conditions met", self.propositions.len()),
        }
    }

    fn describe(&self) -> String {
        let descs: Vec<String> = self.propositions.iter().map(|p| p.describe()).collect();
        format!("ALL({})", descs.join(", "))
    }
}

/// Logical OR: at least one proposition must be satisfied.
pub struct AnyOf<Ctx> {
    pub propositions: Vec<Box<dyn Proposition<Context = Ctx>>>,
}

impl<Ctx: Debug> AnyOf<Ctx> {
    pub fn new(propositions: Vec<Box<dyn Proposition<Context = Ctx>>>) -> Self {
        Self { propositions }
    }
}

impl<Ctx: Debug> Debug for AnyOf<Ctx> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "AnyOf({} props)", self.propositions.len())
    }
}

impl<Ctx: Debug> Proposition for AnyOf<Ctx> {
    type Context = Ctx;

    fn evaluate(&self, context: &Self::Context) -> Evaluation {
        let mut violations = Vec::new();
        for prop in &self.propositions {
            let result = prop.evaluate(context);
            if result.is_satisfied() {
                return Evaluation::Satisfied {
                    reason: format!("AnyOf satisfied: {}", prop.describe()),
                };
            }
            violations.push(format!("{}: {}", prop.describe(), result.reason()));
        }
        Evaluation::Violated {
            reason: format!(
                "AnyOf failed: none of [{}] satisfied",
                violations.join("; ")
            ),
        }
    }

    fn describe(&self) -> String {
        let descs: Vec<String> = self.propositions.iter().map(|p| p.describe()).collect();
        format!("ANY({})", descs.join(", "))
    }
}

/// Logical NOT: the proposition must NOT be satisfied.
#[derive(Debug)]
pub struct Not<P: Proposition> {
    pub proposition: P,
}

impl<P: Proposition> Not<P> {
    pub fn new(proposition: P) -> Self {
        Self { proposition }
    }
}

impl<P: Proposition> Proposition for Not<P> {
    type Context = P::Context;

    fn evaluate(&self, context: &Self::Context) -> Evaluation {
        match self.proposition.evaluate(context) {
            Evaluation::Satisfied { reason } => Evaluation::Violated {
                reason: format!(
                    "NOT failed: {} was satisfied — {}",
                    self.proposition.describe(),
                    reason
                ),
            },
            Evaluation::Violated { reason } => Evaluation::Satisfied {
                reason: format!(
                    "NOT satisfied: {} was violated — {}",
                    self.proposition.describe(),
                    reason
                ),
            },
        }
    }

    fn describe(&self) -> String {
        format!("NOT({})", self.proposition.describe())
    }
}

/// Logical implication: if A then B. A and B can be different proposition types.
#[derive(Debug)]
pub struct Implies<A: Proposition, B: Proposition<Context = A::Context>> {
    pub antecedent: A,
    pub consequent: B,
}

impl<A: Proposition, B: Proposition<Context = A::Context>> Implies<A, B> {
    pub fn new(antecedent: A, consequent: B) -> Self {
        Self {
            antecedent,
            consequent,
        }
    }
}

impl<A: Proposition, B: Proposition<Context = A::Context>> Proposition for Implies<A, B> {
    type Context = A::Context;

    fn evaluate(&self, context: &Self::Context) -> Evaluation {
        match self.antecedent.evaluate(context) {
            Evaluation::Violated { .. } => Evaluation::Satisfied {
                reason: format!(
                    "implication vacuously true: {} not met",
                    self.antecedent.describe()
                ),
            },
            Evaluation::Satisfied { .. } => match self.consequent.evaluate(context) {
                Evaluation::Satisfied { reason } => Evaluation::Satisfied {
                    reason: format!(
                        "{}{} holds: {}",
                        self.antecedent.describe(),
                        self.consequent.describe(),
                        reason
                    ),
                },
                Evaluation::Violated { reason } => Evaluation::Violated {
                    reason: format!(
                        "{} is true but {} failed: {}",
                        self.antecedent.describe(),
                        self.consequent.describe(),
                        reason
                    ),
                },
            },
        }
    }

    fn describe(&self) -> String {
        format!(
            "IF {} THEN {}",
            self.antecedent.describe(),
            self.consequent.describe()
        )
    }
}

// =============================================================================
// Comparison propositions — ordering relationships
// =============================================================================

/// A value that can be extracted from a context and compared.
pub trait Measurable<Ctx>: Debug {
    type Value: PartialOrd + Debug;

    fn measure(&self, context: &Ctx) -> Self::Value;
    fn name(&self) -> &str;
}

/// Comparison operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompareOp {
    LessThan,
    LessOrEqual,
    GreaterThan,
    GreaterOrEqual,
    Equal,
    NotEqual,
}

impl CompareOp {
    pub fn symbol(&self) -> &'static str {
        match self {
            CompareOp::LessThan => "<",
            CompareOp::LessOrEqual => "<=",
            CompareOp::GreaterThan => ">",
            CompareOp::GreaterOrEqual => ">=",
            CompareOp::Equal => "==",
            CompareOp::NotEqual => "!=",
        }
    }

    pub fn check<T: PartialOrd>(&self, left: &T, right: &T) -> bool {
        match self {
            CompareOp::LessThan => left < right,
            CompareOp::LessOrEqual => left <= right,
            CompareOp::GreaterThan => left > right,
            CompareOp::GreaterOrEqual => left >= right,
            CompareOp::Equal => left == right,
            CompareOp::NotEqual => left != right,
        }
    }
}

/// Compare two measurable values from the same context.
#[derive(Debug)]
pub struct Compare<Ctx, L: Measurable<Ctx>, R: Measurable<Ctx>> {
    pub left: L,
    pub op: CompareOp,
    pub right: R,
    _ctx: std::marker::PhantomData<Ctx>,
}

impl<Ctx, L, R> Compare<Ctx, L, R>
where
    L: Measurable<Ctx>,
    R: Measurable<Ctx, Value = L::Value>,
{
    pub fn new(left: L, op: CompareOp, right: R) -> Self {
        Self {
            left,
            op,
            right,
            _ctx: std::marker::PhantomData,
        }
    }
}

impl<Ctx, L, R> Proposition for Compare<Ctx, L, R>
where
    Ctx: Debug,
    L: Measurable<Ctx>,
    R: Measurable<Ctx, Value = L::Value>,
{
    type Context = Ctx;

    fn evaluate(&self, context: &Self::Context) -> Evaluation {
        let lv = self.left.measure(context);
        let rv = self.right.measure(context);
        if self.op.check(&lv, &rv) {
            Evaluation::Satisfied {
                reason: format!(
                    "{} ({:?}) {} {} ({:?})",
                    self.left.name(),
                    lv,
                    self.op.symbol(),
                    self.right.name(),
                    rv
                ),
            }
        } else {
            Evaluation::Violated {
                reason: format!(
                    "{} ({:?}) is NOT {} {} ({:?})",
                    self.left.name(),
                    lv,
                    self.op.symbol(),
                    self.right.name(),
                    rv
                ),
            }
        }
    }

    fn describe(&self) -> String {
        format!(
            "{} {} {}",
            self.left.name(),
            self.op.symbol(),
            self.right.name()
        )
    }
}

/// Convenience: compare a measurable against a constant.
#[derive(Debug)]
pub struct Threshold<Ctx, M: Measurable<Ctx>> {
    pub measurable: M,
    pub op: CompareOp,
    pub threshold: M::Value,
    _ctx: std::marker::PhantomData<Ctx>,
}

impl<Ctx, M> Threshold<Ctx, M>
where
    M: Measurable<Ctx>,
    M::Value: Clone,
{
    pub fn new(measurable: M, op: CompareOp, threshold: M::Value) -> Self {
        Self {
            measurable,
            op,
            threshold,
            _ctx: std::marker::PhantomData,
        }
    }

    pub fn less_than(measurable: M, threshold: M::Value) -> Self {
        Self::new(measurable, CompareOp::LessThan, threshold)
    }

    pub fn greater_than(measurable: M, threshold: M::Value) -> Self {
        Self::new(measurable, CompareOp::GreaterThan, threshold)
    }

    pub fn at_least(measurable: M, threshold: M::Value) -> Self {
        Self::new(measurable, CompareOp::GreaterOrEqual, threshold)
    }

    pub fn at_most(measurable: M, threshold: M::Value) -> Self {
        Self::new(measurable, CompareOp::LessOrEqual, threshold)
    }
}

impl<Ctx, M> Proposition for Threshold<Ctx, M>
where
    Ctx: Debug,
    M: Measurable<Ctx>,
    M::Value: Clone,
{
    type Context = Ctx;

    fn evaluate(&self, context: &Self::Context) -> Evaluation {
        let value = self.measurable.measure(context);
        if self.op.check(&value, &self.threshold) {
            Evaluation::Satisfied {
                reason: format!(
                    "{} ({:?}) {} {:?}",
                    self.measurable.name(),
                    value,
                    self.op.symbol(),
                    self.threshold
                ),
            }
        } else {
            Evaluation::Violated {
                reason: format!(
                    "{} ({:?}) is NOT {} {:?}",
                    self.measurable.name(),
                    value,
                    self.op.symbol(),
                    self.threshold
                ),
            }
        }
    }

    fn describe(&self) -> String {
        format!(
            "{} {} {:?}",
            self.measurable.name(),
            self.op.symbol(),
            self.threshold
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    #[derive(Debug)]
    struct IsPositive;

    impl Proposition for IsPositive {
        type Context = i32;
        fn evaluate(&self, n: &i32) -> Evaluation {
            if *n > 0 {
                Evaluation::Satisfied {
                    reason: format!("{} > 0", n),
                }
            } else {
                Evaluation::Violated {
                    reason: format!("{} <= 0", n),
                }
            }
        }
        fn describe(&self) -> String {
            "is positive".into()
        }
    }

    #[derive(Debug)]
    struct IsEven;

    impl Proposition for IsEven {
        type Context = i32;
        fn evaluate(&self, n: &i32) -> Evaluation {
            if n % 2 == 0 {
                Evaluation::Satisfied {
                    reason: format!("{} is even", n),
                }
            } else {
                Evaluation::Violated {
                    reason: format!("{} is odd", n),
                }
            }
        }
        fn describe(&self) -> String {
            "is even".into()
        }
    }

    #[test]
    fn test_proposition_satisfied() {
        assert!(IsPositive.evaluate(&5).is_satisfied());
        assert!(!IsPositive.evaluate(&-3).is_satisfied());
    }

    #[test]
    fn test_allof() {
        let both = AllOf::new(vec![Box::new(IsPositive), Box::new(IsPositive)]);
        assert!(both.evaluate(&5).is_satisfied());
    }

    #[test]
    fn test_anyof() {
        let either = AnyOf::new(vec![Box::new(IsPositive), Box::new(IsEven)]);
        assert!(either.evaluate(&-4).is_satisfied());
        assert!(either.evaluate(&3).is_satisfied());
        assert!(
            !AnyOf::new(vec![Box::new(IsPositive), Box::new(IsEven)])
                .evaluate(&-3)
                .is_satisfied()
        );
    }

    #[test]
    fn test_not() {
        let not_positive = Not::new(IsPositive);
        assert!(not_positive.evaluate(&-5).is_satisfied());
        assert!(!not_positive.evaluate(&5).is_satisfied());
    }

    #[test]
    fn test_implies() {
        let if_pos_then_even = Implies::new(IsPositive, IsEven);
        assert!(if_pos_then_even.evaluate(&4).is_satisfied());
        assert!(!if_pos_then_even.evaluate(&3).is_satisfied());
        assert!(if_pos_then_even.evaluate(&-3).is_satisfied());
    }

    // --- Measurable / Threshold tests ---

    #[derive(Debug)]
    struct ValueOf;

    impl Measurable<i32> for ValueOf {
        type Value = i32;
        fn measure(&self, n: &i32) -> i32 {
            *n
        }
        fn name(&self) -> &str {
            "value"
        }
    }

    #[test]
    fn test_threshold_greater_than() {
        let check = Threshold::greater_than(ValueOf, 10);
        assert!(check.evaluate(&15).is_satisfied());
        assert!(!check.evaluate(&5).is_satisfied());
    }

    #[test]
    fn test_threshold_less_than() {
        let check = Threshold::less_than(ValueOf, 10);
        assert!(check.evaluate(&5).is_satisfied());
        assert!(!check.evaluate(&15).is_satisfied());
    }

    #[test]
    fn test_threshold_at_least() {
        let check = Threshold::at_least(ValueOf, 10);
        assert!(check.evaluate(&10).is_satisfied());
        assert!(check.evaluate(&11).is_satisfied());
        assert!(!check.evaluate(&9).is_satisfied());
    }

    #[test]
    fn test_compare_op() {
        assert!(CompareOp::LessThan.check(&3, &5));
        assert!(!CompareOp::LessThan.check(&5, &3));
        assert!(CompareOp::Equal.check(&5, &5));
        assert!(CompareOp::NotEqual.check(&3, &5));
        assert!(CompareOp::GreaterOrEqual.check(&5, &5));
    }

    proptest! {
        /// NOT NOT x = x
        #[test]
        fn prop_double_negation(n in -100..100i32) {
            let p = IsPositive;
            let nn = Not::new(Not::new(IsPositive));
            prop_assert_eq!(p.evaluate(&n).is_satisfied(), nn.evaluate(&n).is_satisfied());
        }

        /// AllOf with single element = the element
        #[test]
        fn prop_allof_single(n in -100..100i32) {
            let single = AllOf::new(vec![Box::new(IsPositive)]);
            prop_assert_eq!(single.evaluate(&n).is_satisfied(), IsPositive.evaluate(&n).is_satisfied());
        }

        /// AnyOf with single element = the element
        #[test]
        fn prop_anyof_single(n in -100..100i32) {
            let single = AnyOf::new(vec![Box::new(IsPositive)]);
            prop_assert_eq!(single.evaluate(&n).is_satisfied(), IsPositive.evaluate(&n).is_satisfied());
        }

        /// AllOf(A, B) implies AnyOf(A, B)
        #[test]
        fn prop_allof_implies_anyof(n in -100..100i32) {
            let all = AllOf::new(vec![Box::new(IsPositive), Box::new(IsEven)]);
            let any = AnyOf::new(vec![Box::new(IsPositive), Box::new(IsEven)]);
            if all.evaluate(&n).is_satisfied() {
                prop_assert!(any.evaluate(&n).is_satisfied());
            }
        }

        /// Implication: A → B is equivalent to NOT(A) OR B
        #[test]
        fn prop_implication_equivalence(n in -100..100i32) {
            let implies = Implies::new(IsPositive, IsEven);
            let a = IsPositive.evaluate(&n).is_satisfied();
            let b = IsEven.evaluate(&n).is_satisfied();
            let expected = !a || b;
            prop_assert_eq!(implies.evaluate(&n).is_satisfied(), expected);
        }

        /// Threshold: x > t iff x >= t+1 for integers
        #[test]
        fn prop_threshold_gt_vs_gte(value in -100..100i32, threshold in -50..50i32) {
            let gt = Threshold::greater_than(ValueOf, threshold);
            let gte = Threshold::at_least(ValueOf, threshold + 1);
            prop_assert_eq!(gt.evaluate(&value).is_satisfied(), gte.evaluate(&value).is_satisfied());
        }

        /// CompareOp is consistent with PartialOrd
        #[test]
        fn prop_compare_consistent(a in -100..100i32, b in -100..100i32) {
            prop_assert_eq!(CompareOp::LessThan.check(&a, &b), a < b);
            prop_assert_eq!(CompareOp::GreaterThan.check(&a, &b), a > b);
            prop_assert_eq!(CompareOp::Equal.check(&a, &b), a == b);
            prop_assert_eq!(CompareOp::LessOrEqual.check(&a, &b), a <= b);
            prop_assert_eq!(CompareOp::GreaterOrEqual.check(&a, &b), a >= b);
            prop_assert_eq!(CompareOp::NotEqual.check(&a, &b), a != b);
        }

        /// Evaluation reason is never empty
        #[test]
        fn prop_evaluation_has_reason(n in -100..100i32) {
            let result = IsPositive.evaluate(&n);
            prop_assert!(!result.reason().is_empty());
        }
    }
}