Replay your coding agent sessions as a map and a timeline
Python agent-observabilityai-agentsclaudeclaude-codecodexcoding-agentscursordeveloper-toolsdevtoolsgithub-copilotkirollmobservabilityopencodeprivacypythonsession-replaytypescriptvisualization
fix: confine repo writes at write time, clear search on evidence, token-match check purposes (#37)
Taradepan Rd9a9121559c7
diff --git a/python/src/agentplay/fixes.py b/python/src/agentplay/fixes.pyindex 0b5bbcd..26f8264 100644--- a/python/src/agentplay/fixes.py+++ b/python/src/agentplay/fixes.py@@ -30,7 +30,7 @@ from contextlib import contextmanagerfrom pathlib import Pathfrom typing import Any-from .store import _atomic_write+from .store import OutsideRoot, _atomic_writeALLOWED_FILES = ("CLAUDE.md", "CLAUDE.local.md", ".claude/settings.json", ".claude/settings.local.json")START = "<!-- agentplay:start -->"@@ -198,8 +198,18 @@ 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 _write(path: Path, text: str, root: Path) -> None:+ # Confined at the write itself: a link swapped in after _target resolved must not lead outside the checkout.+ try:+ _atomic_write(path, text.encode("utf-8"), private=False, within=root)+ except OutsideRoot:+ raise FixError("outside_repo", f"{path.name} now points outside {root}. Nothing was written.") from None+++def _unlink(path: Path, root: Path) -> None:+ if not Path(os.path.realpath(path)).is_relative_to(root):+ raise FixError("outside_repo", f"{path.name} now points outside {root}. Nothing was removed.")+ path.unlink(missing_ok=True)def _newline(text: str) -> str:@@ -457,6 +467,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)+ root = Path(grants(base)[repo]).resolve()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.")@@ -464,8 +475,7 @@ def _apply_locked(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)- _write(target, after)+ _write(target, after, root)entry = {"id": uuid.uuid4().hex[:10],"fixId": fix["id"],@@ -491,12 +501,12 @@ def _apply_locked(except BaseException:# Never leave a repo change that cannot be undone.if before is None:- target.unlink(missing_ok=True)+ _unlink(target, root)else:- _write(target, before)+ _write(target, before, root)raiseif before is None and rel in ("CLAUDE.local.md", ".claude/settings.local.json"):- _ignore_locally(Path(grants(base)[repo]).resolve(), rel)+ _ignore_locally(root, rel)return entry@@ -512,13 +522,14 @@ def _undo_locked(base: Path, entry_id: str, reason: str) -> dict[str, Any]:raise FixError("not_found", "Nothing to undo with that id.")# The checkout it was written to, even if the grant has since moved to another one.target = _target(base, entry["repo"], entry["file"], entry.get("root"))+ root = Path(entry.get("root") or grants(base)[entry["repo"]]).resolve()text = _read(target)if text is not None:after = _undo_text(entry, text)if after is None:- target.unlink()+ _unlink(target, root)else:- _write(target, after)+ _write(target, after, root)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.pyindex 847ff09..5d56370 100644--- a/python/src/agentplay/health.py+++ b/python/src/agentplay/health.py@@ -56,18 +56,23 @@ _PURPOSES = ()+def _tokens(verb: str) -> list[str]:+ """The lowercase words of a command, split on anything but letters and digits."""+ low = verb.lower()+ # A compound job word (`type-check`) is one word: joined before splitting, so its+ # pieces (`check`) never become generic and strip a real target.+ for w in (w for _, ws in _PURPOSES for w in ws if not w.isalnum()):+ low = low.replace(w, re.sub(r"[^a-z0-9]+", "", w))+ return [w for w in re.split(r"[^a-z0-9]+", low) if w]++def _scope(verb: str) -> frozenset[str]:"""What a check is narrowed to beyond its job: ``pnpm test:unit`` -> {"unit"}, ``pnpm vitest`` -> {}.Two checks only stand in for each other when their scopes match, so afailing unit suite is never "replaced" by a passing e2e one."""- low = verb.lower()- # A compound job word (`type-check`) is one word: joined before splitting, so its- # pieces (`check`) never become generic and strip a real target.- for w in (w for _, ws in _PURPOSES for w in ws if not w.isalnum()):- low = low.replace(w, re.sub(r"[^a-z0-9]+", "", w))- words = [w for w in re.split(r"[^a-z0-9]+", low) if w][1:]+ words = _tokens(verb)[1:]# Whole job words only (and their plurals): `unittest` or `e2etests` keep their target.job_words = {re.sub(r"[^a-z0-9]+", "", w) for _, ws in _PURPOSES for w in ws}generic = job_words | {"run", "exec", "x"}@@ -75,9 +80,11 @@ def _scope(verb: str) -> frozenset[str]:def purpose(verb: str) -> str | None:- low = verb.lower()- for name, words in _PURPOSES:- if any(w in low for w in words):+ # Whole words (and their plurals), so `latest` is not a test and `rebuild` is not a build.+ words = _tokens(verb)+ tokens = {*words, *(t.removesuffix("s") for t in words)}+ for name, names in _PURPOSES:+ if any(re.sub(r"[^a-z0-9]+", "", w) in tokens for w in names):return namereturn Nonediff --git a/python/src/agentplay/store.py b/python/src/agentplay/store.pyindex de501ba..d0846dc 100644--- a/python/src/agentplay/store.py+++ b/python/src/agentplay/store.py@@ -30,16 +30,23 @@ def root() -> Path:return Path(os.environ.get("AGENTPLAY_HOME") or Path.home() / ".agentplay")-def _atomic_write(path: Path, data: bytes, *, private: bool = True) -> None:+class OutsideRoot(OSError):+ """A write resolved to somewhere outside the directory it was confined to."""++def _atomic_write(path: Path, data: bytes, *, private: bool = True, within: Path | None = None) -> 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).+ default like any editor would create (files in a person's repo). ``within`` refuses a+ write whose final, symlink-resolved path left that directory."""# 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))+ # Checked on the same resolved path the write uses, not on an earlier resolution of it.+ if within is not None and not path.is_relative_to(within):+ raise OutsideRoot(f"{path} is outside {within}")path.parent.mkdir(parents=True, exist_ok=True)try:# lstat for the store: a link planted there must not lend its target's modediff --git a/python/tests/test_fixes_safety.py b/python/tests/test_fixes_safety.pyindex 06ceb5b..5333829 100644--- a/python/tests/test_fixes_safety.py+++ b/python/tests/test_fixes_safety.py@@ -165,6 +165,42 @@ def test_a_symlink_out_of_the_repo_is_still_refused(repo, tmp_path):assert exc.value.code == "outside_repo" and outside.read_text() == "x"+def test_a_link_swapped_in_after_the_check_cannot_redirect_the_write(repo, tmp_path, monkeypatch):+ base, root = repo+ outside = tmp_path / "outside.md"+ outside.write_text("x")++ def swap(*args): # between _target's check and the write, the file becomes a link out+ (root / "CLAUDE.md").symlink_to(outside)+ return "changed\n"++ monkeypatch.setattr(fixes, "_apply_text", swap)+ with pytest.raises(fixes.FixError) as exc:+ fixes.apply(base, FIX, MD)+ assert exc.value.code == "outside_repo" and outside.read_text() == "x"+ assert fixes.journal(base) == []+++def test_undo_never_writes_through_a_link_swapped_in_after_the_check(repo, tmp_path, monkeypatch):+ base, root = repo+ entry = fixes.apply(base, FIX, MD)+ outside = tmp_path / "outside.md"+ outside.write_text("x")+ real = fixes._undo_text++ def swap(*args):+ (root / "CLAUDE.md").unlink()+ (root / "CLAUDE.md").symlink_to(outside)+ return "changed\n"++ monkeypatch.setattr(fixes, "_undo_text", swap)+ with pytest.raises(fixes.FixError) as exc:+ fixes.undo(base, entry["id"])+ assert exc.value.code == "outside_repo" and outside.read_text() == "x"+ monkeypatch.setattr(fixes, "_undo_text", real)+ assert fixes.active(base)++# ------------------------------------------------------------------ 4. unexpected JSON shapesdiff --git a/python/tests/test_search_health_fixes.py b/python/tests/test_search_health_fixes.pyindex d1f95c4..aae24eb 100644--- a/python/tests/test_search_health_fixes.py+++ b/python/tests/test_search_health_fixes.py@@ -461,6 +461,16 @@ def test_a_replacement_check_must_cover_the_same_target():assert health._scope("pnpm run type-check") == health._scope("pnpm tsc")+def test_purpose_matches_whole_command_words_not_substrings():+ assert health.purpose("pnpm test") == health.purpose("pnpm run tests") == "test"+ assert health.purpose("pnpm test:check") == "test"+ assert health.purpose("pnpm run type-check") == "typecheck"+ assert health.purpose("./node_modules/.bin/vitest") == "test"+ assert health.purpose("cargo clippy") == "lint"+ for verb in ("npm run latest", "pnpm rebuild", "git commit", "make specific", "node splint.js", "pnpm contest"):+ assert health.purpose(verb) is None, verb++def test_one_multi_file_reread_charges_one_request():evs = [{"seq": 1, "kind": "read", "agent": "main", "targets": [{"file": 1, "touch": "read"}, {"file": 2, "touch": "read"}]},diff --git a/viewer/src/insights/RunHealthView.test.tsx b/viewer/src/insights/RunHealthView.test.tsxindex c474171..27eef46 100644--- a/viewer/src/insights/RunHealthView.test.tsx+++ b/viewer/src/insights/RunHealthView.test.tsx@@ -1,7 +1,7 @@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 { NuqsTestingAdapter, type OnUrlUpdateFunction } from 'nuqs/adapters/testing';import { afterEach, describe, expect, it, vi } from 'vitest';import type { HealthReport } from '@/core/health';import { SessionMapSourceProvider } from '@/data/SourceContext';@@ -16,7 +16,7 @@ const fix = (id: string) => ({component: 'efficiency',pattern: 'pattern',effect: 'effect',- sessions: [],+ sessions: ['s1'],points: 1,repo: 'r',actions: [{ label: 'Add rule' }],@@ -37,13 +37,17 @@ afterEach(() => {root = host = null;});-function mount(source: Partial<SessionMapSource>, ids: string[]) {+function mount(+ source: Partial<SessionMapSource>,+ ids: string[],+ nuqs: { searchParams?: string; onUrlUpdate?: OnUrlUpdateFunction } = {}+) {host = document.body.appendChild(document.createElement('div'));root = createRoot(host);const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });act(() =>root!.render(- <NuqsTestingAdapter>+ <NuqsTestingAdapter {...nuqs}><QueryClientProvider client={client}><SessionMapSourceProvider source={source as SessionMapSource}><PointsOnTheTable h={report(ids)} range={{}} />@@ -58,6 +62,20 @@ const button = (el: HTMLElement, text: string) =>[...el.querySelectorAll('button')].find((b) => b.textContent?.includes(text)) as HTMLButtonElement;const flush = () => act(async () => {});+describe('PointsOnTheTable evidence links', () => {+ it('clears the explorer search so the evidence session is not filtered out', async () => {+ const onUrlUpdate = vi.fn();+ const el = mount({}, ['a'], { searchParams: '?sq=unrelated&win=7d&tab=insights', onUrlUpdate });+ await act(async () => button(el, '1 session').click());+ // nuqs flushes the URL update on a later tick than the click.+ await vi.waitFor(() => expect(onUrlUpdate).toHaveBeenCalled());+ const url = onUrlUpdate.mock.calls.at(-1)![0].searchParams;+ expect(url.get('session')).toBe('s1');+ expect(url.has('sq')).toBe(false);+ expect(url.get('win')).toBe('7d');+ });+});+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'));diff --git a/viewer/src/insights/RunHealthView.tsx b/viewer/src/insights/RunHealthView.tsxindex 283b010..6a45567 100644--- a/viewer/src/insights/RunHealthView.tsx+++ b/viewer/src/insights/RunHealthView.tsx@@ -22,8 +22,9 @@ type Range = { from?: string; to?: string };/** Navigate to one session (and event) in the explorer. */function useOpenSession() {- const [, setNav] = useQueryStates({ tab: parseAsString, session: parseAsString, at: parseAsString });- return (sessionId: string) => void setNav({ tab: null, session: sessionId, at: null });+ const [, setNav] = useQueryStates({ tab: parseAsString, session: parseAsString, at: parseAsString, sq: parseAsString });+ // sq is cleared: a leftover search could filter the evidence session out of the list.+ return (sessionId: string) => void setNav({ tab: null, session: sessionId, at: null, sq: null });}export function RunHealthView({ range }: { range: Range }) {