Replay your coding agent sessions as a map and a timeline
Python agent-observabilityai-agentsclaudeclaude-codecodexcoding-agentscursordeveloper-toolsdevtoolsgithub-copilotkirollmobservabilityopencodeprivacypythonsession-replaytypescriptvisualization
feat(insights): session facts and GET /api/stats
aiswaryasankartest9139b02df7f0
diff --git a/python/src/agentplay/cli.py b/python/src/agentplay/cli.pyindex 341a485..45917f0 100644--- a/python/src/agentplay/cli.py+++ b/python/src/agentplay/cli.py@@ -284,7 +284,7 @@ def cmd_export(args: argparse.Namespace) -> int:def cmd_import(args: argparse.Namespace) -> int:- from . import builder+ from . import builder, factsst = Store()n = 0@@ -306,7 +306,7 @@ def cmd_import(args: argparse.Namespace) -> int:started = doc["session"]["startedAt"]st.put(doc, {**builder.summary(doc), "sessionId": sid, "sessionDate": started[:10],"sessionTitle": args.title or None, "contentHash": builder.content_hash(doc),- "imported": str(path)})+ "imported": str(path), **facts.stamp(doc)})n += 1st.save_index()print(f"Imported {n} map(s).")diff --git a/python/src/agentplay/facts.py b/python/src/agentplay/facts.pynew file mode 100644index 0000000..b6c3e28--- /dev/null+++ b/python/src/agentplay/facts.py@@ -0,0 +1,237 @@+"""Session facts: the small per-session summary the Insights view aggregates.++Computed from a finished map document, so the same function serves a fresh+build, a backfill over maps already on disk (``ensure_facts``) and an imported+map. Every value comes from fields the map already holds: verbs, repo-relative+paths, counts, tokens and costs. No prompt text, command arguments or file+contents, so facts are as safe to keep as the map they came from.++Facts live on the session's index row under ``facts``. Bump ``FACTS_VERSION``+whenever what this module computes changes: rows with an older version are+recomputed from their stored map the next time stats are read, without+re-reading any transcript.+"""++from __future__ import annotations++from typing import Any++from .builder import _NON_CALL_KINDS, _error_source, estimate_cost_usd++FACTS_VERSION = 1++# Outcomes whose whole cost counts as abandoned spend. `interrupted` is left+# out on purpose: stopping an agent is often the right call.+_ABANDONED = frozenset({"unresolved_errors", "incomplete"})+# How a subagent lane can end without giving its parent anything back.+_DEAD_LANE = frozenset({"no_result", "subagent_failed", "subagent_killed"})+# Event kinds that run a shell command, keyed by verb in `cmd`.+_COMMAND_KINDS = frozenset({"exec", "verify"})+++def _cache_miss_usd(model: str | None, fresh: int) -> float:+ """What ``fresh`` input tokens cost over reading them from a warm cache."""+ if not model or fresh <= 0:+ return 0.0+ full = estimate_cost_usd(model, fresh, 0, 0, 0) or 0.0+ cached = estimate_cost_usd(model, 0, 0, fresh, 0) or 0.0+ return max(0.0, full - cached)+++def _waste(doc: dict[str, Any], evs: list[dict[str, Any]], outcome: str) -> dict[str, float]:+ """Spend that bought nothing that shipped, in USD, split into buckets.++ Cost exists only on ``llm`` events, so a tool-level failure is charged the+ model request that read its result. Each request is charged at most once,+ in bucket order: retry, abandoned, cache miss, re-read, dead subagent.+ Every bucket is an estimate and the viewer labels it as one.+ """+ llm = [e for e in evs if e["kind"] == "llm"]+ charged: set[int] = set()+ out = {"retry": 0.0, "abandoned": 0.0, "cacheMiss": 0.0, "reread": 0.0, "deadSubagent": 0.0}++ def next_llm(e: dict[str, Any]) -> dict[str, Any] | None:+ for x in llm:+ if x["seq"] > e["seq"] and x["agent"] == e["agent"] and x["seq"] not in charged:+ return x+ return None++ def charge(bucket: str, e: dict[str, Any]) -> None:+ x = next_llm(e)+ if x is not None:+ charged.add(x["seq"])+ out[bucket] += float(x.get("cost") or 0.0)++ for e in evs:+ if e["kind"] in _NON_CALL_KINDS:+ continue+ if e.get("err") or e.get("retryOf") is not None:+ charge("retry", e)++ if outcome in _ABANDONED:+ for x in llm:+ if x["seq"] not in charged:+ charged.add(x["seq"])+ out["abandoned"] += float(x.get("cost") or 0.0)++ seen_agent: set[str] = set()+ for x in llm:+ first = x["agent"] not in seen_agent+ seen_agent.add(x["agent"])+ if first or x["seq"] in charged:+ continue+ out["cacheMiss"] += _cache_miss_usd(x.get("model"), int(x.get("in") or 0))++ # A re-read: a file read again with no edit to it since the last read.+ last_read: dict[int, int] = {}+ for e in evs:+ for t in e.get("targets") or []:+ fid = t.get("file")+ if not isinstance(fid, int):+ continue+ if t.get("touch") == "edit":+ last_read.pop(fid, None)+ elif t.get("touch") == "read":+ if fid in last_read:+ charge("reread", e)+ last_read[fid] = e["seq"]++ launches = {e["seq"]: e for e in evs if e["kind"] == "subagent"}+ for a in doc.get("agents") or []:+ launch = launches.get(a.get("launchSeq"))+ dead = a.get("outcome") in _DEAD_LANE or (launch is not None and launch.get("errClass") in _DEAD_LANE)+ if a.get("kind") == "subagent" and dead:+ lane = [x for x in llm if x["agent"] == a.get("id") and x["seq"] not in charged]+ out["deadSubagent"] += sum(float(x.get("cost") or 0.0) for x in lane)++ return {k: round(v, 6) for k, v in out.items()}+++def _rereads_after_compaction(evs: list[dict[str, Any]]) -> int:+ """Files read again after a compaction that had been read before it, with no edit between."""+ read_before: set[int] = set()+ compacted = False+ n = 0+ for e in evs:+ if e["kind"] == "compaction" and e["agent"] == "main":+ compacted = True+ continue+ for t in e.get("targets") or []:+ fid = t.get("file")+ if not isinstance(fid, int):+ continue+ if t.get("touch") == "edit":+ read_before.discard(fid)+ elif t.get("touch") == "read":+ if compacted and fid in read_before:+ n += 1+ read_before.discard(fid)+ elif not compacted:+ read_before.add(fid)+ return n+++def compute(doc: dict[str, Any]) -> dict[str, Any]:+ """The facts for one map document.++ Args:+ doc: an ``agentplay/v1`` map, as the builder emits it or the store holds it.++ Returns:+ A JSON-ready dict; see the module docstring for what it may contain.+ """+ s = doc.get("session") or {}+ t = doc.get("totals") or {}+ evs = sorted(doc.get("events") or [], key=lambda e: e.get("seq", 0))+ outcome = str(s.get("outcome") or "completed")+ llm = [e for e in evs if e["kind"] == "llm"]+ repo_names = {r["id"]: r["name"] for r in doc.get("repos") or [] if "id" in r and "name" in r}++ cmd: dict[str, dict[str, Any]] = {}+ for e in evs:+ if e["kind"] not in _COMMAND_KINDS:+ continue+ verb = str(e.get("verb") or e.get("tool") or "?")[:60]+ c = cmd.setdefault(verb, {"calls": 0, "fails": 0, "retries": 0, "byClass": {}})+ c["calls"] += 1+ if e.get("retryOf") is not None:+ c["retries"] += 1+ if e.get("err"):+ c["fails"] += 1+ cls = str(e.get("errClass") or "other")+ c["byClass"][cls] = c["byClass"].get(cls, 0) + 1++ files: dict[str, dict[str, int]] = {}+ for f in doc.get("files") or []:+ hits, reads, edits = int(f.get("hits") or 0), int(f.get("reads") or 0), int(f.get("edits") or 0)+ if not (hits or reads or edits) or not f.get("path"):+ continue+ key = f"{repo_names.get(f.get('repo'), '')}:{f['path']}"+ files[key] = {"hits": hits, "reads": reads, "edits": edits}++ edits = [e for e in evs if e["kind"] == "edit"]+ verifies = [e for e in evs if e["kind"] == "verify" and not e.get("err")]+ last_edit = max((e["seq"] for e in edits), default=None)+ users = [e for e in evs if e["kind"] == "user" and e.get("agent") == "main"]++ by_source: dict[str, int] = {}+ for e in evs:+ if e.get("err"):+ src = _error_source(e)+ by_source[src] = by_source.get(src, 0) + 1++ return {+ "outcome": outcome,+ "edited": bool(edits),+ "prsCreated": int(t.get("prsCreated") or 0),+ "prsMerged": int(t.get("prsMerged") or 0),+ "costUsd": float(t.get("costUsd") or 0.0),+ "hasCost": any("cost" in e for e in llm),+ "tokens": {+ "in": sum(int(e.get("in") or 0) for e in llm),+ "cw": sum(int(e.get("cw") or 0) for e in llm),+ "cr": sum(int(e.get("cr") or 0) for e in llm),+ "out": sum(int(e.get("out") or 0) for e in llm),+ },+ "costByModel": _cost_by_model(llm),+ "calls": int(t.get("calls") or 0),+ "errors": int(t.get("errors") or 0),+ "retries": int(t.get("retries") or 0),+ "cmd": cmd,+ "errorsByClass": dict(t.get("errorsByClass") or {}),+ "errorsBySource": by_source,+ "files": files,+ "compactions": int(t.get("compactions") or 0),+ "preTokens": [int(e.get("preTokens") or 0) for e in evs if e["kind"] == "compaction"],+ "maxContext": int(t.get("maxContext") or 0),+ "rereadsAfterCompaction": _rereads_after_compaction(evs),+ "verifyAfterLastEdit": last_edit is not None and any(v["seq"] > last_edit for v in verifies),+ "waste": _waste(doc, evs, outcome),+ "stallMs": sum(int(e.get("ms") or 0) for e in evs if e["kind"] == "delay" and e.get("cause") == "stall"),+ "firstPromptChars": int(users[0].get("chars") or 0) if users else 0,+ "userTurns": len(users),+ }+++def _cost_by_model(llm: list[dict[str, Any]]) -> dict[str, float]:+ out: dict[str, float] = {}+ for e in llm:+ if "cost" not in e:+ continue+ m = str(e.get("model") or "unknown")+ out[m] = round(out.get(m, 0.0) + float(e.get("cost") or 0.0), 6)+ return out+++def stamp(doc: dict[str, Any]) -> dict[str, Any]:+ """The index-row fields that carry a map's facts.++ ``facts`` is None for a map that cannot be summarised (an imported+ document missing fields the builder always writes); Insights skips it+ rather than failing the whole view.+ """+ try:+ value: dict[str, Any] | None = compute(doc)+ except (KeyError, TypeError, ValueError, AttributeError):+ value = None+ return {"facts": value, "factsVersion": FACTS_VERSION}diff --git a/python/src/agentplay/pipeline.py b/python/src/agentplay/pipeline.pyindex 2e3ed0b..4eb7369 100644--- a/python/src/agentplay/pipeline.py+++ b/python/src/agentplay/pipeline.py@@ -11,7 +11,7 @@ from dataclasses import dataclass, fieldfrom datetime import UTC, datetimefrom typing import Any-from . import __version__, builder, discover+from . import __version__, builder, discover, factsfrom .store import Storelogger = logging.getLogger("agentplay.pipeline")@@ -68,6 +68,7 @@ def _row("sourcePath": cand.path,"builtWith": __version__,"pathMode": (doc.get("session") or {}).get("pathMode") or "relative",+ **facts.stamp(doc),}@@ -128,6 +129,25 @@ def _sync_titles(store: Store, cand: discover.Candidate, source: Any, *, titles:return changed+def _sync_facts(store: Store, session_id: str) -> bool:+ """Recompute an unchanged session's facts from its stored map when they are missing or stale.++ The cheap pass behind ``facts.FACTS_VERSION``: no transcript is read, only+ the map already on disk.++ Returns:+ True when the row was changed (the caller saves).+ """+ row = store.index.get(session_id)+ if row is None or row.get("factsVersion") == facts.FACTS_VERSION:+ return False+ doc = store.get(session_id)+ if doc is None:+ return False+ row.update(facts.stamp(doc))+ return True++def build_all(*,agents: set[str] | None = None,@@ -193,7 +213,8 @@ def build_all(if not rebuild and store.is_fresh(c.session_id, c.mtime, built_with=__version__, path_mode=effective_mode):report.unchanged += 1report.by_agent[c.agent] += 1- _sync_titles(store, c, source, titles=titles)+ if _sync_titles(store, c, source, titles=titles) | _sync_facts(store, c.session_id):+ pending = Truecontinuetry:doc = discover.build_map(c, source, path_mode=path_mode, hmac_key=hmac_key, version=__version__)diff --git a/python/src/agentplay/server.py b/python/src/agentplay/server.pyindex 9aa8b3a..efe46c4 100644--- a/python/src/agentplay/server.py+++ b/python/src/agentplay/server.py@@ -7,6 +7,7 @@ Binds to 127.0.0.1 only. Serves the static viewer from the package's``GET /api/sessions`` paged session rows (``from``, ``to``, ``search``, ``pageSize``, ``cursor``)``GET /api/map`` one entry per ``session_id`` param, each with a ``url````GET /api/map-doc?id=...`` the map document itself+``GET /api/stats`` session facts for the Insights view (``from``, ``to``: inclusive ``YYYY-MM-DD``)``GET /api/account`` whether to offer the email signup card (see ``account.py``)``GET /api/prompt-images?id=...`` per-turn metadata for images pasted into Claude Code prompts (this machine only)``GET /api/prompt-image?id=...&turn=...&i=...`` one such image, read from the transcript on demand (this machine only)@@ -38,7 +39,7 @@ from pathlib import Pathfrom typing import Anyfrom urllib.parse import parse_qs, quote, urlsplit-from . import account, hook_detail, prompt_images+from . import account, facts, hook_detail, prompt_imagesfrom .store import StoreMAX_PAGE = 200@@ -88,10 +89,15 @@ def _public_row(row: dict[str, Any]) -> dict[str, Any]:return {k: vfor k, v in row.items()- if k not in ("key", "sourcePath", "sourceMtime", "signals", "imported", "taskTitles")+ if k not in ("key", "sourcePath", "sourceMtime", "signals", "imported", "taskTitles", "facts", "factsVersion")}+# What `/api/stats` sends per session besides its facts: enough to filter and+# group (window, agent, repo, model) and to link back to the session.+_STATS_FIELDS = ("sessionId", "sessionDate", "startedAt", "durationMs", "agentTool", "models", "repos")++def _is_loopback(address: Any) -> bool:"""Whether a peer address belongs to this machine's loopback interface.@@ -193,6 +199,11 @@ class _Handler(BaseHTTPRequestHandler):# can tell "no sessions yet" from "no sessions".scanning: threading.Event | None = Nonelock = threading.Lock()+ # Facts for rows written before facts existed (or by an older FACTS_VERSION),+ # computed from the stored map on first read. Kept in memory, keyed by the+ # map's content hash: the server never writes the index, which a background+ # scan may be saving at the same moment. The next build persists them.+ facts_cache: dict[tuple[str, str], dict[str, Any] | None] = {}def log_message(self, fmt: str, *args: Any) -> None: # quiet by defaultreturn@@ -307,6 +318,8 @@ class _Handler(BaseHTTPRequestHandler):return self._maps(q)if url.path == "/api/map-doc":return self._map_doc(q)+ if url.path == "/api/stats":+ return self._stats(q)if url.path == "/api/prompt-images":return self._prompt_images(q)if url.path == "/api/prompt-image":@@ -417,6 +430,31 @@ class _Handler(BaseHTTPRequestHandler):"hasMore": more,})+ def _facts(self, row: dict[str, Any]) -> dict[str, Any] | None:+ if row.get("factsVersion") == facts.FACTS_VERSION:+ return row.get("facts")+ sid = str(row.get("sessionId") or "")+ key = (sid, str(row.get("contentHash") or ""))+ if key not in self.facts_cache:+ doc = self.store.get(sid)+ self.facts_cache[key] = facts.stamp(doc)["facts"] if doc is not None else None+ return self.facts_cache[key]++ def _stats(self, q: dict[str, list[str]]) -> None:+ lo = (q.get("from") or [""])[0]+ hi = (q.get("to") or [""])[0]+ out = []+ for r in self._rows():+ day = r.get("sessionDate") or ""+ if (lo and day < lo) or (hi and day and day > hi):+ continue+ with self.lock:+ f = self._facts(r)+ if f is None:+ continue+ out.append({**{k: r.get(k) for k in _STATS_FIELDS}, "facts": f})+ self._json({"success": True, "factsVersion": facts.FACTS_VERSION, "sessions": out})+def _maps(self, q: dict[str, list[str]]) -> None:ids = (q.get("session_id") or [])[:20]if not ids:diff --git a/python/tests/test_builder.py b/python/tests/test_builder.pyindex 3090604..eec2b14 100644--- a/python/tests/test_builder.py+++ b/python/tests/test_builder.py@@ -11,6 +11,7 @@ from types import SimpleNamespaceimport pytestfrom agentplay import builder as sm+from agentplay import factsSECRET_PROMPT = "please fix the SECRET-PROMPT-TEXT in billing"SECRET_ARG = "--token=hunter2-SECRET-ARG"@@ -228,7 +229,9 @@ def test_acompact_snapshot_is_not_a_subagent_lane(transcript):def test_builder_never_leaks_free_text(transcript):- raw = json.dumps(sm.build_claude_code_map(transcript))+ doc = sm.build_claude_code_map(transcript)+ # Session facts (the Insights summary on the index row) are held to the same contract.+ raw = json.dumps(doc) + json.dumps(facts.compute(doc))for secret in ("SECRET-PROMPT-TEXT","hunter2",@@ -255,7 +258,7 @@ def test_builder_never_leaks_free_text(transcript):"SECRET-OPEN",):assert secret not in raw, secret- verbs = [e.get("verb") for e in json.loads(raw)["events"] if e.get("tool") == "Bash"]+ verbs = [e.get("verb") for e in doc["events"] if e.get("tool") == "Bash"]for _, verb in LEAKY_COMMANDS:assert verb in verbs, verbdiff --git a/python/tests/test_facts.py b/python/tests/test_facts.pynew file mode 100644index 0000000..7a41849--- /dev/null+++ b/python/tests/test_facts.py@@ -0,0 +1,178 @@+"""Session facts (`facts.py`), their backfill, and `GET /api/stats`."""++from __future__ import annotations++import http.client+import json+import threading+from pathlib import Path+from typing import Any++import pytest++from agentplay import facts, pipeline+from agentplay.server import serve+from agentplay.store import Store++DEMO = Path(__file__).resolve().parents[2] / "viewer" / "public" / "demo"+++def _ev(seq: int, kind: str, agent: str = "main", **kw: Any) -> dict[str, Any]:+ return {"seq": seq, "t": seq * 1000, "agent": agent, "err": False, "kind": kind, **kw}+++def _llm(seq: int, cost: float, agent: str = "main", **kw: Any) -> dict[str, Any]:+ return _ev(seq, "llm", agent, model="claude-sonnet-4-5", cost=cost, **{"in": 100, "cw": 0, "cr": 900, "out": 50, **kw})+++def _doc(events: list[dict[str, Any]], *, outcome: str = "completed", sid: str = "s1",+ started: str = "2026-10-01T10:00:00Z", agents: list[dict[str, Any]] | None = None,+ totals: dict[str, Any] | None = None, role: str = "root") -> dict[str, Any]:+ return {+ "schema": "agentplay/v1",+ "session": {"id": sid, "agentTool": "claude-code", "startedAt": started, "durationMs": 60000,+ "models": ["claude-sonnet-4-5"], "outcome": outcome, "role": role},+ "totals": {"calls": 5, "requests": 3, "userTurns": 2, "subagents": 0, "errors": 1, "tokens": 0,+ "costUsd": sum(e.get("cost", 0) for e in events), "filesTouched": 2, "prsCreated": 0,+ **(totals or {})},+ "repos": [{"id": "r0", "name": "acme/api"}],+ "files": [{"id": 0, "repo": "r0", "path": "src/a.ts", "reads": 2, "edits": 1, "hits": 3},+ {"id": 1, "repo": "r0", "path": "src/unused.ts", "reads": 0, "edits": 0, "hits": 0}],+ "agents": agents or [{"id": "main", "kind": "main"}],+ "events": events,+ }+++def test_commands_files_prompt_and_verify():+ doc = _doc([+ _ev(0, "user", chars=420),+ _llm(1, 0.10),+ _ev(2, "verify", verb="pytest", err=True, errClass="exit_code"),+ _llm(3, 0.20),+ _ev(4, "verify", verb="pytest", retryOf=2),+ _ev(5, "edit", targets=[{"file": 0, "touch": "edit"}]),+ _ev(6, "verify", verb="pytest"),+ _ev(7, "user", chars=30),+ ])+ f = facts.compute(doc)+ assert f["cmd"]["pytest"] == {"calls": 3, "fails": 1, "retries": 1, "byClass": {"exit_code": 1}}+ assert f["files"] == {"acme/api:src/a.ts": {"hits": 3, "reads": 2, "edits": 1}} # untouched files dropped+ assert f["firstPromptChars"] == 420 and f["userTurns"] == 2+ assert f["edited"] is True and f["verifyAfterLastEdit"] is True+ assert f["errorsBySource"] == {"tool": 1}+++def test_waste_charges_each_request_once_in_bucket_order():+ # The failed call charges the next request as a retry; the rest of an+ # abandoned session is abandoned spend, never both.+ doc = _doc([+ _llm(0, 0.5),+ _ev(1, "exec", verb="make", err=True, errClass="exit_code"),+ _llm(2, 1.0),+ _llm(3, 2.0),+ ], outcome="unresolved_errors")+ w = facts.compute(doc)["waste"]+ assert w["retry"] == pytest.approx(1.0)+ assert w["abandoned"] == pytest.approx(2.5)+ assert w["cacheMiss"] == 0.0 # every request already charged+++def test_rereads_and_dead_subagents():+ doc = _doc([+ _ev(0, "read", targets=[{"file": 0, "touch": "read"}]),+ _llm(1, 0.1),+ _ev(2, "compaction", preTokens=150000),+ _ev(3, "read", targets=[{"file": 0, "touch": "read"}]),+ _llm(4, 0.3),+ _ev(5, "subagent", err=True, errClass="no_result"),+ _llm(6, 0.7, agent="sub-1"),+ ], agents=[{"id": "main", "kind": "main"}, {"id": "sub-1", "kind": "subagent", "launchSeq": 5}])+ f = facts.compute(doc)+ assert f["rereadsAfterCompaction"] == 1+ assert f["preTokens"] == [150000]+ assert f["waste"]["reread"] == pytest.approx(0.3)+ assert f["waste"]["deadSubagent"] == pytest.approx(0.7)+++def test_stamp_survives_a_map_missing_fields():+ assert facts.stamp({"events": [{"kind": "llm"}]}) == {"facts": None, "factsVersion": facts.FACTS_VERSION}+++def test_demo_index_facts_are_current():+ """Regenerate with `scripts/demo_facts.py` when this fails."""+ index = json.loads((DEMO / "index.json").read_text(encoding="utf-8"))+ for row in index["sessions"]:+ doc = json.loads((DEMO / row["file"]).read_text(encoding="utf-8"))+ assert row.get("factsVersion") == facts.FACTS_VERSION, row["file"]+ assert row.get("facts") == facts.compute(doc), row["file"]+++def _seed(tmp_path: Path, docs: list[dict[str, Any]], *, with_facts: bool) -> Store:+ st = Store(tmp_path)+ for d in docs:+ row = {"sessionId": d["session"]["id"], "sessionDate": d["session"]["startedAt"][:10],+ "startedAt": d["session"]["startedAt"], "agentTool": "claude-code", "models": [],+ "repos": ["acme/api"], "calls": 5, "role": d["session"].get("role"), "contentHash": d["session"]["id"]}+ if with_facts:+ row.update(facts.stamp(d))+ st.put(d, row)+ st.save_index()+ return st+++def test_unchanged_sessions_get_facts_backfilled(tmp_path):+ st = _seed(tmp_path, [_doc([_llm(0, 0.1)])], with_facts=False)+ assert pipeline._sync_facts(st, "s1") is True+ assert st.index["s1"]["factsVersion"] == facts.FACTS_VERSION+ assert pipeline._sync_facts(st, "s1") is False # already current+++def stats_server(tmp_path):+ docs = [+ _doc([_llm(0, 0.1)], sid="old", started="2026-09-01T10:00:00Z"),+ _doc([_llm(0, 0.2)], sid="new", started="2026-10-02T10:00:00Z", totals={"prsCreated": 1}),+ _doc([_llm(0, 0.3)], sid="child", started="2026-10-02T11:00:00Z", role="subagent"),+ ]+ st = _seed(tmp_path, docs, with_facts=False) # rows written before facts existed+ httpd = serve(0, store=st)+ threading.Thread(target=httpd.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True).start()+ try:+ yield httpd, st+ finally:+ httpd.shutdown()+ httpd.server_close()+++def _get(httpd, path: str, headers: dict[str, str] | None = None):+ conn = http.client.HTTPConnection("127.0.0.1", httpd.server_address[1], timeout=5)+ conn.request("GET", path, headers=headers or {})+ resp = conn.getresponse()+ body = resp.read()+ conn.close()+ return resp.status, json.loads(body)+++def test_stats_backfills_in_memory_and_filters(stats_server):+ httpd, st = stats_server+ status, body = _get(httpd, "/api/stats")+ assert status == 200+ ids = {s["sessionId"] for s in body["sessions"]}+ assert ids == {"old", "new"} # subagent sessions are folded into their parent+ new = next(s for s in body["sessions"] if s["sessionId"] == "new")+ assert new["facts"]["prsCreated"] == 1+ assert "facts" not in json.dumps(st.index["new"]) # the server never writes the index+ _, body = _get(httpd, "/api/stats?from=2026-10-01")+ assert [s["sessionId"] for s in body["sessions"]] == ["new"]+++def test_stats_and_sessions_keep_facts_apart(stats_server):+ httpd, _ = stats_server+ _, page = _get(httpd, "/api/sessions")+ assert all("facts" not in s for s in page["sessions"])+++def test_stats_refuses_a_rebinding_host(stats_server):+ httpd, _ = stats_server+ status, _ = _get(httpd, "/api/stats", {"Host": "evil.example:80"})+ assert status == 403diff --git a/scripts/demo_facts.py b/scripts/demo_facts.pynew file mode 100644index 0000000..c3e0348--- /dev/null+++ b/scripts/demo_facts.py@@ -0,0 +1,33 @@+"""Stamp session facts into the viewer's bundled demo index.++The demo has no server, so the Insights view reads facts straight off+``viewer/public/demo/index.json``. Run this after changing a demo map or+``agentplay.facts``; ``tests/test_facts.py`` fails while the two disagree.++ python/.venv/bin/python scripts/demo_facts.py+"""++from __future__ import annotations++import json+import sys+from pathlib import Path++from agentplay import facts++DEMO = Path(__file__).resolve().parent.parent / "viewer" / "public" / "demo"+++def main() -> int:+ index_path = DEMO / "index.json"+ index = json.loads(index_path.read_text(encoding="utf-8"))+ for row in index.get("sessions", []):+ doc = json.loads((DEMO / row["file"]).read_text(encoding="utf-8"))+ row.update(facts.stamp(doc))+ index_path.write_text(json.dumps(index, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")+ print(f"Stamped facts on {len(index.get('sessions', []))} demo sessions.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/viewer/public/demo/index.json b/viewer/public/demo/index.jsonindex f2abd6f..eba4325 100644--- a/viewer/public/demo/index.json+++ b/viewer/public/demo/index.json@@ -51,7 +51,135 @@"state": "open"}],- "file": "claude-code-rate-limit.json"+ "file": "claude-code-rate-limit.json",+ "facts": {+ "outcome": "pr_created",+ "edited": true,+ "prsCreated": 1,+ "prsMerged": 0,+ "costUsd": 1.9251,+ "hasCost": true,+ "tokens": {+ "in": 44660,+ "cw": 178648,+ "cr": 1005692,+ "out": 10680+ },+ "costByModel": {+ "claude-opus-4-5": 1.78135,+ "claude-haiku-4-5": 0.02666,+ "claude-sonnet-4-5": 0.11706+ },+ "calls": 26,+ "errors": 2,+ "retries": 1,+ "cmd": {+ "npm test": {+ "calls": 2,+ "fails": 1,+ "retries": 1,+ "byClass": {+ "exit_code": 1+ }+ },+ "tsc": {+ "calls": 1,+ "fails": 0,+ "retries": 0,+ "byClass": {}+ },+ "git": {+ "calls": 4,+ "fails": 0,+ "retries": 0,+ "byClass": {}+ },+ "gh": {+ "calls": 1,+ "fails": 0,+ "retries": 0,+ "byClass": {}+ }+ },+ "errorsByClass": {+ "exit_code": 1,+ "overloaded": 1+ },+ "errorsBySource": {+ "tool": 1,+ "llm": 1+ },+ "files": {+ "acme/api:README.md": {+ "hits": 0,+ "reads": 1,+ "edits": 0+ },+ "acme/api:src/middleware/index.ts": {+ "hits": 1,+ "reads": 1,+ "edits": 1+ },+ "acme/api:src/middleware/auth.ts": {+ "hits": 1,+ "reads": 1,+ "edits": 0+ },+ "acme/api:src/server.ts": {+ "hits": 1,+ "reads": 1,+ "edits": 0+ },+ "acme/api:src/config/env.ts": {+ "hits": 0,+ "reads": 1,+ "edits": 1+ },+ "acme/api:src/routes/orders.ts": {+ "hits": 0,+ "reads": 1,+ "edits": 1+ },+ "acme/api:package.json": {+ "hits": 0,+ "reads": 1,+ "edits": 0+ },+ "acme/api:src/middleware/rateLimit.ts": {+ "hits": 0,+ "reads": 1,+ "edits": 2+ },+ "acme/api:test/rateLimit.test.ts": {+ "hits": 0,+ "reads": 0,+ "edits": 1+ },+ "acme/api:docs/rate-limits.md": {+ "hits": 0,+ "reads": 0,+ "edits": 1+ }+ },+ "compactions": 1,+ "preTokens": [+ 168400+ ],+ "maxContext": 161000,+ "rereadsAfterCompaction": 0,+ "verifyAfterLastEdit": false,+ "waste": {+ "retry": 0.34456,+ "abandoned": 0.0,+ "cacheMiss": 0.154807,+ "reread": 0.0,+ "deadSubagent": 0.0+ },+ "stallMs": 0,+ "firstPromptChars": 1180,+ "userTurns": 3+ },+ "factsVersion": 1},{"sessionId": "local:codex:0199a3b2-demo-4f0c-8e55-000000000002",@@ -93,7 +221,101 @@"commit": 1},"prs": [],- "file": "codex-flaky-test.json"+ "file": "codex-flaky-test.json",+ "facts": {+ "outcome": "verified",+ "edited": true,+ "prsCreated": 0,+ "prsMerged": 0,+ "costUsd": 0.0851,+ "hasCost": true,+ "tokens": {+ "in": 9136,+ "cw": 36540,+ "cr": 264324,+ "out": 4060+ },+ "costByModel": {+ "gpt-5-codex": 0.08508+ },+ "calls": 12,+ "errors": 2,+ "retries": 1,+ "cmd": {+ "pnpm vitest": {+ "calls": 2,+ "fails": 1,+ "retries": 1,+ "byClass": {+ "exit_code": 1+ }+ },+ "pnpm": {+ "calls": 1,+ "fails": 1,+ "retries": 0,+ "byClass": {+ "exit_code": 1+ }+ },+ "pnpm lint": {+ "calls": 1,+ "fails": 0,+ "retries": 0,+ "byClass": {}+ },+ "git": {+ "calls": 1,+ "fails": 0,+ "retries": 0,+ "byClass": {}+ }+ },+ "errorsByClass": {+ "exit_code": 2+ },+ "errorsBySource": {+ "tool": 2+ },+ "files": {+ "acme/web:src/lib/formatDate.ts": {+ "hits": 1,+ "reads": 1,+ "edits": 1+ },+ "acme/web:src/lib/formatDate.test.ts": {+ "hits": 1,+ "reads": 1,+ "edits": 1+ },+ "acme/web:src/components/OrderRow.tsx": {+ "hits": 1,+ "reads": 0,+ "edits": 0+ },+ "acme/ui-kit:src/date/index.ts": {+ "hits": 0,+ "reads": 1,+ "edits": 0+ }+ },+ "compactions": 0,+ "preTokens": [],+ "maxContext": 38000,+ "rereadsAfterCompaction": 0,+ "verifyAfterLastEdit": true,+ "waste": {+ "retry": 0.02233,+ "abandoned": 0.0,+ "cacheMiss": 0.006602,+ "reread": 0.0,+ "deadSubagent": 0.0+ },+ "stallMs": 0,+ "firstPromptChars": 640,+ "userTurns": 2+ },+ "factsVersion": 1},{"sessionId": "local:cursor:c1d2e3f4-demo-4a5b-9c8d-000000000003",@@ -130,7 +352,58 @@"tasks": 1,"outputs": {},"prs": [],- "file": "cursor-copy-tweak.json"+ "file": "cursor-copy-tweak.json",+ "facts": {+ "outcome": "completed",+ "edited": true,+ "prsCreated": 0,+ "prsMerged": 0,+ "costUsd": 0.0,+ "hasCost": true,+ "tokens": {+ "in": 0,+ "cw": 0,+ "cr": 0,+ "out": 0+ },+ "costByModel": {+ "cursor-auto": 0.0+ },+ "calls": 4,+ "errors": 0,+ "retries": 0,+ "cmd": {},+ "errorsByClass": {},+ "errorsBySource": {},+ "files": {+ "acme/web:src/pages/cart.tsx": {+ "hits": 1,+ "reads": 0,+ "edits": 1+ },+ "acme/web:src/i18n/en.json": {+ "hits": 1,+ "reads": 1,+ "edits": 1+ }+ },+ "compactions": 0,+ "preTokens": [],+ "maxContext": 0,+ "rereadsAfterCompaction": 0,+ "verifyAfterLastEdit": false,+ "waste": {+ "retry": 0.0,+ "abandoned": 0.0,+ "cacheMiss": 0.0,+ "reread": 0.0,+ "deadSubagent": 0.0+ },+ "stallMs": 0,+ "firstPromptChars": 180,+ "userTurns": 1+ },+ "factsVersion": 1}]}