Files
docs-review/docs_review/sandbox.py
T
jaredandClaude Opus 5.5 28b993cb23 feat: local drafter (pi against a self-run model server)
drafter: local runs the pi coding agent against the model resident on an
OpenAI-compatible server at the new local_url input, keyed by the
LOCAL_MODEL_API_KEY secret. It asks the server which model is loaded and
names exactly that one, so it never evicts the resident model. An
unreachable server or no loaded model posts the stage 1 flags with a note
and exits 0; a drafter that ran and failed still exits 1.

pi runs in the existing sandbox with read, ls, edit and write, every
project-local pi file and AGENTS.md ignored, stdin from /dev/null, the task
passed as an @file, and an allowlisted environment. As root with
DOCS_REVIEW_DRAFTER_USER set, it runs as that unprivileged user, which
owns only the sandbox and pi's temporary home.

Both drafters now hash the checkout's .git/config and .git/hooks before
drafting and stop with no further git command if either changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:28:21 -05:00

156 lines
5.5 KiB
Python

"""The drafter's sandbox: an export of the tracked tree with no .git, compared afterwards.
The drafter never runs in the repository. It edits a copy, and only the changes the
caller allows are copied back, so a write to .git, a hook or any other path cannot
reach the checkout the job commits from.
"""
from __future__ import annotations
import hashlib
import os
import shutil
import subprocess
import tempfile
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from docs_review.git import GitError
from docs_review.secrets import scrub_env
from docs_review.tree import inside
ARCHIVE_TIMEOUT_S = 300
def make_sandbox(env: Mapping[str, str]) -> Path:
"""A fresh empty directory under RUNNER_TEMP, or the system temp directory."""
parent = env.get("RUNNER_TEMP")
if parent:
return Path(tempfile.mkdtemp(prefix="docs-review-sandbox-", dir=parent))
return Path(tempfile.mkdtemp(prefix="docs-review-sandbox-"))
def export_tree(cwd: Path, dest: Path) -> None:
"""`git archive HEAD | tar -x -C dest`: the tracked tree at HEAD, without .git."""
env = scrub_env(os.environ)
archive = subprocess.Popen(["git", "archive", "--format=tar", "HEAD"], cwd=cwd,
env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
tar = subprocess.run(["tar", "-x", "-f", "-", "-C", str(dest)],
stdin=archive.stdout, env=env, capture_output=True,
timeout=ARCHIVE_TIMEOUT_S, check=False)
finally:
archive.stdout.close()
archive_err = archive.stderr.read().decode("utf-8", "replace")
archive.stderr.close()
archive.wait()
if archive.returncode != 0:
raise GitError(f"git archive HEAD failed: {archive_err.strip()}")
if tar.returncode != 0:
raise GitError(f"tar -x failed: {tar.stderr.decode('utf-8', 'replace').strip()}")
def remove_symlinks(root: Path) -> tuple[str, ...]:
"""Delete every symlink under root, so the drafter's Edit and Write cannot follow
one out of the sandbox. Returns the removed paths."""
removed = []
for dirpath, dirnames, filenames in os.walk(root):
base = Path(dirpath)
for name in list(filenames) + list(dirnames):
path = base / name
if path.is_symlink():
path.unlink()
removed.append(path.relative_to(root).as_posix())
dirnames[:] = [d for d in dirnames if (base / d).is_dir()]
return tuple(sorted(removed))
class CopyRefused(RuntimeError):
"""A change cannot be copied back safely; the message names the path."""
def digest(path: Path) -> str:
"""A content hash; a symlink hashes its target text and is marked as a link."""
if path.is_symlink():
return "link:" + os.readlink(path)
h = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(1 << 16), b""):
h.update(chunk)
return "file:" + h.hexdigest()
def snapshot(root: Path) -> dict[str, str]:
"""Every file (and symlink) under root, as repository-relative POSIX path -> hash."""
out: dict[str, str] = {}
for dirpath, dirnames, filenames in os.walk(root):
base = Path(dirpath)
names = list(filenames) + [d for d in dirnames if (base / d).is_symlink()]
for name in names:
path = base / name
out[path.relative_to(root).as_posix()] = digest(path)
return out
@dataclass(frozen=True)
class TreeChange:
new: tuple[str, ...]
changed: tuple[str, ...]
deleted: tuple[str, ...]
@property
def paths(self) -> tuple[str, ...]:
return tuple(sorted(self.new + self.changed + self.deleted))
def compare(before: Mapping[str, str], after: Mapping[str, str]) -> TreeChange:
return TreeChange(
new=tuple(sorted(set(after) - set(before))),
changed=tuple(sorted(p for p in set(after) & set(before) if after[p] != before[p])),
deleted=tuple(sorted(set(before) - set(after))),
)
def is_regular(sandbox: Path, rel: str) -> bool:
path = sandbox / rel
return path.is_file() and not path.is_symlink()
def _safe_target(cwd: Path, rel: str) -> Path:
"""cwd/rel, refusing .git, a symlink at or above the destination, or a destination
that resolves outside cwd."""
parts = Path(rel).parts
if not parts or ".git" in parts or ".." in parts or Path(rel).is_absolute():
raise CopyRefused(rel)
current = cwd
for part in parts:
current = current / part
if current.is_symlink():
raise CopyRefused(rel)
target = cwd / rel
if not inside(cwd, target):
raise CopyRefused(rel)
return target
def copy_back(change: TreeChange, sandbox: Path, cwd: Path) -> None:
"""Apply the sandbox's new, changed and deleted files to cwd. Every source and
target is checked before any is written, so a refusal leaves cwd untouched."""
for rel in change.new + change.changed:
if not is_regular(sandbox, rel):
raise CopyRefused(rel)
writes = [(sandbox / rel, _safe_target(cwd, rel)) for rel in change.new + change.changed]
deletes = [_safe_target(cwd, rel) for rel in change.deleted]
for source, target in writes:
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
for target in deletes:
if target.exists():
target.unlink()
def remove(path: Path | None) -> None:
if path is not None:
shutil.rmtree(path, ignore_errors=True)