"""Bounded file-access evidence and before/after diffs for the terminal view. This is observation, not a sandbox. External processes and native writes may bypass it. """ from __future__ import annotations import contextlib import contextvars import functools import os import shlex import sys import time from collections.abc import Awaitable, Callable, Generator from enum import Enum, auto from typing import Protocol, TypeVar, cast import albedo_shell GUARD = contextvars.ContextVar("albedo_trace_guard", default=False) LIMIT = 128 * 1024 SNAPSHOT_BUDGET = 256 * 1024 ACTIVITY_LIMIT = 64 CHANGE_LIMIT = 16 DETAIL_LIMIT = 16_000 class SnapshotState(Enum): MISSING = auto() UNAVAILABLE = auto() @contextlib.contextmanager def unobserved() -> Generator[None, None, None]: """Harness bookkeeping inside this block, and tasks created in it, stay out of the trace.""" token = GUARD.set(True) try: yield finally: GUARD.reset(token) def text(value: object) -> str: return ( os.fsdecode(value) if isinstance(value, (str, bytes, os.PathLike)) else str(value) ) def command(args: object) -> str: """The command as a person would type it: no `sh -c` wrapper, no store path on argv[0].""" if not isinstance(args, (list, tuple)): return text(args) argv = [text(arg) for arg in args] if not argv: return "" script = albedo_shell.shell_script(argv) if script is not None: return script name = os.path.basename(argv[0]) if os.path.isabs(argv[0]) else argv[0] return shlex.join([name, *argv[1:]]) # Records how a noted call ended: whether it worked, and what the person # watching sees of its result. class Done(Protocol): def __call__(self, ok: bool = True, detail: str = "") -> None: ... def _ignored(ok: bool = True, detail: str = "") -> None: return None class Trace: def __init__(self, snapshots: bool = False) -> None: self.snapshots = snapshots self.activities: dict[tuple[str, str], dict[str, object]] = {} self.before: dict[str, str | SnapshotState] = {} self.truncated: bool = False self.sealed: bool = False def activity(self, kind: str, target: object, detail: str = "") -> Done: if self.sealed: return _ignored if len(self.activities) >= ACTIVITY_LIMIT: self.truncated = True return _ignored target = str(target)[:1000] entry: dict[str, object] = {"kind": kind, "target": target} started = time.monotonic() def done(ok: bool = True, detail: str = "") -> None: if self.sealed: return entry["ms"] = round((time.monotonic() - started) * 1000) entry["ok"] = ok if detail: self.truncated |= len(detail) > DETAIL_LIMIT entry["detail"] = detail[:DETAIL_LIMIT] if detail: self.truncated |= len(detail) > DETAIL_LIMIT entry["detail"] = detail[:DETAIL_LIMIT] self.activities[(kind, target)] = entry return done def renamed(self, source: str, destination: str) -> None: if self.sealed or source == destination: return # Atomic editors write a temporary file then replace the real target. # The temporary file is not an edit; snapshot the destination before rename. self.writing(destination) self.before.pop(source, None) def writing(self, path: str) -> None: if self.sealed or path in self.before or scratch(path): return if len(self.before) >= CHANGE_LIMIT: self.truncated = True return self.before[path] = snapshot(path) def display(self, content: str, title: str = "", description: str = "") -> None: if self.sealed: return if len(self.activities) >= ACTIVITY_LIMIT: self.truncated = True return label = ( title.strip() or description.strip() or next((line.strip() for line in content.splitlines() if line.strip()), "") or "content" )[:1000] header = "\n".join( part for part in ( f"**{title.strip()[:1000]}**" if title.strip() else "", description.strip()[:4000], ) if part ) detail = f"{header}\n\n{content}" if header and content else (header or content) self.truncated |= len(detail) > DETAIL_LIMIT entry: dict[str, object] = { "kind": "display", "target": label, "title": title.strip()[:1000], "description": description.strip()[:4000], "detail": content[:DETAIL_LIMIT], } self.activities[(f"display:{len(self.activities)}", label)] = entry def artifact(self, id: str, version: int, title: str) -> None: if self.sealed: return if len(self.activities) >= ACTIVITY_LIMIT: self.truncated = True return entry: dict[str, object] = { "kind": "artifact", "target": title[:1000], "artifact": {"id": id, "version": version}, } self.activities[(f"artifact:{len(self.activities)}", id)] = entry def skill(self, name: str, scope: str, source: str) -> None: if self.sealed or ("skill", name) in self.activities: return if len(self.activities) >= ACTIVITY_LIMIT: self.truncated = True return self.activities[("skill", name)] = { "kind": "skill", "target": name[:1000], "skill": {"scope": scope[:64], "source": source[:1000]}, } def finish(self) -> dict[str, object]: if self.sealed: raise RuntimeError("trace is already sealed") self.sealed = True with unobserved(): changes: list[dict[str, object]] = [] snapshot_bytes = 0 budget_spent = False for path, before in self.before.items(): after = snapshot(path) if before == after and before is not SnapshotState.UNAVAILABLE: continue if ( before is SnapshotState.UNAVAILABLE or after is SnapshotState.UNAVAILABLE ): changes.append( { "path": path[:1000], "kind": "unavailable", "reason": "binary, unreadable, or larger than 128 KiB", } ) continue old_text = before if isinstance(before, str) else None after = after if isinstance(after, str) else "" import difflib # 0.2 MB a kernel that edits no file never needs lines = list( difflib.unified_diff( (old_text or "").splitlines(True), after.splitlines(True), fromfile=path, tofile=path, ) ) diff = "".join(lines) self.truncated |= len(diff) > DETAIL_LIMIT change: dict[str, object] = { "path": path[:1000], "kind": "diff", "diff": diff[:DETAIL_LIMIT], "added": sum(line.startswith("+") for line in lines[2:]), "removed": sum(line.startswith("-") for line in lines[2:]), } if self.snapshots and not budget_spent: size = len((old_text or "").encode("utf-8")) + len( after.encode("utf-8") ) if snapshot_bytes + size <= SNAPSHOT_BUDGET: change["old_text"] = old_text change["new_text"] = after snapshot_bytes += size else: budget_spent = True changes.append(change) return { "activities": [ activity.copy() for activity in self.activities.values() ], "changes": changes, "truncated": self.truncated, } def release(self) -> None: if not self.sealed: raise RuntimeError("trace must be sealed before release") self.before.clear() self.activities.clear() @functools.cache def _temporary() -> tuple[str, ...]: # Where tempfile.gettempdir() looks, read without calling it: it opens a # probe file under a lock, and that open would come back to this hook. roots = {"/tmp", "/var/tmp", "/dev/shm"} roots |= { os.environ[name] for name in ("TMPDIR", "TEMP", "TMP") if os.environ.get(name) } return tuple({os.path.realpath(root).rstrip(os.sep) or os.sep for root in roots}) def scratch(path: str) -> bool: """Whether a write is scratch rather than an edit: in a temporary directory, outside the kernel's working directory and outside any git or jj checkout. A long turn writes many such files, and diffing them only buries the edits.""" real = os.path.realpath(path) root = next((root for root in _temporary() if real.startswith(root + os.sep)), None) if root is None: return False try: if real.startswith(os.path.realpath(os.getcwd()) + os.sep): return False except OSError: pass folder = os.path.dirname(real) while folder.startswith(root + os.sep): if os.path.exists(os.path.join(folder, ".git")) or os.path.exists( os.path.join(folder, ".jj") ): return False folder = os.path.dirname(folder) return True def snapshot(path: str) -> str | SnapshotState: try: if not os.path.exists(path): return SnapshotState.MISSING if not os.path.isfile(path) or os.path.getsize(path) > LIMIT: return SnapshotState.UNAVAILABLE with open(path, "rb") as file: value = file.read(LIMIT + 1) return ( value.decode("utf-8") if len(value) <= LIMIT and b"\0" not in value else SnapshotState.UNAVAILABLE ) except (OSError, UnicodeError): return SnapshotState.UNAVAILABLE class TracedCapture(Protocol): trace: Trace def _no_capture() -> None: return None current: Callable[[], TracedCapture | None] = _no_capture def note(kind: str, target: str, detail: str = "") -> Done: """Record what a harness tool did for the running cell, as it was asked for: the command run() started, the pattern files.find searched. `detail` is what the person watching sees of its result, such as a search's answer. Answers `done(ok=True, detail="")`, which records how the call ended and how long it took, while the cell's trace is still open.""" capture = current() if capture is None: return _ignored return capture.trace.activity(kind, target, detail) def artifact(id: str, version: int, title: str) -> bool: """Record that the running cell made or revised an artifact, so both clients can open it. Answers whether a cell's trace was there to take it.""" capture = current() if capture is None: return False capture.trace.artifact(id, version, title) return True def skill(load: dict[str, str]) -> None: """Record that the running cell loaded a skill, as the daemon named it: `name`, `scope`, and its installed `SKILL.md` as `source`.""" capture = current() if capture is not None: capture.trace.skill(load["name"], load["scope"], load["source"]) Result = TypeVar("Result") async def noted( kind: str, target: str, work: Awaitable[Result], judge: Callable[[Result], tuple[bool, str]] | None = None, detail: str = "", ) -> Result: """Awaits `work`, noted in the cell's trace with how long it took and how it ended: failed if it raised, else as `judge` reads its result (whether it worked, and the detail to show in place of `detail`).""" done = note(kind, target, detail) try: result = await work except BaseException: done(ok=False) raise if not judge: done() else: done(*judge(result)) return result def install(get_capture: Callable[[], TracedCapture | None]) -> None: global current current = get_capture def audit(event: str, args: tuple[object, ...]) -> None: capture = get_capture() if capture is None or capture.trace.sealed or GUARD.get(): return token = GUARD.set(True) try: if event == "open" and isinstance(args[0], (str, bytes)): path = os.path.abspath(os.fsdecode(args[0])) if path == "/proc" or path.startswith("/proc/"): return # process supervision is harness bookkeeping, not user exploration flags = args[2] if not isinstance(flags, int): raise TypeError("invalid open flags") if flags & ( os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_TRUNC | os.O_APPEND ): capture.trace.writing(path) else: capture.trace.activity("read", path) elif event in ("os.rename", "os.replace") and len(args) >= 2: source, destination = ( os.path.abspath(os.fsdecode(cast(str | bytes, path))) for path in args[:2] ) capture.trace.renamed(source, destination) elif event in ("os.listdir", "os.scandir"): path = os.fsdecode(cast(str | bytes, args[0])) if args else "." if path != "/proc" and not path.startswith("/proc/"): capture.trace.activity("list", path) elif event == "subprocess.Popen": capture.trace.activity("run", command(args[1])) except Exception: if not capture.trace.sealed: capture.trace.truncated = True finally: GUARD.reset(token) sys.addaudithook(audit)