The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(cron): add usage_audit.jsonl logger for cron token leak instrumentation
0xarkstar15927c1d24e3
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 659ffa3156a..7549996f809 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -21,6 +21,8 @@ import subprocessimport sysimport threadingimport time+import uuid+from datetime import datetime, timezone# fcntl is Unix-only; on Windows use msvcrt for file lockingtry:@@ -646,6 +648,33 @@ def _shutdown_parallel_pool() -> None:atexit.register(_shutdown_parallel_pool)+# Per-fire usage audit log for cron token spend instrumentation.+# Resolves through _get_hermes_home() so profile-scoped paths work correctly.+def _usage_audit_path() -> Path:+ return _get_hermes_home() / "cron" / "usage_audit.jsonl"+++def _utcnow_iso_ms() -> str:+ """RFC3339 UTC timestamp with millisecond precision and 'Z' suffix."""+ now = datetime.now(timezone.utc)+ # %f gives microseconds; trim to milliseconds.+ return now.strftime("%Y-%m-%dT%H:%M:%S.") + f"{now.microsecond // 1000:03d}Z"+++def _write_usage_audit(record: dict) -> None:+ """Append a single JSONL line to ~/.hermes/cron/usage_audit.jsonl.++ NEVER raises — a logger bug must not break cron jobs. Wraps the entire+ write (path resolve, mkdir, json.dumps, file append) in a single try.+ """+ try:+ path = _usage_audit_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ line = json.dumps(record, ensure_ascii=False)+ with open(path, "a", encoding="utf-8") as f:+ f.write(line + "\n")+ except Exception as e:+ logger.warning("usage_audit write failed: %s", e)def _interpreter_shutting_down(exc: Optional[BaseException] = None) -> bool:@@ -4096,6 +4125,10 @@ def run_job(# env passthrough registrations) when the cron run hops into the worker# thread used for inactivity timeout monitoring._cron_context = contextvars.copy_context()+ # Tag this fire and time the+ # run_conversation call for the usage_audit.jsonl entry.+ _audit_fire_id = uuid.uuid4().hex+ _audit_t_start = time.monotonic()_cron_future = _cron_pool.submit(_cron_context.run, agent.run_conversation, prompt)_inactivity_timeout = Falsetry:@@ -4249,11 +4282,49 @@ def run_job("""logger.info("Job '%s' completed successfully", job_name)++ # Emit one JSONL line per fire for usage audit.+ _audit_duration_ms = int((time.monotonic() - _audit_t_start) * 1000)+ _audit_response_silent = (+ not final_response.strip()+ or SILENT_MARKER in (final_response or "").upper()+ )+ _write_usage_audit({+ "ts": _utcnow_iso_ms(),+ "job_id": job_id,+ "fire_id": _audit_fire_id,+ "prompt_tokens": result.get("prompt_tokens"),+ "completion_tokens": result.get("completion_tokens"),+ "total_tokens": result.get("total_tokens"),+ "response_silent": _audit_response_silent,+ "deliver_target": job.get("deliver"),+ "model": model or None,+ "duration_ms": _audit_duration_ms,+ "error": None,+ })return True, output, final_response, None-+except Exception as e:error_msg = f"{type(e).__name__}: {str(e)}"logger.exception("Job '%s' failed: %s", job_name, error_msg)+ # Best-effort audit write on failure path. _audit_fire_id+ # may be unset if the exception fired before submit() — guard with+ # locals() lookup so the audit write itself never raises.+ if "_audit_fire_id" in locals():+ _audit_duration_ms = int((time.monotonic() - _audit_t_start) * 1000)+ _write_usage_audit({+ "ts": _utcnow_iso_ms(),+ "job_id": job_id,+ "fire_id": _audit_fire_id,+ "prompt_tokens": None,+ "completion_tokens": None,+ "total_tokens": None,+ "response_silent": False,+ "deliver_target": job.get("deliver"),+ "model": (model or None) if "model" in locals() else None,+ "duration_ms": _audit_duration_ms,+ "error": error_msg,+ })output = f"""# Cron Job: {job_name} (FAILED)diff --git a/tests/cron/test_usage_audit_logger.py b/tests/cron/test_usage_audit_logger.pynew file mode 100644index 00000000000..5d941473bf3--- /dev/null+++ b/tests/cron/test_usage_audit_logger.py@@ -0,0 +1,125 @@+"""Tests for the Phase 0.5 cron usage_audit.jsonl logger.++Covers:+- successful write produces a single valid JSONL line with full schema+- missing token info still writes a line with null fields+- writer exception is swallowed (json.dumps raises) — call must return cleanly+- file path is created if parent dir is missing+- timestamp format is RFC3339 UTC with millisecond precision and 'Z' suffix+"""++from __future__ import annotations++import json+import re+from pathlib import Path+from unittest.mock import patch++import pytest++from cron import scheduler+++def tmp_home(tmp_path, monkeypatch):+ """Redirect Path.home() so the audit logger writes under tmp_path."""+ fake_home = tmp_path / "home"+ fake_home.mkdir()+ monkeypatch.setattr(Path, "home", lambda: fake_home)+ return fake_home+++def _read_jsonl(path: Path) -> list[dict]:+ return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line]+++class TestUsageAuditPath:+ def test_resolves_under_user_home(self, tmp_home):+ p = scheduler._usage_audit_path()+ assert p == tmp_home / ".hermes" / "cron" / "usage_audit.jsonl"+++class TestUtcnowIsoMs:+ def test_format_has_millisecond_precision_and_z(self):+ ts = scheduler._utcnow_iso_ms()+ # YYYY-MM-DDTHH:MM:SS.mmmZ+ assert re.match(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$", ts), ts+++class TestWriteUsageAudit:+ def test_successful_write_produces_valid_jsonl(self, tmp_home):+ record = {+ "ts": "2026-05-01T04:23:11.123Z",+ "job_id": "bluenode-dispatch-recommend-sweep",+ "fire_id": "deadbeefcafe",+ "prompt_tokens": 11894,+ "completion_tokens": 287,+ "total_tokens": 12181,+ "response_silent": False,+ "deliver_target": None,+ "model": "google/gemma-4-31b-it",+ "duration_ms": 4231,+ "error": None,+ }+ scheduler._write_usage_audit(record)++ path = scheduler._usage_audit_path()+ assert path.exists()+ lines = _read_jsonl(path)+ assert len(lines) == 1+ assert lines[0] == record++ def test_missing_token_info_writes_line_with_null_fields(self, tmp_home):+ record = {+ "ts": "2026-05-01T04:23:11.123Z",+ "job_id": "j",+ "fire_id": "f",+ "prompt_tokens": None,+ "completion_tokens": None,+ "total_tokens": None,+ "response_silent": True,+ "deliver_target": "telegram",+ "model": None,+ "duration_ms": 12,+ "error": "boom",+ }+ scheduler._write_usage_audit(record)+ lines = _read_jsonl(scheduler._usage_audit_path())+ assert len(lines) == 1+ assert lines[0]["prompt_tokens"] is None+ assert lines[0]["completion_tokens"] is None+ assert lines[0]["total_tokens"] is None+ assert lines[0]["error"] == "boom"++ def test_writer_exception_swallowed(self, tmp_home, caplog):+ # Force json.dumps to raise — writer must NOT propagate.+ with patch("cron.scheduler.json.dumps", side_effect=RuntimeError("kaboom")):+ scheduler._write_usage_audit({"job_id": "x"})++ # File never created.+ assert not scheduler._usage_audit_path().exists()+ # Warning logged with our marker.+ assert any("usage_audit write failed" in rec.message for rec in caplog.records)++ def test_parent_dir_created_if_missing(self, tmp_home):+ # Ensure the .hermes/cron path does not exist yet.+ target = tmp_home / ".hermes" / "cron"+ assert not target.exists()++ scheduler._write_usage_audit({"k": "v"})++ assert target.exists() and target.is_dir()+ assert (target / "usage_audit.jsonl").exists()++ def test_appends_multiple_records(self, tmp_home):+ scheduler._write_usage_audit({"i": 1})+ scheduler._write_usage_audit({"i": 2})+ scheduler._write_usage_audit({"i": 3})+ lines = _read_jsonl(scheduler._usage_audit_path())+ assert [r["i"] for r in lines] == [1, 2, 3]++ def test_unicode_preserved_not_escaped(self, tmp_home):+ # ensure_ascii=False so non-ASCII model names / job names round-trip cleanly.+ scheduler._write_usage_audit({"job_id": "한글", "model": "gemma"})+ text = scheduler._usage_audit_path().read_text(encoding="utf-8")+ assert "한글" in text