Files
nisse/nisse-dev/src/nisse_dev/dump.py
T
dongarandClaude Opus 5.5 3fba958958
CI / checks (push) Skipped
CI / checks (pull_request) Successful in 1m27s
Give each role its own view of the transcript (M1.2)
A model no longer reads another role's turns as its own (#78). The log
stays one record per work item; what a role is shown is projected from
it by Transcript.view() (views.py), which the planner, executor and
helper now build their context from:

- own events unchanged;
- operator messages labelled with their channel, e.g.
  [operator, Matrix] or [operator, comment on PR #165];
- orchestrator facts (a new `fact` event) as [orchestrator] statements;
- the executor sees a helper's handback as [helper report], not its turns;
- a helper sees the approved plan and the executor's milestone work as
  one-line narration;
- the planner sees no other role's work at all.

The orchestrator now writes facts at the points the models must know
about: work item opened, plan approved or rejected, milestone started,
finished or stopped, published (with PR number and URL) or not, review
comment answered, next milestone, task completed or abandoned.

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

107 lines
4.0 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 "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"):
data = json.loads(item["data"])
gate = data.get("gate") or {}
status = item["status"] + (f" ({item['outcome']})" if item["outcome"] else "")
lines.append(
f" {item['id']} {status} position: {item['position']} "
f"scope: {item['scope']} gate: "
+ (f"{gate.get('name')} rev-{gate.get('rev')}" if gate else "none")
)
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())