Skip to content

Replay your coding agent sessions as a map and a timeline

fix: harden autotune, repo writes, search and Run health from review

Taradepan R476d9094e256
diff --git a/python/src/agentplay/autotune.py b/python/src/agentplay/autotune.py
index 17aaa1d..544854d 100644
--- a/python/src/agentplay/autotune.py
+++ b/python/src/agentplay/autotune.py
@@ -10,7 +10,8 @@ Off until turned on for a repo. Each run (at most once a day unless forced):
* a permission or hook fix is queued for the person to approve.
3. Measures every fix it applied on that fix's own metric over the sessions
since. After 15 sessions with less than a 10% improvement the fix is
- undone and logged as retired.
+ undone, logged as retired and not applied by Autotune again. A change the
+ person approved is measured but never retired.
State lives in ``~/.agentplay/autotune.json``; writes go through ``fixes.apply``.
"""
@@ -34,14 +35,20 @@ LOG_MAX = 200
def config(base: Path) -> dict[str, Any]:
+ path = base / CONFIG
try:
- raw = json.loads((base / CONFIG).read_text(encoding="utf-8"))
- except (OSError, ValueError):
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
raw = {}
- raw = raw if isinstance(raw, dict) else {}
+ except (OSError, ValueError):
+ raw = None
+ # Saving defaults over a file we could not read would erase repos, approvals and retired fixes.
+ if not isinstance(raw, dict):
+ raise fixes.FixError("bad_json", f"{path} could not be read as a JSON object; fix or remove it, then try again.")
raw.setdefault("repos", {})
raw.setdefault("pending", [])
raw.setdefault("dismissed", [])
+ raw.setdefault("retired", [])
raw.setdefault("log", [])
raw.setdefault("when", "manual")
return raw
@@ -162,6 +169,9 @@ def _run(store: Any, force: bool, today: str | None) -> dict[str, Any]:
for fx in health.fixes(rows):
if fx["repo"] not in enabled or fx["id"] in done or fx["id"] in queued or fx["id"] in cfg["dismissed"]:
continue
+ # A fix retired for no effect would otherwise be re-applied the next day, forever.
+ if fx["id"] in cfg["retired"]:
+ continue
md = next((a for a in fx["actions"] if a["kind"] == "claude_md"), None)
repo_rows = [r for r in rows if fx["repo"] in (r.get("repos") or [])]
if md:
@@ -189,8 +199,20 @@ def _run(store: Any, force: bool, today: str | None) -> dict[str, Any]:
for e in effects(store):
if e.get("source") != "autotune" or e.get("baseline") is None or e.get("current") is None:
continue
+ # A revoked repo, or one with Autotune switched off, is left as it is until it is back on.
+ if e["repo"] not in enabled:
+ continue
if e["sessionsSince"] >= RETIRE_AFTER and not _improved(e["metric"]["name"], e["baseline"], e["current"]):
- fixes.undo(base, e["id"], reason="no measurable effect")
+ try:
+ fixes.undo(base, e["id"], reason="no measurable effect")
+ except fixes.FixError as exc:
+ # Retried on later runs, but logged once rather than every day the checkout stays broken.
+ if not any(x["kind"] == "error" and x.get("entry") == e["id"] for x in cfg["log"]):
+ _log(cfg, "error", title=e["title"], repo=e["repo"], file=e["file"], entry=e["id"],
+ detail=exc.message)
+ continue
+ if e["fixId"] not in cfg["retired"]:
+ cfg["retired"].append(e["fixId"])
_log(cfg, "retire", title=e["title"], repo=e["repo"], file=e["file"],
detail=f"no measurable change after {e['sessionsSince']} sessions")
summary["retired"].append(e["title"])
@@ -210,7 +232,8 @@ def _approve(store: Any, fix_id: str) -> dict[str, Any]:
item = next((p for p in cfg["pending"] if p["fixId"] == fix_id), None)
if item is None:
raise fixes.FixError("not_found", "That fix is no longer waiting.")
- entry = fixes.apply(store.base, item["fix"], item["action"], source="autotune", baseline=item.get("baseline"))
+ # Not "autotune": the retire loop only removes what Autotune wrote unasked, never what the person approved.
+ entry = fixes.apply(store.base, item["fix"], item["action"], source="approved", baseline=item.get("baseline"))
cfg["pending"] = [p for p in cfg["pending"] if p["fixId"] != fix_id]
_log(cfg, "approve", title=item["fix"]["title"], repo=item["fix"]["repo"], file=item["action"].get("file"),
entry=entry["id"])
@@ -252,7 +275,8 @@ def status(store: Any) -> dict[str, Any]:
def _claude_settings() -> Path:
- return Path.home() / ".claude" / "settings.json"
+ # Resolved so a write replaces a dotfiles-managed symlink's target, not the symlink itself.
+ return (Path.home() / ".claude" / "settings.json").resolve()
def hook_installed() -> bool:
@@ -260,7 +284,13 @@ def hook_installed() -> bool:
data = json.loads(_claude_settings().read_text(encoding="utf-8"))
except (OSError, ValueError):
return False
- groups = ((data.get("hooks") or {}).get("SessionStart") or []) if isinstance(data, dict) else []
+ try:
+ groups = fixes.hook_groups(data, str(_claude_settings()), "SessionStart", create=False)
+ except fixes.FixError:
+ return False # a hand-broken file holds no hook of ours; install_hook reports the shape
+ return _has_hook(groups)
+
+def _has_hook(groups: list[Any]) -> bool:
return any(h.get("command") == HOOK_COMMAND for g in groups for h in g.get("hooks", []))
@@ -271,12 +301,12 @@ def install_hook() -> Path:
data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
except ValueError as exc:
raise fixes.FixError("bad_json", f"{path} is not valid JSON; fix it by hand first.") from exc
- if not hook_installed():
- data.setdefault("hooks", {}).setdefault("SessionStart", []).append(
- {"hooks": [{"type": "command", "command": HOOK_COMMAND}]}
- )
+ # Claude Code's own settings: an unexpected shape is refused, never overwritten.
+ groups = fixes.hook_groups(data, str(path), "SessionStart")
+ if not _has_hook(groups):
+ groups.append({"hooks": [{"type": "command", "command": HOOK_COMMAND}]})
path.parent.mkdir(parents=True, exist_ok=True)
- fixes._atomic_write(path, (json.dumps(data, indent=2) + "\n").encode("utf-8"))
+ fixes._atomic_write(path, (json.dumps(data, indent=2) + "\n").encode("utf-8"), private=False)
return path
@@ -286,11 +316,14 @@ def uninstall_hook() -> None:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
return
- groups = (data.get("hooks") or {}).get("SessionStart") or []
+ try:
+ groups = fixes.hook_groups(data, str(path), "SessionStart", create=False)
+ except fixes.FixError:
+ return # never rewrite a file whose shape we do not understand
kept = fixes.drop_hook(groups, HOOK_COMMAND)
if kept != groups:
if kept:
data["hooks"]["SessionStart"] = kept
else:
del data["hooks"]["SessionStart"]
- fixes._atomic_write(path, (json.dumps(data, indent=2) + "\n").encode("utf-8"))
+ fixes._atomic_write(path, (json.dumps(data, indent=2) + "\n").encode("utf-8"), private=False)
diff --git a/python/src/agentplay/cli.py b/python/src/agentplay/cli.py
index 5c4bc56..7892618 100644
--- a/python/src/agentplay/cli.py
+++ b/python/src/agentplay/cli.py
@@ -11,6 +11,8 @@ import json
import logging
import os
import re
+import shlex
+import shutil
import sys
import threading
import warnings
@@ -352,7 +354,8 @@ def cmd_fix(args: argparse.Namespace) -> int:
from . import fixes
st = Store()
- items = _health_fixes(st)
+ # Undo needs only the journal: a report that fails to compute must never block a revert.
+ items = [] if args.action == "undo" else _health_fixes(st)
if args.action == "list":
if not items:
print("No fixes: nothing specific stands out in the last 30 days.")
@@ -378,6 +381,9 @@ def cmd_fix(args: argparse.Namespace) -> int:
if not fx["actions"]:
print(f"agentplay: {fx['title']}: nothing to write; it names an integration to fix by hand.", file=sys.stderr)
return 1
+ if not 0 <= args.variant < len(fx["actions"]):
+ print(f"agentplay: {fx['title']}: --variant takes 0 to {len(fx['actions']) - 1}.", file=sys.stderr)
+ return 1
action = fx["actions"][args.variant]
try:
entry = fixes.apply(st.base, fx, action, rel=args.to, source="cli")
@@ -427,7 +433,10 @@ def cmd_autotune(args: argparse.Namespace) -> int:
autotune.save(st.base, cfg)
print(f"Add this to your crontab (crontab -e) to run daily at {args.at}:")
hh, mm = args.at.split(":")
- print(f" {int(mm)} {int(hh)} * * * {autotune.HOOK_COMMAND}")
+ # cron's PATH rarely holds pipx, uv or venv bin dirs, so name the command by absolute path.
+ found = shutil.which("agentplay")
+ exe = shlex.quote(os.path.abspath(found)) if found else f"{shlex.quote(sys.executable)} -m agentplay"
+ print(f" {int(mm)} {int(hh)} * * * {autotune.HOOK_COMMAND.replace('agentplay', exe, 1)}")
else:
path = autotune.install_hook()
cfg["when"] = "session-start"
diff --git a/python/src/agentplay/facts.py b/python/src/agentplay/facts.py
index 1d241ea..a01bdd7 100644
--- a/python/src/agentplay/facts.py
+++ b/python/src/agentplay/facts.py
@@ -18,7 +18,10 @@ from typing import Any
from .builder import _NON_CALL_KINDS, _error_source, estimate_cost_usd
-FACTS_VERSION = 4
+FACTS_VERSION = 5
+# Files kept per session in `files`, busiest first; the rest fold into `filesRest`.
+# A huge session would otherwise add hundreds of KB to its index row and to /api/stats.
+MAX_FACT_FILES = 300
# Outcomes whose whole cost counts as abandoned spend. `interrupted` is left
# out on purpose: stopping an agent is often the right call.
@@ -184,6 +187,12 @@ def compute(doc: dict[str, Any]) -> dict[str, Any]:
# 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}
+ files_rest: dict[str, int] = {}
+ if len(files) > MAX_FACT_FILES:
+ ranked = sorted(files.items(), key=lambda kv: (-kv[1]["hits"], -(kv[1]["reads"] + kv[1]["edits"]), kv[0]))
+ rest = [c for _, c in ranked[MAX_FACT_FILES:]]
+ files = dict(ranked[:MAX_FACT_FILES])
+ files_rest = {"count": len(rest), **{k: sum(c[k] for c in rest) for k in ("hits", "reads", "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")]
@@ -235,6 +244,7 @@ def compute(doc: dict[str, Any]) -> dict[str, Any]:
"errorsByClass": dict(t.get("errorsByClass") or {}),
"errorsBySource": by_source,
"files": files,
+ **({"filesRest": files_rest} if files_rest else {}),
"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),
diff --git a/python/src/agentplay/fixes.py b/python/src/agentplay/fixes.py
index 22fd0f5..2050661 100644
--- a/python/src/agentplay/fixes.py
+++ b/python/src/agentplay/fixes.py
@@ -185,13 +185,56 @@ def file_hash(text: str | None) -> str:
return hashlib.sha256((text or "").encode("utf-8")).hexdigest()[:16]
-def current(base: Path, repo: str, rel: str) -> str | None:
+def _read(path: Path) -> str | None:
+ # Bytes, not read_text: newline translation would turn a CRLF file into a whole-file rewrite.
try:
- return _target(base, repo, rel).read_text(encoding="utf-8")
+ return path.read_bytes().decode("utf-8")
except FileNotFoundError:
return None
+def current(base: Path, repo: str, rel: str) -> str | None:
+ return _read(_target(base, repo, rel))
+
+
+def _write(path: Path, text: str) -> None:
+ _atomic_write(path, text.encode("utf-8"), private=False)
+
+
+def _newline(text: str) -> str:
+ """The file's dominant line ending, so lines agentplay adds match the rest."""
+ crlf = text.count("\r\n")
+ return "\r\n" if crlf > text.count("\n") - crlf else "\n"
+
+
+def _ignore_locally(root: Path, rel: str) -> None:
+ """List a personal file agentplay just created in the repo's ``info/exclude`` so ``git add .`` skips it.
+
+ Not ``.gitignore``: that file is shared and tracked. Not journalled: an ignore
+ line for a personal file is harmless after undo. Only the literal anchored
+ line is checked (no git subprocess), so a redundant entry is possible when a
+ global ignore already covers the file.
+ """
+ try:
+ git = root / ".git"
+ if git.is_file(): # a linked worktree or submodule: ".git" holds "gitdir: <path>"
+ line = git.read_text(encoding="utf-8").strip()
+ if not line.startswith("gitdir:"):
+ return
+ git = (root / line[len("gitdir:"):].strip()).resolve()
+ common = git / "commondir" # worktrees share the main checkout's info/exclude
+ if common.is_file():
+ git = (git / common.read_text(encoding="utf-8").strip()).resolve()
+ exclude = git / "info" / "exclude"
+ text = exclude.read_text(encoding="utf-8") if exclude.exists() else ""
+ if f"/{rel}" in text.splitlines():
+ return
+ sep = "" if not text or text.endswith("\n") else "\n"
+ _atomic_write(exclude, f"{text}{sep}/{rel}\n".encode(), private=False)
+ except (OSError, ValueError):
+ pass # The fix itself is written and undoable; a missing ignore line must not fail it.
+
+
# ------------------------------------------------------------------ edits
@@ -199,17 +242,28 @@ def _marker(fix_id: str) -> str:
return f"<!-- agentplay:{fix_id} -->"
-def add_lines(text: str | None, fix_id: str, lines: list[str]) -> str:
+def add_lines(text: str | None, fix_id: str, lines: list[str], rel: str = "CLAUDE.md") -> str:
"""``text`` with ``lines`` added inside the managed block (created at the end if absent)."""
text = text or ""
+ nl = _newline(text)
tagged = [f"- {line} {_marker(fix_id)}" for line in lines]
- if START in text and END in text and text.index(START) < text.index(END):
+ starts, ends = text.count(START), text.count(END)
+ if (starts, ends) == (1, 1) and text.index(START) < text.index(END):
head, rest = text.split(START, 1)
block, tail = rest.split(END, 1)
- kept = [ln for ln in block.strip("\n").split("\n") if ln.strip() and _marker(fix_id) not in ln]
- return f"{head}{START}\n" + "\n".join(kept + tagged) + f"\n{END}{tail}"
- sep = "" if not text or text.endswith("\n\n") else "\n" if text.endswith("\n") else "\n\n"
- return f"{text}{sep}{HEADING}\n\n{START}\n" + "\n".join(tagged) + f"\n{END}\n"
+ kept = [ln.rstrip("\r") for ln in block.split("\n")]
+ kept = [ln for ln in kept if ln.strip() and _marker(fix_id) not in ln]
+ return f"{head}{START}{nl}" + nl.join(kept + tagged) + f"{nl}{END}{tail}"
+ if starts or ends:
+ # Guessing where a half-deleted block ends would swallow the person's own text.
+ raise FixError(
+ "malformed_block",
+ f"The agentplay block in {rel} is broken: it needs one {START} line followed by one {END} line "
+ f"(found {starts} and {ends}). Fix the markers by hand, or delete them along with the lines between, "
+ "then try again.",
+ )
+ sep = "" if not text or text.endswith(nl * 2) else nl if text.endswith("\n") else nl * 2
+ return f"{text}{sep}{HEADING}{nl}{nl}{START}{nl}" + nl.join(tagged) + f"{nl}{END}{nl}"
def remove_lines(text: str, fix_id: str) -> str:
@@ -234,21 +288,65 @@ def _apply_text(action: dict[str, Any], text: str | None, fix_id: str, rel: str)
lines = [str(x) for x in action.get("lines") or [] if str(x).strip()]
if not lines:
raise FixError("empty_fix", "This fix has nothing to write.")
- return add_lines(text, fix_id, lines)
+ return add_lines(text, fix_id, lines, rel)
data = _settings(text, rel)
if kind == "settings_allow":
- allow = data.setdefault("permissions", {}).setdefault("allow", [])
+ allow = _field(_field(data, "permissions", dict, rel, "permissions"), "allow", list, rel, "permissions.allow")
entry = str(action.get("entry") or "")
if entry and entry not in allow:
allow.append(entry)
elif kind == "stop_hook":
- stop = data.setdefault("hooks", {}).setdefault("Stop", [])
+ stop = hook_groups(data, rel, "Stop")
cmd = str(action.get("command") or "")
if not any(h.get("command") == cmd for g in stop for h in g.get("hooks", [])):
stop.append({"hooks": [{"type": "command", "command": cmd}]})
else:
raise FixError("unknown_action", "This fix cannot be written to a file.")
- return json.dumps(data, indent=2) + "\n"
+ return _dump(data, text)
+
+
+def _dump(data: dict[str, Any], like: str | None) -> str:
+ # JSON escapes newlines inside strings, so swapping every "\n" only changes line ends.
+ return (json.dumps(data, indent=2) + "\n").replace("\n", _newline(like or ""))
+
+
+_JSON_TYPES = ((bool, "true/false"), (dict, "an object"), (list, "an array"), (str, "a string"), (type(None), "null"))
+
+
+def _json_type(value: Any) -> str:
+ return next((name for t, name in _JSON_TYPES if isinstance(value, t)), "a number")
+
+
+def _field(data: dict[str, Any], key: str, kind: type, rel: str, where: str, create: bool = True) -> Any:
+ """``data[key]``, created empty if absent; a value of another type is refused, never overwritten."""
+ if key not in data:
+ if not create:
+ return kind()
+ data[key] = kind()
+ value = data[key]
+ if not isinstance(value, kind):
+ raise _shape_error(rel, where, value, _json_type(kind()))
+ return value
+
+
+def _shape_error(rel: str, where: str, value: Any, expected: str) -> FixError:
+ return FixError("bad_json", f"{rel} has {where} as {_json_type(value)}; expected {expected}; fix it by hand first.")
+
+
+def hook_groups(data: Any, rel: str, event: str, create: bool = True) -> list[Any]:
+ """The ``hooks.<event>`` groups, each checked to be ``{"hooks": [{...}, ...]}``."""
+ if not isinstance(data, dict):
+ raise _shape_error(rel, "the top level", data, "an object")
+ hooks = _field(data, "hooks", dict, rel, "hooks", create)
+ groups = _field(hooks, event, list, rel, f"hooks.{event}", create)
+ for i, group in enumerate(groups):
+ where = f"hooks.{event}[{i}]"
+ if not isinstance(group, dict):
+ raise _shape_error(rel, where, group, "an object")
+ for j, hook in enumerate(_field(group, "hooks", list, rel, f"{where}.hooks", create=False)):
+ if not isinstance(hook, dict):
+ raise _shape_error(rel, f"{where}.hooks[{j}]", hook, "an object")
+ return groups
def drop_hook(groups: list[Any], command: Any) -> list[Any]:
@@ -266,22 +364,42 @@ def drop_hook(groups: list[Any], command: Any) -> list[Any]:
return out
-def _undo_text(entry: dict[str, Any], text: str) -> str:
- kind = entry["action"].get("kind")
+# Containers agentplay may add to settings, parents first; the journal records which were absent.
+_CONTAINERS = ("permissions", "permissions.allow", "hooks")
+
+
+def _has(data: Any, dotted: str) -> bool:
+ for part in dotted.split("."):
+ if not isinstance(data, dict) or part not in data:
+ return False
+ data = data[part]
+ return True
+
+
+def _undo_text(entry: dict[str, Any], text: str) -> str | None:
+ """``text`` without the fix; None when all that is left is what agentplay created, so the file can go."""
+ kind, rel = entry["action"].get("kind"), entry["file"]
if kind == "claude_md":
- return remove_lines(text, entry["fixId"])
- data = _settings(text, entry["file"])
+ text = remove_lines(text, entry["fixId"])
+ return None if entry.get("created") and text.split() == f"{HEADING} {START} {END}".split() else text
+ data = _settings(text, rel)
if kind == "settings_allow":
- allow = (data.get("permissions") or {}).get("allow") or []
+ allow = _field(_field(data, "permissions", dict, rel, "permissions", False), "allow", list, rel,
+ "permissions.allow", False)
if entry["action"].get("entry") in allow:
allow.remove(entry["action"]["entry"])
elif kind == "stop_hook":
- stop = (data.get("hooks") or {}).get("Stop")
+ stop = hook_groups(data, rel, "Stop", create=False)
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"
+ for dotted in reversed(entry.get("added") or []):
+ parent, _, key = dotted.rpartition(".")
+ holder = data.get(parent) if parent else data
+ if isinstance(holder, dict) and holder.get(key) in ({}, []):
+ del holder[key]
+ return None if entry.get("created") and not data else _dump(data, text)
def preview(base: Path, repo: str, fix: dict[str, Any], action: dict[str, Any], rel: str | None = None) -> dict[str, Any]:
@@ -324,7 +442,7 @@ def _apply_locked(
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 None
+ before = _read(target)
if 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)
@@ -332,7 +450,7 @@ def _apply_locked(
# 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"))
+ _write(target, after)
entry = {
"id": uuid.uuid4().hex[:10],
"fixId": fix["id"],
@@ -345,7 +463,12 @@ def _apply_locked(
"metric": fix.get("metric"),
"baseline": baseline,
"at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ # So undo can remove what agentplay itself added and nothing the person had.
+ "created": before is None,
}
+ if action.get("kind") != "claude_md":
+ old, new = _settings(before, rel), _settings(after, rel)
+ entry["added"] = [k for k in _CONTAINERS if _has(new, k) and not _has(old, k)]
entries.append(entry)
try:
_save_journal(base, entries)
@@ -354,8 +477,10 @@ def _apply_locked(
if before is None:
target.unlink(missing_ok=True)
else:
- _atomic_write(target, before.encode("utf-8"))
+ _write(target, before)
raise
+ if before is None and rel in ("CLAUDE.local.md", ".claude/settings.local.json"):
+ _ignore_locally(Path(grants(base)[repo]).resolve(), rel)
return entry
@@ -370,9 +495,13 @@ def _undo_locked(base: Path, entry_id: str, reason: str) -> dict[str, Any]:
if entry is None:
raise FixError("not_found", "Nothing to undo with that id.")
target = _target(base, entry["repo"], entry["file"])
- if target.exists():
- text = target.read_text(encoding="utf-8")
- _atomic_write(target, _undo_text(entry, text).encode("utf-8"))
+ text = _read(target)
+ if text is not None:
+ after = _undo_text(entry, text)
+ if after is None:
+ target.unlink()
+ else:
+ _write(target, after)
entry["undoneAt"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
entry["undoReason"] = reason
_save_journal(base, entries)
diff --git a/python/src/agentplay/health.py b/python/src/agentplay/health.py
index 0fb27e9..aba34f9 100644
--- a/python/src/agentplay/health.py
+++ b/python/src/agentplay/health.py
@@ -40,7 +40,7 @@ QUIET_FORMS = {
"vitest": "vitest run --reporter=dot",
"pnpm vitest": "pnpm vitest run --reporter=dot",
"cargo test": "cargo test -q",
- "go test": "go test ./... (without -v)",
+ "go test": "go test ./...", # quiet by default; only -v is verbose
}
NOISY_BYTES = 40_000 # about 10k tokens of output per run
@@ -112,6 +112,7 @@ def totals(rows: Iterable[dict[str, Any]]) -> Totals:
t.tok_cr += int(tok.get("cr") or 0)
t.compacting += int((f.get("compactions") or 0) > 0)
t.reads += sum(int(x.get("reads") or 0) for x in (f.get("files") or {}).values())
+ t.reads += int((f.get("filesRest") or {}).get("reads") or 0) # files past facts.MAX_FACT_FILES
t.rereads_ac += int(f.get("rereadsAfterCompaction") or 0)
t.config_errors += _config_errors(f)
return t
@@ -374,9 +375,9 @@ def fixes(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
def _worst(rows: list[dict[str, Any]], key: str) -> list[dict[str, Any]]:
def why(f: dict[str, Any]) -> tuple[float, str] | None:
if key == "shipping" and f.get("edited") and not f.get("prsCreated"):
- return f.get("costUsd", 0), "edited code, no PR"
+ return f.get("costUsd") or 0, "edited code, no PR"
if key == "verification" and f.get("edited") and not f.get("verifyAfterLastEdit"):
- return f.get("costUsd", 0), "no check after the last edit"
+ return f.get("costUsd") or 0, "no check after the last edit"
if key == "efficiency" and (f.get("errors", 0) + f.get("retries", 0)):
n = f.get("errors", 0) + f.get("retries", 0)
return n, f"{n} failed calls and retries"
diff --git a/python/src/agentplay/pipeline.py b/python/src/agentplay/pipeline.py
index 8b8ceb5..195305e 100644
--- a/python/src/agentplay/pipeline.py
+++ b/python/src/agentplay/pipeline.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import json
import logging
import os
import time
@@ -9,15 +10,18 @@ from collections import Counter
from collections.abc import Callable
from dataclasses import dataclass, field
from datetime import UTC, datetime
+from pathlib import Path
from typing import Any
from . import __version__, builder, discover, facts, fixes, search
-from .store import Store
+from .store import Store, _atomic_write
logger = logging.getLogger("agentplay.pipeline")
# How often a long build writes the index mid-run (seconds).
SAVE_EVERY_S = 2.0
+# A repo name whose checkout could not be found is looked for again after this long.
+UNRESOLVED_RETRY_S = 7 * 86400
@dataclass
@@ -129,6 +133,15 @@ def _sync_titles(store: Store, cand: discover.Candidate, source: Any, *, titles:
return changed
+def _unresolved(base: Path) -> dict[str, float]:
+ """Repo name -> when its checkout was last looked for in vain (``repos-unresolved.json``)."""
+ try:
+ raw = json.loads((base / "repos-unresolved.json").read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return {}
+ return {str(k): float(v) for k, v in raw.items() if isinstance(v, int | float)} if isinstance(raw, dict) else {}
+
+
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.
@@ -211,6 +224,11 @@ def build_all(
# 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()
+ # Names whose session parsed, so a missing root really means no checkout (a failed parse proves nothing).
+ looked: set[str] = set()
+ # Names that failed to resolve recently: re-parsing a session for them each run costs a lot for nothing.
+ missed = _unresolved(store.base)
+ waiting = {n for n, at in missed.items() if time.time() - at < UNRESOLVED_RETRY_S}
for i, c in enumerate(cands):
if pending and time.monotonic() - last_save >= SAVE_EVERY_S:
store.save_index()
@@ -222,12 +240,13 @@ def build_all(
report.by_agent[c.agent] += 1
if _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
+ need = set((store.index.get(c.session_id) or {}).get("repos") or []) - set(known_roots) - tried - waiting
if need:
tried |= need
try:
discover.build_map(c, source, path_mode=path_mode, hmac_key=hmac_key, version=__version__,
resolver=resolver)
+ looked |= need
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)
continue
@@ -257,6 +276,10 @@ def build_all(
# Only names a stored map uses: a checkout merely passed on the way is not recorded.
used = {n for r in store.index.values() for n in r.get("repos") or []}
fixes.record_roots(store.base, {n: p for n, p in resolver.roots().items() if n in used})
+ failed = looked - set(resolver.roots())
+ if failed:
+ _atomic_write(store.base / "repos-unresolved.json",
+ json.dumps({**missed, **dict.fromkeys(failed, time.time())}).encode("utf-8"))
search.refresh(store)
except OSError as exc: # the index is what matters; search catches up next run
report.errors.append(f"search index: {exc}")
diff --git a/python/src/agentplay/search.py b/python/src/agentplay/search.py
index aaf2a50..4571fc4 100644
--- a/python/src/agentplay/search.py
+++ b/python/src/agentplay/search.py
@@ -19,9 +19,9 @@ from typing import Any
from .facts import command_label
-SEARCH_VERSION = 2
+SEARCH_VERSION = 3
FACETS = ("file", "cmd", "mcp", "skill", "subagent", "model", "repo", "host", "err")
-# Postings kept per term per session: enough to step through, small enough to load.
+# Postings kept per term, per touch kind, per session: enough to step through, small enough to load.
MAX_SEQS = 40
_FACET_RE = re.compile(rf"^({'|'.join(FACETS)}):(.+)$", re.I)
@@ -29,15 +29,25 @@ TOUCHES = ("hit", "read", "edit", "fail")
def postings(doc: dict[str, Any]) -> dict[str, list[list[Any]]]:
- """``term -> [[seq, touch], ...]`` for one map. Session-level terms carry seq None."""
+ """``term -> [[seq, touch], ...]`` for one map. Session-level terms carry seq None.
+
+ Each touch kind keeps its first ``MAX_SEQS`` postings; when it overflows, its
+ first posting carries the true total as a third item.
+ """
out: dict[str, list[list[Any]]] = {}
+ firsts: dict[tuple[str, str], list[Any]] = {}
+ totals: dict[tuple[str, str], int] = {}
files = {f.get("id"): f for f in doc.get("files") or []}
repos = {r.get("id"): r.get("name") for r in doc.get("repos") or []}
def add(term: str, seq: int | None, touch: str) -> None:
- lst = out.setdefault(term.lower(), [])
- if len(lst) < MAX_SEQS:
- lst.append([seq, touch])
+ term = term.lower()
+ key = (term, touch)
+ totals[key] = totals.get(key, 0) + 1
+ if totals[key] <= MAX_SEQS:
+ posting = [seq, touch]
+ firsts.setdefault(key, posting)
+ out.setdefault(term, []).append(posting)
for e in doc.get("events") or []:
seq = e.get("seq")
@@ -72,6 +82,9 @@ def postings(doc: dict[str, Any]) -> dict[str, list[list[Any]]]:
for name in repos.values():
if name:
add(f"repo:{name}", None, "hit")
+ for key, n in totals.items():
+ if n > MAX_SEQS:
+ firsts[key].append(n)
return out
@@ -108,7 +121,8 @@ def refresh(store: Any) -> int:
for sid, row in store.index.items():
h = str(row.get("contentHash") or "")
prev = old.get(sid)
- if isinstance(prev, dict) and prev.get("hash") == h:
+ # An empty hash says nothing about content, so it never counts as current.
+ if h and isinstance(prev, dict) and prev.get("hash") == h:
out[sid] = prev
continue
doc = store.get(sid)
@@ -170,39 +184,56 @@ def query(terms_by_session: dict[str, dict[str, list[list[Any]]]], q: str) -> di
hits = [(t, p) for t, ps in terms.items() if _matches(t, facet, value) for p in ps]
if not hits:
continue
- seqs = sorted({p[0] for _, p in hits if p[0] is not None})
groups: dict[tuple[str, str], list[int | None]] = {}
- for t, (seq, touch) in hits:
+ totals: dict[tuple[str, str], int] = {}
+ for t, (seq, touch, *total) in hits:
# The basename and the full-path term of one file are the same match.
key = (_label(t), touch)
if seq not in groups.setdefault(key, []):
groups[key].append(seq)
+ if total:
+ totals[key] = max(totals.get(key, 0), total[0])
+ # Stored postings are capped per touch kind, so cap per kind here too or a
+ # busy file's reads would crowd its edits out of the stepper.
+ by_touch: dict[str, set[int]] = {}
+ for (_, touch), s in groups.items():
+ by_touch.setdefault(touch, set()).update(x for x in s if x is not None)
+ seqs = sorted({x for v in by_touch.values() for x in sorted(v)[:MAX_SEQS]})
+ counts = {k: max(len(s), totals.get(k, 0)) for k, s in groups.items()}
chips = sorted(
(
{
- "label": f"{_VERBS.get(touch, touch)} {label}" + (f" {len(s)}×" if s[0] is not None else ""),
+ "label": f"{_VERBS.get(touch, touch)} {label}" + (f" {counts[label, touch]}×" if s[0] is not None else ""),
"touch": touch,
"seq": min((x for x in s if x is not None), default=None),
- "n": len(s),
+ "n": counts[label, touch],
}
for (label, touch), s in groups.items()
),
key=lambda c: (-TOUCHES.index(c["touch"]) if c["touch"] in TOUCHES else 0, -c["n"]),
)
- out[sid] = {"count": len(seqs) or len(hits), "seqs": seqs[:MAX_SEQS], "chips": chips[:4]}
+ truncated = bool(totals)
+ count = sum(counts.values()) if truncated else len(seqs) or len(hits)
+ out[sid] = {"count": count, "seqs": seqs, "chips": chips[:4]}
return out
def argument_fallback(terms_by_session: dict[str, dict[str, list[list[Any]]]], q: str) -> tuple[str, dict[str, Any]] | None:
"""A query that names command arguments (``pnpm test auth``) can't match: arguments
- are never stored. Retry with the longest command prefix that does match."""
+ are never stored. Retry with the longest leading words that exactly name a recorded
+ command (``pnpm test``) or its family (``git`` for ``git push``), never a substring."""
facet, value = parse(q)
if facet not in (None, "cmd"):
return None
words = value.split()
for n in range(len(words) - 1, 0, -1):
prefix = " ".join(words[:n])
- hits = query(terms_by_session, f"cmd:{prefix}")
+ own = f"cmd:{prefix}"
+ exact = {
+ sid: {t: ps for t, ps in terms.items() if t == own or t.startswith(own + " ")}
+ for sid, terms in terms_by_session.items()
+ }
+ hits = query(exact, own)
if hits:
return prefix, hits
return None
diff --git a/python/src/agentplay/server.py b/python/src/agentplay/server.py
index 03cfb99..4de44b0 100644
--- a/python/src/agentplay/server.py
+++ b/python/src/agentplay/server.py
@@ -535,8 +535,8 @@ class _Handler(BaseHTTPRequestHandler):
sid = str(r.get("sessionId") or "")
h = str(r.get("contentHash") or "")
entry = indexed.get(sid)
- if isinstance(entry, dict) and entry.get("hash") == h:
- out[sid] = entry.get("terms") or {}
+ if isinstance(entry, dict) and entry.get("hash") == h and isinstance(entry.get("terms"), dict):
+ out[sid] = entry["terms"]
continue
key = (sid, h)
if key not in self.search_mem:
diff --git a/python/src/agentplay/store.py b/python/src/agentplay/store.py
index f3064e4..6fec434 100644
--- a/python/src/agentplay/store.py
+++ b/python/src/agentplay/store.py
@@ -17,7 +17,8 @@ import hashlib
import json
import os
import re
-import tempfile
+import stat
+import uuid
from collections.abc import Iterator
from pathlib import Path
from typing import Any
@@ -29,12 +30,30 @@ def root() -> Path:
return Path(os.environ.get("AGENTPLAY_HOME") or Path.home() / ".agentplay")
-def _atomic_write(path: Path, data: bytes) -> None:
+def _atomic_write(path: Path, data: bytes, *, private: bool = True) -> None:
+ """Replace ``path`` with ``data`` atomically, keeping an existing file's mode.
+
+ A new file is 0600 when ``private`` (agentplay's own store), else the umask
+ default like any editor would create (files in a person's repo).
+ """
+ # A person's file may be a dotfiles-managed symlink: write its target, never replace the link.
+ # agentplay's own store never follows one, so a link planted there cannot redirect a write.
+ if not private:
+ path = Path(os.path.realpath(path))
path.parent.mkdir(parents=True, exist_ok=True)
- fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=path.name, suffix=".tmp")
+ try:
+ mode: int | None = stat.S_IMODE(path.stat().st_mode)
+ except FileNotFoundError:
+ mode = None
+ tmp = path.parent / f"{path.name}{uuid.uuid4().hex[:8]}.tmp"
+ # The kernel applies the umask to the create mode, so no process-wide umask juggling between threads.
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)
+ fd = os.open(tmp, flags, 0o600 if private or mode is not None else 0o666)
try:
with os.fdopen(fd, "wb") as fh:
fh.write(data)
+ if mode is not None:
+ os.chmod(tmp, mode)
os.replace(tmp, path)
except BaseException:
try:
diff --git a/python/tests/test_autotune_lifecycle.py b/python/tests/test_autotune_lifecycle.py
new file mode 100644
index 0000000..35f9cc2
--- /dev/null
+++ b/python/tests/test_autotune_lifecycle.py
@@ -0,0 +1,185 @@
+"""Autotune across runs: retiring, revoked repos, approved changes, the hook file and the CLI around it."""
+
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+from typing import Any
+
+import pytest
+
+from agentplay import autotune, cli, fixes, health
+from agentplay.store import Store
+
+MD = {"kind": "claude_md", "file": "CLAUDE.md", "lines": ["Run `pytest -q`."]}
+HOOK = {"kind": "stop_hook", "label": "Add Stop hook", "file": ".claude/settings.json", "command": "pytest"}
+METRIC = {"name": "verified_share"}
+
+
+def _fix(fix_id: str, action: dict[str, Any]) -> dict[str, Any]:
+ return {"id": fix_id, "repo": "acme/api", "title": f"fix {fix_id}", "rule": "r", "pattern": "",
+ "points": 1.0, "metric": METRIC, "actions": [action]}
+
+
+def tuned(tmp_path, monkeypatch):
+ """A granted, enabled repo whose fixes never move their metric; ``due`` makes every applied fix up for review."""
+ root = tmp_path / "checkout"
+ root.mkdir()
+ subprocess.run(["git", "init", "-q", str(root)], check=True)
+ base = tmp_path / "home"
+ base.mkdir()
+ fixes.record_roots(base, {"acme/api": str(root)})
+ fixes.grant(base, "acme/api")
+ autotune.set_repo(base, "acme/api", enabled=True)
+ found: list[dict[str, Any]] = []
+ due: list[bool] = []
+ monkeypatch.setattr(health, "fixes", lambda _rows: found)
+ monkeypatch.setattr(autotune, "root_rows", lambda *_a, **_k: [])
+ monkeypatch.setattr(autotune, "metric", lambda *_a: 0.5)
+ monkeypatch.setattr(autotune, "effects", lambda st: [
+ {**e, "sessionsSince": autotune.RETIRE_AFTER if due else 0, "current": 0.5} for e in fixes.active(st.base)
+ ])
+ return Store(base), root, found, due
+
+
+def test_a_retired_fix_is_not_applied_again(tuned):
+ st, root, found, due = tuned
+ found.append(_fix("md0001", MD))
+ assert autotune.run(st, force=True)["applied"] == ["fix md0001"]
+ due.append(True)
+ assert autotune.run(st, force=True)["retired"] == ["fix md0001"]
+ assert autotune.run(st, force=True)["applied"] == []
+ assert not (root / "CLAUDE.local.md").exists()
+ # Only Autotune skips it: the person can still apply it by hand.
+ fixes.apply(st.base, found[0], MD, rel="CLAUDE.local.md")
+ assert "pytest" in (root / "CLAUDE.local.md").read_text()
+
+def test_switching_autotune_off_leaves_its_fixes_alone(tuned):
+ st, root, found, due = tuned
+ found.append(_fix("md0001", MD))
+ autotune.run(st, force=True)
+ autotune.set_repo(st.base, "acme/api", enabled=False)
+ due.append(True)
+ assert autotune.run(st, force=True)["retired"] == []
+ assert "pytest" in (root / "CLAUDE.local.md").read_text()
+
+def test_an_unreadable_config_is_reported_and_never_overwritten(tuned):
+ st, *_ = tuned
+ path = st.base / autotune.CONFIG
+ path.write_text("{not json")
+ with pytest.raises(fixes.FixError) as exc:
+ autotune.run(st, force=True)
+ assert exc.value.code == "bad_json" and path.read_text() == "{not json"
+
+
+def test_a_revoked_or_broken_repo_does_not_abort_the_run(tuned):
+ st, root, found, due = tuned
+ found.append(_fix("md0001", MD))
+ autotune.run(st, force=True)
+ due.append(True)
+ fixes.revoke(st.base, "acme/api")
+ res = autotune.run(st, force=True, today="2099-01-01")
+ assert res["retired"] == [] and autotune.config(st.base)["lastRun"]
+ assert not [x for x in autotune.config(st.base)["log"] if x["kind"] == "error"]
+ # Granted again but the checkout lost .git: logged once, not on every daily run.
+ fixes.grant(st.base, "acme/api")
+ shutil.rmtree(root / ".git")
+ autotune.run(st, force=True)
+ autotune.run(st, force=True)
+ errors = [x for x in autotune.config(st.base)["log"] if x["kind"] == "error"]
+ assert len(errors) == 1 and "git checkout" in errors[0]["detail"]
+ assert len(fixes.active(st.base)) == 1 # still there to retire once the checkout is back
+
+
+def test_autotune_never_removes_a_change_the_person_approved(tuned):
+ st, root, found, due = tuned
+ found.append(_fix("hook01", HOOK))
+ assert autotune.run(st, force=True)["queued"] == ["fix hook01"]
+ autotune.approve(st, "hook01")
+ due.append(True)
+ assert autotune.run(st, force=True)["retired"] == []
+ assert [e["fixId"] for e in fixes.active(st.base)] == ["hook01"]
+ assert "pytest" in (root / ".claude" / "settings.json").read_text()
+
+
+def test_hook_install_writes_through_a_symlinked_settings_file(tmp_path, monkeypatch):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ real = tmp_path / "dotfiles" / "settings.json"
+ real.parent.mkdir()
+ real.write_text(json.dumps({"theme": "dark"}))
+ (tmp_path / ".claude").mkdir()
+ link = tmp_path / ".claude" / "settings.json"
+ link.symlink_to(real)
+ autotune.install_hook()
+ assert link.is_symlink() and autotune.hook_installed()
+ assert json.loads(real.read_text())["theme"] == "dark"
+ autotune.uninstall_hook()
+ assert link.is_symlink() and not autotune.hook_installed()
+ assert json.loads(real.read_text())["theme"] == "dark"
+
[email protected]("settings", [{"hooks": None}, {"hooks": []}, {"hooks": {"SessionStart": "x"}}, [1]])
+def test_a_hand_broken_settings_file_is_reported_not_crashed_or_rewritten(tmp_path, monkeypatch, settings):
+ monkeypatch.setenv("HOME", str(tmp_path))
+ path = tmp_path / ".claude" / "settings.json"
+ path.parent.mkdir()
+ path.write_text(json.dumps(settings))
+ assert autotune.hook_installed() is False
+ autotune.uninstall_hook()
+ with pytest.raises(fixes.FixError) as exc:
+ autotune.install_hook()
+ assert exc.value.code == "bad_json" and json.loads(path.read_text()) == settings
+
+
+def test_cron_line_names_an_absolute_command(tmp_path, monkeypatch, capsys):
+ monkeypatch.setattr(cli, "Store", lambda: Store(tmp_path))
+ monkeypatch.setattr(fixes, "status", lambda _b: {"repos": []})
+ monkeypatch.setattr(autotune, "uninstall_hook", lambda: None)
+ monkeypatch.setattr(shutil, "which", lambda _n: "/opt/tools/bin/agentplay")
+
+ class A:
+ action, at, repo = "on", "09:30", []
+
+ assert cli.cmd_autotune(A()) == 0
+ assert "30 9 * * * /opt/tools/bin/agentplay autotune run --daily --quiet" in capsys.readouterr().out
+
+
+def test_fix_variant_out_of_range_is_an_error(tmp_path, monkeypatch, capsys):
+ monkeypatch.setattr(cli, "Store", lambda: Store(tmp_path))
+ monkeypatch.setattr(cli, "_health_fixes", lambda *_a, **_k: [_fix("md0001", MD)])
+ applied = []
+ monkeypatch.setattr(fixes, "apply", lambda *a, **k: applied.append(a))
+
+ class A:
+ action, target, to = "apply", "1", None
+
+ for variant in (1, -1):
+ A.variant = variant
+ assert cli.cmd_fix(A()) == 1
+ assert "--variant" in capsys.readouterr().err
+ assert not applied
+
+def test_undo_works_even_when_the_health_report_cannot_be_computed(tuned, monkeypatch, capsys):
+ st, root, found, _ = tuned
+ entry = fixes.apply(st.base, _fix("md0001", MD), MD)
+ monkeypatch.setattr(cli, "Store", lambda: st)
+
+ def broken(*_a, **_k):
+ raise ValueError("a stored map is malformed")
+
+ monkeypatch.setattr(cli, "_health_fixes", broken)
+
+ class A:
+ action, target = "undo", entry["id"]
+
+ assert cli.cmd_fix(A()) == 0 and not (root / "CLAUDE.md").exists()
+
+def test_approving_a_change_after_its_repo_is_revoked_writes_nothing(tuned):
+ st, root, found, _ = tuned
+ found.append(_fix("hook01", HOOK))
+ assert autotune.run(st, force=True)["queued"] == ["fix hook01"]
+ fixes.revoke(st.base, "acme/api")
+ with pytest.raises(fixes.FixError) as exc:
+ autotune.approve(st, "hook01")
+ assert exc.value.code == "not_granted" and not (root / ".claude" / "settings.json").exists()
diff --git a/python/tests/test_fixes_safety.py b/python/tests/test_fixes_safety.py
new file mode 100644
index 0000000..172a0bc
--- /dev/null
+++ b/python/tests/test_fixes_safety.py
@@ -0,0 +1,313 @@
+"""Fix writes never damage a person's files: malformed blocks, line endings, modes, odd JSON, ignores, undo."""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+
+from agentplay import fixes
+from agentplay.store import _atomic_write
+
+# Tests read git's view without the developer's own global ignores (Claude Code adds
+# settings.local.json there), so only what agentplay wrote counts.
+GIT_ENV = {**os.environ, "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1"}
+
+FIX = {"id": "abc123", "repo": "acme/api", "title": "t", "rule": "r", "metric": None}
+MD = {"kind": "claude_md", "file": "CLAUDE.md", "lines": ["Run `pytest -q`."]}
+ALLOW = {"kind": "settings_allow", "file": ".claude/settings.json", "entry": "Bash(ls:*)"}
+HOOK = {"kind": "stop_hook", "file": ".claude/settings.json", "command": "pytest"}
+posix_only = pytest.mark.skipif(sys.platform == "win32", reason="POSIX file modes")
+
+
+def _git(*args: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(["git", *args], env=GIT_ENV, capture_output=True, text=True)
+
+
+def repo(tmp_path):
+ root = tmp_path / "checkout"
+ root.mkdir()
+ _git("init", "-q", str(root))
+ base = tmp_path / "home"
+ base.mkdir()
+ fixes.record_roots(base, {"acme/api": str(root)})
+ fixes.grant(base, "acme/api")
+ return base, root
+
+
+# ------------------------------------------------------------------ 1. malformed blocks
+
+
+ "body",
+ [
+ f"# Mine\n\n{fixes.START}\n- old\n\nMy text.\n", # END deleted
+ f"# Mine\n\n- old\n{fixes.END}\nMy text.\n", # START deleted
+ f"# Mine\n{fixes.END}\nx\n{fixes.START}\n", # out of order
+ f"{fixes.START}\n{fixes.END}\n{fixes.START}\n{fixes.END}\n", # two blocks
+ ],
+)
+def test_a_broken_block_is_refused_and_the_file_is_untouched(repo, body):
+ base, root = repo
+ (root / "CLAUDE.md").write_text(body)
+ with pytest.raises(fixes.FixError) as exc:
+ fixes.preview(base, "acme/api", FIX, MD)
+ assert exc.value.code == "malformed_block" and "CLAUDE.md" in exc.value.message
+ with pytest.raises(fixes.FixError) as exc:
+ fixes.apply(base, FIX, MD)
+ assert exc.value.code == "malformed_block"
+ assert (root / "CLAUDE.md").read_text() == body and not fixes.active(base)
+
+
+def test_undo_after_the_person_breaks_the_block_removes_only_our_lines(repo):
+ base, root = repo
+ (root / "CLAUDE.md").write_text("# Mine\n")
+ entry = fixes.apply(base, FIX, MD)
+ broken = (root / "CLAUDE.md").read_text().replace(fixes.END + "\n", "") + "My text.\n"
+ (root / "CLAUDE.md").write_text(broken)
+ fixes.undo(base, entry["id"])
+ left = (root / "CLAUDE.md").read_text()
+ assert "pytest -q" not in left and left.startswith("# Mine\n") and left.endswith("My text.\n")
+
+
+# ------------------------------------------------------------------ 2. line endings
+
+
+def test_crlf_file_keeps_crlf_through_preview_apply_and_undo(repo):
+ base, root = repo
+ original = b"# Mine\r\n\r\nKeep this.\r\n"
+ (root / "CLAUDE.md").write_bytes(original)
+ pv = fixes.preview(base, "acme/api", FIX, MD)
+ entry = fixes.apply(base, FIX, MD, expect_hash=pv["hash"])
+ raw = (root / "CLAUDE.md").read_bytes()
+ assert raw.startswith(original) and b"\n" not in raw.replace(b"\r\n", b"")
+ assert raw.decode() == pv["after"]
+ second = fixes.apply(base, {**FIX, "id": "zzz"}, {**MD, "lines": ["Second."]})
+ raw = (root / "CLAUDE.md").read_bytes()
+ assert raw.count(fixes.START.encode()) == 1 and b"\n" not in raw.replace(b"\r\n", b"")
+ fixes.undo(base, second["id"])
+ fixes.undo(base, entry["id"])
+ assert (root / "CLAUDE.md").read_bytes().startswith(original)
+ assert b"\n" not in (root / "CLAUDE.md").read_bytes().replace(b"\r\n", b"")
+
+
+def test_crlf_settings_stay_crlf(repo):
+ base, root = repo
+ (root / ".claude").mkdir()
+ (root / ".claude/settings.json").write_bytes(b'{\r\n "model": "x"\r\n}\r\n')
+ fixes.apply(base, FIX, ALLOW)
+ raw = (root / ".claude/settings.json").read_bytes()
+ assert b"\n" not in raw.replace(b"\r\n", b"") and json.loads(raw)["permissions"]["allow"] == ["Bash(ls:*)"]
+
+
+# ------------------------------------------------------------------ 3. modes and symlinks
+
+
+@posix_only
+def test_repo_files_keep_their_mode_and_new_ones_follow_umask(repo):
+ base, root = repo
+ (root / "CLAUDE.md").write_text("# Mine\n")
+ os.chmod(root / "CLAUDE.md", 0o664)
+ entry = fixes.apply(base, FIX, MD)
+ assert (root / "CLAUDE.md").stat().st_mode & 0o777 == 0o664
+ fixes.undo(base, entry["id"])
+ assert (root / "CLAUDE.md").stat().st_mode & 0o777 == 0o664
+ old = os.umask(0o022)
+ try:
+ fixes.apply(base, FIX, ALLOW)
+ finally:
+ os.umask(old)
+ assert (root / ".claude/settings.json").stat().st_mode & 0o777 == 0o644
+
+
+@posix_only
+def test_private_store_files_stay_private(tmp_path):
+ old = os.umask(0o022)
+ try:
+ _atomic_write(tmp_path / "index.json", b"{}")
+ finally:
+ os.umask(old)
+ assert (tmp_path / "index.json").stat().st_mode & 0o777 == 0o600
+
+
+def test_atomic_write_goes_through_a_symlink(tmp_path):
+ real = tmp_path / "dotfiles" / "settings.json"
+ real.parent.mkdir()
+ real.write_text("{}")
+ link = tmp_path / "settings.json"
+ link.symlink_to(real)
+ _atomic_write(link, b'{"a": 1}', private=False)
+ assert link.is_symlink() and real.read_text() == '{"a": 1}'
+ assert [p.name for p in real.parent.iterdir()] == ["settings.json"]
+
+
+def test_a_store_write_replaces_a_planted_symlink_instead_of_following_it(tmp_path):
+ victim = tmp_path / "victim.txt"
+ victim.write_text("keep")
+ link = tmp_path / "store" / "index.json"
+ link.parent.mkdir()
+ link.symlink_to(victim)
+ _atomic_write(link, b"{}")
+ assert not link.is_symlink() and link.read_text() == "{}" and victim.read_text() == "keep"
+
+
+def test_a_symlink_out_of_the_repo_is_still_refused(repo, tmp_path):
+ base, root = repo
+ outside = tmp_path / "outside.md"
+ outside.write_text("x")
+ (root / "CLAUDE.md").symlink_to(outside)
+ with pytest.raises(fixes.FixError) as exc:
+ fixes.apply(base, FIX, MD)
+ assert exc.value.code == "outside_repo" and outside.read_text() == "x"
+
+
+# ------------------------------------------------------------------ 4. unexpected JSON shapes
+
+
+ "action,body",
+ [
+ (ALLOW, {"permissions": None}),
+ (ALLOW, {"permissions": []}),
+ (ALLOW, {"permissions": {"allow": "Bash(ls:*)"}}),
+ (ALLOW, {"permissions": {"allow": None}}),
+ (HOOK, {"hooks": None}),
+ (HOOK, {"hooks": []}),
+ (HOOK, {"hooks": {"Stop": "pytest"}}),
+ (HOOK, {"hooks": {"Stop": ["pytest"]}}),
+ (HOOK, {"hooks": {"Stop": [{"hooks": "pytest"}]}}),
+ (HOOK, {"hooks": {"Stop": [{"hooks": ["pytest"]}]}}),
+ ],
+)
+def test_odd_settings_shapes_are_refused_not_crashed(repo, action, body):
+ base, root = repo
+ (root / ".claude").mkdir()
+ text = json.dumps(body)
+ (root / ".claude/settings.json").write_text(text)
+ for call in (lambda: fixes.preview(base, "acme/api", FIX, action), lambda: fixes.apply(base, FIX, action)):
+ with pytest.raises(fixes.FixError) as exc:
+ call()
+ assert exc.value.code == "bad_json" and "fix it by hand" in exc.value.message
+ assert (root / ".claude/settings.json").read_text() == text
+
+
+ "action,body",
+ [
+ (ALLOW, {"permissions": None}),
+ (ALLOW, {"permissions": "x"}),
+ (ALLOW, {"permissions": {"allow": "Bash(ls:*)"}}),
+ (HOOK, {"hooks": {"Stop": "pytest"}}),
+ (HOOK, {"hooks": {"Stop": [7]}}),
+ ],
+)
+def test_undo_refuses_odd_shapes_and_keeps_the_entry(repo, action, body):
+ base, root = repo
+ entry = fixes.apply(base, FIX, action)
+ text = json.dumps(body)
+ (root / ".claude/settings.json").write_text(text)
+ with pytest.raises(fixes.FixError) as exc:
+ fixes.undo(base, entry["id"])
+ assert exc.value.code == "bad_json"
+ assert (root / ".claude/settings.json").read_text() == text and fixes.active(base)
+
+
+# ------------------------------------------------------------------ 5. personal files stay out of git
+
+
+ "rel,action",
+ [
+ ("CLAUDE.local.md", {**MD, "file": "CLAUDE.local.md"}),
+ (".claude/settings.local.json", {**ALLOW, "file": ".claude/settings.local.json"}),
+ ],
+)
+def test_personal_files_agentplay_creates_are_git_ignored(repo, rel, action):
+ base, root = repo
+ gitignore = root / ".gitignore"
+ gitignore.write_text("node_modules\n")
+ entry = fixes.apply(base, FIX, action, rel=rel)
+ assert _git("-C", str(root), "check-ignore", "-q", rel).returncode == 0
+ assert gitignore.read_text() == "node_modules\n"
+ fixes.undo(base, entry["id"])
+ fixes.apply(base, FIX, action, rel=rel) # created again: the exclude line is not repeated
+ assert (root / ".git/info/exclude").read_text().count(f"/{rel}\n") == 1
+
+
+def test_shared_files_and_existing_personal_files_are_not_ignored(repo):
+ base, root = repo
+ fixes.apply(base, FIX, MD)
+ (root / "CLAUDE.local.md").write_text("# mine\n")
+ fixes.apply(base, FIX, {**MD, "file": "CLAUDE.local.md"}, rel="CLAUDE.local.md")
+ assert _git("-C", str(root), "check-ignore", "-q", "CLAUDE.md").returncode == 1
+ assert _git("-C", str(root), "check-ignore", "-q", "CLAUDE.local.md").returncode == 1
+
+
+def test_an_unreadable_exclude_file_does_not_fail_the_fix(repo):
+ base, root = repo
+ (root / ".git/info/exclude").write_bytes(b"caf\xe9\n")
+ fixes.apply(base, FIX, {**MD, "file": "CLAUDE.local.md"}, rel="CLAUDE.local.md")
+ assert fixes.active(base) and (root / ".git/info/exclude").read_bytes() == b"caf\xe9\n"
+
+
+def test_ignore_in_a_linked_worktree_goes_to_the_common_exclude(repo, tmp_path):
+ base, root = repo
+ assert (
+ _git(
+ "-C", str(root), "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "init"
+ ).returncode
+ == 0
+ )
+ wt = tmp_path / "wt"
+ assert _git("-C", str(root), "worktree", "add", "-q", str(wt)).returncode == 0
+ fixes.grant(base, "acme/wt", str(wt))
+ fixes.apply(base, {**FIX, "repo": "acme/wt"}, {**MD, "file": "CLAUDE.local.md"}, rel="CLAUDE.local.md")
+ assert _git("-C", str(wt), "check-ignore", "-q", "CLAUDE.local.md").returncode == 0
+
+
+# ------------------------------------------------------------------ 6. undo leaves no residue
+
+
[email protected]("action", [MD, ALLOW, HOOK])
+def test_undo_removes_a_file_agentplay_created(repo, action):
+ base, root = repo
+ entry = fixes.apply(base, FIX, action)
+ fixes.undo(base, entry["id"])
+ assert not (root / action["file"]).exists()
+
+
+def test_undo_keeps_a_created_file_once_the_person_wrote_in_it(repo):
+ base, root = repo
+ entry = fixes.apply(base, FIX, MD)
+ with (root / "CLAUDE.md").open("a") as fh:
+ fh.write("\nMy own line.\n")
+ fixes.undo(base, entry["id"])
+ assert "My own line." in (root / "CLAUDE.md").read_text()
+ entry = fixes.apply(base, FIX, ALLOW)
+ data = json.loads((root / ".claude/settings.json").read_text())
+ (root / ".claude/settings.json").write_text(json.dumps({**data, "model": "x"}))
+ fixes.undo(base, entry["id"])
+ assert json.loads((root / ".claude/settings.json").read_text()) == {"model": "x"}
+
+
+def test_undo_prunes_only_the_containers_agentplay_added(repo):
+ base, root = repo
+ (root / ".claude").mkdir()
+ (root / ".claude/settings.json").write_text('{"model": "x", "hooks": {}}')
+ entry = fixes.apply(base, FIX, ALLOW)
+ fixes.undo(base, entry["id"])
+ hook = fixes.apply(base, FIX, HOOK)
+ fixes.undo(base, hook["id"])
+ assert json.loads((root / ".claude/settings.json").read_text()) == {"model": "x", "hooks": {}}
+
+
+def test_undo_of_one_of_two_fixes_keeps_the_file(repo):
+ base, root = repo
+ first = fixes.apply(base, FIX, ALLOW)
+ fixes.apply(base, {**FIX, "id": "zzz"}, {**ALLOW, "entry": "Bash(cat:*)"})
+ fixes.undo(base, first["id"])
+ assert json.loads((root / ".claude/settings.json").read_text()) == {"permissions": {"allow": ["Bash(cat:*)"]}}
diff --git a/python/tests/test_search_health_fixes.py b/python/tests/test_search_health_fixes.py
index 5239eab..a483339 100644
--- a/python/tests/test_search_health_fixes.py
+++ b/python/tests/test_search_health_fixes.py
@@ -267,7 +267,8 @@ def test_health_route_and_writes_through_the_api(repo):
"from": "2098-12-01", "to": "2099-01-01"})
assert status == 200 and (root / "CLAUDE.md").exists()
status, _ = _req(httpd, "POST", "/api/fix", {"action": "undo", "entry": done["entry"]["id"]})
- assert status == 200 and "pytest" not in (root / "CLAUDE.md").read_text()
+ # The fix created CLAUDE.md, so undoing it removes the file.
+ assert status == 200 and not (root / "CLAUDE.md").exists()
status, at = _req(httpd, "GET", "/api/autotune")
assert status == 200 and at["repos"][0]["granted"] is True
finally:
diff --git a/python/tests/test_search_quality.py b/python/tests/test_search_quality.py
new file mode 100644
index 0000000..9ee82d2
--- /dev/null
+++ b/python/tests/test_search_quality.py
@@ -0,0 +1,174 @@
+"""Search fallback, per-kind posting caps, unresolved-repo memory and capped facts.files."""
+
+from __future__ import annotations
+
+import http.client
+import json
+import shutil
+import threading
+from typing import Any
+
+from test_local_tool import _write_claude_session, env # noqa: F401 - env is a fixture
+
+from agentplay import discover, facts, pipeline, search
+from agentplay.server import serve
+from agentplay.store import Store
+
+
+def _ev(seq: int, kind: str = "exec", **kw: Any) -> dict[str, Any]:
+ return {"seq": seq, "t": seq * 1000, "agent": "main", "err": False, "kind": kind, **kw}
+
+
+def _doc(events: list[dict[str, Any]], files: list[dict[str, Any]] | None = None) -> dict[str, Any]:
+ return {
+ "schema": "agentplay/v1",
+ "session": {"id": "s1", "agentTool": "claude-code", "startedAt": "2026-10-01T10:00:00Z", "durationMs": 1,
+ "models": [], "outcome": "completed", "role": "root"},
+ "totals": {}, "repos": [{"id": "r0", "name": "acme/api"}], "files": files or [], "events": events,
+ }
+
+
+# ------------------------------------------------------------------ argument fallback
+
+def _terms() -> dict[str, dict[str, list[list[Any]]]]:
+ return {"a": {"cmd:pnpm test": [[3, "read"]], "cmd:eslint-fix": [[4, "read"]], "cmd:prefix": [[5, "read"]]}}
+
+
+def test_fallback_needs_a_recorded_command_not_a_substring():
+ terms = _terms()
+ assert search.argument_fallback(terms, "pnpm test --watch")[0] == "pnpm test"
+ assert search.argument_fallback(terms, "pnpm install foo")[0] == "pnpm" # family of `pnpm test`
+ assert search.argument_fallback(terms, "fix login bug") is None # `fix` is only inside eslint-fix
+ assert search.argument_fallback(terms, "pre something") is None
+
+
+def test_natural_language_query_returns_no_sessions_and_no_note(env): # noqa: F811
+ _write_claude_session(env["home"], "11111111-0000-0000-0000-000000000001", env["repo"])
+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))
+ httpd = serve(0, store=Store(env["sm"]))
+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
+ try:
+ conn = http.client.HTTPConnection("127.0.0.1", httpd.server_address[1])
+ conn.request("GET", "/api/sessions?search=fix%20login%20bug")
+ body = json.loads(conn.getresponse().read())
+ assert body["sessions"] == [] and body["searchNote"] is None
+ finally:
+ httpd.shutdown()
+
+
+# ------------------------------------------------------------------ true counts per touch kind
+
+def _busy_doc() -> dict[str, Any]:
+ n = search.MAX_SEQS + 10
+ evs = [_ev(i, "read", targets=[{"file": 0, "touch": "read"}]) for i in range(n)]
+ evs += [_ev(n, "edit", targets=[{"file": 0, "touch": "edit"}]), _ev(n + 1, "edit", targets=[{"file": 0, "touch": "edit"}])]
+ return _doc(evs, [{"id": 0, "repo": "r0", "path": "src/a.ts"}])
+
+
+def test_busy_file_keeps_its_edits_and_true_counts():
+ n = search.MAX_SEQS + 10
+ hit = search.query({"s": search.postings(_busy_doc())}, "file:a.ts")["s"]
+ by_touch = {c["touch"]: c for c in hit["chips"]}
+ assert by_touch["edit"]["n"] == 2 and by_touch["read"]["n"] == n
+ assert by_touch["read"]["label"] == f"read a.ts {n}×"
+ assert hit["count"] == n + 2
+ assert {n, n + 1} <= set(hit["seqs"]) # the stepper can reach the edits
+ stored = search.postings(_busy_doc())["file:a.ts"]
+ assert len(stored) == search.MAX_SEQS + 2 # stored size stays bounded
+
+
+def test_old_search_index_is_rebuilt(tmp_path):
+ st = Store(tmp_path)
+ doc = _busy_doc()
+ st.put(doc, {"sessionId": "s1", "contentHash": "h1", "calls": 1})
+ st.save_index()
+ (tmp_path / "search.json").write_text(json.dumps({"version": search.SEARCH_VERSION - 1, "sessions": {
+ "s1": {"hash": "h1", "terms": {"file:a.ts": [[1, "read"]]}}}}))
+ assert search.refresh(st) == 1
+
+
+def test_empty_content_hash_is_always_stale(tmp_path):
+ st = Store(tmp_path)
+ st.put(_busy_doc(), {"sessionId": "s1", "contentHash": "", "calls": 1})
+ st.save_index()
+ assert search.refresh(st) == 1
+ assert search.refresh(st) == 1
+
+
+def test_search_file_with_non_dict_terms_is_rebuilt_not_a_500(tmp_path):
+ st = Store(tmp_path)
+ st.put(_busy_doc(), {"sessionId": "s1", "contentHash": "h1", "calls": 1, "sessionDate": "2026-10-01"})
+ st.save_index()
+ (tmp_path / "search.json").write_text(json.dumps({"version": search.SEARCH_VERSION, "sessions": {
+ "s1": {"hash": "h1", "terms": ["oops"]}}}))
+ httpd = serve(0, store=Store(tmp_path))
+ threading.Thread(target=httpd.serve_forever, daemon=True).start()
+ try:
+ conn = http.client.HTTPConnection("127.0.0.1", httpd.server_address[1])
+ conn.request("GET", "/api/sessions?search=a.ts")
+ resp = conn.getresponse()
+ assert resp.status == 200
+ assert [s["sessionId"] for s in json.loads(resp.read())["sessions"]] == ["s1"]
+ finally:
+ httpd.shutdown()
+
+
+# ------------------------------------------------------------------ unresolved repos
+
+def test_unresolved_repo_is_not_re_parsed_every_run(env, monkeypatch): # noqa: F811
+ _write_claude_session(env["home"], "11111111-0000-0000-0000-000000000001", env["repo"])
+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))
+ (env["sm"] / "repos.json").unlink()
+ shutil.rmtree(env["repo"]) # the checkout is gone: the name can never resolve again
+ calls: list[str] = []
+ real = discover.build_map
+ monkeypatch.setattr(discover, "build_map", lambda *a, **k: (calls.append("x"), real(*a, **k))[1])
+ for _ in range(3):
+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))
+ assert len(calls) == 1
+
+
+def test_unresolved_repo_is_retried_after_the_wait(env, monkeypatch): # noqa: F811
+ _write_claude_session(env["home"], "11111111-0000-0000-0000-000000000001", env["repo"])
+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))
+ (env["sm"] / "repos.json").unlink()
+ shutil.rmtree(env["repo"])
+ calls: list[str] = []
+ real = discover.build_map
+ monkeypatch.setattr(discover, "build_map", lambda *a, **k: (calls.append("x"), real(*a, **k))[1])
+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))
+ monkeypatch.setattr(pipeline, "UNRESOLVED_RETRY_S", 0)
+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))
+ assert len(calls) == 2
+
+
+def test_a_lookup_that_crashed_is_not_cached_as_unresolved(env, monkeypatch): # noqa: F811
+ _write_claude_session(env["home"], "11111111-0000-0000-0000-000000000001", env["repo"])
+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))
+ (env["sm"] / "repos.json").unlink()
+
+ def broken(*a, **k):
+ raise RuntimeError("transcript unreadable")
+
+ monkeypatch.setattr(discover, "build_map", broken)
+ pipeline.build_all(agents={"claude-code"}, store=Store(env["sm"]))
+ # The parse failed, not the lookup: the checkout still exists and is found on the next run.
+ assert not (env["sm"] / "repos-unresolved.json").exists()
+
+
+# ------------------------------------------------------------------ capped facts.files
+
+def test_facts_files_are_capped_to_the_busiest_with_a_remainder():
+ n = facts.MAX_FACT_FILES + 25
+ files = [{"id": i, "repo": "r0", "path": f"f{i}.ts", "hits": i + 1, "reads": 1, "edits": 0} for i in range(n)]
+ f = facts.compute(_doc([], files))
+ assert len(f["files"]) == facts.MAX_FACT_FILES
+ assert f"acme/api:f{n - 1}.ts" in f["files"] and "acme/api:f0.ts" not in f["files"]
+ rest = f["filesRest"]
+ assert rest["count"] == 25 and rest["reads"] == 25 and rest["hits"] == sum(range(1, 26))
+ assert sum(x["reads"] for x in f["files"].values()) + rest["reads"] == n
+
+
+def test_small_sessions_have_no_remainder():
+ f = facts.compute(_doc([], [{"id": 0, "repo": "r0", "path": "a.ts", "hits": 1, "reads": 1, "edits": 0}]))
+ assert "filesRest" not in f
diff --git a/viewer/public/demo/index.json b/viewer/public/demo/index.json
index e825798..0857974 100644
--- a/viewer/public/demo/index.json
+++ b/viewer/public/demo/index.json
@@ -234,7 +234,7 @@
"reworkEdits": 0,
"stepsToFirstEdit": 5
},
- "factsVersion": 4
+ "factsVersion": 5
},
{
"sessionId": "local:codex:0199a3b2-demo-4f0c-8e55-000000000002",
@@ -389,7 +389,7 @@
"reworkEdits": 0,
"stepsToFirstEdit": 7
},
- "factsVersion": 4
+ "factsVersion": 5
},
{
"sessionId": "local:cursor:c1d2e3f4-demo-4a5b-9c8d-000000000003",
@@ -486,7 +486,7 @@
"reworkEdits": 0,
"stepsToFirstEdit": 2
},
- "factsVersion": 4
+ "factsVersion": 5
}
]
}
diff --git a/viewer/src/explorer/SessionList.test.tsx b/viewer/src/explorer/SessionList.test.tsx
new file mode 100644
index 0000000..c8cbc63
--- /dev/null
+++ b/viewer/src/explorer/SessionList.test.tsx
@@ -0,0 +1,54 @@
+import { act } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+import { sessionExplorerSessionSchema } from '@/core/schema';
+import { SessionList } from './SessionList';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const session = (seqs: number[]) =>
+ sessionExplorerSessionSchema.parse({
+ sessionId: 's1',
+ startedAt: '2026-01-02T03:04:05Z',
+ search: { count: seqs.length, seqs, chips: [] },
+ });
+
+let host: HTMLElement | null = null;
+afterEach(() => {
+ host?.remove();
+ host = null;
+});
+
+function render(seqs: number[]) {
+ host ??= document.body.appendChild(document.createElement('div'));
+ const root = (host as HTMLElement & { _root?: ReturnType<typeof createRoot> });
+ root._root ??= createRoot(host);
+ act(() =>
+ root._root!.render(
+ <SessionList
+ sessions={[session(seqs)]}
+ selectedId="s1"
+ onSelect={() => {}}
+ onOpen={() => {}}
+ search="x"
+ onSearch={() => {}}
+ hasMore={false}
+ loadingMore={false}
+ onLoadMore={() => {}}
+ onJump={() => {}}
+ />
+ )
+ );
+ return host;
+}
+
+describe('SearchMatches stepper', () => {
+ it('restarts at the first match when the match list changes', () => {
+ const el = render([1, 2, 3, 4, 5]);
+ const next = () => el.querySelector<HTMLButtonElement>('[aria-label="Next match"]')!;
+ for (let k = 0; k < 4; k++) act(() => next().click());
+ expect(el.textContent).toContain('Match 5 of 5');
+ render([7, 8]);
+ expect(el.textContent).toContain('Match 1 of 2');
+ });
+});
diff --git a/viewer/src/explorer/SessionList.tsx b/viewer/src/explorer/SessionList.tsx
index 1406b09..94aee4c 100644
--- a/viewer/src/explorer/SessionList.tsx
+++ b/viewer/src/explorer/SessionList.tsx
@@ -286,7 +286,7 @@ function SessionRow({
<SessionRowBadges s={s} unavailable={unavailable} />
</button>
{s.search && onJump ? (
- <SearchMatches search={s.search} selected={selected} onJump={onJump} />
+ <SearchMatches key={s.search.seqs.join(',')} search={s.search} selected={selected} onJump={onJump} />
) : null}
{/* Always there for the selected row -- you just clicked it, so that
* is where the next step belongs. Quiet on the rest until pointed at
@@ -364,7 +364,8 @@ const TOUCH_DOT: Record<string, string> = {
/**
* What a searched session matched on, as chips that open it at that event,
- * and on the selected row a stepper through every matching event.
+ * and on the selected row a stepper through every matching event. Callers
+ * key it on the match list so the stepper restarts when the matches change.
*/
function SearchMatches({
search,
diff --git a/viewer/src/insights/AutotuneView.tsx b/viewer/src/insights/AutotuneView.tsx
index 33b1dc3..26ab71b 100644
--- a/viewer/src/insights/AutotuneView.tsx
+++ b/viewer/src/insights/AutotuneView.tsx
@@ -7,7 +7,7 @@ import { useSessionMapSource } from '@/data/SourceContext';
import { cn } from '@/lib/utils';
import type { AppliedEffect, AutotuneStatus } from '@/core/health';
import { InfoButton } from './InfoButton';
-import { Panel } from './panels';
+import { ErrorText, Panel } from './panels';
export function AutotuneView() {
const source = useSessionMapSource();
@@ -44,11 +44,7 @@ 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>
- );
+ return <ErrorText>{(write.error as Error).message}</ErrorText>;
}
function Summary({ s }: { s: AutotuneStatus }) {
@@ -103,12 +99,12 @@ function Repos({ s }: { s: AutotuneStatus }) {
<span className="inline-flex items-center gap-1 ds-text-body-xs-semibold text-ds-success-darker">
<Check size={13} aria-hidden /> Can write
</span>
- <Button variant="link" size="sm" className="h-7 px-1 text-xs" onClick={() => write.mutate({ path: '/api/repos', body: { action: 'revoke', repo: r.name } })}>
+ <Button variant="link" size="sm" className="h-7 px-1 text-xs" disabled={write.isPending} onClick={() => write.mutate({ path: '/api/repos', body: { action: 'revoke', repo: r.name } })}>
Revoke
</Button>
</>
) : r.root ? (
- <Button size="sm" className="h-7 text-xs" onClick={() => write.mutate({ path: '/api/repos', body: { action: 'grant', repo: r.name } })}>
+ <Button size="sm" className="h-7 text-xs" disabled={write.isPending} onClick={() => write.mutate({ path: '/api/repos', body: { action: 'grant', repo: r.name } })}>
Allow writes
</Button>
) : (
@@ -121,6 +117,7 @@ function Repos({ s }: { s: AutotuneStatus }) {
<input
type="checkbox"
checked={r.enabled}
+ disabled={write.isPending}
onChange={(e) => write.mutate({ path: '/api/autotune', body: { action: e.target.checked ? 'enable' : 'disable', repo: r.name } })}
className="size-4 accent-[var(--ds-brand-default)]"
/>
@@ -130,7 +127,7 @@ function Repos({ s }: { s: AutotuneStatus }) {
<input
type="checkbox"
checked={r.claudeMd === 'auto'}
- disabled={!r.enabled}
+ disabled={!r.enabled || write.isPending}
onChange={(e) => write.mutate({ path: '/api/autotune', body: { action: 'shared', repo: r.name, value: e.target.checked } })}
className="size-4 accent-[var(--ds-brand-default)]"
/>
@@ -195,13 +192,13 @@ function Waiting({ s }: { s: AutotuneStatus }) {
</div>
</div>
<div className="flex flex-wrap gap-2">
- <Button size="sm" className="h-7 text-xs" onClick={() => write.mutate({ path: '/api/autotune', body: { action: 'approve', fixId: p.fixId } })}>
+ <Button size="sm" className="h-7 text-xs" disabled={write.isPending} onClick={() => write.mutate({ path: '/api/autotune', body: { action: 'approve', fixId: p.fixId } })}>
{p.action.label}
</Button>
- <Button variant="outline" size="sm" className="h-7 text-xs" onClick={() => write.mutate({ path: '/api/autotune', body: { action: 'dismiss', fixId: p.fixId } })}>
+ <Button variant="outline" size="sm" className="h-7 text-xs" disabled={write.isPending} onClick={() => write.mutate({ path: '/api/autotune', body: { action: 'dismiss', fixId: p.fixId } })}>
Not now
</Button>
- <Button variant="link" size="sm" className="h-7 px-1 text-xs" onClick={() => write.mutate({ path: '/api/autotune', body: { action: 'never', fixId: p.fixId } })}>
+ <Button variant="link" size="sm" className="h-7 px-1 text-xs" disabled={write.isPending} onClick={() => write.mutate({ path: '/api/autotune', body: { action: 'never', fixId: p.fixId } })}>
Never suggest this
</Button>
</div>
diff --git a/viewer/src/insights/RunHealthView.test.tsx b/viewer/src/insights/RunHealthView.test.tsx
new file mode 100644
index 0000000..c474171
--- /dev/null
+++ b/viewer/src/insights/RunHealthView.test.tsx
@@ -0,0 +1,105 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { HealthReport } from '@/core/health';
+import { SessionMapSourceProvider } from '@/data/SourceContext';
+import type { SessionMapSource } from '@/data/source';
+import { PointsOnTheTable } from './RunHealthView';
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const fix = (id: string) => ({
+ id,
+ title: `Fix ${id}`,
+ component: 'efficiency',
+ pattern: 'pattern',
+ effect: 'effect',
+ sessions: [],
+ points: 1,
+ repo: 'r',
+ actions: [{ label: 'Add rule' }],
+});
+const report = (ids: string[]) =>
+ ({
+ fixes: ids.map(fix),
+ applied: [],
+ repos: [{ name: 'r', root: '/r', granted: true }],
+ titles: {},
+ }) as unknown as HealthReport;
+
+let root: Root | null = null;
+let host: HTMLElement | null = null;
+afterEach(() => {
+ act(() => root?.unmount());
+ host?.remove();
+ root = host = null;
+});
+
+function mount(source: Partial<SessionMapSource>, ids: string[]) {
+ host = document.body.appendChild(document.createElement('div'));
+ root = createRoot(host);
+ const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
+ act(() =>
+ root!.render(
+ <NuqsTestingAdapter>
+ <QueryClientProvider client={client}>
+ <SessionMapSourceProvider source={source as SessionMapSource}>
+ <PointsOnTheTable h={report(ids)} range={{}} />
+ </SessionMapSourceProvider>
+ </QueryClientProvider>
+ </NuqsTestingAdapter>
+ )
+ );
+ return host;
+}
+const button = (el: HTMLElement, text: string) =>
+ [...el.querySelectorAll('button')].find((b) => b.textContent?.includes(text)) as HTMLButtonElement;
+const flush = () => act(async () => {});
+
+describe('PointsOnTheTable writes', () => {
+ it('shows a failed per-card Apply instead of a dead button', async () => {
+ const write = vi.fn().mockRejectedValue(new Error('file changed since preview'));
+ const el = mount({ write }, ['a']);
+ await act(async () => button(el, 'Add rule').click());
+ // The mutation's error state lands on a later tick than the click, so poll rather than flush once.
+ await vi.waitFor(async () => {
+ await flush();
+ expect(el.querySelector('[role="alert"]')?.textContent).toBe('file changed since preview');
+ });
+ });
+
+ it('applies all fixes in order, stays disabled, and reports where it stopped', async () => {
+ const settle: Array<(ok: boolean) => void> = [];
+ const write = vi.fn(() => new Promise((res, rej) => settle.push((ok) => (ok ? res({}) : rej(new Error('boom'))))));
+ const el = mount({ write }, ['a', 'b', 'c']);
+ await act(async () => button(el, 'Apply 3 fixes').click());
+ expect(write).toHaveBeenCalledTimes(1);
+ expect(button(el, 'Apply 3 fixes').disabled).toBe(true);
+ await act(async () => settle[0](true));
+ expect(write).toHaveBeenCalledTimes(2);
+ expect(button(el, 'Apply 3 fixes').disabled).toBe(true);
+ await act(async () => settle[1](false));
+ await flush();
+ expect(write).toHaveBeenCalledTimes(2);
+ expect(el.querySelector('[role="alert"]')?.textContent).toBe('Applied 1 of 3. "Fix b" failed: boom');
+ expect(button(el, 'Apply 3 fixes').disabled).toBe(false);
+ });
+
+ it('clears the preview after a successful apply and reports a failed preview', async () => {
+ const fixPreview = vi
+ .fn()
+ .mockResolvedValueOnce({ file: 'AGENTS.md', hash: 'h', before: '', after: 'x' })
+ .mockRejectedValueOnce(new Error('nope'));
+ const write = vi.fn().mockResolvedValue({});
+ const el = mount({ write, fixPreview }, ['a']);
+ await act(async () => button(el, 'Preview change').click());
+ expect(el.textContent).toContain('AGENTS.md');
+ await act(async () => button(el, 'Add rule').click());
+ expect(write).toHaveBeenCalledWith('/api/fix', expect.objectContaining({ hash: 'h' }));
+ expect(el.textContent).not.toContain('AGENTS.md');
+ await act(async () => button(el, 'Preview change').click());
+ expect(el.querySelector('[role="alert"]')?.textContent).toBe('Could not load the preview: nope');
+ });
+});
diff --git a/viewer/src/insights/RunHealthView.tsx b/viewer/src/insights/RunHealthView.tsx
index fbae2fd..94c8fff 100644
--- a/viewer/src/insights/RunHealthView.tsx
+++ b/viewer/src/insights/RunHealthView.tsx
@@ -16,7 +16,7 @@ import {
type HealthComponent,
type HealthReport,
} from '@/core/health';
-import { Panel } from './panels';
+import { ErrorText, Panel } from './panels';
type Range = { from?: string; to?: string };
@@ -213,13 +213,32 @@ const COMPONENT_LABEL: Record<string, string> = {
environment: 'Environment',
};
-function PointsOnTheTable({ h, range }: { h: HealthReport; range: Range }) {
+export function PointsOnTheTable({ h, range }: { h: HealthReport; range: Range }) {
const write = useWrite();
const [showAll, setShowAll] = useState(false);
+ // Own flag: write.isPending drops between sequential calls and would re-enable the button mid-run.
+ const [applying, setApplying] = useState(false);
+ const [batchError, setBatchError] = useState<string | null>(null);
const applied = new Map(h.applied.map((a) => [a.fixId, a]));
const repos = new Map(h.repos.map((r) => [r.name, r]));
const fixes = showAll ? h.fixes : h.fixes.slice(0, 5);
const pending = h.fixes.filter((f) => !applied.has(f.id) && f.actions.length && repos.get(f.repo)?.granted);
+ const applyAll = async () => {
+ setApplying(true);
+ setBatchError(null);
+ let done = 0;
+ try {
+ // One at a time: the server serializes writes, and we stop at the first failure.
+ for (const f of pending) {
+ await write.mutateAsync({ path: '/api/fix', body: { action: 'apply', fix: f.id, i: 0, ...range } });
+ done++;
+ }
+ } catch (e) {
+ setBatchError(`Applied ${done} of ${pending.length}. "${pending[done].title}" failed: ${(e as Error).message}`);
+ } finally {
+ setApplying(false);
+ }
+ };
const gain = h.fixes.filter((f) => !applied.has(f.id)).reduce((s, f) => s + f.points, 0);
return (
<Panel
@@ -230,23 +249,15 @@ function PointsOnTheTable({ h, range }: { h: HealthReport; range: Range }) {
pending.length ? (
<Button
size="sm"
- disabled={write.isPending}
- onClick={() => {
- for (const f of pending) {
- write.mutate({ path: '/api/fix', body: { action: 'apply', fix: f.id, i: 0, ...range } });
- }
- }}
+ disabled={applying}
+ onClick={() => void applyAll()}
>
Apply {pending.length} {pending.length === 1 ? 'fix' : 'fixes'}
</Button>
) : null
}
>
- {write.isError ? (
- <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>
- ) : null}
+ {batchError ? <ErrorText>{batchError}</ErrorText> : null}
{h.fixes.length ? (
<>
<p className="ds-text-body-xs-medium text-ds-text-subtle">
@@ -297,15 +308,24 @@ function FixCard({
const open = useOpenSession();
const [preview, setPreview] = useState<{ i: number; p: FixPreview } | null>(null);
const [copied, setCopied] = useState(false);
+ const [previewing, setPreviewing] = useState(false);
+ const [previewError, setPreviewError] = useState<string | null>(null);
const showPreview = async (i: number) => {
if (preview?.i === i) return setPreview(null);
if (!source.fixPreview) return;
+ setPreviewing(true);
+ setPreviewError(null);
try {
setPreview({ i, p: await source.fixPreview({ fix: fix.id, i, ...range }) });
- } catch {
+ } catch (e) {
setPreview(null);
+ setPreviewError(`Could not load the preview: ${(e as Error).message}`);
+ } finally {
+ setPreviewing(false);
}
};
+ // A preview (and its hash) is stale once the file has been written or restored.
+ const onWritten = { onSuccess: () => setPreview(null) };
return (
<li className={cn('flex flex-col gap-2 rounded-lg border p-3', applied ? 'border-ds-brand-subtlest bg-ds-brand-lightest' : 'border-ds-border-subtlest')}>
<div className="flex gap-3">
@@ -347,7 +367,7 @@ function FixCard({
size="sm"
className="h-7 px-1"
disabled={write.isPending}
- onClick={() => write.mutate({ path: '/api/fix', body: { action: 'undo', entry: applied.id } })}
+ onClick={() => write.mutate({ path: '/api/fix', body: { action: 'undo', entry: applied.id } }, onWritten)}
>
Undo
</Button>
@@ -363,15 +383,18 @@ function FixCard({
primary={i === 0}
disabled={write.isPending}
onClick={() =>
- write.mutate({
- path: '/api/fix',
- body: { action: 'apply', fix: fix.id, i, hash: preview?.i === i ? preview.p.hash : undefined, ...range },
- })
+ write.mutate(
+ {
+ path: '/api/fix',
+ body: { action: 'apply', fix: fix.id, i, hash: preview?.i === i ? preview.p.hash : undefined, ...range },
+ },
+ onWritten
+ )
}
/>
))}
- <Button variant="link" size="sm" className="h-7 px-1 text-xs" onClick={() => void showPreview(0)}>
- {preview ? 'Hide change' : 'Preview change'}
+ <Button variant="link" size="sm" className="h-7 px-1 text-xs" disabled={previewing} onClick={() => void showPreview(0)}>
+ {previewing ? 'Loading preview' : 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 {fix.id}</code>
@@ -409,6 +432,8 @@ function FixCard({
</div>
</div>
</div>
+ {write.isError ? <ErrorText>{(write.error as Error).message}</ErrorText> : null}
+ {previewError ? <ErrorText>{previewError}</ErrorText> : null}
{preview ? (
<div className="ml-[3.75rem] overflow-hidden rounded-md border border-ds-border-subtlest">
<div className="flex justify-between bg-ds-gray-subtlest px-3 py-1 font-mono text-xs text-ds-text-default">
diff --git a/viewer/src/insights/panels.tsx b/viewer/src/insights/panels.tsx
index 30a4e09..383711c 100644
--- a/viewer/src/insights/panels.tsx
+++ b/viewer/src/insights/panels.tsx
@@ -26,6 +26,15 @@ import type { TermKey } from './glossary';
// ------------------------------------------------------------------ shared
+/** Inline failure message, announced to screen readers. */
+export function ErrorText({ children }: { children: ReactNode }) {
+ return (
+ <p role="alert" className="rounded-md bg-ds-danger-subtlest px-3 py-2 ds-text-body-xs-medium text-ds-danger-darkest">
+ {children}
+ </p>
+ );
+}
+
export function Panel({
title,
term,