Skip to main content

qualia_core_db/governance/
coord_seams.rs

1//! R8: Concrete wiring of `CoordHostSeams` to daemon infrastructure.
2//!
3//! The coordination ISA (`governance/coordination.rs`) defines host seams
4//! that it cannot decide itself:
5//! - `verify_root_delegation` — is an agent's delegation signed by the root key?
6//! - `yield_to_suspended_queue` — enqueue a suspended transaction
7//! - `mint_performance_vc` — mint a performance Verifiable Credential to the graph
8//!
9//! The default seams (`default_seams()`) are fail-closed: verify returns false,
10//! yield is a no-op, mint returns 0. This module provides `daemon_seams()` which
11//! wires these to the actual daemon infrastructure:
12//! - `verify_root_delegation` → checks a delegation table backed by `crdt::DelegatedAccess`
13//! - `yield_to_suspended_queue` → `crdt::SuspendedTransactionQueue::push`
14//! - `mint_performance_vc` → `daemon_graph::extend_with_ontology_quins_slice`
15//!   with a performance VC quin, returns the `perf_vc_hash`
16
17use crate::foundation::crdt::{DelegatedAccess, SuspendedTransaction, SuspendedTransactionQueue};
18use crate::governance::coordination::{perf_vc_hash, CoordHostSeams};
19use crate::NQuin;
20use std::sync::Mutex;
21
22/// Global suspended transaction queue (R8 wiring).
23static SUSPENDED_QUEUE: Mutex<Option<SuspendedTransactionQueue>> = Mutex::new(None);
24
25/// Global delegation table (R8 wiring).
26/// Maps agent_did_hash (first 8 bytes of delegate_did) → DelegatedAccess.
27static DELEGATION_TABLE: Mutex<Option<Vec<(u64, DelegatedAccess)>>> = Mutex::new(None);
28
29/// Initialize the daemon-backed coordination seams (R8).
30///
31/// This wires the fail-closed default seams to actual daemon infrastructure.
32/// Call once at daemon startup.
33pub fn init_daemon_seams() {
34    {
35        let mut q = SUSPENDED_QUEUE.lock().unwrap();
36        if q.is_none() {
37            *q = Some(SuspendedTransactionQueue::new());
38        }
39    }
40    {
41        let mut t = DELEGATION_TABLE.lock().unwrap();
42        if t.is_none() {
43            *t = Some(Vec::new());
44        }
45    }
46}
47
48/// Register a delegation for an agent (R8).
49/// Allows `verify_root_delegation` to return true for this agent.
50/// The `agent_did_hash` is derived from the first 8 bytes of the delegate's DID.
51pub fn register_delegation(agent_did_hash: u64, access: DelegatedAccess) {
52    init_daemon_seams();
53    let mut t = DELEGATION_TABLE.lock().unwrap();
54    if let Some(ref mut table) = *t {
55        if let Some(entry) = table.iter_mut().find(|(h, _)| *h == agent_did_hash) {
56            entry.1 = access;
57        } else {
58            table.push((agent_did_hash, access));
59        }
60    }
61}
62
63/// Create daemon-backed coordination seams (R8).
64///
65/// These seams wire the coordination ISA to the actual daemon:
66/// - `verify_root_delegation`: checks the delegation table
67/// - `yield_to_suspended_queue`: pushes to the global queue
68/// - `mint_performance_vc`: mints a VC quin to the daemon graph
69pub fn daemon_seams() -> CoordHostSeams {
70    init_daemon_seams();
71    CoordHostSeams {
72        verify_root_delegation: Box::new(|agent_did_hash, _root_did_hash| {
73            verify_delegation_impl(agent_did_hash)
74        }),
75        yield_to_suspended_queue: Box::new(|task_hash, token_limit| {
76            yield_to_suspended_queue_impl(task_hash, token_limit)
77        }),
78        mint_performance_vc: Box::new(|agent_did_hash, declared, actual, validation| {
79            mint_performance_vc_impl(agent_did_hash, declared, actual, validation)
80        }),
81    }
82}
83
84fn verify_delegation_impl(agent_did_hash: u64) -> bool {
85    let t = DELEGATION_TABLE.lock().unwrap();
86    if let Some(ref table) = *t {
87        for &(h, ref access) in table.iter() {
88            if h == agent_did_hash {
89                // Verify the delegation: check expiry and context
90                // Use u64::MAX as current timestamp so non-zero expiry always passes
91                return crate::foundation::crdt::CrdtResolver::verify_delegation(
92                    access,
93                    0,
94                    u64::MAX,
95                );
96            }
97        }
98    }
99    false
100}
101
102fn yield_to_suspended_queue_impl(task_hash: u64, _token_limit: u64) {
103    let mut q = SUSPENDED_QUEUE.lock().unwrap();
104    if let Some(ref mut queue) = *q {
105        let tx = SuspendedTransaction {
106            agreement_id: task_hash,
107            collected_signatures: 0,
108            threshold: 1,
109            registers: [None; 16],
110            bytecode_buffer: [None; 64],
111            yielded_op: None,
112            suspended_quin: NQuin {
113                subject: task_hash,
114                predicate: 0,
115                object: 0,
116                context: 0,
117                metadata: 0,
118                parity: 0,
119            },
120        };
121        let _ = queue.push(tx);
122    }
123}
124
125fn mint_performance_vc_impl(
126    agent_did_hash: u64,
127    declared: u64,
128    actual: u64,
129    validation: bool,
130) -> u64 {
131    // Compute the performance record using the coordination ISA's evaluator
132    let rec = crate::governance::coordination::eval_performance_rating(
133        agent_did_hash,
134        declared,
135        actual,
136        validation,
137    );
138    let vc_hash = perf_vc_hash(&rec);
139
140    // Mint the VC as a quin to the daemon graph
141    #[cfg(not(target_arch = "wasm32"))]
142    {
143        let vc_quin = NQuin {
144            subject: agent_did_hash,
145            predicate: crate::q_hash("q42:hasPerformanceVC"),
146            object: vc_hash,
147            context: crate::q_hash("q42:coordination"),
148            metadata: if validation { 1 } else { 0 },
149            parity: 0,
150        };
151        crate::daemon_graph::extend_with_ontology_quins_slice(&[vc_quin]);
152    }
153
154    // Suppress unused warning when not writing to graph
155    let _ = rec;
156    vc_hash
157}
158
159/// Get the number of suspended transactions (for diagnostics/testing).
160pub fn suspended_queue_len() -> usize {
161    let q = SUSPENDED_QUEUE.lock().unwrap();
162    if let Some(ref queue) = *q {
163        queue.queue.iter().filter(|s| s.is_some()).count()
164    } else {
165        0
166    }
167}
168
169/// Clear the suspended queue and delegation table (for testing).
170pub fn reset_daemon_seams() {
171    {
172        let mut q = SUSPENDED_QUEUE.lock().unwrap();
173        *q = Some(SuspendedTransactionQueue::new());
174    }
175    {
176        let mut t = DELEGATION_TABLE.lock().unwrap();
177        *t = Some(Vec::new());
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184
185    fn make_delegation(agent_hash: u64) -> DelegatedAccess {
186        let mut delegate = [0u8; 32];
187        let bytes = agent_hash.to_le_bytes();
188        delegate[..8].copy_from_slice(&bytes);
189        DelegatedAccess {
190            principal_did: [0xCA; 32],
191            delegate_did: delegate,
192            context_bound: 0,
193            expiration_timestamp: u64::MAX,
194            cryptographic_proof: [0u8; 64],
195        }
196    }
197
198    #[test]
199    fn r8_daemon_seams_verify_delegation() {
200        reset_daemon_seams();
201        let agent_hash = 0xDEAD_BEEF_u64;
202        register_delegation(agent_hash, make_delegation(agent_hash));
203
204        let seams = daemon_seams();
205        assert!((seams.verify_root_delegation)(agent_hash, 0xCAFE));
206        // Unknown agent should fail
207        assert!(!(seams.verify_root_delegation)(0x1234_5678, 0));
208    }
209
210    #[test]
211    fn r8_daemon_seams_verify_unknown_fails_closed() {
212        reset_daemon_seams();
213        let seams = daemon_seams();
214        assert!(!(seams.verify_root_delegation)(0xBAD_F00D, 0));
215    }
216
217    #[test]
218    fn r8_daemon_seams_yield_to_suspended_queue() {
219        reset_daemon_seams();
220        let seams = daemon_seams();
221        assert_eq!(suspended_queue_len(), 0);
222        (seams.yield_to_suspended_queue)(0x1234, 1000);
223        assert_eq!(suspended_queue_len(), 1);
224        (seams.yield_to_suspended_queue)(0x5678, 2000);
225        assert_eq!(suspended_queue_len(), 2);
226    }
227
228    #[test]
229    fn r8_daemon_seams_mint_performance_vc() {
230        reset_daemon_seams();
231        let seams = daemon_seams();
232        let vc_hash = (seams.mint_performance_vc)(0xA1, 1000, 800, true);
233        assert_ne!(vc_hash, 0);
234        // Deterministic: same inputs → same hash
235        let seams2 = daemon_seams();
236        let vc_hash2 = (seams2.mint_performance_vc)(0xA1, 1000, 800, true);
237        assert_eq!(vc_hash, vc_hash2);
238    }
239
240    #[test]
241    fn r8_daemon_seams_mint_vc_validation_flag() {
242        reset_daemon_seams();
243        let seams = daemon_seams();
244        let h1 = (seams.mint_performance_vc)(0xA2, 1000, 800, true);
245        let seams2 = daemon_seams();
246        let h2 = (seams2.mint_performance_vc)(0xA2, 1000, 800, false);
247        assert_ne!(h1, h2);
248    }
249
250    #[test]
251    fn r8_default_seams_fail_closed() {
252        let seams = crate::governance::coordination::default_seams();
253        assert!(!(seams.verify_root_delegation)(0x1234, 0));
254        (seams.yield_to_suspended_queue)(0, 0);
255        assert_eq!((seams.mint_performance_vc)(0, 0, 0, false), 0);
256    }
257}