"""Durable journals: events.jsonl (everything the charger tells us) and seen_tags.json (unknown idTags captured in learn mode). JSONL now, SQLite later — the append-only line format survives crashes and is trivially greppable/ingestable, which is all the current phase needs. """ import json import logging from datetime import datetime, timezone from pathlib import Path from typing import Optional HERE = Path(__file__).resolve().parent EVENTS_PATH = HERE / "events.jsonl" SEEN_PATH = HERE / "seen_tags.json" log = logging.getLogger("journal") def now() -> str: return datetime.now(timezone.utc).isoformat() def record_event(event: str, cp_id: str, **data) -> None: entry = {"time": now(), "event": event, "cp": cp_id, **data} try: with EVENTS_PATH.open("a", encoding="utf-8") as f: f.write(json.dumps(entry, ensure_ascii=False, default=str) + "\n") except Exception: log.exception("failed to journal event %r", event) def read_events(limit: int = 100, event: Optional[str] = None) -> list: if not EVENTS_PATH.exists(): return [] lines = EVENTS_PATH.read_text(encoding="utf-8").splitlines() entries = [json.loads(line) for line in lines if line.strip()] if event is not None: entries = [e for e in entries if e.get("event") == event] return entries[-limit:] def record_seen(id_tag: str, context: str) -> None: try: seen = json.loads(SEEN_PATH.read_text(encoding="utf-8")) if SEEN_PATH.exists() else {} except Exception: seen = {} entry = seen.get(id_tag, {"count": 0, "first_seen": now(), "contexts": []}) entry["count"] += 1 entry["last_seen"] = now() if context not in entry["contexts"]: entry["contexts"].append(context) seen[id_tag] = entry SEEN_PATH.write_text(json.dumps(seen, indent=2), encoding="utf-8") def read_seen() -> dict: if not SEEN_PATH.exists(): return {} return json.loads(SEEN_PATH.read_text(encoding="utf-8"))