"""Structured operational logging (architecture L12). One JSON object per line to stderr (journald captures it when running as a service). Every event carries the fixed envelope: ts, agent, event, task_id, cause. Logs are diagnostic, never load-bearing — nothing may read them back to derive state. """ import json import sys from datetime import UTC, datetime from typing import Any, TextIO class OpLog: def __init__(self, agent: str, stream: TextIO | None = None) -> None: self.agent = agent # Correlation ID for the enclosing unit of work; the orchestrator sets # it when a unit starts and clears it when the unit ends (L12). self.task_id: str | None = None self._stream = stream if stream is not None else sys.stderr def emit(self, event: str, *, cause: str, **fields: Any) -> None: record: dict[str, Any] = { "ts": datetime.now(UTC).isoformat(), "agent": self.agent, "event": event, "task_id": self.task_id, "cause": cause, **fields, } self._stream.write(json.dumps(record) + "\n") self._stream.flush()