diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index eb810a6..fd7bc16 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-observer", - "version": "1.5.3", + "version": "1.6.0", "description": "Measure agent work across Codex, Claude Code, OpenCode and Grok Build from native records, and compare behavior by model and AgentsMD version.", "author": { "name": "toolboxmd", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 171e1b5..3740327 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-observer", - "version": "1.5.3", + "version": "1.6.0", "description": "Measure agent work across Codex, Claude Code, OpenCode and Grok Build from native records, and compare behavior by model and AgentsMD version.", "author": { "name": "toolboxmd", diff --git a/.grok-plugin/plugin.json b/.grok-plugin/plugin.json index 11649d2..83cf6cc 100644 --- a/.grok-plugin/plugin.json +++ b/.grok-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-observer", - "version": "1.5.3", + "version": "1.6.0", "description": "Measure agent work across Codex, Claude Code, OpenCode and Grok Build from native records, and compare behavior by model and AgentsMD version.", "author": { "name": "toolboxmd", diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f99f62..4d219bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [1.6.0] - 2026-11-25 + +### Added + +- Report native session freshness in health and fail when the ledger falls behind + ## [1.5.3] - 2026-11-23 ### Changed diff --git a/README.md b/README.md index e0f8608..130f0d7 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ agent-observer sessions list --project myapp --since 2026-09-01 agent-observer diagnose --since 2026-09-01 # repeated work and behavior incidents agent-observer thread-misuse --since 2026-10-01 # deep Chromeria spawns, cross-thread messages agent-observer compare --by agentsmd # behavior per AgentsMD version -agent-observer health # live sessions Observer cannot see +agent-observer health # session visibility and ledger freshness agent-observer claims --session claude: # final-report claims checked against tool calls agent-observer delegation-modes --since 2026-10-01 # planner delegation versus a dispatcher thread agent-observer event show [ ...] # full tool input, result and assistant text from the native log @@ -708,11 +708,26 @@ the process, directory and fix. Missing, failed, malformed or timed-out process scans are reported as unavailable with a reason; each `ps` or `lsof` invocation has a five-second timeout, and other health checks continue. -Health exits 0 when it finds no invisible sessions, unavailable scans or Cue -schema/read failures; it exits 4 when any is reported, and 2 for invalid -command-line arguments. Optional missing or unsynced Cue evidence stays visible -without failing health. An unread ledger -is reported as unknown and does not by itself change the exit status. +Health also compares the newest native record with the newest successful ledger +import for each harness. It counts native sources newer than that harness's +latest import. Claude, Codex and Muse use transcript file modification times. +Codex includes rollouts imported by Model Router. +Grok counts each session directory once using its newest event log or session +metadata file. +OpenCode counts sessions by their latest session, message or part timestamp. +Chromeria and Router use database and WAL modification times. These comparisons +measure lag for each harness. Individual missing imports can predate its newest +successful import. + +Health exits 4 for an invisible session, an unavailable check, a Cue +schema/read failure, or a freshness gap. A gap means native records exist and +the ledger has no import for that harness, or the newest native record is more +than 3600 seconds newer than its latest import. Set +`health --sync-interval-seconds N` to match your sync cadence. +`health --json` includes the interval and the `ledger_freshness` map, with +Unix timestamps in seconds, newer-source counts, lag and status. Health +exits 0 when its checks pass and 2 for invalid arguments. Optional missing +or unsynced Cue evidence stays visible without failing health. ## Ledger schema 3 diff --git a/VERSION b/VERSION index 8af85be..dc1e644 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.5.3 +1.6.0 diff --git a/agent_observer/adapters/bare.py b/agent_observer/adapters/bare.py index da199ce..7b8863c 100644 --- a/agent_observer/adapters/bare.py +++ b/agent_observer/adapters/bare.py @@ -22,6 +22,7 @@ from typing import Callable from . import t3 +from .discovery import path_info TURN_ITEMS = "orchestration_v2_projection_turn_items" # Chromeria ids every receipt ``bare-receipt::`` @@ -74,12 +75,13 @@ def _receipts(path: str) -> dict: return roots -def receipt_roots(harness: str) -> tuple[list, dict]: +def receipt_roots(harness: str, *, strict: bool = False) -> tuple[list, dict]: """Recorded roots (None when a receipt names none) and the base report.""" - path = t3.state_path() + path = t3.state_path(strict=strict) report = {"state_db": path, "state": "unused", "receipts": 0, "roots": 0, "gaps": []} - if not os.path.exists(path): + exists = path_info(path) is not None if strict else os.path.exists(path) + if not exists: report["state"] = "no T3 state" return [], report try: @@ -95,13 +97,16 @@ def receipt_roots(harness: str) -> tuple[list, dict]: def discover(harness: str, - paths_under: Callable[[str], list[str]]) -> tuple[list[str], dict]: + paths_under: Callable[[str], list[str]], *, + strict: bool = False) -> tuple[list[str], dict]: """Record paths under every receipt root for harness, plus the report. paths_under(root) lists one root's records. Roots are canonical, so aliases of one directory are read once. """ - rows, report = receipt_roots(harness) + rows, report = receipt_roots(harness, strict=strict) + if strict and report["state"] == "unreadable T3 state": + raise OSError(report["error"]) roots, gaps = [], [] for root in rows: if not isinstance(root, str) or not root: @@ -116,6 +121,8 @@ def discover(harness: str, gaps.append({"root": real, "reason": "missing on this machine"}) continue except OSError: + if strict: + raise gaps.append({"root": real, "reason": "unreadable"}) continue roots.append(real) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index d7dec46..eb26574 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -13,7 +13,6 @@ from __future__ import annotations -import glob import json import os import sqlite3 @@ -22,6 +21,7 @@ from ..identity import SessionIdentity, skill_from_path from ..ingest import (JsonlSource, MissingNativeId, fingerprint, insert_event, iso_ts, text_hash) +from .discovery import record_paths HARNESS = "claude" SEMANTICS = "claude:input_excludes_cache,output_includes_thinking" @@ -219,10 +219,10 @@ def _mark_finalized(con, rid: str) -> None: " VALUES(?, ?)", (rid, _time.time())) -def discover(root: str | None = None) -> list[str]: +def discover(root: str | None = None, *, strict: bool = False) -> list[str]: root = root or DEFAULT_ROOT - main = glob.glob(os.path.join(root, "*", "*.jsonl")) - subs = glob.glob(os.path.join(root, "*", "*", "subagents", "agent-*.jsonl")) + main = record_paths(root, "*", "*.jsonl", strict=strict) + subs = record_paths(root, "*", "*", "subagents", "agent-*.jsonl", strict=strict) return sorted(main + subs) diff --git a/agent_observer/adapters/codex.py b/agent_observer/adapters/codex.py index 2c291c8..d9b2c23 100644 --- a/agent_observer/adapters/codex.py +++ b/agent_observer/adapters/codex.py @@ -12,7 +12,6 @@ from __future__ import annotations -import glob import json import math import os @@ -23,6 +22,7 @@ from ..ingest import (JsonlSource, MissingNativeId, fingerprint, insert_event, iso_ts, stored_path, text_hash) from . import bare +from .discovery import record_paths def _native_ordinal(obj) -> int | None: @@ -223,30 +223,31 @@ def _validate_bucket(bucket, *, allow_none: bool = True): raise _MalformedUsage("malformed usage counter") -def _rollout_paths(root: str) -> list[str]: +def _rollout_paths(root: str, *, strict: bool = False) -> list[str]: """Rollout files under root. A missing directory contributes none.""" - return glob.glob(os.path.join(root, "**", "rollout-*.jsonl"), recursive=True) + return record_paths(root, "**", "rollout-*.jsonl", strict=strict) -def _live_and_archived(live_root: str, archive_root: str) -> list[str]: +def _live_and_archived(live_root: str, archive_root: str, *, strict: bool = False) -> list[str]: """One home's live rollouts plus archived ones whose basename is not live.""" - live = _rollout_paths(live_root) + live = _rollout_paths(live_root, strict=strict) live_names = {os.path.basename(path) for path in live} - archived = [path for path in _rollout_paths(archive_root) + archived = [path for path in _rollout_paths(archive_root, strict=strict) if os.path.basename(path) not in live_names] return live + archived -def _bare_home(root: str) -> list[str]: +def _bare_home(root: str, *, strict: bool = False) -> list[str]: """A bare receipt root (``/sessions``) plus its sibling archive.""" return _live_and_archived( - root, os.path.join(os.path.dirname(root), "archived_sessions")) + root, os.path.join(os.path.dirname(root), "archived_sessions"), strict=strict) -def _default_paths() -> tuple[list[str], dict]: +def _default_paths(*, strict: bool = False) -> tuple[list[str], dict]: """The normal home plus every Chromeria bare root, and the bare report.""" - paths = _live_and_archived(DEFAULT_ROOT, ARCHIVE_ROOT) - found, report = bare.discover(HARNESS, _bare_home) + paths = _live_and_archived(DEFAULT_ROOT, ARCHIVE_ROOT, strict=strict) + found, report = bare.discover(HARNESS, lambda root: _bare_home(root, strict=strict), + strict=strict) return sorted(paths + found), report @@ -256,7 +257,7 @@ def _stored(con: sqlite3.Connection, paths: list[str]) -> list[str]: return sorted({stored_path(con, HARNESS, path, seen) for path in paths}) -def discover(root: str | None = None) -> list[str]: +def discover(root: str | None = None, *, strict: bool = False) -> list[str]: """Rollout files under one root, or every default home. An explicit root is that directory only. With root unset, scan @@ -267,8 +268,8 @@ def discover(root: str | None = None) -> list[str]: stay. Dedup is by basename, not by thread id. """ if root: - return sorted(_rollout_paths(root)) - return _default_paths()[0] + return sorted(_rollout_paths(root, strict=strict)) + return _default_paths(strict=strict)[0] def sync(con: sqlite3.Connection, root: str | None = None, full: bool = False, diff --git a/agent_observer/adapters/discovery.py b/agent_observer/adapters/discovery.py new file mode 100644 index 0000000..765d4a1 --- /dev/null +++ b/agent_observer/adapters/discovery.py @@ -0,0 +1,66 @@ +"""Native file discovery with an option to surface access errors.""" + +import glob +import os +import stat +from fnmatch import fnmatchcase + + +def path_info(path: str) -> os.stat_result | None: + """Missing paths are optional and access errors are meaningful.""" + try: + return os.stat(path) + except (FileNotFoundError, NotADirectoryError): + return None + + +def sqlite_mtime(path: str) -> float | None: + """Newest database or WAL with frames, following the database's symlinks.""" + path = os.path.realpath(path) + stamps = [] + for candidate, min_size in ((path, 0), (path + "-wal", 33)): + info = path_info(candidate) + if info is not None and stat.S_ISREG(info.st_mode) and info.st_size >= min_size: + stamps.append(info.st_mtime) + return max(stamps, default=None) + + +def record_paths(root: str, *parts: str, strict: bool = False) -> list[str]: + """Match adapter layouts. Strict discovery must distinguish empty and unreadable.""" + if not strict: + return glob.glob(os.path.join(root, *parts), recursive="**" in parts) + return list(_walk(root, parts)) + + +def _walk(path, parts, ancestors=frozenset()): + info = path_info(path) + if info is None: + return + if not parts: + if stat.S_ISREG(info.st_mode): + yield path + return + if not stat.S_ISDIR(info.st_mode): + return + pattern, *rest = parts + if pattern == "**": + key = (info.st_dev, info.st_ino) + if key in ancestors: + return + yield from _walk(path, rest) + children = ancestors | {key} + for name in _visible_entries(path): + yield from _walk(os.path.join(path, name), parts, children) + elif "*" in pattern: + for name in _visible_entries(path): + if fnmatchcase(name, pattern): + yield from _walk(os.path.join(path, name), rest) + else: + yield from _walk(os.path.join(path, pattern), rest) + + +def _visible_entries(path: str) -> list[str]: + try: + return [name for name in os.listdir(path) if not name.startswith(".")] + except (FileNotFoundError, NotADirectoryError): + return [] diff --git a/agent_observer/adapters/grok.py b/agent_observer/adapters/grok.py index 5b1af9a..00135f7 100644 --- a/agent_observer/adapters/grok.py +++ b/agent_observer/adapters/grok.py @@ -22,6 +22,7 @@ import os import re import sqlite3 +import stat import urllib.parse from .. import db, privacy @@ -29,10 +30,12 @@ from ..ingest import (JsonlSource, fingerprint, insert_event, iso_ts, stored_path, text_hash) from . import bare +from .discovery import path_info HARNESS = "grok" SEMANTICS = "grok:input_includes_cached,output_includes_reasoning" DEFAULT_ROOT = os.path.expanduser("~/.grok/sessions") +SESSION_RECORD_FILES = ("updates.jsonl", "events.jsonl", "summary.json", "chat_history.jsonl") CAPABILITIES = [ ("model_usage", True, "one responses row per turn_completed prompt_id; input includes cached reads, output includes reasoning"), @@ -235,10 +238,11 @@ def _classify_prompt(prompt_idx: str, chat: dict, return "unknown", 0 -def _default_paths() -> tuple[list[str], dict]: +def _default_paths(*, strict: bool = False) -> tuple[list[str], dict]: """The normal sessions plus every Chromeria bare root's, and the report.""" - found, report = bare.discover(HARNESS, _sessions_under) - return _sessions_under(DEFAULT_ROOT) + found, report + found, report = bare.discover(HARNESS, lambda root: _sessions_under(root, strict=strict), + strict=strict) + return _sessions_under(DEFAULT_ROOT, strict=strict) + found, report def _stored(con: sqlite3.Connection, paths: list[str] @@ -256,44 +260,55 @@ def _stored(con: sqlite3.Connection, paths: list[str] return out -def discover(root: str | None = None) -> list[str]: +def discover(root: str | None = None, *, strict: bool = False) -> list[str]: """Session directories under `/`. With root unset, the normal sessions root and each sessions root a - Chromeria bare receipt names (#92). + Chromeria bare receipt names (#92). Strict discovery reports listing + errors for health while accepting missing optional directories. """ if not root: - return _default_paths()[0] - return _sessions_under(root) + return _default_paths(strict=strict)[0] + return _sessions_under(root, strict=strict) -def _sessions_under(root: str) -> list[str]: - if _looks_like_session(root): - return [root] +def _session_entries(path: str, strict: bool) -> list[str]: try: - groups = sorted(os.listdir(root)) + return sorted(os.listdir(path)) + except (FileNotFoundError, NotADirectoryError): + return [] except OSError: + if strict: + raise return [] + + +def _sessions_under(root: str, *, strict: bool = False) -> list[str]: + if _looks_like_session(root, strict=strict): + return [root] out = [] - for group in groups: + for group in _session_entries(root, strict): group_dir = os.path.join(root, group) - if not os.path.isdir(group_dir): + if not _session_path_is(group_dir, stat.S_ISDIR, os.path.isdir, strict): continue - try: - children = sorted(os.listdir(group_dir)) - except OSError: - continue - for child in children: + for child in _session_entries(group_dir, strict): session_dir = os.path.join(group_dir, child) - if os.path.isdir(session_dir) and _looks_like_session(session_dir): + if (_session_path_is(session_dir, stat.S_ISDIR, os.path.isdir, strict) + and _looks_like_session(session_dir, strict=strict)): out.append(session_dir) return out -def _looks_like_session(path: str) -> bool: - return any(os.path.isfile(os.path.join(path, name)) for name in - ("updates.jsonl", "events.jsonl", "summary.json", - "chat_history.jsonl")) +def _session_path_is(path, is_mode, permissive, strict): + if not strict: + return permissive(path) + info = path_info(path) + return info is not None and is_mode(info.st_mode) + + +def _looks_like_session(path: str, *, strict: bool = False) -> bool: + return any(_session_path_is(os.path.join(path, name), stat.S_ISREG, os.path.isfile, strict) + for name in SESSION_RECORD_FILES) class _SyncCtx: @@ -351,6 +366,8 @@ def sync(con: sqlite3.Connection, root: str | None = None, full: bool = False, except (OSError, sqlite3.DatabaseError, UnicodeDecodeError) as exc: totals["failed"].append({"path": path, "error": str(exc)}) continue + for error in stats.get("metadata_errors", []): + totals["failed"].append({"path": path, "error": error}) if "session_key" in stats: imported.update(new_files.values()) totals["sources"] += 1 @@ -381,13 +398,17 @@ def _resolve_source(source: str, root: str | None) -> list[str]: return discover(root) -def _read_json(path: str): +def _read_summary(path: str) -> dict: try: with open(path, encoding="utf-8", errors="replace") as fh: obj = json.load(fh) - except (OSError, ValueError): - return None - return obj if isinstance(obj, dict) else None + except FileNotFoundError: + return {} + except ValueError as exc: + raise OSError("invalid Grok summary JSON") from exc + if not isinstance(obj, dict): + raise OSError("Grok summary must be a JSON object") + return obj def _content_text(content) -> str: @@ -571,17 +592,18 @@ def _ensure_grok_meta_table(con: sqlite3.Connection) -> None: " summary_fp TEXT, chat_fp TEXT)") except sqlite3.DatabaseError: pass - for column in ("chat_seen_json", "chat_synthetic_json", "chat_effort", - "chat_reliable"): - try: - cols = {row["name"] for row in con.execute( - f"PRAGMA table_info({_GROK_META_TABLE})")} - except sqlite3.DatabaseError: - return + try: + cols = {row["name"] for row in con.execute( + f"PRAGMA table_info({_GROK_META_TABLE})")} + except sqlite3.DatabaseError: + return + for column, affinity in (("chat_seen_json", "TEXT"), ("chat_synthetic_json", "TEXT"), + ("chat_effort", "TEXT"), ("chat_reliable", "TEXT"), + ("imported_at", "REAL"), ("pending", "INTEGER")): if column not in cols: try: con.execute( - f"ALTER TABLE {_GROK_META_TABLE} ADD COLUMN {column} TEXT") + f"ALTER TABLE {_GROK_META_TABLE} ADD COLUMN {column} {affinity}") except sqlite3.DatabaseError: pass @@ -594,40 +616,60 @@ def _summary_fingerprint(summary: dict) -> str: return hashlib.sha256(f"{_IMPORT_VERSION}:{canonical}".encode("utf-8", "replace")).hexdigest() +def newest_metadata_import(con: sqlite3.Connection) -> float | None: + """Latest summary/chat import, when this ledger tracks metadata imports.""" + if "imported_at" not in {row[1] for row in con.execute( + f"PRAGMA table_info({_GROK_META_TABLE})")}: + return None + return con.execute(f"SELECT MAX(imported_at) FROM {_GROK_META_TABLE}").fetchone()[0] + + +def complete_import_watermarks(con: sqlite3.Connection) -> tuple[float | None, float | None]: + """Return transcript and metadata watermarks for complete sessions.""" + columns = {row[1] for row in con.execute(f"PRAGMA table_info({_GROK_META_TABLE})")} + where = "" + if "pending" in columns: + where = (f" AND NOT EXISTS (SELECT 1 FROM {_GROK_META_TABLE} m" + " WHERE m.session_key='grok:' || s.session_id AND m.pending=1)") + transcript = con.execute( + f"SELECT MAX(s.imported_at) FROM sources s WHERE s.harness='grok'{where}").fetchone()[0] + return transcript, newest_metadata_import(con) + + def _stored_meta(con: sqlite3.Connection, session_key: str): """Stored chat/summary state or Nones when absent/unreadable. Returns (summary_fp, chat_fp, seen_set, synthetic_set, chat_effort, - chat_reliable). Mark collections are None when the row or its mark + chat_reliable, imported_at). Mark collections are None when the row or its mark columns are absent, so the caller falls back to parsing the chat file. """ try: row = con.execute( f"SELECT summary_fp, chat_fp, chat_seen_json," - f" chat_synthetic_json, chat_effort, chat_reliable" + f" chat_synthetic_json, chat_effort, chat_reliable, imported_at" f" FROM {_GROK_META_TABLE}" " WHERE session_key=?", (session_key,)).fetchone() except sqlite3.DatabaseError: - return None, None, None, None, None, None + return (None,) * 7 if row is None: - return None, None, None, None, None, None + return (None,) * 7 try: summary_fp = row["summary_fp"] chat_fp = row["chat_fp"] except (KeyError, TypeError, IndexError): - return None, None, None, None, None, None + return (None,) * 7 try: seen_raw = row["chat_seen_json"] synth_raw = row["chat_synthetic_json"] chat_effort = row["chat_effort"] reliable_raw = row["chat_reliable"] except (KeyError, TypeError, IndexError): - return summary_fp, chat_fp, None, None, None, None + return summary_fp, chat_fp, None, None, None, None, None try: seen = set(json.loads(seen_raw)) if seen_raw else set() synthetic = set(json.loads(synth_raw)) if synth_raw else set() except (TypeError, ValueError): - return summary_fp, chat_fp, None, None, None, None + return summary_fp, chat_fp, None, None, None, None, None if reliable_raw is None: reliable = None elif isinstance(reliable_raw, int): @@ -636,12 +678,12 @@ def _stored_meta(con: sqlite3.Connection, session_key: str): reliable = reliable_raw == "1" else: reliable = None - return summary_fp, chat_fp, seen, synthetic, chat_effort, reliable + return summary_fp, chat_fp, seen, synthetic, chat_effort, reliable, row["imported_at"] def _store_meta(con: sqlite3.Connection, session_key: str, summary_fp: str | None, chat_fp: str | None, - chat: dict | None = None) -> None: + chat: dict | None, imported_at: float) -> None: """Persist fingerprints plus parsed chat marks for the fast path.""" _ensure_grok_meta_table(con) if chat is None: @@ -662,10 +704,10 @@ def _store_meta(con: sqlite3.Connection, session_key: str, con.execute( f"INSERT OR REPLACE INTO {_GROK_META_TABLE}" "(session_key, summary_fp, chat_fp, chat_seen_json," - " chat_synthetic_json, chat_effort, chat_reliable)" - " VALUES(?,?,?,?,?,?,?)", + " chat_synthetic_json, chat_effort, chat_reliable, imported_at)" + " VALUES(?,?,?,?,?,?,?,?)", (session_key, summary_fp, chat_fp, seen_json, synth_json, - chat_effort, chat_reliable)) + chat_effort, chat_reliable, imported_at)) except sqlite3.DatabaseError: pass @@ -682,7 +724,7 @@ def _chat_fingerprint(session_dir: str) -> str: try: with open(path, "rb") as bfh: raw_bytes = bfh.read() - except OSError: + except FileNotFoundError: return "missing" try: return hashlib.sha256(raw_bytes).hexdigest() @@ -1437,18 +1479,54 @@ def import_grok_session(con: sqlite3.Connection, session_dir: str, for name in ("updates.jsonl", "events.jsonl")}) updates_path = source_paths.get("updates.jsonl") events_path = source_paths.get("events.jsonl") - summary = _read_json(os.path.join(session_dir, "summary.json")) or {} + metadata_imported_at = db.now() + summary_path = os.path.join(session_dir, "summary.json") + metadata_errors = [] + metadata_mtime = None + summary = {} + summary_unavailable = False + chat_fp_current = None + try: + summary_stat = path_info(summary_path) + summary = _read_summary(summary_path) + if summary_stat is not None: + metadata_mtime = summary_stat.st_mtime + except OSError as exc: + summary_unavailable = True + metadata_errors.append(str(exc)) + try: + chat_stat = path_info(os.path.join(session_dir, "chat_history.jsonl")) + chat_fp_current = _chat_fingerprint(session_dir) + if chat_stat is not None: + metadata_mtime = max(metadata_mtime or 0, chat_stat.st_mtime) + except OSError as exc: + metadata_errors.append(str(exc)) + stats["metadata_errors"] = metadata_errors info = summary.get("info") if isinstance(summary.get("info"), dict) else {} - # Fail closed on unsafe identifiers: the native session id comes only - # from a validated summary.info.id or a validated directory basename. - # Anything else never reaches session keys, response ids, submission - # ids or event keys. + # Validate every candidate before it can become a ledger identity. basename = os.path.basename(session_dir.rstrip(os.sep)) safe_basename = _valid_native_id(basename) raw_info_id = info.get("id") valid_info_id = _valid_native_id(raw_info_id) \ if isinstance(raw_info_id, str) and raw_info_id else None - native_sid = valid_info_id or safe_basename + # A failed summary read can use identity already established for a + # transcript, while a readable native ID takes precedence. + _ensure_grok_meta_table(con) + recorded_id = None + for path in (updates_path, events_path): + if path is None: + continue + row = con.execute("SELECT session_id FROM sources WHERE harness=? AND path=?", + (HARNESS, path)).fetchone() + if row is not None: + recorded_id = _valid_native_id(row["session_id"]) + if recorded_id is not None: + break + if recorded_id is None and valid_info_id is None: + recorded_id = _notification_session_id(updates_path, events_path) + if recorded_id is None and summary_unavailable: + return stats + native_sid = valid_info_id or recorded_id or safe_basename if native_sid is None: # No safe native id: quarantine under the fixed missing_id # category with no record values. The source_path locates the @@ -1520,9 +1598,14 @@ def import_grok_session(con: sqlite3.Connection, session_dir: str, # Change state before any full parse. JsonlSource does a stat plus a # small tail read, never a full parse. - updates_src = (JsonlSource(con, HARNESS, updates_path, full=full) + previous = con.execute( + f"SELECT imported_at, pending FROM {_GROK_META_TABLE} WHERE session_key=?", + (r.session_key,)).fetchone() + retry = previous is not None and bool(previous["pending"]) + replay = full or (retry and not metadata_errors) + updates_src = (JsonlSource(con, HARNESS, updates_path, full=replay) if updates_path and os.path.isfile(updates_path) else None) - events_src = (JsonlSource(con, HARNESS, events_path, full=full) + events_src = (JsonlSource(con, HARNESS, events_path, full=replay) if events_path and os.path.isfile(events_path) else None) r.updates_src = updates_src r.events_src = events_src @@ -1558,10 +1641,8 @@ def import_grok_session(con: sqlite3.Connection, session_dir: str, except (KeyError, TypeError, IndexError): stored_role = None summary_fp = _summary_fingerprint(summary) - chat_fp_current = _chat_fingerprint(session_dir) - _ensure_grok_meta_table(con) (stored_summary_fp, stored_chat_fp, stored_seen, stored_synthetic, - stored_chat_effort, stored_chat_reliable) = _stored_meta(con, + stored_chat_effort, stored_chat_reliable, stored_imported_at) = _stored_meta(con, r.session_key) stored_marks = _chat_from_stored(stored_chat_fp, stored_seen, stored_synthetic, stored_chat_effort, @@ -1579,6 +1660,10 @@ def import_grok_session(con: sqlite3.Connection, session_dir: str, r.meta.get("role") == "subagent" and stored_role != "subagent") meta_changed = (stored_summary_fp != summary_fp or stored_chat_fp != chat_fp_current) + invalid_chat = "invalid or incomplete Grok chat history" + if (stored_chat_fp == chat_fp_current and chat_fp_current not in (None, "missing") + and stored_chat_reliable is False): + metadata_errors.append(invalid_chat) chat = None @@ -1598,11 +1683,18 @@ def _get_chat() -> dict: stored_chat_reliable) if chat is not None: return chat - chat = _read_chat(session_dir, r) + try: + chat = _read_chat(session_dir, r) + except OSError as exc: + metadata_errors.append(str(exc)) + chat = {"reliable": False} + if (chat.get("fp") not in (None, "missing") and not chat["reliable"] + and invalid_chat not in metadata_errors): + metadata_errors.append(invalid_chat) return chat if known and not updates_new and not events_new and not privacy_stale \ - and not full: + and not (full or retry or metadata_errors): if not meta_changed and stored_marks is not None \ and not new_parent_via_index and not new_role_via_evidence: # Fully unchanged: no parse of updates/events and no JSON parse @@ -1622,6 +1714,13 @@ def _get_chat() -> dict: updates_new = updates_src is not None and not updates_src.unchanged events_new = events_src is not None and not events_src.unchanged if not updates_new and not events_new: + if not metadata_errors and metadata_mtime is not None and ( + stored_imported_at is None or metadata_mtime > stored_imported_at): + # The reads above revalidated the same metadata bytes. + con.execute(f"UPDATE {_GROK_META_TABLE} SET imported_at=?" + " WHERE session_key=?", + (metadata_imported_at, r.session_key)) + con.commit() stats["unchanged"] = True stats["session_key"] = r.session_key return stats @@ -1654,8 +1753,9 @@ def _get_chat() -> dict: **late_fields) # Reclassify without records is covered by the force above # (no parse, no duplicates). - _store_meta(con, r.session_key, summary_fp, chat_fp_current, - chat) + if not metadata_errors: + _store_meta(con, r.session_key, summary_fp, chat_fp_current, + chat, metadata_imported_at) con.commit() stats["unchanged"] = False stats["session_key"] = r.session_key @@ -1860,11 +1960,27 @@ def _replay_error(ordinal: int, category: str, line: str = "") -> None: "(SELECT version FROM agentsmd_versions WHERE sha256=sessions.instructions_sha256), ?)" " WHERE session_key=?", (json.dumps(evidence, sort_keys=True) if evidence else None, version, r.session_key)) - _store_meta(con, r.session_key, summary_fp, chat_fp_current, chat) - if updates_src is not None: - stats.update(updates_src.finish(session_id=r.native_sid)) - if events_src is not None: - stats.update(events_src.finish(session_id=r.native_sid)) + if not metadata_errors: + _store_meta(con, r.session_key, summary_fp, chat_fp_current, chat, metadata_imported_at) + else: + # Keep the last complete watermark while the transcript rows and their + # import timestamps remain available to other ledger consumers. + last_complete = stored_imported_at + if not retry and last_complete is None: + last_complete = con.execute( + "SELECT MAX(imported_at) FROM sources WHERE harness=? AND session_id=?", + (HARNESS, r.native_sid)).fetchone()[0] + con.execute( + f"INSERT INTO {_GROK_META_TABLE}(session_key, imported_at, pending) VALUES(?,?,1)" + " ON CONFLICT(session_key) DO UPDATE SET imported_at=excluded.imported_at, pending=1", + (r.session_key, last_complete)) + for source in (updates_src, events_src): + if source is not None and (not metadata_errors or not source.unchanged): + same_snapshot = (source.mtime_ns, source.ino, source.size) == ( + source.row["mtime_ns"], source.row["ino"], source.row["size_bytes"]) + if metadata_errors and same_snapshot and not source.privacy_stale and not full: + continue + stats.update(source.finish(session_id=r.native_sid)) stats["session_key"] = r.session_key stats["unchanged"] = bool( (updates_src is None or updates_src.unchanged) @@ -1892,7 +2008,7 @@ def _read_chat(session_dir: str, r: _Reader) -> dict: try: with open(path, "rb") as bfh: raw_bytes = bfh.read() - except OSError: + except FileNotFoundError: chat["reliable"] = False return chat try: @@ -1903,7 +2019,7 @@ def _read_chat(session_dir: str, r: _Reader) -> dict: chat["reliable"] = False try: fh = open(path, encoding="utf-8", errors="replace") - except OSError: + except FileNotFoundError: chat["reliable"] = False return chat with fh: @@ -1949,6 +2065,60 @@ def _read_chat(session_dir: str, r: _Reader) -> dict: return chat +def _notification_session_id(updates_path, events_path) -> str | None: + """Read identity evidence only from complete native records.""" + for path, updates in ((events_path, False), (updates_path, True)): + if not path: + continue + try: + for _ordinal, raw in _complete_lines(path): + try: + record = json.loads(raw) + except ValueError: + continue + if not isinstance(record, dict): + continue + if updates: + params = record.get("params") + if record.get("method") not in METHODS or not isinstance(params, dict): + continue + update = params.get("update") + if not isinstance(update, dict): + continue + kind = update.get("sessionUpdate") + if kind in ("tool_call", "tool_call_update"): + if _valid_native_id(update.get("toolCallId")) is None: + continue + elif kind in ("user_message_chunk", "agent_message_chunk"): + if not _content_text(update.get("content")): + continue + if kind == "user_message_chunk": + meta = update.get("_meta") + if (not isinstance(meta, dict) + or _valid_prompt_index(meta.get("promptIndex")) is None): + continue + elif kind == "turn_completed": + if _valid_native_id(update.get("prompt_id") or update.get("promptId")) is None: + continue + try: + _validated_usage_counters(update) + except _AdapterError: + continue + elif not isinstance(kind, str) or ( + kind not in COMPACTION_KINDS and kind not in EXTENSION_KINDS): + continue + native_id = params.get("sessionId") + else: + if record.get("type") != "turn_started": + continue + native_id = record.get("session_id") + if (session_id := _valid_native_id(native_id)) is not None: + return session_id + except FileNotFoundError: + continue + return None + + def _complete_lines(path: str): """(ordinal, text) for every non-blank complete line from the start. @@ -2674,10 +2844,9 @@ def _tool_name(update: dict): def _tool_call(r: _Reader, src: JsonlSource, update: dict, params: dict, ordinal: int, ts) -> None: - raw_call = update.get("toolCallId") - if not isinstance(raw_call, str) or _safe_token(raw_call) is None: + call_id = _valid_native_id(update.get("toolCallId")) + if call_id is None: raise _AdapterError("schema_error") - call_id = raw_call raw = update.get("rawInput") name = _tool_name(update) target = _safe_target(raw) @@ -2690,10 +2859,9 @@ def _tool_call(r: _Reader, src: JsonlSource, update: dict, params: dict, def _tool_call_update(r: _Reader, src: JsonlSource, update: dict, params: dict, ordinal: int, ts) -> None: - raw_call = update.get("toolCallId") - if not isinstance(raw_call, str) or _safe_token(raw_call) is None: + call_id = _valid_native_id(update.get("toolCallId")) + if call_id is None: raise _AdapterError("schema_error") - call_id = raw_call turn_id = _turn_id(r, params) # Keep every validated location until a later terminal update, rather # than relying on the single representative path stored on the read row. diff --git a/agent_observer/adapters/muse.py b/agent_observer/adapters/muse.py index 5eaf97a..11e6098 100644 --- a/agent_observer/adapters/muse.py +++ b/agent_observer/adapters/muse.py @@ -34,7 +34,6 @@ from __future__ import annotations -import glob import json import os import re @@ -43,6 +42,7 @@ from .. import db from ..identity import SessionIdentity from ..ingest import JsonlSource, MissingNativeId, fingerprint, insert_event +from .discovery import record_paths HARNESS = "muse" @@ -99,11 +99,11 @@ def _str(value) -> str | None: return value if isinstance(value, str) and value else None -def discover(root: str | None = None) -> list[str]: +def discover(root: str | None = None, *, strict: bool = False) -> list[str]: root = root or DEFAULT_ROOT - main = glob.glob(os.path.join(root, "*", "*", "*", "*", "session.jsonl")) - children = glob.glob(os.path.join(root, "*", "*", "*", "*", "subagent", - "*", "session.jsonl")) + main = record_paths(root, "*", "*", "*", "*", "session.jsonl", strict=strict) + children = record_paths(root, "*", "*", "*", "*", "subagent", + "*", "session.jsonl", strict=strict) return sorted(main + children) diff --git a/agent_observer/adapters/opencode.py b/agent_observer/adapters/opencode.py index 42a3159..4e433d1 100644 --- a/agent_observer/adapters/opencode.py +++ b/agent_observer/adapters/opencode.py @@ -22,6 +22,7 @@ from .. import db, privacy from ..identity import SessionIdentity, skill_from_path from ..ingest import fingerprint, insert_event, iso_ts, text_hash +from .discovery import path_info HARNESS = "opencode" SEMANTICS = "opencode:input_excludes_cache,reasoning_separate" @@ -73,9 +74,10 @@ def _resolve_db(path: str | None) -> str: return candidate -def discover(root: str | None = None) -> list[str]: +def discover(root: str | None = None, *, strict: bool = False) -> list[str]: path = _resolve_db(root) - return [path] if os.path.exists(path) else [] + exists = path_info(path) is not None if strict else os.path.exists(path) + return [path] if exists else [] def _native_columns(native: sqlite3.Connection, table: str) -> set[str]: diff --git a/agent_observer/adapters/router.py b/agent_observer/adapters/router.py index 988b83c..04aff9a 100644 --- a/agent_observer/adapters/router.py +++ b/agent_observer/adapters/router.py @@ -55,19 +55,20 @@ from __future__ import annotations -import glob import hashlib import json import math import os import re import sqlite3 +import stat import subprocess import urllib.parse from .. import db, privacy from ..ingest import iso_ts from . import codex as _codex +from .discovery import path_info, record_paths, sqlite_mtime HARNESS = "router" ROUTER_SCHEMA_VERSION = 2 @@ -236,7 +237,7 @@ _CONTENT_HASH_RE = re.compile(r"^[0-9a-fA-F]{64}$") -def discover(root: str | None = None) -> list[str]: +def discover(root: str | None = None, *, strict: bool = False) -> list[str]: roots = [root] if root is not None else [ os.environ.get("DURABLE_RUNNER_STATE_DIR"), DEFAULT_ROOT, LEGACY_ROOT] paths = [] @@ -245,7 +246,12 @@ def discover(root: str | None = None) -> list[str]: continue path, _ = _resolve_paths(os.path.expanduser(candidate), None) canonical = _canonical_source_path(path) - if os.path.isfile(canonical) and canonical not in paths: + if strict: + info = path_info(canonical) + exists = info is not None and stat.S_ISREG(info.st_mode) + else: + exists = os.path.isfile(canonical) + if exists and canonical not in paths: paths.append(canonical) return paths @@ -502,6 +508,13 @@ def _sync_ledger(con: sqlite3.Connection, db_path: str, totals: dict, Returns (changed, invocations, bound) so the caller can reconcile usage after the router-owned rollouts are imported. """ + checked_at = db.now() + try: + source_mtime = sqlite_mtime(db_path) + except OSError: + # Metadata inspection is optional for sync. SQLite determines + # whether the database snapshot itself can be read. + source_mtime = None src = _open_ro(db_path) try: row = _get_source_row(con, db_path) @@ -543,6 +556,9 @@ def _sync_ledger(con: sqlite3.Connection, db_path: str, totals: dict, # reconciliation once the router-owned rollouts land. bound, bound_pairs = _snapshot_bindings(con, jobs, invocations) totals["bindings"] = len(bound_pairs) + if source_mtime is not None and source_mtime > row["imported_at"]: + con.execute("UPDATE sources SET imported_at=? WHERE id=?", + (checked_at, row["id"])) return False, invocations, bound task_ids = {j.get("request_id"): _job_task_id(j) for j in jobs} for job in jobs: @@ -1325,33 +1341,26 @@ def _validate_source_event(con: sqlite3.Connection, db_path: str, return False +def _rollouts_under(rollout_root: str, *, strict: bool = False) -> list[str]: + paths = set(record_paths(rollout_root, "codex-sessions", "**", "rollout-*.jsonl", + strict=strict)) + paths.update(record_paths(rollout_root, "kits", "*", "sessions", "**", + "rollout-*.jsonl", strict=strict)) + return list(dict.fromkeys(os.path.realpath(path) for path in sorted(paths))) + + +def discover_rollouts(*, strict: bool = False) -> list[str]: + """Codex rollouts read by default Router sync, including its fallback root.""" + roots = [os.path.dirname(path) for path in discover(strict=strict)] or [DEFAULT_ROOT] + return list(dict.fromkeys(path for root in roots + for path in _rollouts_under(root, strict=strict))) + + def _sync_rollouts(con: sqlite3.Connection, rollout_root: str, totals: dict, full: bool = False) -> bool: - """Import router-owned Codex rollouts through the Codex adapter. - - Every rollout continues through ``_codex.import_codex_file`` with the - full flag, so main-session classification, sanitized excerpts, - whitelisted details and targets, fixed categories and in-place privacy - corrections come from the core importer. No Codex privacy logic is - duplicated here. - """ - patterns = ( - os.path.join(rollout_root, "codex-sessions", "**", "rollout-*.jsonl"), - os.path.join(rollout_root, "kits", "*", "sessions", "**", - "rollout-*.jsonl")) - paths = set() - for pattern in patterns: - paths.update(glob.glob(pattern, recursive=True)) + """Import router-owned rollouts through the core Codex importer.""" changed = False - seen: set[str] = set() - for path in sorted(paths): - try: - canonical = os.path.realpath(path) - except OSError: - canonical = path - if canonical in seen: - continue - seen.add(canonical) + for canonical in _rollouts_under(rollout_root): try: stats = _codex.import_codex_file(con, canonical, full=full) except (OSError, sqlite3.DatabaseError, UnicodeDecodeError, diff --git a/agent_observer/adapters/t3.py b/agent_observer/adapters/t3.py index 2ed9efc..787d846 100644 --- a/agent_observer/adapters/t3.py +++ b/agent_observer/adapters/t3.py @@ -66,6 +66,7 @@ import sqlite3 from .. import db, privacy +from .discovery import path_info # A PR head branch as T3 snapshots it; anything else is not stored. BRANCH_RE = re.compile(r"^[A-Za-z0-9._/-]{1,200}$") @@ -117,12 +118,14 @@ def t3_home(root: str | None = None) -> str: return os.environ.get("T3CODE_HOME") or os.path.expanduser("~/.t3") -def state_path(root: str | None = None, source: str | None = None) -> str: +def state_path(root: str | None = None, source: str | None = None, *, + strict: bool = False) -> str: """The T3 state database: explicit source, else Chromeria V2, else V1.""" if source: return source v2 = os.path.join(t3_home(root), V2_RELATIVE) - if os.path.exists(v2): + exists = path_info(v2) is not None if strict else os.path.exists(v2) + if exists: return v2 return os.path.join(t3_home(root), STATE_RELATIVE) diff --git a/agent_observer/cli.py b/agent_observer/cli.py index e8edf46..9dc5bad 100644 --- a/agent_observer/cli.py +++ b/agent_observer/cli.py @@ -14,6 +14,7 @@ from .adapters import bare as _bare from . import analysis as _analysis from . import db as _db +from . import health as _health from . import identity as _identity from . import interventions as _interventions from . import placement @@ -383,7 +384,10 @@ def _scope(parser): pb.add_argument("--dry-run", action="store_true", help="print the comment, post nothing") pb.add_argument("--json", action="store_true", dest="as_json", default=argparse.SUPPRESS) - hl = sub.add_parser("health", help="find live sessions Observer cannot see") + hl = sub.add_parser("health", help="check session visibility and ledger freshness") + hl.add_argument("--sync-interval-seconds", type=_nonnegative, + default=_health.DEFAULT_SYNC_INTERVAL_SECONDS, + help="maximum native-to-ledger lag in seconds (default: %(default)s)") hl.add_argument("--json", action="store_true", dest="as_json", default=argparse.SUPPRESS) cl = sub.add_parser("claims", help="check a Claude Code session's final report against its tool calls") @@ -732,15 +736,18 @@ def main(argv=None) -> int: def _health_check(ns) -> int: - from . import health as _health con = None - if os.path.exists(ns.db): - try: - con = _db.connect_read_only(ns.db) - except (RuntimeError, sqlite3.Error): - con = None + ledger_error = None + try: + os.stat(ns.db) + con = _db.connect_read_only(ns.db) + except FileNotFoundError: + pass + except (OSError, RuntimeError, sqlite3.Error) as exc: + ledger_error = _health.error_reason(exc) try: - result = _health.check(con=con) + result = _health.check(con=con, ledger_error=ledger_error, + sync_interval_seconds=ns.sync_interval_seconds) finally: if con is not None: con.close() @@ -767,7 +774,19 @@ def _health_check(ns) -> int: for harness, roots in result["bare_roots"].items(): for line in _bare_lines(harness, roots): print(f"- {harness} {line.strip()}") - return 4 if result["findings"] or result["unavailable"] or result["cue"]["status"] in {"schema_drift", "unreadable_database"} else 0 + print(f"Ledger freshness (sync interval: {result['sync_interval_seconds']} seconds)") + for harness, row in result["ledger_freshness"].items(): + native = _health.format_timestamp(row["newest_native_at"]) + imported = _health.format_timestamp(row["newest_import_at"]) + status = row["status"].replace("_", " ") + gap = f", {row['newer_sources']} newer sources" if row["newer_sources"] is not None else "" + if row["lag_seconds"] is not None: + gap += f", lag {row['lag_seconds']:.0f} seconds" + print(f"- {harness}: {status}, newest native {native}, newest import {imported}{gap}") + stale = any(row["status"] in {"stale", "never_synced"} + for row in result["ledger_freshness"].values()) + cue_failed = result["cue"]["status"] in {"schema_drift", "unreadable_database"} + return 4 if stale or result["findings"] or result["unavailable"] or cue_failed else 0 def _capabilities(ns) -> int: diff --git a/agent_observer/health.py b/agent_observer/health.py index c64a4c2..75cc6c8 100644 --- a/agent_observer/health.py +++ b/agent_observer/health.py @@ -1,4 +1,4 @@ -"""Session visibility: find live agent sessions whose records Observer cannot see. +"""Check session visibility and whether the ledger is keeping up with native records. A Claude Code session started from inside another one inherits the parent's child-session marker and saves no transcript unless the launcher scrubs the @@ -15,13 +15,38 @@ import json import os import sqlite3 +import stat import subprocess import time +from contextlib import closing, nullcontext +from datetime import datetime +from pathlib import Path + +from .adapters import bare as bare_adapter +from .adapters.discovery import path_info, sqlite_mtime CLAUDE_FIX = ("start the session with the parent's CLAUDE_CODE_*, CLAUDECODE, CLAUDE_PID " "and CLAUDE_EFFORT variables unset, or with CLAUDE_CODE_FORCE_SESSION_PERSISTENCE=1") GRACE_SECONDS = 120 SCAN_TIMEOUT_SECONDS = 5 +DEFAULT_SYNC_INTERVAL_SECONDS = 3600 + + +def error_reason(exc: Exception) -> str: + """Describe a freshness failure without rendering paths or source text.""" + if isinstance(exc, PermissionError): + return "permission denied" + if isinstance(exc, OSError): + return os.strerror(exc.errno) if exc.errno is not None else "source unavailable" + if isinstance(exc, sqlite3.Error): + return getattr(exc, "sqlite_errorname", "SQLite read failed") + return "ledger unavailable" + + +def format_timestamp(stamp) -> str: + if stamp is None: + return "unknown" + return datetime.fromtimestamp(stamp).astimezone().isoformat(timespec="seconds") def _alive(pid: int) -> bool: @@ -142,19 +167,20 @@ def check_opencode(processes: list[dict], db_path: str | None = None) -> list[di con = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=5.0) except sqlite3.Error: con = None - for proc in live: - seen = None - if con is not None: - row = con.execute("SELECT MAX(time_updated) FROM session WHERE directory=?", - (proc["cwd"],)).fetchone() - seen = row[0] / 1000.0 if row and row[0] else None - if seen is None or (proc.get("started") and seen < proc["started"]): - findings.append({ - "host": "opencode", "pid": proc["pid"], "cwd": proc["cwd"], - "problem": "running OpenCode process has no session record since it started", - "fix": "keep OpenCode's data directory reachable (no XDG_DATA_HOME override)"}) - if con is not None: - con.close() + with closing(con) if con is not None else nullcontext(): + for proc in live: + seen = None + if con is not None: + row = con.execute( + "SELECT MAX(time_updated) FROM session WHERE directory=?" + " AND typeof(time_updated) IN ('integer', 'real')", + (proc["cwd"],)).fetchone() + seen = row[0] / 1000.0 if row and row[0] else None + if seen is None or (proc.get("started") and seen < proc["started"]): + findings.append({ + "host": "opencode", "pid": proc["pid"], "cwd": proc["cwd"], + "problem": "running OpenCode process has no session record since it started", + "fix": "keep OpenCode's data directory reachable (no XDG_DATA_HOME override)"}) return findings @@ -198,13 +224,158 @@ def bare_roots() -> dict: Reported beside the findings, never as one: a gap is a record root, not a running session. """ - from .adapters import bare, codex, grok - with bare.one_read(): - return {codex.HARNESS: bare.discover(codex.HARNESS, codex._bare_home)[1], - grok.HARNESS: bare.discover(grok.HARNESS, grok._sessions_under)[1]} + from .adapters import codex, grok + with bare_adapter.one_read(): + return {codex.HARNESS: bare_adapter.discover(codex.HARNESS, codex._bare_home)[1], + grok.HARNESS: bare_adapter.discover(grok.HARNESS, grok._sessions_under)[1]} + + +def _mtime(path: str) -> float | None: + info = path_info(path) + if info is not None and stat.S_ISREG(info.st_mode): + return info.st_mtime + return None + + +def _opencode_record_times(paths): + for path in paths: + uri = Path(path).absolute().as_uri() + "?mode=ro" + with closing(sqlite3.connect(uri, uri=True, timeout=SCAN_TIMEOUT_SECONDS)) as native: + # A message or part can advance without touching its session row. + # Read only timestamps, following the same source boundary as sync. + session_cols = {row[1] for row in native.execute("PRAGMA table_info(session)")} + if "id" not in session_cols: + raise sqlite3.DatabaseError("OpenCode session table unavailable") + timestamp_columns = ("time_created", "time_updated") + selects = [f"SELECT id AS session_id, {col} AS oldest, {col} AS newest," + f" typeof({col}) NOT IN ('integer', 'real', 'null') AS invalid FROM session" + for col in timestamp_columns if col in session_cols] + for table in ("message", "part"): + cols = {row[1] for row in native.execute(f"PRAGMA table_info({table})")} + if "session_id" in cols: + selects.extend(f"SELECT session_id, MIN({col}), MAX({col})," + f" MAX(typeof({col}) NOT IN ('integer', 'real', 'null'))" + f" FROM {table} GROUP BY session_id" + for col in timestamp_columns if col in cols) + if not selects: + raise sqlite3.DatabaseError("OpenCode session timestamps unavailable") + combined = " UNION ALL ".join(selects) + for oldest, newest, invalid in native.execute( + f"WITH activity AS ({combined})" + " SELECT MIN(oldest), MAX(newest), MAX(invalid)" + " FROM activity JOIN session ON session.id = activity.session_id" + " GROUP BY session.id"): + if invalid: + raise ValueError("invalid timestamp") + if newest is not None: + format_timestamp(oldest / 1000) + yield newest / 1000 + + +def _native_record_times(harness, paths): + from .adapters import grok + + if harness == "opencode": + yield from _opencode_record_times(paths) + return + seen_files = set() + for path in dict.fromkeys(paths): + if harness == "grok": + # One session directory can contain two independently imported logs. + times = (_mtime(os.path.join(path, name)) + for name in grok.SESSION_RECORD_FILES) + elif harness == "codex": + info = path_info(path) + if info is None or not stat.S_ISREG(info.st_mode): + continue + identity = (info.st_dev, info.st_ino) + if identity not in seen_files: + seen_files.add(identity) + yield info.st_mtime + continue + elif harness in ("t3", "router"): + times = (sqlite_mtime(path),) + else: + times = (_mtime(path),) + newest = max((stamp for stamp in times if stamp is not None), default=None) + if newest is not None: + yield newest + + +def _discover_native_paths(harness, adapter): + from .adapters import router + if harness == "t3": + return [adapter.state_path(strict=True)] + paths = adapter.discover(strict=True) + if harness == "codex": + paths.extend(router.discover_rollouts(strict=True)) + if harness == "grok": + return [os.path.realpath(path) for path in paths] + return paths + + +def _ledger_freshness(con, sync_interval_seconds, unavailable, ledger_error): + from .adapters import available, grok + + imports = {} + if con is not None: + try: + imports = {harness: (stamp,) for harness, stamp in con.execute( + "SELECT harness, MAX(imported_at) FROM sources" + " WHERE harness != 'grok' GROUP BY harness")} + imports["grok"] = grok.complete_import_watermarks(con) + except sqlite3.Error as exc: + ledger_error = error_reason(exc) + if ledger_error is not None: + unavailable.append({"check": "ledger freshness", "reason": ledger_error}) + freshness = {} + for harness, adapter in available().items(): + import_times = imports.get(harness, ()) + try: + for stamp in import_times: + format_timestamp(stamp) + except (OverflowError, OSError, TypeError, ValueError): + unavailable.append({"check": f"{harness} ledger import", "reason": "invalid timestamp"}) + freshness[harness] = {"newest_native_at": None, "newest_import_at": None, + "newer_sources": None, "lag_seconds": None, + "status": "unavailable"} + continue + imported = max((stamp for stamp in import_times if stamp is not None), default=None) + try: + paths = _discover_native_paths(harness, adapter) + records = list(_native_record_times(harness, paths)) + newest = max(records, default=None) + format_timestamp(newest) + format_timestamp(min(records, default=None)) + except (OverflowError, OSError, TypeError, ValueError, sqlite3.Error) as exc: + reason = error_reason(exc) if isinstance(exc, (OSError, sqlite3.Error)) else "invalid timestamp" + unavailable.append({"check": f"{harness} native record scan", "reason": reason}) + freshness[harness] = {"newest_native_at": None, "newest_import_at": imported, + "newer_sources": None, "lag_seconds": None, + "status": "unavailable"} + continue + newer = lag = None + if ledger_error is not None: + status = "unavailable" + elif newest is None: + newer = 0 + status = "no_native_records" + elif imported is None: + newer = len(records) + status = "never_synced" + else: + newer = sum(stamp > imported for stamp in records) + lag = max(0, newest - imported) + status = "stale" if lag > sync_interval_seconds else ( + "within_interval" if newer else "current") + freshness[harness] = {"newest_native_at": newest, "newest_import_at": imported, + "newer_sources": newer, "lag_seconds": lag, "status": status} + return freshness -def check(processes=None, registry=None, con=None, bare=None) -> dict: + +def check(processes=None, registry=None, con=None, bare=None, *, + sync_interval_seconds=DEFAULT_SYNC_INTERVAL_SECONDS, ledger_error=None) -> dict: unavailable = [] if processes is None: try: @@ -217,12 +388,27 @@ def check(processes=None, registry=None, con=None, bare=None) -> dict: unavailable.append({"check": "working directory", "host": proc["name"], "pid": proc["pid"], "reason": proc["cwd_error"]}) registry = claude_registry() if registry is None else registry - findings = check_claude(registry) + check_opencode(processes) + check_codex(processes) + findings = check_claude(registry) + try: + findings.extend(check_opencode(processes)) + except sqlite3.Error as exc: + unavailable.append({"check": "OpenCode visibility", "reason": error_reason(exc)}) + findings.extend(check_codex(processes)) from . import cue + with bare_adapter.one_read(): + freshness = _ledger_freshness(con, sync_interval_seconds, unavailable, ledger_error) + roots = bare_roots() if bare is None else bare + conflicts = None + if con is not None: + try: + conflicts = identity_conflicts(con) + except sqlite3.Error as exc: + unavailable.append({"check": "identity conflicts", "reason": error_reason(exc)}) return {"cue": cue.health(con), "findings": findings, "unavailable": unavailable, - "identity_conflicts": identity_conflicts(con) if con is not None else None, - "bare_roots": bare_roots() if bare is None else bare, + "identity_conflicts": conflicts, + "bare_roots": roots, + "ledger_freshness": freshness, "sync_interval_seconds": sync_interval_seconds, "checked": {"claude_sessions": len(registry), "processes": len(processes)}, "note": ("Codex app-server and exec sessions and OpenCode servers are not " diff --git a/tests/test_bare_roots.py b/tests/test_bare_roots.py index 80c8432..9e8ba22 100644 --- a/tests/test_bare_roots.py +++ b/tests/test_bare_roots.py @@ -547,6 +547,24 @@ def test_health_reports_gaps_beside_findings(self): [{"root": gone, "reason": "missing on this machine"}]) self.assertEqual(result["bare_roots"]["grok"]["state"], "unused") + def test_unreadable_codex_bare_root_is_unavailable(self): + root = self.bare_sessions("codex", "denied") + self.receipts(("codex", root)) + listdir = os.listdir + + def checked_listdir(path): + if path == root: + raise PermissionError("fixture bare root unreadable") + return listdir(path) + + with patch.object(os, "listdir", checked_listdir): + result = health.check(processes=[], registry=[]) + self.assertEqual(result["ledger_freshness"]["codex"]["status"], "unavailable") + self.assertIn({"check": "codex native record scan", + "reason": "permission denied"}, result["unavailable"]) + self.assertEqual(result["bare_roots"]["codex"]["gaps"], + [{"root": root, "reason": "unreadable"}]) + def test_health_without_lsof_reports_both_gaps_in_one_run(self): gone = self.bare_sessions("codex", "gone") self.receipts(("codex", gone)) diff --git a/tests/test_health.py b/tests/test_health.py index aa68474..9aedf05 100644 --- a/tests/test_health.py +++ b/tests/test_health.py @@ -4,13 +4,15 @@ import io import json import os +from pathlib import Path import sqlite3 import tempfile import time import unittest from unittest.mock import patch -from agent_observer import cli, health +from agent_observer import cli, db, health, ingest +from agent_observer.adapters import claude, codex, grok, muse, opencode, router class ScanAvailabilityTest(unittest.TestCase): @@ -20,6 +22,7 @@ def setUp(self): self.path = patch.dict(os.environ, {"PATH": self.tmp.name}) self.path.start() self.addCleanup(self.path.stop) + self.enterContext(patch.object(health, "_ledger_freshness", return_value={})) self.tool("ps", "printf '201 Mon Oct 19 10:00:00 2026 codex\\n'") def tool(self, name, body): @@ -162,7 +165,8 @@ def test_each_cue_status_remains_visible_with_appropriate_exit(self): with self.subTest(status=status,json=as_json): result={'checked': {'claude_sessions':0,'processes':0}, 'findings':[],'unavailable':[],'identity_conflicts':[], - 'bare_roots':{},'cue':{'status':status}} + 'bare_roots':{},'cue':{'status':status}, + 'ledger_freshness':{},'sync_interval_seconds':3600} output=io.StringIO() with patch.object(health,'check',return_value=result), \ contextlib.redirect_stdout(output): @@ -175,6 +179,746 @@ def test_each_cue_status_remains_visible_with_appropriate_exit(self): self.assertIn('Cue evidence: '+status,output.getvalue()) +class LedgerFreshnessTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.ledger = self.root / "observer.db" + for adapter in (claude, codex, grok, muse, opencode, router): + self.enterContext(patch.object(adapter, "DEFAULT_ROOT", + str(self.root / adapter.HARNESS))) + self.enterContext(patch.object(codex, "ARCHIVE_ROOT", str(self.root / "archive"))) + self.enterContext(patch.object(router, "LEGACY_ROOT", str(self.root / "legacy"))) + self.enterContext(patch.dict(os.environ, {"T3CODE_HOME": str(self.root / "t3"), + "DURABLE_RUNNER_STATE_DIR": ""})) + self.enterContext(patch.object(health, "process_table", return_value=[])) + self.enterContext(patch.object(health, "claude_registry", return_value=[])) + self.enterContext(patch("agent_observer.cue.health", return_value={"status": "no_cue"})) + + def source(self, path, modified_at): + path = self.root / path + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("private fixture text that health must never print") + os.utime(path, (modified_at, modified_at)) + + def imports(self, **harness_times): + with contextlib.closing(db.connect(str(self.ledger))) as con, con: + db.init_db(con) + con.executemany( + "INSERT INTO sources(harness, path, sha256, imported_at) VALUES(?,?,?,?)", + [(harness, "fixture", "hash", stamp) for harness, stamp in harness_times.items()]) + + def run_health(self, *args): + out = io.StringIO() + with contextlib.redirect_stdout(out): + code = cli.main(["--db", str(self.ledger), "health", *args]) + self.assertNotIn("private fixture text", out.getvalue()) + return code, out.getvalue() + + def test_stale_harness_is_not_hidden_by_a_fresher_import_from_another(self): + self.source("claude/project/old.jsonl", 10_000) + self.source("claude/project/new.jsonl", 22_000) + self.source("claude/project/new/subagents/agent-child.jsonl", 20_000) + self.source("archive/rollout-old-thread.jsonl", 18_000) + self.imports(claude=11_000, codex=23_000) + + code, output = self.run_health("--json") + self.assertEqual(code, 4) + result = json.loads(output) + self.assertEqual(result["sync_interval_seconds"], 3600) + self.assertEqual(result["ledger_freshness"]["claude"], { + "newest_native_at": 22_000, "newest_import_at": 11_000, + "newer_sources": 2, "lag_seconds": 11_000, "status": "stale", + }) + self.assertEqual(result["ledger_freshness"]["codex"]["newer_sources"], 0) + self.assertEqual(result["ledger_freshness"]["codex"]["newest_native_at"], 18_000) + code, output = self.run_health() + self.assertEqual(code, 4) + self.assertIn("claude: stale", output) + self.assertIn("11000 seconds", output) + self.assertIn("2 newer sources", output) + + def test_current_and_within_interval(self): + self.source("claude/project/recent.jsonl", 14_600) + self.source("grok/project/session/updates.jsonl", 11_000) + self.source("grok/project/session/events.jsonl", 10_000) + self.imports(claude=11_000, grok=10_000) + + code, output = self.run_health("--json") + self.assertEqual(code, 0) + freshness = json.loads(output)["ledger_freshness"] + self.assertEqual(freshness["claude"]["newer_sources"], 1) + self.assertEqual(freshness["claude"]["status"], "within_interval") + self.assertEqual(freshness["grok"]["newer_sources"], 1) + self.assertEqual(freshness["codex"]["status"], "no_native_records") + self.assertEqual(freshness["muse"]["status"], "no_native_records") + self.assertEqual(self.run_health("--sync-interval-seconds", "3599")[0], 4) + + def test_missing_or_empty_ledger_names_never_synced_harness(self): + self.source("grok/project/session/updates.jsonl", 10_000) + self.source("grok/project/session/events.jsonl", 11_000) + for create in (False, True): + with self.subTest(create=create): + if create: + self.imports() + code, output = self.run_health("--json") + self.assertEqual(code, 4) + self.assertEqual(json.loads(output)["ledger_freshness"]["grok"], { + "newest_native_at": 11_000, "newest_import_at": None, + "newer_sources": 1, "lag_seconds": None, "status": "never_synced", + }) + self.assertIn("grok: never synced", self.run_health()[1]) + + def test_opencode_counts_sessions_with_newer_parts_in_wal(self): + path = self.root / "opencode" + with contextlib.closing(sqlite3.connect(path)) as native: + native.execute("PRAGMA journal_mode=WAL") + native.executescript(""" + CREATE TABLE session (id TEXT, time_updated INTEGER); + CREATE TABLE part (session_id TEXT, time_updated INTEGER, data TEXT); + INSERT INTO session VALUES ('first', 10000000), ('second', 11000000); + INSERT INTO part VALUES ('first', 19900000, 'private fixture text'), + ('first', 20000000, 'private fixture text'), + ('second', NULL, 'private fixture text'); + """) + self.imports(opencode=11_000) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + self.assertEqual(json.loads(output)["ledger_freshness"]["opencode"], { + "newest_native_at": 20_000, "newest_import_at": 11_000, + "newer_sources": 1, "lag_seconds": 9_000, "status": "stale", + }) + + def test_opencode_counts_child_creation_without_an_update(self): + with contextlib.closing(sqlite3.connect(self.root / "opencode")) as native: + native.executescript(""" + CREATE TABLE session (id TEXT, time_updated INTEGER); + CREATE TABLE message (session_id TEXT, time_created INTEGER, time_updated INTEGER); + CREATE TABLE part (session_id TEXT, time_created INTEGER); + INSERT INTO session VALUES ('first', 10000000), ('second', 11000000); + INSERT INTO message VALUES ('first', 19000000, NULL); + INSERT INTO part VALUES ('second', 20000000); + """) + self.imports(opencode=11_000) + code, output = self.run_health() + self.assertEqual(code, 4) + self.assertIn("opencode: stale", output) + self.assertIn("2 newer sources", output) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + self.assertEqual(json.loads(output)["ledger_freshness"]["opencode"], { + "newest_native_at": 20_000, "newest_import_at": 11_000, + "newer_sources": 2, "lag_seconds": 9_000, "status": "stale", + }) + + def test_opencode_visibility_query_failure_keeps_freshness_available(self): + path = self.root / "opencode" + self.source("claude/project/fixture.jsonl", 20_000) + self.imports(claude=11_000) + process = {"pid": 201, "name": "opencode", "command": "opencode", "cwd": "/fixture"} + check_opencode = health.check_opencode + with patch.object(health, "process_table", return_value=[process]), \ + patch.object(health, "check_opencode", + side_effect=lambda processes: check_opencode(processes, str(path))): + for corrupt in (False, True): + with self.subTest(corrupt=corrupt): + if corrupt: + path.write_bytes(b"private fixture text") + else: + with contextlib.closing(sqlite3.connect(path)) as native: + native.executescript(""" + CREATE TABLE session (id TEXT, directory TEXT, time_created INTEGER); + INSERT INTO session VALUES ('session', '/fixture', 20000000); + """) + code, output = self.run_health() + self.assertEqual(code, 4) + self.assertIn("OpenCode visibility unavailable:", output) + self.assertIn("claude: stale", output) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + result = json.loads(output) + self.assertIn("OpenCode visibility", + [check["check"] for check in result["unavailable"]]) + self.assertEqual(result["ledger_freshness"]["claude"]["status"], "stale") + self.assertEqual(result["ledger_freshness"]["opencode"]["status"], + "unavailable" if corrupt else "never_synced") + + def test_unreadable_ledger_is_not_mistaken_for_never_synced(self): + self.source("observer.db", 10_000) + self.source("claude/project/new.jsonl", 20_000) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + result = json.loads(output) + self.assertEqual(result["ledger_freshness"]["claude"]["status"], "unavailable") + self.assertEqual(result["unavailable"][0]["check"], "ledger freshness") + + def test_router_rollouts_contribute_to_codex_freshness(self): + self.source("router/jobs.db", 10_000) + self.source("router/kits/kit/sessions/2026/rollout-kit.jsonl", 20_000) + self.source("router/codex-sessions/2026/rollout-shared.jsonl", 21_000) + self.imports(codex=11_000, router=11_000) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + rows = json.loads(output)["ledger_freshness"] + self.assertEqual(rows["codex"]["status"], "stale") + self.assertEqual(rows["codex"]["newest_native_at"], 21_000) + self.assertEqual(rows["codex"]["newer_sources"], 2) + self.assertEqual(rows["router"]["status"], "current") + + def test_unreadable_grok_directory_is_reported_as_unavailable(self): + self.source("grok/project/session/updates.jsonl", 20_000) + self.imports(grok=11_000) + listdir = os.listdir + for unreadable in (self.root / "grok", self.root / "grok/project"): + def checked_listdir(path): + if Path(path) == unreadable: + raise PermissionError("fixture directory unreadable") + return listdir(path) + + with self.subTest(unreadable=unreadable), \ + patch.object(grok.os, "listdir", side_effect=checked_listdir): + code, output = self.run_health("--json") + self.assertEqual(code, 4) + result = json.loads(output) + self.assertEqual(result["ledger_freshness"]["grok"]["status"], "unavailable") + self.assertIn({"check": "grok native record scan", + "reason": "permission denied"}, result["unavailable"]) + + def test_failed_identity_query_preserves_freshness_json(self): + self.source("claude/project/new.jsonl", 20_000) + self.imports(claude=11_000) + with contextlib.closing(sqlite3.connect(self.ledger)) as con: + con.execute("DROP TABLE import_errors") + code, output = self.run_health("--json") + self.assertEqual(code, 4) + result = json.loads(output) + self.assertIsNone(result["identity_conflicts"]) + self.assertEqual(result["unavailable"][0]["check"], "identity conflicts") + self.assertEqual(result["ledger_freshness"]["claude"]["status"], "stale") + + def test_denied_listing_in_glob_layouts_is_unavailable(self): + self.source("claude/project/new.jsonl", 20_000) + self.source("codex/2026/11/rollout-normal.jsonl", 20_000) + self.source("router/codex-sessions/2026/rollout-owned.jsonl", 20_000) + self.source("muse/2026/11/25/session/session.jsonl", 20_000) + self.imports(claude=11_000, codex=11_000, muse=11_000) + listdir = os.listdir + scandir = os.scandir + for harness, folder in ( + ("claude", "claude/project"), ("codex", "codex/2026/11"), + ("codex", "router/codex-sessions/2026"), ("muse", "muse/2026/11")): + def checked_listdir(path): + if path == str(self.root / folder): + raise PermissionError("fixture directory unreadable") + return listdir(path) + + def checked_scandir(path): + if path == str(self.root / folder): + raise PermissionError("fixture directory unreadable") + return scandir(path) + + with self.subTest(folder=folder), patch.object(os, "listdir", checked_listdir), \ + patch.object(os, "scandir", checked_scandir): + code, output = self.run_health("--json") + self.assertEqual(code, 4) + result = json.loads(output) + self.assertEqual(result["ledger_freshness"][harness]["status"], "unavailable") + self.assertIn({"check": f"{harness} native record scan", + "reason": "permission denied"}, result["unavailable"]) + + def test_grok_file_stat_permission_failure_is_unavailable(self): + path = "grok/project/session/updates.jsonl" + self.source(path, 20_000) + self.imports(grok=11_000) + stat = os.stat + + def checked_stat(target, *args, **kwargs): + if target == str(self.root / path): + raise PermissionError("fixture record unreachable") + return stat(target, *args, **kwargs) + + with patch.object(os, "stat", checked_stat): + code, output = self.run_health("--json") + self.assertEqual(code, 4) + result = json.loads(output) + self.assertEqual(result["ledger_freshness"]["grok"]["status"], "unavailable") + self.assertIn({"check": "grok native record scan", + "reason": "permission denied"}, result["unavailable"]) + + def test_freshness_scan_does_not_render_private_source_path(self): + from errno import EACCES + + native = self.root / "claude/private-project-name" + error = PermissionError(EACCES, "Permission denied", str(native)) + with patch.object(claude, "discover", side_effect=error): + for args in ((), ("--json",)): + with self.subTest(args=args): + code, output = self.run_health(*args) + self.assertEqual(code, 4) + self.assertIn("permission denied", output) + self.assertNotIn("private-project-name", output) + + def test_health_keeps_ledger_permission_diagnostic_path_free(self): + from errno import EACCES + + stat = os.stat + + def checked_stat(path, *args, **kwargs): + if path == str(self.ledger): + raise PermissionError(EACCES, "Permission denied", "/private-ledger/observer.db") + return stat(path, *args, **kwargs) + + with patch.object(os, "stat", checked_stat): + for args in ((), ("--json",)): + code, output = self.run_health(*args) + self.assertEqual(code, 4) + self.assertIn("permission denied", output) + self.assertNotIn("private-ledger", output) + + def test_out_of_range_opencode_time_reports_unavailable_in_both_formats(self): + with contextlib.closing(sqlite3.connect(self.root / "opencode")) as native: + native.executescript("CREATE TABLE session(id TEXT, time_updated INTEGER);" + "INSERT INTO session VALUES ('fixture', 1760000000000000);") + self.source("claude/project/fixture.jsonl", 10_000) + self.imports(claude=11_000) + code, output = self.run_health() + self.assertEqual(code, 4) + self.assertIn("opencode native record scan unavailable: invalid timestamp", output) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + rows = json.loads(output)["ledger_freshness"] + self.assertEqual(rows["opencode"]["status"], "unavailable") + self.assertEqual(rows["claude"]["status"], "current") + + def test_malformed_opencode_time_does_not_hide_newer_session(self): + with contextlib.closing(sqlite3.connect(self.root / "opencode")) as native: + native.executescript(""" + CREATE TABLE session(id TEXT, time_updated INTEGER); + CREATE TABLE message(session_id TEXT, time_updated INTEGER); + INSERT INTO session VALUES ('fixture', 20000000); + INSERT INTO message VALUES ('fixture', NULL), ('fixture', 'private fixture text'); + """) + self.source("claude/project/fixture.jsonl", 10_000) + self.imports(claude=11_000, opencode=11_000) + code, output = self.run_health() + self.assertEqual(code, 4) + self.assertIn("opencode native record scan unavailable: invalid timestamp", output) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + rows = json.loads(output)["ledger_freshness"] + self.assertEqual(rows["opencode"]["status"], "unavailable") + self.assertEqual(rows["claude"]["status"], "current") + + def test_malformed_grok_import_time_leaves_other_harnesses_available(self): + self.source("claude/project/fixture.jsonl", 10_000) + self.source("grok/project/session/events.jsonl", 20_000) + self.imports(claude=11_000, grok=11_000) + with contextlib.closing(db.connect(str(self.ledger))) as con, con: + con.executescript(""" + CREATE TABLE grok_session_meta(session_key TEXT, imported_at REAL); + INSERT INTO grok_session_meta VALUES ('grok:fixture', 'private fixture text'); + """) + code, output = self.run_health() + self.assertEqual(code, 4) + self.assertIn("grok ledger import unavailable: invalid timestamp", output) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + rows = json.loads(output)["ledger_freshness"] + self.assertEqual(rows["grok"]["status"], "unavailable") + self.assertEqual(rows["claude"]["status"], "current") + + def test_denied_chromeria_v2_state_is_unavailable_for_state_and_receipts(self): + path = self.root / "t3/userdata/chromeria-v2.sqlite" + path.parent.mkdir(parents=True) + stat = os.stat + + def checked_stat(target, *args, **kwargs): + if target == str(path): + raise PermissionError("fixture V2 state unreachable") + return stat(target, *args, **kwargs) + + with patch.object(os, "stat", checked_stat): + code, output = self.run_health("--json") + self.assertEqual(code, 4) + rows = json.loads(output)["ledger_freshness"] + for harness in ("t3", "codex", "grok"): + self.assertEqual(rows[harness]["status"], "unavailable") + + def test_grok_metadata_only_lag_clears_after_import(self): + session = self.root / "grok/project/session-one" + session.mkdir(parents=True) + summary = session / "summary.json" + summary.write_text('{"info":{"id":"session-one"}}') + os.utime(summary, (20_000, 20_000)) + self.imports(grok=11_000) + + code, output = self.run_health("--json") + self.assertEqual(code, 4) + self.assertEqual(json.loads(output)["ledger_freshness"]["grok"]["newer_sources"], 1) + + with contextlib.closing(db.connect(str(self.ledger))) as con: + self.assertEqual(grok.sync(con)["failed"], []) + self.assertEqual(con.execute("SELECT COUNT(*) FROM sessions").fetchone()[0], 1) + code, output = self.run_health("--json") + self.assertEqual(code, 0) + row = json.loads(output)["ledger_freshness"]["grok"] + self.assertEqual(row["status"], "current") + self.assertGreaterEqual(row["newest_import_at"], 20_000) + + with contextlib.closing(db.connect(str(self.ledger))) as con: + con.execute("UPDATE grok_session_meta SET imported_at=NULL") + con.commit() + self.assertEqual(grok.sync(con)["failed"], []) + self.assertEqual(self.run_health("--json")[0], 0) + + def test_codex_counts_hard_linked_rollouts_once(self): + self.source("codex/2026/rollout-first.jsonl", 20_000) + os.link(self.root / "codex/2026/rollout-first.jsonl", + self.root / "codex/2026/rollout-alias.jsonl") + self.imports(codex=11_000) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + self.assertEqual(json.loads(output)["ledger_freshness"]["codex"]["newer_sources"], 1) + + def test_grok_revalidates_identical_metadata_and_retries_denied_reads(self): + summary = self.root / "grok/project/session-one/summary.json" + self.source("grok/project/session-one/summary.json", 10_000) + summary.write_text('{"info":{"id":"session-one"}}') + os.utime(summary, (10_000, 10_000)) + self.imports() + with contextlib.closing(db.connect(str(self.ledger))) as con: + with patch.object(db, "now", return_value=11_000): + self.assertEqual(grok.sync(con)["failed"], []) + os.utime(summary, (20_000, 20_000)) + self.assertEqual(self.run_health("--json")[0], 4) + with patch.object(db, "now", return_value=21_000): + self.assertEqual(grok.sync(con)["failed"], []) + self.assertEqual(self.run_health("--json")[0], 0) + summary.write_text('{"info":{"id":"session-one"},"head_branch":"fresh"}') + os.utime(summary, (30_000, 30_000)) + real_open = open + + def denied_open(path, *args, **kwargs): + if path == str(summary): + raise PermissionError("fixture refused summary read") + return real_open(path, *args, **kwargs) + + with patch("builtins.open", denied_open), patch.object(db, "now", return_value=31_000): + self.assertEqual(len(grok.sync(con)["failed"]), 1) + self.assertEqual(grok.newest_metadata_import(con), 21_000) + self.assertEqual(self.run_health("--json")[0], 4) + with patch.object(db, "now", return_value=32_000): + self.assertEqual(grok.sync(con)["failed"], []) + self.assertEqual(self.run_health("--json")[0], 0) + + def test_chromeria_freshness_follows_symlink_to_wal(self): + link = self.root / "t3/userdata/chromeria-v2.sqlite" + link.parent.mkdir(parents=True) + target = self.root / "native.sqlite" + link.symlink_to(target) + self.imports(t3=11_000) + with contextlib.closing(sqlite3.connect(target)) as native: + native.execute("PRAGMA journal_mode=WAL") + native.executescript("CREATE TABLE evidence(value); INSERT INTO evidence VALUES (1);") + os.utime(target, (10_000, 10_000)) + os.utime(str(target) + "-wal", (20_000, 20_000)) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + row = json.loads(output)["ledger_freshness"]["t3"] + self.assertEqual(row["newest_native_at"], 20_000) + self.assertEqual(row["status"], "stale") + + def test_grok_retry_keeps_recorded_identity_and_counts_alias_once(self): + record_path = self.root / "grok/project/directory-id/updates.jsonl" + record_path.parent.mkdir(parents=True) + summary = record_path.with_name("summary.json") + summary.write_text(json.dumps({"info": {"id": "native-id"}, + "current_model_id": "grok-4", + "reasoning_effort": "high"})) + os.utime(summary, (10_000, 10_000)) + alias = record_path.parent.with_name("alias") + alias.symlink_to(record_path.parent, target_is_directory=True) + + def append_completion(prompt, stamp): + completion = {"timestamp": stamp, "method": "_x.ai/session/update", + "params": {"sessionId": "native-id", "update": { + "sessionUpdate": "turn_completed", "prompt_id": prompt, + "usage": {"inputTokens": 10, "outputTokens": 2}}}} + with record_path.open("a") as file: + file.write(json.dumps(completion) + "\n") + os.utime(record_path, (stamp, stamp)) + + append_completion("first", 10_000) + self.imports() + real_open = open + + def denied_open(path, *args, **kwargs): + if os.path.basename(path) == "summary.json": + raise PermissionError("fixture refused summary read") + return real_open(path, *args, **kwargs) + + with contextlib.closing(db.connect(str(self.ledger))) as con: + with patch.object(db, "now", return_value=11_000), patch.object(ingest, "now", return_value=11_000): + self.assertEqual(grok.sync(con)["failed"], []) + append_completion("second", 20_000) + for stamp in (21_000, 21_500): + with patch("builtins.open", denied_open), patch.object(db, "now", return_value=stamp), \ + patch.object(ingest, "now", return_value=stamp): + self.assertTrue(grok.sync(con)["failed"]) + source = con.execute("SELECT session_id, imported_at FROM sources").fetchone() + self.assertEqual(tuple(source), ("native-id", 21_000)) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + self.assertEqual(json.loads(output)["ledger_freshness"]["grok"]["newer_sources"], 1) + with patch.object(db, "now", return_value=22_000), patch.object(ingest, "now", return_value=22_000): + self.assertEqual(grok.sync(con)["failed"], []) + rows = con.execute("SELECT DISTINCT session_key, model, effort FROM responses").fetchall() + self.assertEqual([tuple(row) for row in rows], [("grok:native-id", "grok-4", "high")]) + self.assertEqual(con.execute("SELECT COUNT(*) FROM responses").fetchone()[0], 2) + self.assertEqual(self.run_health("--json")[0], 0) + + def test_bad_grok_summary_keeps_transcript_ingestion(self): + updates = "grok/project/session-one/updates.jsonl" + self.source(updates, 20_000) + completion = {"timestamp": 20_000, "method": "_x.ai/session/update", + "params": {"sessionId": "session-one", + "update": {"sessionUpdate": "turn_completed", + "prompt_id": "prompt-one", + "usage": {"inputTokens": 10, "outputTokens": 2}}}} + (self.root / updates).write_text(json.dumps(completion) + "\n") + (self.root / "grok/project/session-one/summary.json").write_text('{"incomplete":') + self.imports() + with contextlib.closing(db.connect(str(self.ledger))) as con: + result = grok.sync(con) + self.assertEqual(result["responses_inserted"], 1) + self.assertEqual(result["failed"][0]["error"], "invalid Grok summary JSON") + self.assertIsNone(grok.newest_metadata_import(con)) + self.assertGreater(con.execute( + "SELECT imported_at FROM sources WHERE harness='grok'").fetchone()[0], 0) + code, output = self.run_health("--json") + self.assertEqual(code, 4) + self.assertEqual(json.loads(output)["ledger_freshness"]["grok"]["status"], "never_synced") + + summary = self.root / "grok/project/session-one/summary.json" + summary.write_text('{"info":{"id":"session-one"}}') + with contextlib.closing(db.connect(str(self.ledger))) as con: + self.assertEqual(grok.sync(con)["failed"], []) + self.assertIsNotNone(grok.newest_metadata_import(con)) + self.assertEqual(self.run_health("--json")[0], 0) + + def test_grok_first_partial_transcript_uses_native_notification_id(self): + folder = self.root / "grok/project/directory-id" + folder.mkdir(parents=True) + summary = folder / "summary.json" + summary.write_text('{"info":{"id":"native-id"},"current_model_id":"grok-4"}') + os.utime(summary, (10_000, 10_000)) + self.imports() + real_open = open + + def denied_open(path, *args, **kwargs): + if path == str(summary): + raise PermissionError("fixture refused summary read") + return real_open(path, *args, **kwargs) + + with contextlib.closing(db.connect(str(self.ledger))) as con: + with patch.object(db, "now", return_value=11_000): + self.assertEqual(grok.sync(con)["failed"], []) + update = folder / "updates.jsonl" + completion = {"timestamp": 20_000, "method": "_x.ai/session/update", + "params": {"sessionId": "native-id", "update": { + "sessionUpdate": "turn_completed", "prompt_id": "first", + "usage": {"inputTokens": 10, "outputTokens": 2}}}} + update.write_text(json.dumps(completion) + "\n") + os.utime(update, (20_000, 20_000)) + with patch("builtins.open", denied_open), patch.object(db, "now", return_value=21_000), \ + patch.object(ingest, "now", return_value=21_000): + self.assertTrue(grok.sync(con)["failed"]) + self.assertEqual(self.run_health("--json")[0], 4) + with patch.object(db, "now", return_value=22_000), patch.object(ingest, "now", return_value=22_000): + self.assertEqual(grok.sync(con)["failed"], []) + rows = con.execute("SELECT session_key, model FROM responses").fetchall() + self.assertEqual([tuple(row) for row in rows], [("grok:native-id", "grok-4")]) + self.assertEqual(self.run_health("--json")[0], 0) + + def test_grok_waits_for_summary_when_first_log_has_no_native_id(self): + folder = self.root / "grok/project/directory-id" + folder.mkdir(parents=True) + summary = folder / "summary.json" + summary.write_text('{"info":{"id":"native-id"},"current_model_id":"grok-4"}') + self.imports() + (folder / "events.jsonl").write_text("{}\n") + real_open = open + + def denied_open(path, *args, **kwargs): + if path == str(summary): + raise PermissionError("fixture refused summary read") + return real_open(path, *args, **kwargs) + + with contextlib.closing(db.connect(str(self.ledger))) as con: + with patch("builtins.open", denied_open): + self.assertTrue(grok.sync(con)["failed"]) + self.assertEqual(con.execute("SELECT COUNT(*) FROM sessions").fetchone()[0], 0) + completion = {"timestamp": 20_000, "method": "_x.ai/session/update", + "params": {"update": {"sessionUpdate": "turn_completed", + "prompt_id": "first", + "usage": {"inputTokens": 10, "outputTokens": 2}}}} + (folder / "updates.jsonl").write_text(json.dumps(completion) + "\n") + with patch("builtins.open", denied_open): + self.assertTrue(grok.sync(con)["failed"]) + self.assertEqual(con.execute("SELECT COUNT(*) FROM responses").fetchone()[0], 0) + summary.write_text('{"info":{"id":"native-id"},"current_model_id":"grok-4"}') + self.assertEqual(grok.sync(con)["failed"], []) + rows = con.execute("SELECT session_key FROM sessions").fetchall() + self.assertEqual([row[0] for row in rows], ["grok:native-id"]) + self.assertEqual(con.execute("SELECT session_key FROM responses").fetchone()[0], + "grok:native-id") + self.assertEqual(self.run_health("--json")[0], 0) + + def test_grok_first_event_supplies_native_id_without_summary(self): + self.source("grok/project/directory-id/events.jsonl", 20_000) + event = self.root / "grok/project/directory-id/events.jsonl" + event.write_text('{"type":"turn_started","session_id":"native-id",' + '"ts":"2026-11-25T18:00:00Z"}\n') + event.with_name("updates.jsonl").write_text( + '{"method":"session/update","params":{"sessionId":"wrong-id"}}\n' + '{"method":"session/update","params":{"sessionId":"wrong-id",' + '"update":{"sessionUpdate":"unrecognized"}}}\n' + '{"method":"session/update","params":{"sessionId":"wrong-id",' + '"update":{"sessionUpdate":"tool_call"}}}\n') + self.imports() + with contextlib.closing(db.connect(str(self.ledger))) as con: + result = grok.sync(con) + self.assertEqual(result["failed"], []) + self.assertEqual(result["events_inserted"], 1) + self.assertEqual(con.execute("SELECT session_key FROM events").fetchone()[0], + "grok:native-id") + + def test_grok_readable_summary_can_fall_back_to_directory_id(self): + folder = self.root / "grok/project/directory-id" + folder.mkdir(parents=True) + (folder / "summary.json").write_text('{"head_branch":"main"}') + (folder / "events.jsonl").write_text( + '{"type":"turn_ended","ts":"2026-11-25T18:00:00Z","outcome":"completed"}\n') + self.imports() + with contextlib.closing(db.connect(str(self.ledger))) as con: + self.assertEqual(grok.sync(con)["failed"], []) + self.assertEqual(con.execute("SELECT session_key FROM events").fetchone()[0], + "grok:directory-id") + (folder / "summary.json").write_text('{"info":{"id":"native-id"}}') + with (folder / "events.jsonl").open("a") as file: + file.write('{"type":"turn_started","ts":"2026-11-25T18:01:00Z"}\n') + self.assertEqual(grok.sync(con)["failed"], []) + self.assertEqual(con.execute( + "SELECT session_key FROM events WHERE name='turn_started'").fetchone()[0], + "grok:native-id") + + def test_grok_valid_tool_call_supplies_id_with_bad_summary(self): + folder = self.root / "grok/project/directory-id" + folder.mkdir(parents=True) + (folder / "summary.json").write_text('{"incomplete":') + (folder / "updates.jsonl").write_text( + '{"method":"session/update","params":{"sessionId":"wrong-id",' + '"update":{"sessionUpdate":"tool_call"}}}\n' + '{"method":"session/update","params":{"sessionId":"native-id",' + '"update":{"sessionUpdate":"tool_call","toolCallId":"call-one"}}}\n') + self.imports() + with contextlib.closing(db.connect(str(self.ledger))) as con: + result = grok.sync(con) + self.assertEqual(result["failed"][0]["error"], "invalid Grok summary JSON") + self.assertEqual(result["events_inserted"], 1) + self.assertEqual(con.execute("SELECT session_key FROM events").fetchone()[0], + "grok:native-id") + + def test_grok_message_updates_supply_id_with_bad_summary(self): + folder = self.root / "grok/project/directory-id" + folder.mkdir(parents=True) + (folder / "summary.json").write_text('{"incomplete":') + updates = [ + {"method": "session/update", "params": { + "sessionId": "native-id", "update": { + "sessionUpdate": kind, "content": {"type": "text", "text": "fixture"}, + "_meta": {"promptIndex": 0}}, + "_meta": {"promptId": "prompt-one", "promptIndex": 0}}} + for kind in ("user_message_chunk", "agent_message_chunk") + ] + (folder / "updates.jsonl").write_text("".join(json.dumps(row) + "\n" for row in updates)) + self.imports() + with contextlib.closing(db.connect(str(self.ledger))) as con: + result = grok.sync(con) + self.assertEqual(result["failed"][0]["error"], "invalid Grok summary JSON") + self.assertEqual(con.execute("SELECT session_key FROM user_messages").fetchone()[0], + "grok:native-id") + self.assertEqual(con.execute( + "SELECT session_key FROM events WHERE family='assistant_message'").fetchone()[0], + "grok:native-id") + + def test_grok_compaction_and_extension_updates_supply_native_identity(self): + self.imports() + for kind in ("auto_compact_started", "retry_state"): + folder = self.root / "grok/project" / kind + folder.mkdir(parents=True) + (folder / "summary.json").write_text('{"incomplete":') + update = {"method": "session/update", "params": { + "sessionId": f"{kind}-native", "update": {"sessionUpdate": kind}}} + (folder / "updates.jsonl").write_text(json.dumps(update) + "\n") + with contextlib.closing(db.connect(str(self.ledger))) as con: + stats = grok.sync(con) + self.assertEqual([item["error"] for item in stats["failed"]], + ["invalid Grok summary JSON"] * 2) + rows = con.execute("SELECT session_key, name FROM events ORDER BY name").fetchall() + self.assertEqual([tuple(row) for row in rows], [ + ("grok:auto_compact_started-native", "auto_compact_started"), + ("grok:retry_state-native", "retry_state"), + ]) + + def test_bad_grok_metadata_keeps_health_stale(self): + cases = ( + ("summary.json", '{"incomplete":', "updates.jsonl", "{}\n", False, None), + ("summary.json", '{"incomplete":', "events.jsonl", "", False, None), + ("summary.json", '{"incomplete":', "updates.jsonl", "{}\n", True, None), + ("summary.json", '{"incomplete":', "updates.jsonl", "{}\n", False, ""), + ("summary.json", '{"incomplete":', "updates.jsonl", "{}\n", False, "{"), + ("chat_history.jsonl", "invalid json\n", None, "", False, None), + ) + for filename, content, log, log_content, full, append in cases: + with self.subTest(filename=filename, log=log, full=full, append=append), \ + tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) + session = base / "grok/project/session-one" + session.mkdir(parents=True) + if log is not None: + transcript = session / log + transcript.write_text(log_content) + os.utime(transcript, (10_000, 10_000)) + summary = session / "summary.json" + summary.write_text('{"info":{"id":"session-one"},"head_branch":"fixture"}') + os.utime(summary, (10_000, 10_000)) + ledger = base / "observer.db" + with contextlib.closing(db.connect(str(ledger))) as con: + db.init_db(con) + with patch.object(db, "now", return_value=11_000), \ + patch.object(ingest, "now", return_value=11_000): + self.assertEqual(grok.sync(con, root=str(base / "grok"))["failed"], []) + metadata = session / filename + metadata.write_text(content) + os.utime(metadata, (20_000, 20_000)) + if append is not None: + with transcript.open("a") as file: + file.write(append) + os.utime(transcript, (20_000, 20_000)) + with patch.object(db, "now", return_value=21_000), \ + patch.object(ingest, "now", return_value=21_000): + result = grok.sync(con, root=str(base / "grok"), full=full) + self.assertTrue(result["failed"]) + self.assertEqual(grok.newest_metadata_import(con), 11_000) + with patch.object(grok, "DEFAULT_ROOT", str(base / "grok")), \ + patch.object(self, "ledger", ledger): + code, output = self.run_health("--json") + self.assertEqual(code, 4) + self.assertEqual(json.loads(output)["ledger_freshness"]["grok"]["status"], "stale") + + class ClaudeVisibilityTest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() @@ -228,6 +972,18 @@ def test_opencode_process_without_session_record(self): findings = health.check_opencode(self.procs("opencode", "opencode"), self.db) self.assertEqual([f["pid"] for f in findings], [202]) + def test_opencode_process_with_malformed_session_timestamp(self): + with contextlib.closing(sqlite3.connect(self.db)) as con, con: + con.execute("UPDATE session SET time_updated = 'invalid'") + findings = health.check_opencode(self.procs("opencode", "opencode"), self.db) + self.assertEqual([f["pid"] for f in findings], [201, 202]) + + def test_opencode_visibility_keeps_valid_session_beside_malformed_timestamp(self): + with contextlib.closing(sqlite3.connect(self.db)) as con, con: + con.execute("INSERT INTO session VALUES ('invalid', '/p/seen', 'invalid')") + findings = health.check_opencode(self.procs("opencode", "opencode"), self.db) + self.assertEqual([f["pid"] for f in findings], [202]) + def test_codex_cli_without_rollout(self): findings = health.check_codex(self.procs("codex", "codex"), os.path.join(self.tmp.name, "sessions")) diff --git a/tests/test_router.py b/tests/test_router.py index aba12cc..eff4c07 100644 --- a/tests/test_router.py +++ b/tests/test_router.py @@ -1508,6 +1508,33 @@ def counting_import_job(con, db_path, job, totals): self.assertEqual(stats["bindings"], first["bindings"]) self.assertEqual(stats["bindings"], 7) + def test_unchanged_source_revalidates_newer_database_mtime(self): + from unittest.mock import patch + + with patch.object(router.db, "now", return_value=11_000): + self.assertEqual(router.sync(self.con, root=self.state)["failed"], []) + os.utime(self.db_path, (20_000, 20_000)) + with patch.object(router.db, "now", return_value=21_000): + stats = router.sync(self.con, root=self.state) + self.assertEqual(stats["unchanged"], 1) + self.assertEqual(stats["failed"], []) + row = self.con.execute( + "SELECT imported_at FROM sources WHERE harness='router'").fetchone() + self.assertEqual(row["imported_at"], 21_000) + + def test_router_sync_keeps_importing_when_timestamp_probe_is_denied(self): + from unittest.mock import patch + + with patch.object(router, "sqlite_mtime", side_effect=PermissionError("WAL denied")): + self.assertEqual(router.sync(self.con, root=self.state)["failed"], []) + query = "SELECT imported_at FROM sources WHERE harness='router'" + recorded = self.con.execute(query).fetchone()[0] + with patch.object(router.db, "now", return_value=recorded + 100): + result = router.sync(self.con, root=self.state) + self.assertEqual(result["failed"], []) + self.assertEqual(result["unchanged"], 1) + self.assertEqual(self.con.execute(query).fetchone()[0], recorded) + def test_stale_source_version_refreshes_and_replaces_errors(self): src = sqlite3.connect(self.db_path) src.execute(