import time
from typing import Dict, Any, Optional, Tuple
try:
from ._core import AKIEngine
except ImportError:
AKIEngine = None
from .pq_fortification import PQFortification, PQCRYPTO_AVAILABLE
from .self_learning import CoherenceWeightUpdater
from .sovereign_witness import CommonwealthEternalWitness
class AgDRMantle:
def __init__(
self,
fo_i: str = "Accountability",
enable_pq: bool = False,
enable_self_learning: bool = False,
enable_sovereign: bool = False,
nemoclaw_mode: bool = True,
pq_keypair: Optional[Tuple[bytes, bytes]] = None,
):
self.fo_i = fo_i
self.enable_pq = enable_pq
self.enable_self_learning = enable_self_learning
self.enable_sovereign = enable_sovereign
if AKIEngine is None:
raise ImportError(
"AgDR-Phoenix Rust extension (_core) is not built. "
"Run: maturin develop --release"
)
self.phoenix = AKIEngine(fo_i=fo_i)
if self.enable_pq:
if not PQCRYPTO_AVAILABLE:
raise ImportError(
"Post-quantum fortification requested but pqcrypto is not installed. "
"Install with: pip install agdr-mantle[post-quantum]"
)
self.pq = PQFortification(keypair=pq_keypair)
else:
self.pq = None
self.learning = CoherenceWeightUpdater() if self.enable_self_learning else None
self.witness = (
CommonwealthEternalWitness(nemoclaw_mode=nemoclaw_mode)
if self.enable_sovereign
else None
)
def seal(self, ppp: Dict[str, Any]) -> Dict[str, Any]:
t_total_start = time.perf_counter_ns()
t_aki = time.perf_counter_ns()
aki_seal = self.phoenix.seal_ppp(ppp)
aki_latency_ns = time.perf_counter_ns() - t_aki
fortification_latency_ns = 0
if self.pq:
t_pq = time.perf_counter_ns()
aki_seal = self.pq.wrap(aki_seal)
fortification_latency_ns = time.perf_counter_ns() - t_pq
if self.learning:
coherence = self._compute_coherence(aki_seal)
if coherence > 0.92:
self.learning.update_weights(aki_seal, coherence)
sovereign_record = None
if self.witness:
sovereign_record = self.witness.capture_medical(
agent_id=ppp.get("provenance", "unknown"),
patient_pseudo=ppp.get("place", "unknown"),
reasoning_trace=ppp.get("purpose", ""),
)
total_latency_ns = time.perf_counter_ns() - t_total_start
return {
"aki_seal": aki_seal.hex() if isinstance(aki_seal, (bytes, bytearray)) else str(aki_seal),
"pq_applied": self.enable_pq,
"pq_algorithm": "ML-DSA-65" if self.enable_pq else None,
"self_learning_applied": self.enable_self_learning,
"sovereign_witness": sovereign_record,
"aki_latency_us": aki_latency_ns / 1000,
"fortification_latency_us": fortification_latency_ns / 1000,
"total_latency_us": total_latency_ns / 1000,
"tier_breakdown": {
"core_aki": "captured",
"implementation_phoenix": "sealed",
"fortification_mantle": "applied" if (self.enable_pq or self.enable_sovereign) else "not_applied",
},
}
def _compute_coherence(self, sealed: bytes) -> float:
return 0.95