"""Append-only JSONL telemetry for audit-code runs.""" from __future__ import annotations import json from datetime import datetime, timezone from pathlib import Path def _now() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def _append(log_path: Path, record: dict) -> None: log_path.parent.mkdir(parents=True, exist_ok=True) with log_path.open("a", encoding="utf-8") as f: f.write(json.dumps(record) + "\n") def append_subagent_run( log_path: Path, *, run_id: str, repo: str, mode: str, agent: str, model: str, input_tokens: int, output_tokens: int, duration_ms: int, finding_count: int, ) -> None: _append(log_path, { "kind": "subagent_run", "ts": _now(), "run_id": run_id, "repo": repo, "mode": mode, "agent": agent, "model": model, "input_tokens": input_tokens, "output_tokens": output_tokens, "duration_ms": duration_ms, "finding_count": finding_count, }) def append_verdict( log_path: Path, *, run_id: str, agent: str, rule_id: str, file: str, line: int, verdict: str, notes: str = "", ) -> None: if verdict not in {"kept", "dismissed", "false_positive"}: raise ValueError(f"invalid verdict: {verdict!r}") _append(log_path, { "kind": "verdict", "ts": _now(), "run_id": run_id, "agent": agent, "rule_id": rule_id, "file": file, "line": line, "verdict": verdict, "notes": notes, }) def read_runs(log_path: Path) -> list[dict]: if not log_path.exists(): return [] return [ json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines() if line.strip() ]