"""Deterministic registered rules and seed derivation for world engines.""" import hashlib import inspect import math from collections.abc import Callable from datetime import UTC, datetime from world_compiler.domain.events import ( EventEnvelope, EventType, Provenance, ResolvedPrincipal, RuleAppliedPayload, WorldStateChangedPayload, ) from world_compiler.domain.schemas.rules import DecisionRule from world_compiler.infrastructure.database.store import EventStore from world_compiler.runtime.orchestrator.context import SessionScope from world_compiler.runtime.rules.symbols import REGISTRY_VERSION __all__ = [ "REGISTRY_VERSION", "RULE_REGISTRY", "apply_rule", "derive_seed", "registry_hashes", "rule_hash", ] def defect_rate_update(current: float, adjustment: float) -> float: """Return the deterministic next defect rate for the registered v1 rule.""" return round(current + adjustment, 6) RULE_REGISTRY: dict[str, Callable] = {"defect_rate_update": defect_rate_update} def rule_hash(name: str) -> str: """Return the source hash for one registered deterministic rule.""" try: fn = RULE_REGISTRY[name] except KeyError as exc: raise KeyError(f"unknown registered rule {name!r}") from exc return hashlib.sha256(inspect.getsource(fn).encode("utf-8")).hexdigest() def registry_hashes() -> dict[str, str]: """Return the source hashes for the complete registered-rule catalog.""" return {name: rule_hash(name) for name in RULE_REGISTRY} def derive_seed(session_seed: int, stream: str, turn: int | str) -> int: """Derive a stable SQLite-safe seed from a stream discriminator.""" material = f"{session_seed}:{stream}:{turn}".encode() return int.from_bytes(hashlib.sha256(material).digest()[:8], "big") & ( (1 << 63) - 1 ) def apply_rule( rule: DecisionRule, world: dict, store: EventStore, scope: SessionScope, turn: int, ) -> dict: """Apply one registered pure rule and append its auditable state delta.""" if len(rule.writes_variables) != 1: raise ValueError("v1 deterministic rules must write exactly one variable") try: fn = RULE_REGISTRY[rule.registered_fn] except KeyError as exc: raise KeyError(f"unknown registered rule {rule.registered_fn!r}") from exc variable_id = rule.writes_variables[0] try: current = world[variable_id] except KeyError as exc: raise KeyError(f"world is missing rule variable {variable_id!r}") from exc world_inputs = {"current": current} collisions = world_inputs.keys() & rule.params.keys() if collisions: names = ", ".join(sorted(collisions)) raise ValueError(f"rule params collide with world-derived inputs: {names}") inputs = {**rule.params, **world_inputs} _require_finite_numbers(inputs, "rule inputs") output = fn(**inputs) _require_finite_numbers({variable_id: output}, "rule outputs") new_world = dict(world) new_world[variable_id] = output outputs = {variable_id: output} changes = {variable_id: {"from": current, "to": output}} state_visibility = _variable_visibility(scope, variable_id) existing = { event.event_id: event for event in store.read_all( scope.tenant_id, scope.course_id, scope.session_id, scope.scenario_id, scope.scenario_version, ) } scope_prefix = f"{scope.tenant_id}:{scope.course_id}:{scope.session_id}" rule_event_id = f"rule:{scope_prefix}:{rule.rule_id}:{turn}" state_event_id = f"world:{scope_prefix}:{rule.rule_id}:{turn}" rule_event = _event( event_id=rule_event_id, scope=scope, turn=turn, event_type=EventType.RULE_APPLIED, payload=RuleAppliedPayload( rule_id=rule.rule_id, rule_hash=rule_hash(rule.registered_fn), inputs=inputs, outputs=outputs, ).model_dump(mode="json"), visibility=[_instructor(scope)], created_at=_existing_or_now(existing, rule_event_id), ) store.append("rules_engine", rule_event, idempotency_key=rule_event_id) state_event = _event( event_id=state_event_id, scope=scope, turn=turn, event_type=EventType.WORLD_STATE_CHANGED, payload=WorldStateChangedPayload(changes=changes).model_dump(mode="json"), visibility=state_visibility, parent_event_ids=[rule_event.event_id], created_at=_existing_or_now(existing, state_event_id), ) store.append("rules_engine", state_event, idempotency_key=state_event_id) return new_world def _event( *, event_id: str, scope: SessionScope, turn: int, event_type: EventType, payload: dict, visibility: list[ResolvedPrincipal], parent_event_ids: list[str] | None = None, created_at: datetime, ) -> EventEnvelope: parent_event_ids = parent_event_ids or [] return EventEnvelope( event_id=event_id, tenant_id=scope.tenant_id, course_id=scope.course_id, session_id=scope.session_id, scenario_id=scope.scenario_id, scenario_version=scope.scenario_version, turn=turn, actor_id=None, event_type=event_type, payload=payload, visibility=visibility, provenance=Provenance(source_event_ids=list(parent_event_ids)), rng_seed=None, parent_event_ids=list(parent_event_ids), retention_class=scope.retention_class, created_at=created_at, ) def _variable_visibility( scope: SessionScope, variable_id: str ) -> list[ResolvedPrincipal]: templates = scope.world_variable_visibility.get(variable_id) if not templates: raise ValueError(f"world variable {variable_id!r} has no governance visibility") return [ template.resolve( scope.tenant_id, scope.course_id, scope.session_id, dict(scope.role_to_actor), ) for template in templates ] def _require_finite_numbers(values: dict, label: str) -> None: nonfinite = [ name for name, value in values.items() if isinstance(value, (int, float)) and not isinstance(value, bool) and not math.isfinite(value) ] if nonfinite: names = ", ".join(sorted(nonfinite)) raise ValueError(f"{label} must be finite: {names}") def _existing_or_now(existing: dict[str, EventEnvelope], event_id: str) -> datetime: prior = existing.get(event_id) return prior.created_at if prior is not None else datetime.now(UTC) def _instructor(scope: SessionScope) -> ResolvedPrincipal: return ResolvedPrincipal( kind="instructor", tenant_id=scope.tenant_id, course_id=scope.course_id, session_id=scope.session_id, )