Replay your coding agent sessions as a map and a timeline
Python agent-observabilityai-agentsclaudeclaude-codecodexcoding-agentscursordeveloper-toolsdevtoolsgithub-copilotkirollmobservabilityopencodeprivacypythonsession-replaytypescriptvisualization
fix: address review findings on fixes, Autotune, facts and Insights
aiswaryasankartest23da50d26682
diff --git a/python/src/agentplay/autotune.py b/python/src/agentplay/autotune.pyindex 418235b..17aaa1d 100644--- a/python/src/agentplay/autotune.py+++ b/python/src/agentplay/autotune.py@@ -61,6 +61,11 @@ def _log(cfg: dict[str, Any], kind: str, **kw: Any) -> None:def set_repo(base: Path, repo: str, *, enabled: bool | None = None, claude_md: str | None = None) -> dict[str, Any]:+ with fixes.write_lock(base):+ return _set_repo(base, repo, enabled, claude_md)+++def _set_repo(base: Path, repo: str, enabled: bool | None, claude_md: str | None) -> dict[str, Any]:cfg = config(base)r = cfg["repos"].setdefault(repo, {"enabled": False, "claudeMd": "ask"})if enabled is not None:@@ -107,14 +112,17 @@ def metric(rows: list[dict[str, Any]], m: dict[str, Any] | None) -> float | Noneif name == "out_bytes":return sum(c.get("outBytes", 0) for c in cs) / calls if calls else Noneif name == "denials":- return sum((c.get("byClass") or {}).get("permission_denied", 0) for c in cs) / len(rows) if rows else None+ # The same classes Run health counts as denied (health._cmds).+ denied = sum((c.get("byClass") or {}).get(k, 0) for c in cs for k in ("permission_denied", "blocked"))+ return denied / len(rows) if rows else Nonereturn Nonedef _improved(name: str, before: float, after: float) -> bool:if name == "verified_share":- return after >= before * (1 + MIN_GAIN) or after - before >= MIN_GAIN- return after <= before * (1 - MIN_GAIN)+ # `after >= before * 1.1` alone holds for an unchanged 0%; require a real rise.+ return after > before and (after >= before * (1 + MIN_GAIN) or after - before >= MIN_GAIN)+ return after < before and after <= before * (1 - MIN_GAIN)def effects(store: Any) -> list[dict[str, Any]]:@@ -131,6 +139,13 @@ def effects(store: Any) -> list[dict[str, Any]]:def run(store: Any, *, force: bool = False, today: str | None = None) -> dict[str, Any]:+ # Held across the daily check, the writes and the final save, so two overlapping+ # runs (two sessions starting at once) cannot both apply the same fix.+ with fixes.write_lock(store.base):+ return _run(store, force, today)+++def _run(store: Any, force: bool, today: str | None) -> dict[str, Any]:base = store.basecfg = config(base)today = today or datetime.now(UTC).strftime("%Y-%m-%d")@@ -156,6 +171,8 @@ def run(store: Any, *, force: bool = False, today: str | None = None) -> dict[stentry = fixes.apply(base, fx, md, rel=rel, source="autotune",baseline=metric(repo_rows, fx.get("metric")))except fixes.FixError as exc:+ if exc.code == "already_present":+ continue_log(cfg, "error", title=fx["title"], repo=fx["repo"], detail=exc.message)continue_log(cfg, "add", title=fx["title"], repo=fx["repo"], file=rel, entry=entry["id"])@@ -184,6 +201,11 @@ def run(store: Any, *, force: bool = False, today: str | None = None) -> dict[stdef approve(store: Any, fix_id: str) -> dict[str, Any]:+ with fixes.write_lock(store.base):+ return _approve(store, fix_id)+++def _approve(store: Any, fix_id: str) -> dict[str, Any]:cfg = config(store.base)item = next((p for p in cfg["pending"] if p["fixId"] == fix_id), None)if item is None:@@ -197,6 +219,11 @@ def approve(store: Any, fix_id: str) -> dict[str, Any]:def dismiss(store: Any, fix_id: str, *, forever: bool = False) -> None:+ with fixes.write_lock(store.base):+ _dismiss(store, fix_id, forever)+++def _dismiss(store: Any, fix_id: str, forever: bool) -> None:cfg = config(store.base)cfg["pending"] = [p for p in cfg["pending"] if p["fixId"] != fix_id]if forever and fix_id not in cfg["dismissed"]:@@ -260,8 +287,8 @@ def uninstall_hook() -> None:except (OSError, ValueError):returngroups = (data.get("hooks") or {}).get("SessionStart") or []- kept = [g for g in groups if not any(h.get("command") == HOOK_COMMAND for h in g.get("hooks", []))]- if len(kept) != len(groups):+ kept = fixes.drop_hook(groups, HOOK_COMMAND)+ if kept != groups:if kept:data["hooks"]["SessionStart"] = keptelse:diff --git a/python/src/agentplay/builder.py b/python/src/agentplay/builder.pyindex 942a461..d795853 100644--- a/python/src/agentplay/builder.py+++ b/python/src/agentplay/builder.py@@ -172,6 +172,8 @@ class RepoResolver:def __init__(self) -> None:self._cache: dict[str, tuple[str, str, str] | None] = {}+ # name -> root, most recently resolved last, so a shared name keeps the latest checkout.+ self._roots: dict[str, str] = {}def resolve(self, path: str) -> tuple[str, str, str] | None:p = Path(path)@@ -193,11 +195,17 @@ class RepoResolver:d = d.parentfor k in seen:self._cache[k] = result+ if result:+ self._roots.pop(result[1], None)+ self._roots[result[1]] = result[0]return resultdef roots(self) -> dict[str, str]:- """Repo name -> checkout root for every repo resolved so far (local use only)."""- return {name: root for v in self._cache.values() if v for root, name, _ in [v]}+ """Repo name -> checkout root for every repo resolved so far (local use only).++ When two checkouts share a name, the one resolved most recently wins.+ """+ return dict(self._roots)@staticmethoddef _remote(root: Path, git: Path) -> tuple[str, str]:diff --git a/python/src/agentplay/cli.py b/python/src/agentplay/cli.pyindex abc1153..20b8285 100644--- a/python/src/agentplay/cli.py+++ b/python/src/agentplay/cli.py@@ -331,6 +331,18 @@ def _health_fixes(st: Store, days: int = 30) -> list[dict]:return health.fixes(autotune.root_rows(st, since=since))+def _pick_fix(st: Store, items: list[dict], target: str) -> dict | None:+ """A fix by its 1-based number in ``items`` or by id (the viewer shows ids, over any window)."""+ if target.isdigit():+ n = int(target)+ return items[n - 1] if 1 <= n <= len(items) else None+ if not target:+ return None+ return next((f for f in items if f["id"] == target), None) or next(+ (f for f in _health_fixes(st, days=36500) if f["id"] == target), None+ )++def cmd_fix(args: argparse.Namespace) -> int:from . import fixes@@ -354,10 +366,9 @@ def cmd_fix(args: argparse.Namespace) -> int:return 1print(f"Undid: {entry['title']} ({entry['repo']}, {entry['file']}).")return 0- try:- fx = items[int(args.target) - 1]- except (ValueError, IndexError):- print("agentplay: give the number from `agentplay fix list`.", file=sys.stderr)+ fx = _pick_fix(st, items, args.target)+ if fx is None:+ print("agentplay: give a number from `agentplay fix list`, or a fix id from the viewer.", file=sys.stderr)return 1if not fx["actions"]:print(f"agentplay: {fx['title']}: nothing to write; it names an integration to fix by hand.", file=sys.stderr)@@ -401,6 +412,8 @@ def cmd_autotune(args: argparse.Namespace) -> int:autotune.set_repo(st.base, repo, enabled=True)cfg = autotune.config(st.base)if args.at:+ # One schedule only: a leftover SessionStart hook would run first and the cron run would skip.+ autotune.uninstall_hook()cfg["when"] = args.atautotune.save(st.base, cfg)print(f"Add this to your crontab (crontab -e) to run daily at {args.at}:")@@ -426,7 +439,10 @@ def cmd_autotune(args: argparse.Namespace) -> int:for title in res[k]:print(f"{k}: {title}")elif args.action == "undo":- entry = fixes.undo(st.base, args.repo[0] if args.repo else "")+ if not args.entry:+ print("agentplay: give the entry id from `agentplay autotune status`.", file=sys.stderr)+ return 1+ entry = fixes.undo(st.base, args.entry)print(f"Undid: {entry['title']}.")else:s = autotune.status(st)@@ -435,6 +451,8 @@ def cmd_autotune(args: argparse.Namespace) -> int:print(f"{'●' if r.get('enabled') and r['granted'] else '○'} {r['name']}")for p in s["pending"]:print(f"waiting: {p['title']} ({p['repo']}) - approve it in the viewer")+ for e in s["active"]:+ print(f"active: {e['title']} ({e['repo']}, {e['file']}) - undo with `agentplay autotune undo {e['id']}`")except fixes.FixError as exc:print(f"agentplay: {exc.message}", file=sys.stderr)return 1@@ -496,7 +514,7 @@ def parser() -> argparse.ArgumentParser:fx = sub.add_parser("fix", parents=[common], help="list, apply or undo Run health fixes")fx.add_argument("action", choices=["list", "apply", "undo"])- fx.add_argument("target", nargs="?", default="", help="fix number (apply) or entry id (undo)")+ fx.add_argument("target", nargs="?", default="", help="fix number or id (apply), or entry id (undo)")fx.add_argument("--variant", type=int, default=0, help="which of a fix's actions to apply (default: the first)")fx.add_argument("--to", choices=["CLAUDE.md", "CLAUDE.local.md"], help="instruction file to write to")fx.set_defaults(fn=cmd_fix)@@ -509,6 +527,7 @@ def parser() -> argparse.ArgumentParser:at = sub.add_parser("autotune", parents=[common], help="apply fixes daily and retire the ones that don't help")at.add_argument("action", choices=["on", "off", "run", "status", "undo"], nargs="?", default="status")+ at.add_argument("entry", nargs="?", default="", help="entry id to undo (from `autotune status`)")at.add_argument("--repo", action="append", help="repo name (repeatable; default: every granted repo)")at.add_argument("--at", help="run daily at HH:MM from cron instead of on session start")at.add_argument("--daily", action="store_true", help="skip if it already ran today")diff --git a/python/src/agentplay/facts.py b/python/src/agentplay/facts.pyindex 674d772..857db19 100644--- a/python/src/agentplay/facts.py+++ b/python/src/agentplay/facts.py@@ -24,7 +24,7 @@ FACTS_VERSION = 3# 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"})+_DEAD_LANE = frozenset({"no_result", "subagent_failed", "subagent_error", "subagent_killed"})# Event kinds that run a shell command, keyed by verb in `cmd`._COMMAND_KINDS = frozenset({"exec", "verify"})@@ -56,11 +56,19 @@ def _waste(doc: dict[str, Any], evs: list[dict[str, Any]], outcome: str) -> dictreturn xreturn None+ # Cache-miss estimates are only part of a request's cost, so a later bucket can still take+ # the whole request; when it does, the estimate moves out of cacheMiss rather than counting twice.+ misses: dict[int, float] = {}++ def take(x: dict[str, Any], bucket: str) -> None:+ charged.add(x["seq"])+ out["cacheMiss"] -= misses.pop(x["seq"], 0.0)+ out[bucket] += float(x.get("cost") or 0.0)+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)+ take(x, bucket)for e in evs:if e["kind"] in _NON_CALL_KINDS:@@ -80,7 +88,10 @@ def _waste(doc: dict[str, Any], evs: list[dict[str, Any]], outcome: str) -> dictseen_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))+ miss = _cache_miss_usd(x.get("model"), int(x.get("in") or 0))+ if miss > 0:+ misses[x["seq"]] = miss+ out["cacheMiss"] += miss# A re-read: a file read again with no edit to it since the last read.last_read: dict[int, int] = {}@@ -101,10 +112,10 @@ def _waste(doc: dict[str, Any], evs: list[dict[str, Any]], outcome: str) -> dictlaunch = 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)+ for x in [x for x in llm if x["agent"] == a.get("id") and x["seq"] not in charged]:+ take(x, "deadSubagent")- return {k: round(v, 6) for k, v in out.items()}+ return {k: round(max(v, 0.0), 6) for k, v in out.items()}def _rereads_after_compaction(evs: list[dict[str, Any]]) -> int:@@ -170,7 +181,9 @@ def compute(doc: dict[str, Any]) -> dict[str, Any]:if not (hits or reads or edits) or not f.get("path"):continuekey = f"{repo_names.get(f.get('repo'), '')}:{f['path']}"- files[key] = {"hits": hits, "reads": reads, "edits": edits}+ # Two repos can share a display name; add their counters rather than drop one.+ prev = files.get(key) or {"hits": 0, "reads": 0, "edits": 0}+ files[key] = {"hits": prev["hits"] + hits, "reads": prev["reads"] + reads, "edits": prev["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")]diff --git a/python/src/agentplay/fixes.py b/python/src/agentplay/fixes.pyindex 0186aad..6ef85d9 100644--- a/python/src/agentplay/fixes.py+++ b/python/src/agentplay/fixes.py@@ -22,8 +22,11 @@ from __future__ import annotationsimport hashlibimport jsonimport os+import threadingimport timeimport uuid+from collections.abc import Iterator+from contextlib import contextmanagerfrom pathlib import Pathfrom typing import Any@@ -44,6 +47,49 @@ class FixError(Exception):self.message = message+# ------------------------------------------------------------------ locking++_held = threading.local()+++@contextmanager+def write_lock(base: Path) -> Iterator[None]:+ """Serialize writers (server threads, the CLI and the SessionStart hook) on ``base/write.lock``.++ Re-entrant within a thread, so ``autotune.run`` can hold it across the+ ``apply`` calls it makes.+ """+ depth = getattr(_held, "depth", 0)+ if depth:+ _held.depth = depth + 1+ try:+ yield+ finally:+ _held.depth -= 1+ return+ base.mkdir(parents=True, exist_ok=True)+ with open(base / "write.lock", "a+b") as fh:+ _lock_file(fh, True)+ _held.depth = 1+ try:+ yield+ finally:+ _held.depth = 0+ _lock_file(fh, False)+++def _lock_file(fh: Any, on: bool) -> None:+ try:+ import fcntl+ except ImportError: # Windows+ import msvcrt++ fh.seek(0)+ msvcrt.locking(fh.fileno(), msvcrt.LK_LOCK if on else msvcrt.LK_UNLCK, 1)+ return+ fcntl.flock(fh.fileno(), fcntl.LOCK_EX if on else fcntl.LOCK_UN)++# ------------------------------------------------------------------ local files@@ -87,16 +133,18 @@ def grant(base: Path, repo: str, root: str | None = None) -> str:resolved = Path(path).expanduser().resolve()if not (resolved / ".git").exists():raise FixError("not_a_repo", f"{resolved} is not a git checkout.")- g = grants(base)- g[repo] = str(resolved)- _write_json(base / "grants.json", g)+ with write_lock(base):+ g = grants(base)+ g[repo] = str(resolved)+ _write_json(base / "grants.json", g)return str(resolved)def revoke(base: Path, repo: str) -> None:- g = grants(base)- if g.pop(repo, None) is not None:- _write_json(base / "grants.json", g)+ with write_lock(base):+ g = grants(base)+ if g.pop(repo, None) is not None:+ _write_json(base / "grants.json", g)def journal(base: Path) -> list[dict[str, Any]]:@@ -200,6 +248,21 @@ def _apply_text(action: dict[str, Any], text: str | None, fix_id: str, rel: str)return json.dumps(data, indent=2) + "\n"+def drop_hook(groups: list[Any], command: Any) -> list[Any]:+ """``groups`` without the hook that runs ``command``; other hooks in a group stay, empty groups go."""+ out = []+ for g in groups:+ if not isinstance(g, dict):+ out.append(g)+ continue+ hooks = [h for h in g.get("hooks", []) if not (isinstance(h, dict) and h.get("command") == command)]+ if len(hooks) == len(g.get("hooks", [])):+ out.append(g)+ elif hooks:+ out.append({**g, "hooks": hooks})+ return out++def _undo_text(entry: dict[str, Any], text: str) -> str:kind = entry["action"].get("kind")if kind == "claude_md":@@ -210,12 +273,11 @@ def _undo_text(entry: dict[str, Any], text: str) -> str:if entry["action"].get("entry") in allow:allow.remove(entry["action"]["entry"])elif kind == "stop_hook":- stop = (data.get("hooks") or {}).get("Stop") or []- data["hooks"]["Stop"] = [- g for g in stop if not any(h.get("command") == entry["action"].get("command") for h in g.get("hooks", []))- ]- if not data["hooks"]["Stop"]:- del data["hooks"]["Stop"]+ stop = (data.get("hooks") or {}).get("Stop")+ if stop:+ data["hooks"]["Stop"] = drop_hook(stop, entry["action"].get("command"))+ if not data["hooks"]["Stop"]:+ del data["hooks"]["Stop"]return json.dumps(data, indent=2) + "\n"@@ -246,11 +308,26 @@ def apply(raise FixError("file_not_allowed", "Instructions go in CLAUDE.md or CLAUDE.local.md.")if action.get("kind") in ("settings_allow", "stop_hook") and not rel.startswith(".claude/"):raise FixError("file_not_allowed", "Settings go in .claude/settings.json or .claude/settings.local.json.")+ with write_lock(base):+ return _apply_locked(base, fix, action, repo, rel, expect_hash, source, baseline)+++def _apply_locked(+ base: Path, fix: dict[str, Any], action: dict[str, Any], repo: str, rel: str,+ expect_hash: str | None, source: str, baseline: Any,+) -> dict[str, Any]:+ entries = journal(base)+ if any(e.get("fixId") == fix["id"] and e.get("repo") == repo and e.get("file") == rel+ and not e.get("undoneAt") for e in entries):+ raise FixError("already_applied", f"This fix is already in {rel}. Undo it first to write it again.")target = _target(base, repo, rel)before = target.read_text(encoding="utf-8") if target.exists() else Noneif expect_hash is not None and expect_hash != file_hash(before):raise FixError("changed", f"{rel} changed since the preview. Look again before applying.")after = _apply_text(action, before, fix["id"], rel)+ if after == before or (action.get("kind") != "claude_md" and _settings(before, rel) == _settings(after, rel)):+ # Already there (the person added it themselves): nothing to write, so nothing to undo later.+ raise FixError("already_present", f"{rel} already has this.")target.parent.mkdir(parents=True, exist_ok=True)_atomic_write(target, after.encode("utf-8"))entry = {@@ -266,13 +343,25 @@ def apply("baseline": baseline,"at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),}- entries = journal(base)entries.append(entry)- _save_journal(base, entries)+ try:+ _save_journal(base, entries)+ except BaseException:+ # Never leave a repo change that cannot be undone.+ if before is None:+ target.unlink(missing_ok=True)+ else:+ _atomic_write(target, before.encode("utf-8"))+ raisereturn entrydef undo(base: Path, entry_id: str, *, reason: str = "undone") -> dict[str, Any]:+ with write_lock(base):+ return _undo_locked(base, entry_id, reason)+++def _undo_locked(base: Path, entry_id: str, reason: str) -> dict[str, Any]:entries = journal(base)entry = next((e for e in entries if e.get("id") == entry_id and not e.get("undoneAt")), None)if entry is None:diff --git a/python/src/agentplay/pipeline.py b/python/src/agentplay/pipeline.pyindex 57a0c91..8b8ceb5 100644--- a/python/src/agentplay/pipeline.py+++ b/python/src/agentplay/pipeline.py@@ -207,6 +207,10 @@ def build_all(# Shared across builds, so each checkout is resolved once and its root can# be recorded (locally, in repos.json) for writing fixes later.resolver = builder.RepoResolver()+ # Repos a stored map names but whose checkout was never recorded (maps built before+ # roots were): each is re-resolved once per run from one of its sessions.+ known_roots = fixes.known_roots(store.base)+ tried: set[str] = set()for i, c in enumerate(cands):if pending and time.monotonic() - last_save >= SAVE_EVERY_S:store.save_index()@@ -218,6 +222,14 @@ def build_all(report.by_agent[c.agent] += 1if _sync_titles(store, c, source, titles=titles) | _sync_facts(store, c.session_id):pending = True+ need = {n for n in (store.index.get(c.session_id) or {}).get("repos") or []} - set(known_roots) - tried+ if need:+ tried |= need+ try:+ discover.build_map(c, source, path_mode=path_mode, hmac_key=hmac_key, version=__version__,+ resolver=resolver)+ except Exception: # noqa: BLE001 - only for its roots; the stored map stays as it is+ logger.debug("root lookup failed for %s", c.session_id, exc_info=True)continuetry: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 1521efe..03cfb99 100644--- a/python/src/agentplay/server.py+++ b/python/src/agentplay/server.py@@ -209,7 +209,6 @@ class _Handler(BaseHTTPRequestHandler):# can tell "no sessions yet" from "no sessions".scanning: threading.Event | None = Nonelock = threading.Lock()- write_lock = 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@@ -387,8 +386,9 @@ class _Handler(BaseHTTPRequestHandler):action = body.get("action") if isinstance(body, dict) else Noneif url.path != "/api/account":try:- # Its own lock: a write reads the index through `self.lock` itself.- with self.write_lock:+ # Shared with the CLI and the SessionStart hook (a file lock, not `self.lock`:+ # a write reads the index through `self.lock` itself).+ with fixes.write_lock(self.store.base):return self._write(url.path, str(action or ""), body)except fixes.FixError as exc:return self._error(409, exc.code, exc.message)diff --git a/python/tests/test_search_health_fixes.py b/python/tests/test_search_health_fixes.pyindex a676bec..fe782d1 100644--- a/python/tests/test_search_health_fixes.py+++ b/python/tests/test_search_health_fixes.py@@ -306,3 +306,87 @@ def test_command_label_only_names_vcs_actions_on_git_and_gh():assert command_label({"verb": "git", "vcs": {"action": "push"}}) == "git push"assert command_label({"verb": "pnpm test", "vcs": {"action": "status"}}) == "pnpm test"+++def test_undo_never_removes_what_was_there_before(repo):+ base, root = repo+ fixes.grant(base, "acme/api")+ (root / ".claude").mkdir()+ allow = {"kind": "settings_allow", "file": ".claude/settings.local.json", "entry": "Bash(ls:*)"}+ (root / ".claude/settings.local.json").write_text('{"permissions": {"allow": ["Bash(ls:*)"]}}')+ with pytest.raises(fixes.FixError) as exc:+ fixes.apply(base, FIX, allow)+ assert exc.value.code == "already_present" and not fixes.active(base)+ # A Stop group holding someone else's hook keeps it when ours is undone.+ (root / ".claude/settings.json").write_text(+ '{"hooks": {"Stop": [{"hooks": [{"type": "command", "command": "lint"}]}]}}'+ )+ hook = {"kind": "stop_hook", "file": ".claude/settings.json", "command": "pytest"}+ entry = fixes.apply(base, FIX, hook)+ data = json.loads((root / ".claude/settings.json").read_text())+ data["hooks"]["Stop"][0]["hooks"].append({"type": "command", "command": "pytest"})+ (root / ".claude/settings.json").write_text(json.dumps(data))+ fixes.undo(base, entry["id"])+ stop = json.loads((root / ".claude/settings.json").read_text())["hooks"]["Stop"]+ assert [h["command"] for g in stop for h in g["hooks"]] == ["lint"]+++def test_applying_twice_is_refused_and_a_failed_journal_rolls_back(repo, monkeypatch):+ base, root = repo+ fixes.grant(base, "acme/api")+ fixes.apply(base, FIX, MD)+ with pytest.raises(fixes.FixError) as exc:+ fixes.apply(base, FIX, MD)+ assert exc.value.code == "already_applied"++ def boom(*_a: Any) -> None:+ raise OSError("disk full")++ monkeypatch.setattr(fixes, "_save_journal", boom)+ with pytest.raises(OSError):+ fixes.apply(base, {**FIX, "id": "other"}, {**MD, "file": "CLAUDE.local.md"}, rel="CLAUDE.local.md")+ assert not (root / "CLAUDE.local.md").exists()+++def test_write_lock_is_reentrant(tmp_path):+ with fixes.write_lock(tmp_path), fixes.write_lock(tmp_path):+ pass+++def test_retirement_needs_a_real_gain_and_counts_blocked_denials():+ assert not autotune._improved("verified_share", 0.0, 0.0)+ assert autotune._improved("verified_share", 0.0, 0.5)+ assert not autotune._improved("fail_rate", 0.0, 0.0)+ rows = [{"facts": {"cmd": {"pnpm": {"calls": 2, "byClass": {"blocked": 1, "permission_denied": 1}}}}}]+ assert autotune.metric(rows, {"name": "denials", "verb": "pnpm"}) == 2+++def test_cache_miss_requests_are_charged_once():+ evs = [+ {"seq": 1, "kind": "llm", "agent": "main", "cost": 1.0, "in": 1000, "model": "claude-sonnet-4"},+ {"seq": 2, "kind": "read", "agent": "main", "targets": [{"file": 1, "touch": "read"}]},+ {"seq": 3, "kind": "read", "agent": "main", "targets": [{"file": 1, "touch": "read"}]},+ {"seq": 4, "kind": "llm", "agent": "main", "cost": 1.0, "in": 1_000_000, "model": "claude-sonnet-4"},+ ]+ waste = facts._waste({"agents": []}, evs, "completed")+ # Request 4 is a re-read's: its full cost goes there, and its cache-miss estimate leaves cacheMiss.+ assert waste["reread"] == 1.0 and waste["cacheMiss"] == 0+++def test_subagent_errors_count_as_dead_lanes():+ assert "subagent_error" in facts._DEAD_LANE+++def test_resolver_roots_keep_the_latest_checkout(tmp_path):+ from agentplay.builder import RepoResolver++ a, b = tmp_path / "a" / "api", tmp_path / "b" / "api"+ for d in (a, b):+ d.mkdir(parents=True)+ subprocess.run(["git", "init", "-q", str(d)], check=True)+ r = RepoResolver()+ r.resolve(str(a))+ r.resolve(str(b))+ r.resolve(str(a))+ name = next(iter(r.roots()))+ assert r.roots()[name] == str(a)diff --git a/viewer/src/core/insights.ts b/viewer/src/core/insights.tsindex 243a640..1caeadb 100644--- a/viewer/src/core/insights.ts+++ b/viewer/src/core/insights.ts@@ -53,10 +53,18 @@ export const sessionFactsSchema = z.object({});export type SessionFacts = z.infer<typeof sessionFactsSchema>;+const isoDay = z+ .string()+ .regex(/^\d{4}-\d{2}-\d{2}/)+ .refine((v) => !Number.isNaN(Date.parse(`${v.slice(0, 10)}T00:00:00Z`)))+ .nullable()+ .catch(null);+export const insightsSessionSchema = z.object({sessionId: z.string(),- sessionDate: z.string().nullable().catch(null),- startedAt: z.string().nullable().catch(null),+ // An imported map can carry any string here; a date that doesn't parse is treated as missing.+ sessionDate: isoDay,+ startedAt: isoDay,agentTool: z.string().catch('unknown'),models: z.array(z.string()).catch([]),repos: z.array(z.string()).catch([]),@@ -173,9 +181,10 @@ export const OUTCOME_ORDER: SessionOutcome[] = ['incomplete',];-/** Monday (UTC) of the week holding `iso`, as `YYYY-MM-DD`. */+/** Monday (UTC) of the week holding `iso`, as `YYYY-MM-DD` (empty when `iso` is not a date). */export function weekStart(iso: string): string {const d = new Date(`${iso.slice(0, 10)}T00:00:00Z`);+ if (Number.isNaN(d.getTime())) return '';const dow = (d.getUTCDay() + 6) % 7;d.setUTCDate(d.getUTCDate() - dow);return d.toISOString().slice(0, 10);@@ -194,6 +203,7 @@ export function outcomesByWeek(rows: InsightsSession[]): OutcomeWeek[] {const day = r.sessionDate ?? r.startedAt;if (!day) continue;const w = weekStart(day);+ if (!w) continue;byWeek.set(w, [...(byWeek.get(w) ?? []), r]);}return [...byWeek.entries()]@@ -259,12 +269,15 @@ export function spendByDay(return { days, series: [...series.entries()].map(([key, total]) => ({ key, total })) };}-/** Every UTC day from `first` through `last`, so a chart shows quiet days as gaps. */+/**+ * Every UTC day from `first` through `last`, so a chart shows quiet days as gaps.+ * Uncapped on purpose: callers bucket every day `spendByDay` returns, so the range must cover them all.+ */export function dayRange(first: string, last: string): string[] {const out: string[] = [];const d = new Date(`${first}T00:00:00Z`);const end = new Date(`${last}T00:00:00Z`);- while (d <= end && out.length < 400) {+ while (d <= end) {out.push(d.toISOString().slice(0, 10));d.setUTCDate(d.getUTCDate() + 1);}diff --git a/viewer/src/explorer/SessionExplorer.tsx b/viewer/src/explorer/SessionExplorer.tsxindex 67d186e..2137e5b 100644--- a/viewer/src/explorer/SessionExplorer.tsx+++ b/viewer/src/explorer/SessionExplorer.tsx@@ -293,7 +293,8 @@ export function SessionExplorer({// Picking a session shows its map and Details; the list stays, so// the next one is one click away rather than one back-out away.onSelect={(id) => {- if (id !== selectedId) void setScopeParams(CLEAR_SCOPE_PARAMS);+ // Always clear: a task, model or subagent scope may not contain the hit's event.+ void setScopeParams(CLEAR_SCOPE_PARAMS);void data.setSelected(id);}}// Open descends into it, on every task: any task/model narrowing from@@ -310,7 +311,8 @@ export function SessionExplorer({onLoadMore={() => void list.fetchNextPage()}unavailable={data.mapQuery.unavailable}onJump={(id, seq) => {- if (id !== selectedId) void setScopeParams(CLEAR_SCOPE_PARAMS);+ // Always clear: a task, model or subagent scope may not contain the hit's event.+ void setScopeParams(CLEAR_SCOPE_PARAMS);void data.setSelected(id);void setJumpAt(seq);}}diff --git a/viewer/src/insights/AutotuneView.tsx b/viewer/src/insights/AutotuneView.tsxindex 048a8b4..33b1dc3 100644--- a/viewer/src/insights/AutotuneView.tsx+++ b/viewer/src/insights/AutotuneView.tsx@@ -42,6 +42,15 @@ export function AutotuneView() {);}+function WriteError({ write }: { write: ReturnType<typeof useWrite> }) {+ if (!write.isError) return null;+ return (+ <p role="alert" className="rounded-md bg-ds-danger-subtlest px-3 py-2 ds-text-body-xs-medium text-ds-danger-darkest">+ {(write.error as Error).message}+ </p>+ );+}+function Summary({ s }: { s: AutotuneStatus }) {const on = s.repos.filter((r) => r.enabled && r.granted);const write = useWrite();@@ -66,6 +75,11 @@ function Summary({ s }: { s: AutotuneStatus }) {>Run now</Button>+ {write.isError ? (+ <div className="basis-full">+ <WriteError write={write} />+ </div>+ ) : null}</section>);}@@ -73,7 +87,8 @@ function Summary({ s }: { s: AutotuneStatus }) {function Repos({ s }: { s: AutotuneStatus }) {const write = useWrite();return (- <Panel title="Repos it can write to" question="Found in your sessions. It writes nowhere else.">+ <Panel title="Repository Access" question="Repositories found in your sessions. Autotune writes nowhere else.">+ <WriteError write={write} />{s.repos.length ? (<ul className="flex flex-col gap-2">{s.repos.map((r) => (@@ -136,7 +151,7 @@ function Repos({ s }: { s: AutotuneStatus }) {function Schedule({ s }: { s: AutotuneStatus }) {return (- <Panel title="When it runs" question="No background service needed.">+ <Panel title="Run Schedule"><p className="ds-text-body-xs-medium text-ds-text-default">{s.hookInstalled? 'At the first Claude Code session each day, from a SessionStart hook in your user settings.'@@ -159,10 +174,11 @@ function Waiting({ s }: { s: AutotuneStatus }) {const write = useWrite();return (<Panel- title="Waiting for you"+ title="Pending Approval"question="Changes that grant access or run code. Autotune never makes these on its own."action={s.pending.length ? <Badge variant="warning">{s.pending.length} waiting</Badge> : null}>+ <WriteError write={write} />{s.pending.length ? (<ul className="flex flex-col gap-2">{s.pending.map((p) => (@@ -211,7 +227,8 @@ function Log({ s }: { s: AutotuneStatus }) {const write = useWrite();const active = new Map(s.active.map((e) => [e.id, e]));return (- <Panel title="What Autotune changed" question="Each change is measured on its own metric. No effect after 15 sessions means it is removed.">+ <Panel title="Change History" question="Each change is measured on its own metric. A change with no effect after 15 sessions is removed.">+ <WriteError write={write} />{s.log.length ? (<ol className="flex flex-col">{s.log.map((l, i) => {@@ -228,7 +245,7 @@ function Log({ s }: { s: AutotuneStatus }) {<div className="min-w-0 flex-1"><div className="flex flex-wrap justify-between gap-2"><span className="ds-text-body-xs-semibold text-ds-text-darker">- {{ add: 'Added', approve: 'You approved', queue: 'Waiting for you', retire: 'Retired', error: 'Could not write' }[l.kind] ?? l.kind}: {l.title}+ {{ add: 'Added', approve: 'You approved', queue: 'Pending approval', retire: 'Retired', error: 'Could not write' }[l.kind] ?? l.kind}: {l.title}</span><span className="ds-text-body-xs-medium text-ds-text-subtle">{l.at ? new Date(l.at).toLocaleDateString() : ''}</span></div>diff --git a/viewer/src/insights/RunHealthView.tsx b/viewer/src/insights/RunHealthView.tsxindex 6cb5540..fbae2fd 100644--- a/viewer/src/insights/RunHealthView.tsx+++ b/viewer/src/insights/RunHealthView.tsx@@ -253,11 +253,10 @@ function PointsOnTheTable({ h, range }: { h: HealthReport; range: Range }) {Up to +{gain.toFixed(1)} points if every open fix works. Overlapping fixes are not double counted in the score itself.</p><ol className="flex flex-col gap-2">- {fixes.map((f, n) => (+ {fixes.map((f) => (<FixCardkey={f.id}fix={f}- n={h.fixes.indexOf(f) + 1 || n + 1}applied={applied.get(f.id)}repo={repos.get(f.repo)}range={range}@@ -282,14 +281,12 @@ function PointsOnTheTable({ h, range }: { h: HealthReport; range: Range }) {function FixCard({fix,- n,applied,repo,range,titles,}: {fix: Fix;- n: number;applied?: { id: string; file: string };repo?: { name: string; root: string | null; granted: boolean };range: Range;@@ -377,7 +374,7 @@ function FixCard({{preview ? 'Hide change' : 'Preview change'}</Button><span className="ds-text-body-xs-medium text-ds-text-subtle">- or run <code className="rounded bg-ds-gray-subtlest px-1.5 py-0.5 font-mono text-ds-text-darker">agentplay fix apply {n}</code>+ or run <code className="rounded bg-ds-gray-subtlest px-1.5 py-0.5 font-mono text-ds-text-darker">agentplay fix apply {fix.id}</code></span></>) : repo?.root ? (diff --git a/viewer/src/insights/panels.tsx b/viewer/src/insights/panels.tsxindex 7d35e2f..30a4e09 100644--- a/viewer/src/insights/panels.tsx+++ b/viewer/src/insights/panels.tsx@@ -227,7 +227,9 @@ export function SpendPanel({ rows }: { rows: InsightsSession[] }) {const buckets = new Map<string, Record<string, number>>();for (const d of range) buckets.set(weekly ? weekStart(d) : d, buckets.get(weekly ? weekStart(d) : d) ?? {});for (const d of days) {- const b = buckets.get(weekly ? weekStart(d.day) : d.day)!;+ const key = weekly ? weekStart(d.day) : d.day;+ const b = buckets.get(key) ?? {};+ buckets.set(key, b);for (const [k, v] of Object.entries(d.parts)) b[k] = (b[k] ?? 0) + v;}const bars = [...buckets.entries()].map(([key, parts]) => ({