"""Append-only governance events and a pure, replayable run-state projection.""" from __future__ import annotations import json import os import threading from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path from uuid import uuid4 from afk_developer.fsutil import atomic_write_text EVENT_SCHEMA_VERSION = 1 SNAPSHOT_SCHEMA_VERSION = 1 EVENT_KINDS = frozenset( { "counter_incremented", "environment_rejected", "environment_repair_approved", "environment_resolved", "environment_contract_rebased", "effect_completed", "effect_intended", "product_validation_attested", "vision_observed", "run_event_recorded", "supervisor_decision_recorded", "task_status_changed", } ) class EventLogError(ValueError): """Raised when an authoritative event stream is malformed or inconsistent.""" class EventValidationError(ValueError): """Raised before an event can enter the authoritative event stream.""" @dataclass(frozen=True) class DurableEvent: schema_version: int sequence: int id: str occurred_at: str kind: str payload: dict[str, object] def to_record(self) -> dict[str, object]: return { "schema_version": self.schema_version, "sequence": self.sequence, "id": self.id, "occurred_at": self.occurred_at, "kind": self.kind, "payload": self.payload, } @classmethod def from_record(cls, record: object) -> "DurableEvent": if not isinstance(record, dict): raise EventLogError("Event record must be a JSON object.") required = {"schema_version", "sequence", "id", "occurred_at", "kind", "payload"} if set(record) != required: raise EventLogError("Event record has an unsupported schema.") event = cls( schema_version=record["schema_version"], sequence=record["sequence"], id=record["id"], occurred_at=record["occurred_at"], kind=record["kind"], payload=record["payload"], ) _validate_event(event) return event @dataclass class RunProjection: last_sequence: int = 0 last_event_id: str = "" applied_event_ids: set[str] = field(default_factory=set) task_statuses: dict[str, str] = field(default_factory=dict) counters: dict[str, int] = field(default_factory=dict) decisions: dict[str, str] = field(default_factory=dict) pending_effects: dict[str, str] = field(default_factory=dict) environment_fingerprint: str = "" environment_contract: dict[str, object] = field(default_factory=dict) environment_rejection: dict[str, str] = field(default_factory=dict) environment_repair_fingerprint: str = "" environment_repair_reason: str = "" latest_run_events: dict[str, dict[str, object]] = field(default_factory=dict) attempt_summaries: dict[str, list[dict[str, object]]] = field(default_factory=dict) product_validations: dict[str, dict[str, object]] = field(default_factory=dict) vision_observations: dict[str, list[dict[str, object]]] = field(default_factory=dict) def apply(self, event: DurableEvent) -> None: if event.id in self.applied_event_ids: return if event.sequence <= self.last_sequence: raise EventLogError(f"Event sequence {event.sequence} is behind the projection cursor.") if event.sequence != self.last_sequence + 1: raise EventLogError(f"Event sequence gap before {event.sequence}.") if event.kind == "task_status_changed": self.task_statuses[str(event.payload["task_id"])] = str(event.payload["status"]) elif event.kind == "counter_incremented": counter = str(event.payload["counter"]) self.counters[counter] = self.counters.get(counter, 0) + int(event.payload["amount"]) elif event.kind == "supervisor_decision_recorded": self.decisions[str(event.payload["decision_id"])] = str(event.payload["action"]) self._increment_counter("supervisor_decisions") elif event.kind == "effect_intended": self.pending_effects[str(event.payload["effect_id"])] = str(event.payload["operation"]) elif event.kind == "effect_completed": self.pending_effects.pop(str(event.payload["effect_id"]), None) elif event.kind in {"environment_resolved", "environment_contract_rebased"}: self.environment_fingerprint = str(event.payload["fingerprint"]) self.environment_contract = dict(event.payload["contract"]) self.environment_rejection = {} elif event.kind == "environment_rejected": self.environment_rejection = { "code": str(event.payload["code"]), "detail": str(event.payload["detail"]), } elif event.kind == "environment_repair_approved": self.environment_repair_fingerprint = str(event.payload["fingerprint"]) self.environment_repair_reason = str(event.payload["reason"]) elif event.kind == "product_validation_attested": self.product_validations[str(event.payload["task_id"])] = { "kind": event.payload["validation_kind"], "observation": event.payload["observation"], "artifact_sha256": event.payload.get("artifact_sha256", {}), } elif event.kind == "vision_observed": self.vision_observations[str(event.payload["task_id"])] = list( event.payload["observations"] ) elif event.kind == "run_event_recorded": task_id = str(event.payload.get("task_id", "")) if task_id: rendered = { "kind": event.payload["run_kind"], "text": event.payload["text"], "data": event.payload.get("data", {}), "sequence": event.sequence, } self.latest_run_events[task_id] = rendered status = { "task_passed": "passed", "task_failed": "failed", "task_escalated": "escalated", "task_decomposed": "decomposed", }.get(str(event.payload["run_kind"])) if status: self.task_statuses[task_id] = status if event.payload["run_kind"] == "attempt_summary": summaries = self.attempt_summaries.setdefault(task_id, []) summaries.append(rendered) role = str((event.payload.get("data") or {}).get("role", "")) if role in {"coder", "coder_light", "researcher"}: self._increment_counter("worker_attempts") effort = str((event.payload.get("data") or {}).get("reasoning_effort", "")) if effort in {"high", "xhigh"}: self._increment_counter("strong_model_calls") elif event.payload["run_kind"] == "task_escalated": self._increment_counter("human_escalations") elif (event.payload.get("data") or {}).get("human_validation"): self._increment_counter("human_escalations") elif (event.payload.get("data") or {}).get("mechanical_repair"): self._increment_counter("mechanical_repairs") self.applied_event_ids.add(event.id) self.last_sequence = event.sequence self.last_event_id = event.id def _increment_counter(self, name: str) -> None: self.counters[name] = self.counters.get(name, 0) + 1 def to_record(self) -> dict[str, object]: return { "schema_version": SNAPSHOT_SCHEMA_VERSION, "last_sequence": self.last_sequence, "last_event_id": self.last_event_id, "applied_event_ids": sorted(self.applied_event_ids), "task_statuses": self.task_statuses, "counters": self.counters, "decisions": self.decisions, "pending_effects": self.pending_effects, "environment_fingerprint": self.environment_fingerprint, "environment_contract": self.environment_contract, "environment_rejection": self.environment_rejection, "environment_repair_fingerprint": self.environment_repair_fingerprint, "environment_repair_reason": self.environment_repair_reason, "latest_run_events": self.latest_run_events, "attempt_summaries": self.attempt_summaries, "product_validations": self.product_validations, "vision_observations": self.vision_observations, } @classmethod def from_record(cls, record: object) -> "RunProjection": if not isinstance(record, dict) or record.get("schema_version") != SNAPSHOT_SCHEMA_VERSION: raise EventLogError("Projection snapshot has an unsupported schema.") try: projection = cls( last_sequence=record["last_sequence"], last_event_id=record["last_event_id"], applied_event_ids=set(record["applied_event_ids"]), task_statuses=dict(record["task_statuses"]), counters=dict(record["counters"]), decisions=dict(record["decisions"]), pending_effects=dict(record["pending_effects"]), environment_fingerprint=record["environment_fingerprint"], environment_contract=dict(record["environment_contract"]), environment_rejection=dict(record["environment_rejection"]), environment_repair_fingerprint=record["environment_repair_fingerprint"], environment_repair_reason=record["environment_repair_reason"], latest_run_events=dict(record["latest_run_events"]), attempt_summaries={ str(task_id): list(summaries) for task_id, summaries in dict(record["attempt_summaries"]).items() }, product_validations=dict(record["product_validations"]), vision_observations={ str(task_id): list(observations) for task_id, observations in dict(record["vision_observations"]).items() }, ) except (KeyError, TypeError, ValueError) as exc: raise EventLogError("Projection snapshot is malformed.") from exc if projection.last_sequence < 0 or not isinstance(projection.last_event_id, str): raise EventLogError("Projection snapshot has an invalid cursor.") return projection class DurableEventStore: """Owns append/fsync persistence; complete history is never rewritten.""" def __init__(self, path: Path) -> None: self.path = path self._lock = threading.Lock() def append( self, kind: str, payload: dict[str, object], *, event_id: str | None = None ) -> DurableEvent: with self._lock: self._discard_torn_tail() events = self.read_events() event = DurableEvent( schema_version=EVENT_SCHEMA_VERSION, sequence=len(events) + 1, id=event_id or uuid4().hex, occurred_at=datetime.now(timezone.utc).isoformat(), kind=kind, payload=dict(payload), ) _validate_event(event) if event.id in {item.id for item in events}: raise EventLogError(f"Duplicate event ID: {event.id}") serialized = json.dumps( event.to_record(), ensure_ascii=True, sort_keys=True, separators=(",", ":") ) self.path.parent.mkdir(parents=True, exist_ok=True) with self.path.open("a", encoding="utf-8", newline="\n") as handle: handle.write(serialized + "\n") handle.flush() os.fsync(handle.fileno()) return event def read_events(self) -> list[DurableEvent]: if not self.path.is_file(): return [] raw = self.path.read_bytes() records = raw.splitlines(keepends=True) events: list[DurableEvent] = [] for index, raw_line in enumerate(records): is_last = index == len(records) - 1 if not raw_line.endswith((b"\n", b"\r")): if is_last: break raise EventLogError("Event log contains an incomplete non-final record.") try: record = json.loads(raw_line) except (UnicodeDecodeError, json.JSONDecodeError) as exc: raise EventLogError( f"Event log contains invalid JSON at record {index + 1}." ) from exc event = DurableEvent.from_record(record) if event.sequence != len(events) + 1: raise EventLogError(f"Event log sequence is invalid at record {index + 1}.") if event.id in {item.id for item in events}: raise EventLogError(f"Duplicate event ID: {event.id}") events.append(event) return events def _discard_torn_tail(self) -> None: if not self.path.is_file(): return raw = self.path.read_bytes() if not raw or raw.endswith((b"\n", b"\r")): return last_newline = max(raw.rfind(b"\n"), raw.rfind(b"\r")) with self.path.open("r+b") as handle: handle.truncate(last_newline + 1) handle.flush() os.fsync(handle.fileno()) class EventProjector: """Builds and atomically caches an idempotent projection from a durable log.""" def rebuild(self, store: DurableEventStore, snapshot_path: Path | None = None) -> RunProjection: events = store.read_events() projection = self._load_usable_snapshot(snapshot_path, events) if snapshot_path else None projection = projection or RunProjection() for event in events[projection.last_sequence :]: projection.apply(event) return projection def save_snapshot(self, path: Path, projection: RunProjection) -> None: atomic_write_text( path, json.dumps(projection.to_record(), ensure_ascii=True, sort_keys=True) ) def _load_usable_snapshot(self, path: Path, events: list[DurableEvent]) -> RunProjection | None: if not path.is_file(): return None try: snapshot = RunProjection.from_record(json.loads(path.read_text(encoding="utf-8"))) except (OSError, json.JSONDecodeError, EventLogError): return None if snapshot.last_sequence == 0: return snapshot if not snapshot.last_event_id else None if snapshot.last_sequence > len(events): return None if events[snapshot.last_sequence - 1].id != snapshot.last_event_id: return None return snapshot def _validate_event(event: DurableEvent) -> None: if event.schema_version != EVENT_SCHEMA_VERSION: raise EventValidationError("Unsupported event schema version.") if not isinstance(event.sequence, int) or event.sequence < 1: raise EventValidationError("Event sequence must be a positive integer.") if not isinstance(event.id, str) or not event.id: raise EventValidationError("Event ID must be non-empty.") if event.kind not in EVENT_KINDS: raise EventValidationError(f"Unknown event kind: {event.kind}") if not isinstance(event.payload, dict): raise EventValidationError("Event payload must be an object.") _require_non_empty_fields(event.payload, *_required_fields(event.kind)) if event.kind == "counter_incremented": amount = event.payload["amount"] if not isinstance(amount, int) or isinstance(amount, bool) or amount < 1: raise EventValidationError("counter_incremented amount must be a positive integer.") if event.kind == "supervisor_decision_recorded" and event.payload["action"] not in { "approve_decomposition", "escalate", }: raise EventValidationError("supervisor_decision_recorded action is unsupported.") def _required_fields(kind: str) -> tuple[str, ...]: return { "counter_incremented": ("counter", "amount"), "environment_rejected": ("code", "detail"), "environment_repair_approved": ("fingerprint", "contract", "reason"), "environment_resolved": ("fingerprint", "contract"), "environment_contract_rebased": ( "fingerprint", "contract", "task_id", "dependency_inputs", "primary_revision", ), "effect_completed": ("effect_id", "outcome"), "effect_intended": ("effect_id", "operation"), "product_validation_attested": ("task_id", "validation_kind", "observation"), "vision_observed": ("task_id", "observations"), "run_event_recorded": ("run_kind", "text"), "supervisor_decision_recorded": ("decision_id", "action"), "task_status_changed": ("task_id", "status"), }[kind] def _require_non_empty_fields(payload: dict[str, object], *names: str) -> None: for name in names: value = payload.get(name) if value is None or (isinstance(value, str) and not value.strip()): raise EventValidationError(f"Event payload requires non-empty {name}.")