"""A readable dump of a state store, for bring-up runs and debugging. python -m nisse_dev.dump STATE_DB [--full] Opens the store read-only (SQLite `mode=ro`), so it is safe to run against a live agent's database: it never migrates, writes or locks it. Prints the work items and which is active, pending intents, and the canonical log, one event per line with its work item and actor; long texts are shortened unless `--full` is given. """ import argparse import json import sqlite3 import sys from pathlib import Path from typing import Any SHORT = 160 # characters of each text shown without --full def _connect(path: Path) -> sqlite3.Connection: conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True) conn.row_factory = sqlite3.Row return conn def _clip(text: str, full: bool) -> str: text = text.replace("\n", " ⏎ ") if not full else text if full or len(text) <= SHORT: return text return text[:SHORT] + f" … [{len(text) - SHORT} more]" def _event_line(kind: str, payload: dict[str, Any], full: bool) -> str: match kind: case "user_message": return f"USER [{payload.get('source', '')}]: {_clip(payload['text'], full)}" case "assistant_text": return f"ASSISTANT ({payload.get('model', '')}): {_clip(payload['text'], full)}" case "tool_call": args = json.dumps(payload.get("arguments", {}), ensure_ascii=False) return f"CALL {payload['tool']} {_clip(args, full)}" case "tool_result": mark = "ok" if payload.get("success") else "FAILED" return f" result ({mark}): {_clip(str(payload.get('result', '')), full)}" case "plan_submitted": plan = payload["plan"] return f"PLAN ({payload.get('model', '')}, {len(plan)} chars): {_clip(plan, full)}" case "fact": return f"FACT: {_clip(payload['text'], full)}" case "action_verdict": return ( f" VERDICT {payload.get('effect', '')} ({payload.get('rule', '')}), " f"{payload.get('decision', '')}: {payload.get('reason', '')}" ) case "gate_opened": return f"GATE {payload.get('gate', '')}: {payload.get('reason', '')}" case _: return f"{kind.upper()}: {_clip(json.dumps(payload, ensure_ascii=False), full)}" def render(path: Path, *, full: bool = False) -> str: conn = _connect(path) lines: list[str] = [] agent = conn.execute("SELECT * FROM agent WHERE id = 1").fetchone() active = agent["active_item"] if agent else None lines.append(f"active work item: {active or '(none: idle)'}") for item in conn.execute("SELECT * FROM work_items ORDER BY opened_at"): loop = json.loads(item["data"]).get("loop") or {} status = item["status"] + (f" ({item['outcome']})" if item["outcome"] else "") waiting = ( f" waits for: {loop['wait']}" if item["position"] == "WAITING" else "" ) lines.append( f" {item['id']} {status} position: {item['position']} " f"scope: {item['scope']} rev-{loop.get('rev', 0)}{waiting}" ) pending = conn.execute( "SELECT id, kind, payload, work_item FROM intent_log WHERE status = 'pending'" ).fetchall() for row in pending: lines.append( f"pending intent #{row['id']} {row['kind']} " f"[{row['work_item'] or 'agent'}]: {row['payload']}" ) lines.append("") for row in conn.execute("SELECT * FROM canonical_events ORDER BY id"): payload = json.loads(row["payload"]) time = row["ts"][11:19] where = f"[{row['work_item'] or 'agent'}/{row['actor']}]" lines.append( f"#{row['id']} {time} {where} {_event_line(row['type'], payload, full)}" ) conn.close() return "\n".join(lines) def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("state_db", type=Path) parser.add_argument("--full", action="store_true", help="don't shorten texts") args = parser.parse_args(argv) if not args.state_db.exists(): print(f"no state store at {args.state_db}", file=sys.stderr) return 1 print(render(args.state_db, full=args.full)) return 0 if __name__ == "__main__": sys.exit(main())