Skip to main content

qualia_core_db/governance/
coordination.rs

1//! Multi-agent **coordination opcodes** — `MULTI_AGENT_PROTOCOL.md`, Sentinel bytecode
2//! block **0x70–0x7F** (the deontic ISA owns 0x50–0x53; this block is collision-free).
3//!
4//! These govern the mechanical ingestion + evaluation of coordination nquins and execute
5//! atomically in the Sentinel VM. This module is the **decidable core** of the three
6//! opcodes — the expiry gate, the anti-usury resource contract + circuit breakers, and the
7//! fidelity/efficiency arithmetic — as deterministic, zero-heap, tested functions. The
8//! non-decidable substrate is passed in as a seam, never stubbed here:
9//!
10//! * `0x70` root-delegation **signature verification** → a `verify` closure the daemon
11//!   backs with the key-vault Root Key (secure enclave);
12//! * `0x71` **`SuspendedTransactionQueue`** yield → the caller acts on
13//!   [`CoordFault::InsufficientGlobalResources`];
14//! * `0x72` **VC minting** to the Semantic Shared Context Graph → the caller writes the
15//!   [`PerformanceRecord`] as an nquin; the privileged (daemon-only) gate is the caller's.
16//!
17//! Wiring an operand-stack execution path into `webizen_bytecode` (today a per-quin
18//! matcher) + the substrate above is the next increment; the semantics are fixed here.
19
20use crate::modalities::socioeconomics::{check_usury, UsuryError, USURY_OVERAGE_PERCENT_DEFAULT};
21
22/// `0x70` — verify cryptographic delegation Human-Root → ephemeral agent.
23pub const OP_AUTHORIZATION_GRANT: u8 = 0x70;
24/// `0x71` — declare the hard computational boundaries (anti-usury layer) for a task.
25pub const OP_RESOURCE_DECLARATION: u8 = 0x71;
26/// `0x72` — privileged: mint the performance VC at task resolution (Sentinel daemon only).
27pub const OP_PERFORMANCE_RATING: u8 = 0x72;
28
29/// Coordination-layer faults. Each dumps the current VM frame.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum CoordFault {
32    /// `0x70` `ERR_GRANT_EXPIRED` — the delegation's validity timestamp is in the past.
33    GrantExpired { now: u64, valid_until: u64 },
34    /// `0x70` `ERR_UNAUTHORIZED_ACTOR` — root-delegation signature verification failed.
35    UnauthorizedActor { agent: u64 },
36    /// `0x71` `ERR_INSUFFICIENT_GLOBAL_RESOURCES` — declared ceiling exceeds the daemon's
37    /// current global allowance; the intent must yield to the `SuspendedTransactionQueue`.
38    InsufficientGlobalResources { declared: u64, global_limit: u64 },
39    /// `0x72` — invoked by a non-privileged (synthetic) actor; only the Sentinel daemon may.
40    PrivilegeViolation,
41}
42
43/// **`0x70` OP_AUTHORIZATION_GRANT.** Stack: `[Agent_DID_Hash, Human_Root_DID_Hash,
44/// Metadata_Timestamp]`. Pops the timestamp first (expiry gate), then verifies the
45/// delegation signature against the active Root Key (the `verify_root_delegation` seam).
46///
47/// Returns `Ok(true)` when valid — the VM then pushes `1` and registers the agent's session
48/// in the Sentinel context. A failure is a fault (push `0`, dump the frame): `GrantExpired`
49/// if `current_epoch > metadata_timestamp`, else `UnauthorizedActor` if the signature is
50/// invalid.
51pub fn eval_authorization_grant(
52    agent_did_hash: u64,
53    human_root_did_hash: u64,
54    metadata_timestamp: u64,
55    current_epoch: u64,
56    verify_root_delegation: impl FnOnce(u64, u64) -> bool,
57) -> Result<bool, CoordFault> {
58    if current_epoch > metadata_timestamp {
59        return Err(CoordFault::GrantExpired {
60            now: current_epoch,
61            valid_until: metadata_timestamp,
62        });
63    }
64    if verify_root_delegation(agent_did_hash, human_root_did_hash) {
65        Ok(true)
66    } else {
67        Err(CoordFault::UnauthorizedActor {
68            agent: agent_did_hash,
69        })
70    }
71}
72
73/// The live resource contract + hardware circuit breakers a granted task runs under
74/// (established by `0x71`). Deterministic, zero-heap.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct ResourceContract {
77    pub task_id_hash: u64,
78    /// Declared token ceiling — the anti-usury bound for [`Self::burn_tokens`].
79    pub token_ceiling: u64,
80    /// Decrementing clock-cycle breaker.
81    pub cycles_remaining: u64,
82    /// Summation tracker of tokens burned so far.
83    pub tokens_burned: u64,
84}
85
86impl ResourceContract {
87    /// Charge `n` clock cycles against the decrementing breaker. Returns `false` (breaker
88    /// tripped) when the budget would underflow — the caller must halt the task.
89    #[must_use]
90    pub fn tick_cycles(&mut self, n: u64) -> bool {
91        match self.cycles_remaining.checked_sub(n) {
92            Some(rem) => {
93                self.cycles_remaining = rem;
94                true
95            }
96            None => {
97                self.cycles_remaining = 0;
98                false
99            }
100        }
101    }
102
103    /// Add `n` to the token-burn tracker. `Err(UsuryError)` once the cumulative burn breaches
104    /// the **usury ceiling** (declared ceiling + the default overage) — the anti-usury layer.
105    pub fn burn_tokens(&mut self, n: u64) -> Result<(), UsuryError> {
106        self.tokens_burned = self.tokens_burned.saturating_add(n);
107        check_usury(
108            self.tokens_burned,
109            self.token_ceiling,
110            USURY_OVERAGE_PERCENT_DEFAULT,
111        )
112    }
113}
114
115/// **`0x71` OP_RESOURCE_DECLARATION.** Stack: `[Task_ID_Hash, Token_Ceiling,
116/// Max_Clock_Cycles]`. Allocates the declared bounds to a fresh [`ResourceContract`] and
117/// arms its circuit breakers. Errors with `InsufficientGlobalResources` (→ yield to the
118/// `SuspendedTransactionQueue`) when the declared ceiling exceeds the daemon's global
119/// allowance.
120pub fn eval_resource_declaration(
121    task_id_hash: u64,
122    token_ceiling: u64,
123    max_clock_cycles: u64,
124    global_token_limit: u64,
125) -> Result<ResourceContract, CoordFault> {
126    if token_ceiling > global_token_limit {
127        return Err(CoordFault::InsufficientGlobalResources {
128            declared: token_ceiling,
129            global_limit: global_token_limit,
130        });
131    }
132    Ok(ResourceContract {
133        task_id_hash,
134        token_ceiling,
135        cycles_remaining: max_clock_cycles,
136        tokens_burned: 0,
137    })
138}
139
140/// The performance verdict minted by `0x72` — the inputs to the performance-VC nquin written
141/// to the Semantic Shared Context Graph.
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub struct PerformanceRecord {
144    pub agent_did_hash: u64,
145    /// `1` = task validated; `0` = validation failed (hallucination / semantic conflict).
146    pub fidelity: u8,
147    /// `(declared − actual) / declared` in basis points (signed). **Negative ⇒ usury**
148    /// (over-burn) ⇒ severe reputation slashing.
149    pub efficiency_bp: i64,
150    /// The cumulative burn breached the declared token ceiling (the bright-line extraction
151    /// event the Darwinian scheduler hard-quarantines).
152    pub usurious: bool,
153}
154
155/// **`0x72` OP_PERFORMANCE_RATING** (privileged). Stack: `[Agent_DID_Hash, Declared_Tokens,
156/// Actual_Tokens_Burned, Validation_Boolean]`. Computes fidelity + efficiency and flags
157/// usury. The VM then mints the VC nquin and pushes its hash; the daemon-only privilege gate
158/// is the caller's (`require_privileged`).
159pub fn eval_performance_rating(
160    agent_did_hash: u64,
161    declared_tokens: u64,
162    actual_tokens_burned: u64,
163    validation_ok: bool,
164) -> PerformanceRecord {
165    let fidelity = u8::from(validation_ok);
166    let efficiency_bp = if declared_tokens == 0 {
167        0
168    } else {
169        ((declared_tokens as i128 - actual_tokens_burned as i128) * 10_000
170            / declared_tokens as i128) as i64
171    };
172    let usurious = check_usury(
173        actual_tokens_burned,
174        declared_tokens,
175        USURY_OVERAGE_PERCENT_DEFAULT,
176    )
177    .is_err();
178    PerformanceRecord {
179        agent_did_hash,
180        fidelity,
181        efficiency_bp,
182        usurious,
183    }
184}
185
186/// Privilege gate for `0x72`: only the Sentinel daemon may mint performance VCs.
187pub fn require_privileged(is_sentinel_daemon: bool) -> Result<(), CoordFault> {
188    if is_sentinel_daemon {
189        Ok(())
190    } else {
191        Err(CoordFault::PrivilegeViolation)
192    }
193}
194
195// ─── Darwinian compute-priority weighting (daemon_swarm.rs policy) ─────────────────
196//
197// Exponential decay on *windowed* fidelity faults (an honest single miss is forgiven and can
198// recover above the floor); a usury event is a bright-line extraction act → immediate hard
199// quarantine (priority 0). Deterministic integer math.
200
201/// Full compute priority of an unfaulted agent.
202pub const PRIORITY_BASE: u64 = 10_000;
203/// Redemption floor — an honest agent decaying on fidelity faults never fully starves and can
204/// climb back. (Usury bypasses the floor: it quarantines to 0.)
205pub const PRIORITY_FLOOR: u64 = 100;
206
207/// Darwinian compute priority from an agent's recent record: `usury_event` ⇒ `0` (hard
208/// quarantine); otherwise `PRIORITY_BASE × (1/2)^windowed_faults`, clamped at `PRIORITY_FLOOR`.
209pub fn compute_priority(windowed_faults: u32, usury_event: bool) -> u64 {
210    if usury_event {
211        return 0;
212    }
213    let mut p = PRIORITY_BASE;
214    for _ in 0..windowed_faults {
215        p /= 2;
216    }
217    p.max(PRIORITY_FLOOR)
218}
219
220// ─── Coordination operand-stack VM (ISA 0x70–0x7F) ────────────────────────────────
221//
222// `webizen_bytecode` is a per-quin matcher; the coordination ISA is instead a small
223// **fixed-depth operand-stack machine**. A program PUSHes the opcode operands then executes
224// 0x70 / 0x71 / 0x72 with the stack effects in MULTI_AGENT_PROTOCOL.md §5. Zero-heap (the
225// stack is a fixed array), keeping the Sentinel VM's bounded discipline.
226
227/// Operand-stack depth — fixed/bounded like the rest of the VM.
228pub const COORD_STACK_DEPTH: usize = 16;
229/// `0x7F` — push the next 8 little-endian bytes as a `u64` operand.
230pub const OP_PUSH_U64: u8 = 0x7F;
231
232/// Host-provided seams the coordination VM cannot decide itself (the daemon backs these).
233pub struct CoordContext<V: Fn(u64, u64) -> bool> {
234    /// Current epoch — the `0x70` expiry gate.
235    pub current_epoch: u64,
236    /// The daemon's global token allowance — the `0x71` admission check.
237    pub global_token_limit: u64,
238    /// Whether the caller is the privileged Sentinel daemon — gates `0x72`.
239    pub is_sentinel_daemon: bool,
240    /// Root-delegation signature verification against the enclave Root Key — `0x70`.
241    pub verify_root_delegation: V,
242}
243
244/// Host-side seams bundled for the coordination ISA (R8).
245pub struct CoordHostSeams {
246    /// Verify root delegation signature (0x70).
247    /// Returns true if agent_did_hash is validly delegated by human_root_did_hash.
248    pub verify_root_delegation: Box<dyn Fn(u64, u64) -> bool + Send + Sync>,
249    /// Yield to SuspendedTransactionQueue (0x71).
250    /// Called when InsufficientGlobalResources is raised.
251    pub yield_to_suspended_queue: Box<dyn Fn(u64, u64) + Send + Sync>,
252    /// Mint a performance VC to the graph (0x72).
253    /// Returns the nquin_hash of the minted VC.
254    pub mint_performance_vc: Box<dyn Fn(u64, u64, u64, bool) -> u64 + Send + Sync>,
255}
256
257/// Conservative fail-closed default host seams (R8).
258pub fn default_seams() -> CoordHostSeams {
259    CoordHostSeams {
260        verify_root_delegation: Box::new(|_agent, _root| false),
261        yield_to_suspended_queue: Box::new(|_task, _limit| ()),
262        mint_performance_vc: Box::new(|_agent, _declared, _actual, _validation| 0),
263    }
264}
265
266impl Default for CoordHostSeams {
267    fn default() -> Self {
268        default_seams()
269    }
270}
271
272/// Execution context for coordination programs backed by full host seams (R8).
273pub struct CoordSeamContext<'a> {
274    pub current_epoch: u64,
275    pub global_token_limit: u64,
276    pub is_sentinel_daemon: bool,
277    pub seams: &'a CoordHostSeams,
278}
279
280/// What a coordination program produced (besides the operand stack).
281#[derive(Debug, Clone, PartialEq, Eq, Default)]
282pub struct CoordOutcome {
283    /// `0x70` result, if executed.
284    pub granted: Option<bool>,
285    /// `0x71` contract, if executed — the host arms the breakers / yields to the queue.
286    pub contract: Option<ResourceContract>,
287    /// `0x72` record, if executed — the host mints the VC nquin into the context graph.
288    pub performance: Option<PerformanceRecord>,
289    /// Top of the operand stack at halt (e.g. the minted VC hash), if any.
290    pub stack_top: Option<u64>,
291}
292
293/// Coordination VM faults.
294#[derive(Debug, Clone, PartialEq, Eq)]
295pub enum CoordVmError {
296    StackUnderflow,
297    StackOverflow,
298    /// Truncated operand or an unknown opcode.
299    InvalidProgram,
300    /// An opcode raised a coordination fault — the frame is dumped.
301    Fault(CoordFault),
302}
303
304/// Deterministic VC identity for a minted performance record — the `nquin_hash` `0x72` pushes
305/// to confirm minting. The host writes the full [`PerformanceRecord`] to the context graph.
306pub fn perf_vc_hash(rec: &PerformanceRecord) -> u64 {
307    crate::q_hash(&format!(
308        "q42:perfVC:{}:{}:{}:{}",
309        rec.agent_did_hash, rec.fidelity, rec.efficiency_bp, rec.usurious
310    ))
311}
312
313/// Execute a coordination-ISA program against a fresh fixed-depth operand stack.
314pub fn execute_coordination<V: Fn(u64, u64) -> bool>(
315    program: &[u8],
316    ctx: &CoordContext<V>,
317) -> Result<CoordOutcome, CoordVmError> {
318    let mut stack = [0u64; COORD_STACK_DEPTH];
319    let mut sp = 0usize;
320    let mut ip = 0usize;
321    let mut outcome = CoordOutcome::default();
322
323    while ip < program.len() {
324        match program[ip] {
325            OP_PUSH_U64 => {
326                if ip + 9 > program.len() {
327                    return Err(CoordVmError::InvalidProgram);
328                }
329                if sp >= COORD_STACK_DEPTH {
330                    return Err(CoordVmError::StackOverflow);
331                }
332                let bytes: [u8; 8] = program[ip + 1..ip + 9]
333                    .try_into()
334                    .map_err(|_| CoordVmError::InvalidProgram)?;
335                stack[sp] = u64::from_le_bytes(bytes);
336                sp += 1;
337                ip += 9;
338            }
339            OP_AUTHORIZATION_GRANT => {
340                if sp < 3 {
341                    return Err(CoordVmError::StackUnderflow);
342                }
343                // [Agent, Root, Timestamp] — Timestamp on top.
344                let timestamp = stack[sp - 1];
345                let root = stack[sp - 2];
346                let agent = stack[sp - 3];
347                sp -= 3;
348                let granted = eval_authorization_grant(
349                    agent,
350                    root,
351                    timestamp,
352                    ctx.current_epoch,
353                    &ctx.verify_root_delegation,
354                )
355                .map_err(CoordVmError::Fault)?;
356                stack[sp] = u64::from(granted);
357                sp += 1;
358                outcome.granted = Some(granted);
359                ip += 1;
360            }
361            OP_RESOURCE_DECLARATION => {
362                if sp < 3 {
363                    return Err(CoordVmError::StackUnderflow);
364                }
365                // [Task, Ceiling, MaxCycles] — MaxCycles on top.
366                let max_cycles = stack[sp - 1];
367                let ceiling = stack[sp - 2];
368                let task = stack[sp - 3];
369                sp -= 3;
370                let contract =
371                    eval_resource_declaration(task, ceiling, max_cycles, ctx.global_token_limit)
372                        .map_err(CoordVmError::Fault)?;
373                outcome.contract = Some(contract);
374                ip += 1;
375            }
376            OP_PERFORMANCE_RATING => {
377                require_privileged(ctx.is_sentinel_daemon).map_err(CoordVmError::Fault)?;
378                if sp < 4 {
379                    return Err(CoordVmError::StackUnderflow);
380                }
381                // [Agent, Declared, Actual, Validation] — Validation on top.
382                let validation = stack[sp - 1] != 0;
383                let actual = stack[sp - 2];
384                let declared = stack[sp - 3];
385                let agent = stack[sp - 4];
386                sp -= 4;
387                let rec = eval_performance_rating(agent, declared, actual, validation);
388                if sp >= COORD_STACK_DEPTH {
389                    return Err(CoordVmError::StackOverflow);
390                }
391                stack[sp] = perf_vc_hash(&rec);
392                sp += 1;
393                outcome.performance = Some(rec);
394                ip += 1;
395            }
396            _ => return Err(CoordVmError::InvalidProgram),
397        }
398    }
399
400    outcome.stack_top = (sp > 0).then(|| stack[sp - 1]);
401    Ok(outcome)
402}
403
404/// Execute a coordination-ISA program against full host seams (R8).
405pub fn execute_coordination_with_seams(
406    program: &[u8],
407    ctx: &CoordSeamContext,
408) -> Result<CoordOutcome, CoordVmError> {
409    let mut stack = [0u64; COORD_STACK_DEPTH];
410    let mut sp = 0usize;
411    let mut ip = 0usize;
412    let mut outcome = CoordOutcome::default();
413
414    while ip < program.len() {
415        match program[ip] {
416            OP_PUSH_U64 => {
417                if ip + 9 > program.len() {
418                    return Err(CoordVmError::InvalidProgram);
419                }
420                if sp >= COORD_STACK_DEPTH {
421                    return Err(CoordVmError::StackOverflow);
422                }
423                let bytes: [u8; 8] = program[ip + 1..ip + 9]
424                    .try_into()
425                    .map_err(|_| CoordVmError::InvalidProgram)?;
426                stack[sp] = u64::from_le_bytes(bytes);
427                sp += 1;
428                ip += 9;
429            }
430            OP_AUTHORIZATION_GRANT => {
431                if sp < 3 {
432                    return Err(CoordVmError::StackUnderflow);
433                }
434                let timestamp = stack[sp - 1];
435                let root = stack[sp - 2];
436                let agent = stack[sp - 3];
437                sp -= 3;
438                let granted =
439                    eval_authorization_grant(agent, root, timestamp, ctx.current_epoch, |a, r| {
440                        (ctx.seams.verify_root_delegation)(a, r)
441                    })
442                    .map_err(CoordVmError::Fault)?;
443                stack[sp] = u64::from(granted);
444                sp += 1;
445                outcome.granted = Some(granted);
446                ip += 1;
447            }
448            OP_RESOURCE_DECLARATION => {
449                if sp < 3 {
450                    return Err(CoordVmError::StackUnderflow);
451                }
452                let max_cycles = stack[sp - 1];
453                let ceiling = stack[sp - 2];
454                let task = stack[sp - 3];
455                sp -= 3;
456                match eval_resource_declaration(task, ceiling, max_cycles, ctx.global_token_limit) {
457                    Ok(contract) => {
458                        outcome.contract = Some(contract);
459                    }
460                    Err(
461                        fault @ CoordFault::InsufficientGlobalResources {
462                            declared,
463                            global_limit,
464                        },
465                    ) => {
466                        (ctx.seams.yield_to_suspended_queue)(declared, global_limit);
467                        return Err(CoordVmError::Fault(fault));
468                    }
469                    Err(fault) => return Err(CoordVmError::Fault(fault)),
470                }
471                ip += 1;
472            }
473            OP_PERFORMANCE_RATING => {
474                require_privileged(ctx.is_sentinel_daemon).map_err(CoordVmError::Fault)?;
475                if sp < 4 {
476                    return Err(CoordVmError::StackUnderflow);
477                }
478                let validation = stack[sp - 1] != 0;
479                let actual = stack[sp - 2];
480                let declared = stack[sp - 3];
481                let agent = stack[sp - 4];
482                sp -= 4;
483                let rec = eval_performance_rating(agent, declared, actual, validation);
484                let vc_hash = (ctx.seams.mint_performance_vc)(agent, declared, actual, validation);
485                let hash = if vc_hash != 0 {
486                    vc_hash
487                } else {
488                    perf_vc_hash(&rec)
489                };
490                if sp >= COORD_STACK_DEPTH {
491                    return Err(CoordVmError::StackOverflow);
492                }
493                stack[sp] = hash;
494                sp += 1;
495                outcome.performance = Some(rec);
496                ip += 1;
497            }
498            _ => return Err(CoordVmError::InvalidProgram),
499        }
500    }
501
502    outcome.stack_top = (sp > 0).then(|| stack[sp - 1]);
503    Ok(outcome)
504}
505
506#[cfg(test)]
507mod tests {
508    use super::*;
509
510    /// Append `OP_PUSH_U64 <v LE>` to a program.
511    fn push(p: &mut Vec<u8>, v: u64) {
512        p.push(OP_PUSH_U64);
513        p.extend_from_slice(&v.to_le_bytes());
514    }
515
516    #[test]
517    fn grant_gate_checks_expiry_then_signature() {
518        // Valid + in-window → granted.
519        assert_eq!(
520            eval_authorization_grant(0xA, 0xB0, 100, 50, |_, _| true),
521            Ok(true)
522        );
523        // Expired (now > valid_until) before signature is even checked.
524        assert_eq!(
525            eval_authorization_grant(0xA, 0xB0, 100, 101, |_, _| panic!(
526                "must not verify when expired"
527            )),
528            Err(CoordFault::GrantExpired {
529                now: 101,
530                valid_until: 100
531            })
532        );
533        // In-window but bad signature → unauthorized.
534        assert_eq!(
535            eval_authorization_grant(0xA, 0xB0, 100, 50, |_, _| false),
536            Err(CoordFault::UnauthorizedActor { agent: 0xA })
537        );
538    }
539
540    #[test]
541    fn resource_declaration_and_circuit_breakers() {
542        // Over the global allowance → yield to the suspended queue.
543        assert_eq!(
544            eval_resource_declaration(7, 5000, 1000, 4000),
545            Err(CoordFault::InsufficientGlobalResources {
546                declared: 5000,
547                global_limit: 4000
548            })
549        );
550        let mut c = eval_resource_declaration(7, 1000, 10, 4000).unwrap();
551        // Cycle breaker decrements and trips on underflow.
552        assert!(c.tick_cycles(6));
553        assert_eq!(c.cycles_remaining, 4);
554        assert!(!c.tick_cycles(5), "underflow trips the breaker");
555        assert_eq!(c.cycles_remaining, 0);
556        // Token burn is fine up to the 110% usury ceiling (1100), usurious past it.
557        assert!(c.burn_tokens(1000).is_ok());
558        assert!(c.burn_tokens(100).is_ok()); // exactly at ceiling
559        assert!(c.burn_tokens(1).is_err(), "1101 > 1100 ceiling ⇒ usury");
560    }
561
562    #[test]
563    fn performance_rating_computes_fidelity_efficiency_usury() {
564        // Validated, under budget → fidelity 1, positive efficiency, not usurious.
565        let good = eval_performance_rating(0xA, 1000, 800, true);
566        assert_eq!(good.fidelity, 1);
567        assert_eq!(good.efficiency_bp, 2000); // (1000-800)/1000 = +20% = 2000 bp
568        assert!(!good.usurious);
569        // Hallucination → fidelity 0.
570        assert_eq!(eval_performance_rating(0xA, 1000, 900, false).fidelity, 0);
571        // Over-burn → negative efficiency + usurious.
572        let bad = eval_performance_rating(0xA, 1000, 1300, true);
573        assert_eq!(bad.efficiency_bp, -3000); // (1000-1300)/1000 = -30%
574        assert!(bad.usurious);
575    }
576
577    #[test]
578    fn privilege_gate_blocks_synthetic_agents() {
579        assert_eq!(require_privileged(true), Ok(()));
580        assert_eq!(
581            require_privileged(false),
582            Err(CoordFault::PrivilegeViolation)
583        );
584    }
585
586    #[test]
587    fn darwinian_priority_forgives_mistakes_quarantines_extraction() {
588        // No faults → full priority.
589        assert_eq!(compute_priority(0, false), PRIORITY_BASE);
590        // Honest single miss → halved, not killed (recoverable).
591        assert_eq!(compute_priority(1, false), 5000);
592        assert_eq!(compute_priority(2, false), 2500);
593        // Sustained failure decays toward — but never below — the redemption floor.
594        assert_eq!(compute_priority(20, false), PRIORITY_FLOOR);
595        // Usury is the bright line: immediate hard quarantine regardless of fault count.
596        assert_eq!(compute_priority(0, true), 0);
597        assert_eq!(compute_priority(1, true), 0);
598    }
599
600    #[test]
601    fn coordination_vm_executes_grant_program() {
602        // PUSH agent, PUSH root, PUSH timestamp(100), GRANT — epoch 50, valid signature.
603        let mut prog = Vec::new();
604        push(&mut prog, 0xA);
605        push(&mut prog, 0xB0);
606        push(&mut prog, 100);
607        prog.push(OP_AUTHORIZATION_GRANT);
608        let ctx = CoordContext {
609            current_epoch: 50,
610            global_token_limit: 10_000,
611            is_sentinel_daemon: false,
612            verify_root_delegation: |_a, _r| true,
613        };
614        let out = execute_coordination(&prog, &ctx).unwrap();
615        assert_eq!(out.granted, Some(true));
616        assert_eq!(out.stack_top, Some(1)); // pushed 1 (True)
617
618        // Expired epoch → GrantExpired fault, signature never consulted.
619        let ctx_exp = CoordContext {
620            current_epoch: 101,
621            global_token_limit: 10_000,
622            is_sentinel_daemon: false,
623            verify_root_delegation: |_a, _r| panic!("must not verify when expired"),
624        };
625        assert_eq!(
626            execute_coordination(&prog, &ctx_exp),
627            Err(CoordVmError::Fault(CoordFault::GrantExpired {
628                now: 101,
629                valid_until: 100
630            }))
631        );
632
633        // Bad signature → UnauthorizedActor.
634        let ctx_bad = CoordContext {
635            current_epoch: 50,
636            global_token_limit: 10_000,
637            is_sentinel_daemon: false,
638            verify_root_delegation: |_a, _r| false,
639        };
640        assert_eq!(
641            execute_coordination(&prog, &ctx_bad),
642            Err(CoordVmError::Fault(CoordFault::UnauthorizedActor {
643                agent: 0xA
644            }))
645        );
646    }
647
648    #[test]
649    fn coordination_vm_executes_resource_and_performance_programs() {
650        let ctx = CoordContext {
651            current_epoch: 0,
652            global_token_limit: 4000,
653            is_sentinel_daemon: true,
654            verify_root_delegation: |_a, _r| true,
655        };
656        // RESOURCE_DECLARATION: PUSH task, ceiling(1000), max_cycles(50), DECLARE.
657        let mut prog = Vec::new();
658        push(&mut prog, 7);
659        push(&mut prog, 1000);
660        push(&mut prog, 50);
661        prog.push(OP_RESOURCE_DECLARATION);
662        let c = execute_coordination(&prog, &ctx).unwrap().contract.unwrap();
663        assert_eq!(c.token_ceiling, 1000);
664        assert_eq!(c.cycles_remaining, 50);
665
666        // Over the global allowance → InsufficientGlobalResources (→ suspended queue).
667        let mut prog2 = Vec::new();
668        push(&mut prog2, 7);
669        push(&mut prog2, 5000);
670        push(&mut prog2, 50);
671        prog2.push(OP_RESOURCE_DECLARATION);
672        assert_eq!(
673            execute_coordination(&prog2, &ctx),
674            Err(CoordVmError::Fault(
675                CoordFault::InsufficientGlobalResources {
676                    declared: 5000,
677                    global_limit: 4000
678                }
679            ))
680        );
681
682        // PERFORMANCE_RATING (privileged): PUSH agent, declared(1000), actual(800), valid(1), RATE.
683        let mut prog3 = Vec::new();
684        push(&mut prog3, 0xA);
685        push(&mut prog3, 1000);
686        push(&mut prog3, 800);
687        push(&mut prog3, 1);
688        prog3.push(OP_PERFORMANCE_RATING);
689        let out3 = execute_coordination(&prog3, &ctx).unwrap();
690        let rec = out3.performance.unwrap();
691        assert_eq!(rec.fidelity, 1);
692        assert_eq!(rec.efficiency_bp, 2000);
693        assert_eq!(out3.stack_top, Some(perf_vc_hash(&rec))); // minted-VC hash pushed
694
695        // A non-privileged caller cannot mint → PrivilegeViolation.
696        let ctx_np = CoordContext {
697            current_epoch: 0,
698            global_token_limit: 4000,
699            is_sentinel_daemon: false,
700            verify_root_delegation: |_a, _r| true,
701        };
702        assert_eq!(
703            execute_coordination(&prog3, &ctx_np),
704            Err(CoordVmError::Fault(CoordFault::PrivilegeViolation))
705        );
706    }
707
708    #[test]
709    fn coordination_vm_guards_stack_bounds() {
710        let ctx = CoordContext {
711            current_epoch: 0,
712            global_token_limit: 4000,
713            is_sentinel_daemon: true,
714            verify_root_delegation: |_a, _r| true,
715        };
716        // GRANT with too few operands → underflow (frame dumped, not silent).
717        let mut prog = Vec::new();
718        push(&mut prog, 1);
719        prog.push(OP_AUTHORIZATION_GRANT);
720        assert_eq!(
721            execute_coordination(&prog, &ctx),
722            Err(CoordVmError::StackUnderflow)
723        );
724        // Truncated PUSH operand → invalid program.
725        assert_eq!(
726            execute_coordination(&[OP_PUSH_U64, 1, 2, 3], &ctx),
727            Err(CoordVmError::InvalidProgram)
728        );
729    }
730
731    #[test]
732    fn default_seams_fail_closed() {
733        let seams = default_seams();
734        // verify_root_delegation is fail-closed by default
735        assert!(!(seams.verify_root_delegation)(0x1234, 0x5678));
736        // mint_performance_vc is 0 by default (unwired)
737        assert_eq!((seams.mint_performance_vc)(0x1, 1000, 800, true), 0);
738    }
739
740    #[test]
741    fn execute_coordination_grant_with_seams() {
742        let mut seams = default_seams();
743        seams.verify_root_delegation = Box::new(|agent, root| agent == 0xA && root == 0xB);
744
745        let ctx = CoordSeamContext {
746            current_epoch: 10,
747            global_token_limit: 5000,
748            is_sentinel_daemon: true,
749            seams: &seams,
750        };
751
752        let mut prog = Vec::new();
753        push(&mut prog, 0xA);
754        push(&mut prog, 0xB);
755        push(&mut prog, 100);
756        prog.push(OP_AUTHORIZATION_GRANT);
757
758        let outcome = execute_coordination_with_seams(&prog, &ctx).unwrap();
759        assert_eq!(outcome.granted, Some(true));
760        assert_eq!(outcome.stack_top, Some(1));
761    }
762
763    #[test]
764    fn execute_coordination_resource_declaration() {
765        use std::sync::atomic::{AtomicU64, Ordering};
766        use std::sync::Arc;
767        let yielded = Arc::new(AtomicU64::new(0));
768        let yielded_clone = yielded.clone();
769
770        let mut seams = default_seams();
771        seams.yield_to_suspended_queue = Box::new(move |declared, _| {
772            yielded_clone.store(declared, Ordering::SeqCst);
773        });
774
775        let ctx = CoordSeamContext {
776            current_epoch: 0,
777            global_token_limit: 2000,
778            is_sentinel_daemon: true,
779            seams: &seams,
780        };
781
782        // Within limits -> success
783        let mut prog_ok = Vec::new();
784        push(&mut prog_ok, 42);
785        push(&mut prog_ok, 1000);
786        push(&mut prog_ok, 20);
787        prog_ok.push(OP_RESOURCE_DECLARATION);
788
789        let out = execute_coordination_with_seams(&prog_ok, &ctx).unwrap();
790        assert_eq!(out.contract.unwrap().token_ceiling, 1000);
791
792        // Exceeds limit -> yields to suspended queue and returns fault
793        let mut prog_err = Vec::new();
794        push(&mut prog_err, 42);
795        push(&mut prog_err, 3000);
796        push(&mut prog_err, 20);
797        prog_err.push(OP_RESOURCE_DECLARATION);
798
799        let err = execute_coordination_with_seams(&prog_err, &ctx);
800        assert!(matches!(
801            err,
802            Err(CoordVmError::Fault(
803                CoordFault::InsufficientGlobalResources { .. }
804            ))
805        ));
806        assert_eq!(yielded.load(Ordering::SeqCst), 3000);
807    }
808
809    #[test]
810    fn execute_coordination_performance_rating() {
811        let mut seams = default_seams();
812        seams.mint_performance_vc = Box::new(|agent, declared, actual, valid| {
813            if valid && declared >= actual {
814                agent ^ 0xFEED_FACE
815            } else {
816                0
817            }
818        });
819
820        let ctx = CoordSeamContext {
821            current_epoch: 0,
822            global_token_limit: 5000,
823            is_sentinel_daemon: true,
824            seams: &seams,
825        };
826
827        let mut prog = Vec::new();
828        push(&mut prog, 0x1234);
829        push(&mut prog, 1000);
830        push(&mut prog, 500);
831        push(&mut prog, 1);
832        prog.push(OP_PERFORMANCE_RATING);
833
834        let out = execute_coordination_with_seams(&prog, &ctx).unwrap();
835        let rec = out.performance.unwrap();
836        assert_eq!(rec.fidelity, 1);
837        assert_eq!(out.stack_top, Some(0x1234 ^ 0xFEED_FACE));
838    }
839}