Skip to main content

qualia_cooperative_core/
trigger.rs

1//! The **Trigger algebra** (ADR §7.1) — *when* a delegated authority activates.
2//!
3//! A `Trigger` is a bounded boolean expression over primitive predicates. Authority can activate on
4//! **cryptographic / temporal conditions** (a verifiable event, a time window, a deadman/liveness
5//! switch) AND / OR on **subjective human consensus** (e.g. *two registered physicians attest
6//! incapacity*), composed freely with `All` / `Any` / `Not`.
7//!
8//! This is deliberately **both, composed** (ADR §7.1): purely-cryptographic predicates cannot capture
9//! clinical judgement, and purely-subjective attestation is not accountable. `HumanConsensus` requires
10//! *signed* attestations carrying a role/capacity credential, so subjective judgement becomes part of the
11//! evidence chain — accountable and contestable — rather than a black box.
12//!
13//! Load-bearing philosophy (this crate is **supported agency**, not a warden model): a `Trigger` only
14//! ever governs the activation of a delegation over *personhood* (socio-legal agency). It amplifies a
15//! person's agency (an accountant, a clinical psychologist, a work-peer, or — when someone is isolated —
16//! a declared software source of truth). *Selfhood* is inherent to the person and is never delegated, so
17//! nothing here can be used to trigger control over it. Higher-stakes / selfhood-adjacent domains simply
18//! demand higher `m`-of-`n` thresholds.
19//!
20//! `evaluate` is a **bounded, deterministic** recursion over the tree: given a `TriggerContext` (the
21//! current time, which events have occurred, the collected attestations, and the last liveness ping) it
22//! returns whether the trigger has fired. It never allocates unboundedly and has no side effects.
23
24use serde::{Deserialize, Serialize};
25
26/// A composable activation condition for a delegated authority (ADR §7.1).
27///
28/// Serialized with serde's default externally-tagged representation (a self-describing tree),
29/// e.g. `{"all":[{"verifiable_event":{...}},{"human_consensus":{...}}]}`. Internal tagging
30/// (`#[serde(tag=...)]`) is deliberately NOT used: this enum is recursive with sequence-wrapping
31/// newtype variants (`All(Vec<Trigger>)`, `Not(Box<Trigger>)`), which internal tagging cannot
32/// represent and which drives serde's serializer into an unbounded trait-resolution overflow.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35pub enum Trigger {
36    /// A cryptographically verifiable event/attestation identified by a stable id has occurred
37    /// (e.g. `er_admission`, `death_certificate`, an on-chain/ILP receipt).
38    VerifiableEvent { event_id: String },
39
40    /// The current time falls in `[from_unix, to_unix]`. An open upper bound (`to_unix: None`) means
41    /// "from `from_unix` onward, indefinitely".
42    TemporalWindow {
43        from_unix: u32,
44        #[serde(default, skip_serializing_if = "Option::is_none")]
45        to_unix: Option<u32>,
46    },
47
48    /// Liveness / deadman switch: fires once at least `timeout_secs` have elapsed since the principal
49    /// was last seen (`last_seen_unix`). Used for posthumous / incapacity fallbacks.
50    DeadmanSwitch {
51        last_seen_unix: u32,
52        timeout_secs: u32,
53    },
54
55    /// `m`-of-`n` **signed** human attestations meeting an optional required capacity/role credential
56    /// (e.g. 2-of-N `registered_physician` attesting incapacity). `n` is advisory metadata describing
57    /// the expected pool size; only `m` (the threshold) and the required capacity gate activation.
58    HumanConsensus {
59        #[serde(default, skip_serializing_if = "Option::is_none")]
60        required_capacity: Option<String>,
61        m: u32,
62        n: u32,
63    },
64
65    /// Conjunction — fires only if **every** child fires. An empty `All` is vacuously true.
66    All(Vec<Trigger>),
67
68    /// Disjunction — fires if **any** child fires. An empty `Any` is vacuously false.
69    Any(Vec<Trigger>),
70
71    /// Negation — fires iff the inner trigger does not.
72    Not(Box<Trigger>),
73}
74
75/// A single human attestation: the role/capacity it was made under (a taxonomy `TermId`, kept as an
76/// optional `String` here so the vocabulary stays open) and whether it is cryptographically signed.
77///
78/// Only *signed* attestations count toward a `HumanConsensus` threshold — an unsigned attestation is not
79/// part of the accountable evidence chain, so it cannot activate authority over someone.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct Attestation {
82    /// The role/capacity credential the attestation was made under (e.g.
83    /// `urn:qualia:agency-domain:welfare:healthcare` or a `registered_physician` capacity term).
84    /// `None` = an attestation carrying no specific declared capacity.
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub capacity: Option<String>,
87    /// Whether this attestation is cryptographically signed. Unsigned attestations never count.
88    pub signed: bool,
89}
90
91impl Attestation {
92    /// A signed attestation made under a specific capacity/role credential.
93    pub fn signed(capacity: impl Into<String>) -> Self {
94        Self {
95            capacity: Some(capacity.into()),
96            signed: true,
97        }
98    }
99
100    /// A signed attestation with no specific declared capacity.
101    pub fn signed_anon() -> Self {
102        Self {
103            capacity: None,
104            signed: true,
105        }
106    }
107
108    /// An unsigned attestation (does not count toward consensus).
109    pub fn unsigned(capacity: impl Into<String>) -> Self {
110        Self {
111            capacity: Some(capacity.into()),
112            signed: false,
113        }
114    }
115}
116
117/// The evaluation context — the observable world state a `Trigger` is tested against. All fields are
118/// data the delegation infrastructure already collects (event log, liveness pings, the attestation
119/// queue); `evaluate` reads them without mutation.
120#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
121pub struct TriggerContext {
122    /// Current wall-clock time (unix seconds).
123    pub now_unix: u32,
124    /// Ids of verifiable events known to have occurred.
125    #[serde(default)]
126    pub occurred_events: Vec<String>,
127    /// Collected human attestations (signed and unsigned).
128    #[serde(default)]
129    pub attestations: Vec<Attestation>,
130    /// The principal's last liveness ping (unix seconds), if any — feeds `DeadmanSwitch`.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub last_liveness_unix: Option<u32>,
133}
134
135impl TriggerContext {
136    /// A context anchored at `now_unix` with no events, attestations, or liveness signal.
137    pub fn at(now_unix: u32) -> Self {
138        Self {
139            now_unix,
140            ..Default::default()
141        }
142    }
143
144    /// Builder — sets event.
145    pub fn with_event(mut self, event_id: impl Into<String>) -> Self {
146        self.occurred_events.push(event_id.into());
147        self
148    }
149
150    /// Builder — sets attestation.
151    pub fn with_attestation(mut self, att: Attestation) -> Self {
152        self.attestations.push(att);
153        self
154    }
155
156    /// Builder — sets liveness.
157    pub fn with_liveness(mut self, last_liveness_unix: u32) -> Self {
158        self.last_liveness_unix = Some(last_liveness_unix);
159        self
160    }
161}
162
163/// Count the signed attestations in `ctx` that satisfy an optional required capacity.
164///
165/// A required capacity of `None` accepts any signed attestation; a required capacity of `Some(cap)`
166/// accepts only signed attestations whose `capacity == Some(cap)`.
167fn count_matching_attestations(required_capacity: Option<&str>, ctx: &TriggerContext) -> u32 {
168    ctx.attestations
169        .iter()
170        .filter(|att| att.signed)
171        .filter(|att| match required_capacity {
172            None => true,
173            Some(cap) => att.capacity.as_deref() == Some(cap),
174        })
175        .count()
176        // Attestation counts are tiny; saturate rather than risk a (practically impossible) overflow.
177        .min(u32::MAX as usize) as u32
178}
179
180/// Evaluate a `Trigger` against a `TriggerContext`. Deterministic, side-effect-free, and bounded by the
181/// size of the trigger tree (recursion depth = tree depth).
182///
183/// Semantics (ADR §7.1):
184/// - `VerifiableEvent` — the event id is present in `ctx.occurred_events`.
185/// - `TemporalWindow` — `now_unix >= from_unix` and (no upper bound, or `now_unix <= to_unix`).
186/// - `DeadmanSwitch` — a liveness signal exists and `now_unix - last_liveness >= timeout_secs`
187///   (saturating; a missing liveness signal never fires).
188/// - `HumanConsensus` — at least `m` signed attestations match the required capacity (`n` is advisory).
189/// - `All` — every child fires. `Any` — some child fires. `Not` — the inner trigger does not.
190pub fn evaluate(trigger: &Trigger, ctx: &TriggerContext) -> bool {
191    match trigger {
192        Trigger::VerifiableEvent { event_id } => ctx.occurred_events.iter().any(|e| e == event_id),
193        Trigger::TemporalWindow { from_unix, to_unix } => {
194            ctx.now_unix >= *from_unix && to_unix.map_or(true, |t| ctx.now_unix <= t)
195        }
196        Trigger::DeadmanSwitch {
197            last_seen_unix,
198            timeout_secs,
199        } => ctx
200            .last_liveness_unix
201            .map(|ls| ls.max(*last_seen_unix))
202            .or(Some(*last_seen_unix))
203            .map_or(false, |seen| {
204                // Fires only once the elapsed time since last-seen reaches the timeout.
205                ctx.now_unix.saturating_sub(seen) >= *timeout_secs
206            }),
207        Trigger::HumanConsensus {
208            required_capacity,
209            m,
210            ..
211        } => count_matching_attestations(required_capacity.as_deref(), ctx) >= *m,
212        Trigger::All(children) => children.iter().all(|c| evaluate(c, ctx)),
213        Trigger::Any(children) => children.iter().any(|c| evaluate(c, ctx)),
214        Trigger::Not(inner) => !evaluate(inner, ctx),
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    const PHYSICIAN: &str = "urn:qualia:capacity:registered-physician";
223    const NURSE: &str = "urn:qualia:capacity:registered-nurse";
224    const ER_ADMISSION: &str = "er_admission";
225
226    // ---- primitives: VerifiableEvent ----
227
228    #[test]
229    fn verifiable_event_true_when_present_false_when_absent() {
230        let t = Trigger::VerifiableEvent {
231            event_id: ER_ADMISSION.into(),
232        };
233        let present = TriggerContext::at(1000).with_event(ER_ADMISSION);
234        let absent = TriggerContext::at(1000).with_event("unrelated_event");
235        assert!(evaluate(&t, &present));
236        assert!(!evaluate(&t, &absent));
237        // Empty context also fails.
238        assert!(!evaluate(&t, &TriggerContext::at(1000)));
239    }
240
241    // ---- primitives: TemporalWindow ----
242
243    #[test]
244    fn temporal_window_bounded_range() {
245        let t = Trigger::TemporalWindow {
246            from_unix: 100,
247            to_unix: Some(200),
248        };
249        assert!(!evaluate(&t, &TriggerContext::at(99))); // before
250        assert!(evaluate(&t, &TriggerContext::at(100))); // inclusive lower
251        assert!(evaluate(&t, &TriggerContext::at(150))); // inside
252        assert!(evaluate(&t, &TriggerContext::at(200))); // inclusive upper
253        assert!(!evaluate(&t, &TriggerContext::at(201))); // after
254    }
255
256    #[test]
257    fn temporal_window_open_upper_bound_is_indefinite() {
258        let t = Trigger::TemporalWindow {
259            from_unix: 100,
260            to_unix: None,
261        };
262        assert!(!evaluate(&t, &TriggerContext::at(99)));
263        assert!(evaluate(&t, &TriggerContext::at(100)));
264        assert!(evaluate(&t, &TriggerContext::at(u32::MAX)));
265    }
266
267    // ---- primitives: DeadmanSwitch ----
268
269    #[test]
270    fn deadman_switch_fires_only_after_timeout() {
271        let t = Trigger::DeadmanSwitch {
272            last_seen_unix: 1000,
273            timeout_secs: 3600,
274        };
275        // No liveness in context: falls back to last_seen_unix baked into the trigger.
276        assert!(!evaluate(&t, &TriggerContext::at(1000))); // 0 elapsed
277        assert!(!evaluate(&t, &TriggerContext::at(4599))); // 3599 elapsed, just short
278        assert!(evaluate(&t, &TriggerContext::at(4600))); // exactly 3600 elapsed
279        assert!(evaluate(&t, &TriggerContext::at(10_000))); // well past
280    }
281
282    #[test]
283    fn deadman_switch_uses_latest_liveness_ping() {
284        let t = Trigger::DeadmanSwitch {
285            last_seen_unix: 1000,
286            timeout_secs: 3600,
287        };
288        // A fresher liveness ping resets the clock: last seen at 5000, now 6000 → only 1000 elapsed.
289        let fresh = TriggerContext::at(6000).with_liveness(5000);
290        assert!(!evaluate(&t, &fresh));
291        // Old liveness ping older than the baked-in last_seen still uses the newer of the two.
292        let stale_ping = TriggerContext::at(4600).with_liveness(500);
293        assert!(evaluate(&t, &stale_ping)); // max(1000,500)=1000, 3600 elapsed → fires
294    }
295
296    // ---- primitives: HumanConsensus ----
297
298    #[test]
299    fn human_consensus_counts_only_signed_matching_capacity() {
300        let t = Trigger::HumanConsensus {
301            required_capacity: Some(PHYSICIAN.into()),
302            m: 2,
303            n: 5,
304        };
305        // Two signed physicians → fires.
306        let ok = TriggerContext::at(0)
307            .with_attestation(Attestation::signed(PHYSICIAN))
308            .with_attestation(Attestation::signed(PHYSICIAN));
309        assert!(evaluate(&t, &ok));
310
311        // One physician + one nurse → only one matches → below threshold.
312        let wrong_capacity = TriggerContext::at(0)
313            .with_attestation(Attestation::signed(PHYSICIAN))
314            .with_attestation(Attestation::signed(NURSE));
315        assert!(!evaluate(&t, &wrong_capacity));
316
317        // Two physicians but one unsigned → only one counts → fails (accountability requires signature).
318        let one_unsigned = TriggerContext::at(0)
319            .with_attestation(Attestation::signed(PHYSICIAN))
320            .with_attestation(Attestation::unsigned(PHYSICIAN));
321        assert!(!evaluate(&t, &one_unsigned));
322    }
323
324    #[test]
325    fn human_consensus_below_threshold_fails() {
326        let t = Trigger::HumanConsensus {
327            required_capacity: Some(PHYSICIAN.into()),
328            m: 3,
329            n: 5,
330        };
331        let two = TriggerContext::at(0)
332            .with_attestation(Attestation::signed(PHYSICIAN))
333            .with_attestation(Attestation::signed(PHYSICIAN));
334        assert!(!evaluate(&t, &two)); // 2 < 3
335    }
336
337    #[test]
338    fn human_consensus_without_required_capacity_accepts_any_signed() {
339        let t = Trigger::HumanConsensus {
340            required_capacity: None,
341            m: 2,
342            n: 2,
343        };
344        let mixed = TriggerContext::at(0)
345            .with_attestation(Attestation::signed(PHYSICIAN))
346            .with_attestation(Attestation::signed(NURSE));
347        assert!(evaluate(&t, &mixed)); // any two signed count
348                                       // But unsigned still never counts.
349        let one_signed = TriggerContext::at(0)
350            .with_attestation(Attestation::signed(PHYSICIAN))
351            .with_attestation(Attestation::unsigned(NURSE));
352        assert!(!evaluate(&t, &one_signed));
353    }
354
355    #[test]
356    fn human_consensus_n_is_advisory_only() {
357        // n smaller than the number present, or than m, must not affect activation — only m gates.
358        let t = Trigger::HumanConsensus {
359            required_capacity: None,
360            m: 1,
361            n: 0,
362        };
363        let ctx = TriggerContext::at(0).with_attestation(Attestation::signed_anon());
364        assert!(evaluate(&t, &ctx));
365    }
366
367    // ---- composition: All / Any / Not ----
368
369    #[test]
370    fn empty_all_is_true_empty_any_is_false() {
371        assert!(evaluate(&Trigger::All(vec![]), &TriggerContext::at(0)));
372        assert!(!evaluate(&Trigger::Any(vec![]), &TriggerContext::at(0)));
373    }
374
375    #[test]
376    fn not_inverts_child() {
377        let ev = Trigger::VerifiableEvent {
378            event_id: ER_ADMISSION.into(),
379        };
380        let not_ev = Trigger::Not(Box::new(ev.clone()));
381        let with = TriggerContext::at(0).with_event(ER_ADMISSION);
382        let without = TriggerContext::at(0);
383        assert!(evaluate(&ev, &with) && !evaluate(&not_ev, &with));
384        assert!(!evaluate(&ev, &without) && evaluate(&not_ev, &without));
385    }
386
387    #[test]
388    fn any_and_all_compose() {
389        let a = Trigger::VerifiableEvent {
390            event_id: "a".into(),
391        };
392        let b = Trigger::VerifiableEvent {
393            event_id: "b".into(),
394        };
395        let all = Trigger::All(vec![a.clone(), b.clone()]);
396        let any = Trigger::Any(vec![a.clone(), b.clone()]);
397
398        let only_a = TriggerContext::at(0).with_event("a");
399        let both = TriggerContext::at(0).with_event("a").with_event("b");
400
401        assert!(!evaluate(&all, &only_a)); // All needs both
402        assert!(evaluate(&all, &both));
403        assert!(evaluate(&any, &only_a)); // Any needs one
404        assert!(!evaluate(&any, &TriggerContext::at(0))); // neither
405    }
406
407    // ---- the ADR §7.1 crisis composite ----
408
409    #[test]
410    fn crisis_composite_verifiable_event_and_two_of_n_physicians() {
411        // The canonical ADR example: fire on ER admission AND 2-of-N registered physicians attesting.
412        let crisis = Trigger::All(vec![
413            Trigger::VerifiableEvent {
414                event_id: ER_ADMISSION.into(),
415            },
416            Trigger::HumanConsensus {
417                required_capacity: Some(PHYSICIAN.into()),
418                m: 2,
419                n: 5,
420            },
421        ]);
422
423        // Full crisis: admitted + two physicians attest → activates.
424        let full = TriggerContext::at(1_700_000_000)
425            .with_event(ER_ADMISSION)
426            .with_attestation(Attestation::signed(PHYSICIAN))
427            .with_attestation(Attestation::signed(PHYSICIAN));
428        assert!(evaluate(&crisis, &full));
429
430        // Admitted but only one physician has attested → consensus below threshold → does NOT activate.
431        let one_doctor = TriggerContext::at(1_700_000_000)
432            .with_event(ER_ADMISSION)
433            .with_attestation(Attestation::signed(PHYSICIAN));
434        assert!(!evaluate(&crisis, &one_doctor));
435
436        // Two physicians attest but no verifiable admission event → does NOT activate.
437        let no_event = TriggerContext::at(1_700_000_000)
438            .with_attestation(Attestation::signed(PHYSICIAN))
439            .with_attestation(Attestation::signed(PHYSICIAN));
440        assert!(!evaluate(&crisis, &no_event));
441    }
442
443    #[test]
444    fn deeply_nested_composite_evaluates() {
445        // (window AND (event OR deadman)) AND NOT(revocation event)
446        let trigger = Trigger::All(vec![
447            Trigger::TemporalWindow {
448                from_unix: 100,
449                to_unix: Some(1000),
450            },
451            Trigger::Any(vec![
452                Trigger::VerifiableEvent {
453                    event_id: "consent".into(),
454                },
455                Trigger::DeadmanSwitch {
456                    last_seen_unix: 100,
457                    timeout_secs: 500,
458                },
459            ]),
460            Trigger::Not(Box::new(Trigger::VerifiableEvent {
461                event_id: "revoked".into(),
462            })),
463        ]);
464
465        // now=200: in window; consent present; not revoked → fires.
466        let ok = TriggerContext::at(200).with_event("consent");
467        assert!(evaluate(&trigger, &ok));
468
469        // Revocation present → NOT clause fails the whole All.
470        let revoked = TriggerContext::at(200)
471            .with_event("consent")
472            .with_event("revoked");
473        assert!(!evaluate(&trigger, &revoked));
474
475        // now=700: consent absent, but deadman fired (700-100=600 >= 500) → Any still true → fires.
476        let deadman = TriggerContext::at(700);
477        assert!(evaluate(&trigger, &deadman));
478
479        // now=1001: outside temporal window → whole All fails regardless of the rest.
480        let out_of_window = TriggerContext::at(1001).with_event("consent");
481        assert!(!evaluate(&trigger, &out_of_window));
482    }
483
484    // ---- serde round-trip ----
485
486    #[test]
487    fn trigger_serde_round_trips() {
488        let trigger = Trigger::All(vec![
489            Trigger::VerifiableEvent {
490                event_id: ER_ADMISSION.into(),
491            },
492            Trigger::HumanConsensus {
493                required_capacity: Some(PHYSICIAN.into()),
494                m: 2,
495                n: 5,
496            },
497            Trigger::Not(Box::new(Trigger::TemporalWindow {
498                from_unix: 0,
499                to_unix: None,
500            })),
501        ]);
502        let json = serde_json::to_string(&trigger).expect("serialize");
503        // Externally tagged: variant name is the key, e.g. {"all":[{"human_consensus":{...}}]}.
504        assert!(json.contains("\"all\""));
505        assert!(json.contains("\"human_consensus\""));
506        let back: Trigger = serde_json::from_str(&json).expect("deserialize");
507        assert_eq!(trigger, back);
508    }
509
510    #[test]
511    fn context_and_attestation_serde_round_trip() {
512        let ctx = TriggerContext::at(42)
513            .with_event(ER_ADMISSION)
514            .with_attestation(Attestation::signed(PHYSICIAN))
515            .with_attestation(Attestation::unsigned(NURSE))
516            .with_liveness(40);
517        let json = serde_json::to_string(&ctx).expect("serialize");
518        let back: TriggerContext = serde_json::from_str(&json).expect("deserialize");
519        assert_eq!(ctx, back);
520    }
521
522    #[test]
523    fn attestation_constructors_are_correct() {
524        assert_eq!(
525            Attestation::signed(PHYSICIAN),
526            Attestation {
527                capacity: Some(PHYSICIAN.to_string()),
528                signed: true
529            }
530        );
531        assert_eq!(
532            Attestation::signed_anon(),
533            Attestation {
534                capacity: None,
535                signed: true
536            }
537        );
538        assert_eq!(
539            Attestation::unsigned(NURSE),
540            Attestation {
541                capacity: Some(NURSE.to_string()),
542                signed: false
543            }
544        );
545    }
546}