Files
nisse/nisse-dev/src/nisse_dev/dump.py
T
dongarandClaude Opus 5.5 ea4376eaa1
CI / checks (push) Skipped
CI / checks (pull_request) Successful in 2m10s
CI / e2e (pull_request) Successful in 10m30s
M3.1: action classes and the fast path
Every execution tool call, the driver's and a helper's, gets a verdict
from code before it runs (P3, P4, D6).

- nisse_core.actions, nisse-core's first code: Action and Verdict, and
  reading shell commands statically, segment by segment (cd, wrappers,
  sh -c). What can't be read that way is unknown; a line is as bad as
  its worst command.
- nisse_dev.loop.actions, the rule table: reading, checks and tests are
  harmless; workspace edits, local git and installs on the build VM are
  contained; pushing, other hosts, uploads, publishing, the forge's own
  tools, deleting outside the workspace and wrecking the VM are
  dangerous; changing branches by hand is refused (the harness owns
  branches) with a pointer to the milestone tools.
- A dangerous call isn't run. The item waits on the operator with a
  question rendered from the action, and `allow` lets exactly that
  action run once. A helper can't ask, so it is refused and told to
  hand back. Unknown actions run, logged, until the classifier (M3.2).
- Every verdict is an action_verdict event, which no model sees, and an
  oplog line; `details` shows the counts and every action not simply
  run.
- The property walk gains dangerous_only_when_allowed (checked against
  a mutant that doesn't use the allow up); the slice e2e checks every
  call was judged and none needed an allow.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PPQ14L3LikyefCMFBqEbKE
2026-10-08 04:32:13 +00:00

113 lines
4.3 KiB
Python

"""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())