1use crate::modalities::socioeconomics::{check_usury, UsuryError, USURY_OVERAGE_PERCENT_DEFAULT};
21
22pub const OP_AUTHORIZATION_GRANT: u8 = 0x70;
24pub const OP_RESOURCE_DECLARATION: u8 = 0x71;
26pub const OP_PERFORMANCE_RATING: u8 = 0x72;
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum CoordFault {
32 GrantExpired { now: u64, valid_until: u64 },
34 UnauthorizedActor { agent: u64 },
36 InsufficientGlobalResources { declared: u64, global_limit: u64 },
39 PrivilegeViolation,
41}
42
43pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct ResourceContract {
77 pub task_id_hash: u64,
78 pub token_ceiling: u64,
80 pub cycles_remaining: u64,
82 pub tokens_burned: u64,
84}
85
86impl ResourceContract {
87 #[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 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
115pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub struct PerformanceRecord {
144 pub agent_did_hash: u64,
145 pub fidelity: u8,
147 pub efficiency_bp: i64,
150 pub usurious: bool,
153}
154
155pub 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
186pub 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
195pub const PRIORITY_BASE: u64 = 10_000;
203pub const PRIORITY_FLOOR: u64 = 100;
206
207pub 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
220pub const COORD_STACK_DEPTH: usize = 16;
229pub const OP_PUSH_U64: u8 = 0x7F;
231
232pub struct CoordContext<V: Fn(u64, u64) -> bool> {
234 pub current_epoch: u64,
236 pub global_token_limit: u64,
238 pub is_sentinel_daemon: bool,
240 pub verify_root_delegation: V,
242}
243
244pub struct CoordHostSeams {
246 pub verify_root_delegation: Box<dyn Fn(u64, u64) -> bool + Send + Sync>,
249 pub yield_to_suspended_queue: Box<dyn Fn(u64, u64) + Send + Sync>,
252 pub mint_performance_vc: Box<dyn Fn(u64, u64, u64, bool) -> u64 + Send + Sync>,
255}
256
257pub 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
272pub 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#[derive(Debug, Clone, PartialEq, Eq, Default)]
282pub struct CoordOutcome {
283 pub granted: Option<bool>,
285 pub contract: Option<ResourceContract>,
287 pub performance: Option<PerformanceRecord>,
289 pub stack_top: Option<u64>,
291}
292
293#[derive(Debug, Clone, PartialEq, Eq)]
295pub enum CoordVmError {
296 StackUnderflow,
297 StackOverflow,
298 InvalidProgram,
300 Fault(CoordFault),
302}
303
304pub 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
313pub 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 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 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 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
404pub 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 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 assert_eq!(
520 eval_authorization_grant(0xA, 0xB0, 100, 50, |_, _| true),
521 Ok(true)
522 );
523 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 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 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 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 assert!(c.burn_tokens(1000).is_ok());
558 assert!(c.burn_tokens(100).is_ok()); assert!(c.burn_tokens(1).is_err(), "1101 > 1100 ceiling ⇒ usury");
560 }
561
562 #[test]
563 fn performance_rating_computes_fidelity_efficiency_usury() {
564 let good = eval_performance_rating(0xA, 1000, 800, true);
566 assert_eq!(good.fidelity, 1);
567 assert_eq!(good.efficiency_bp, 2000); assert!(!good.usurious);
569 assert_eq!(eval_performance_rating(0xA, 1000, 900, false).fidelity, 0);
571 let bad = eval_performance_rating(0xA, 1000, 1300, true);
573 assert_eq!(bad.efficiency_bp, -3000); 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 assert_eq!(compute_priority(0, false), PRIORITY_BASE);
590 assert_eq!(compute_priority(1, false), 5000);
592 assert_eq!(compute_priority(2, false), 2500);
593 assert_eq!(compute_priority(20, false), PRIORITY_FLOOR);
595 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 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)); 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 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 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 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 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))); 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 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 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 assert!(!(seams.verify_root_delegation)(0x1234, 0x5678));
736 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 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 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}