tests / unittest (push) Failing after 28s
drafter: local runs the pi agent against the model already loaded on a self-hosted server, as an unprivileged user, in the same sandbox as the Claude drafter. It fails soft when the server is unreachable or has no model loaded. Both drafters now refuse to continue if git metadata changed during drafting, and strip project pi configuration from the sandbox. Tested live against a self-hosted server: one run, 12 turns, docs PR opened. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
280 lines
12 KiB
Python
280 lines
12 KiB
Python
"""Running the drafter in a sandbox and taking back only the changes it may make."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import dataclasses
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from collections.abc import Iterable, Mapping
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
from docs_review import git, local, sandbox
|
|
from docs_review.draft import DraftResult, claude_argv, parse_claude_output
|
|
from docs_review.inputs import Inputs, expand_patterns, matches_any
|
|
from docs_review.secrets import secret_values
|
|
from docs_review.tree import read_in_tree
|
|
|
|
DRAFT_TIMEOUT_S = 1500
|
|
DRAFTER_ENV = frozenset({
|
|
"PATH", "HOME", "LANG", "TMPDIR", "TERM", "CLAUDE_CODE_OAUTH_TOKEN",
|
|
"ANTHROPIC_API_KEY", "DISABLE_UPDATES", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
|
|
})
|
|
REPO_INSTRUCTIONS = "CLAUDE.md"
|
|
CREDENTIAL_NOTE = "drafted edits contained a credential value; nothing committed"
|
|
DIRTY_NOTE = "working tree not clean before drafting"
|
|
EXPORT_NOTE = "drafter failed: could not export the tree for drafting: {reason}"
|
|
EXPORT_REASON_MAX = 200
|
|
NO_CREDENTIAL_NOTE = "drafter: claude but no Claude credential is set"
|
|
CREDENTIAL_VARS = ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY")
|
|
NO_LOCAL_KEY_NOTE = "drafter: local but LOCAL_MODEL_API_KEY is not set"
|
|
GIT_METADATA_NOTE = "drafter changed git metadata; nothing committed"
|
|
REFUSED_NOTE = "drafter failed: refusing to copy back `{path}` (symlink or outside the repository)"
|
|
|
|
|
|
def drafter_env(env: Mapping[str, str]) -> dict[str, str]:
|
|
"""Only what Claude needs; the Gitea bot token and the rest stay behind."""
|
|
return {k: v for k, v in env.items() if k in DRAFTER_ENV or k.startswith("LC_")}
|
|
|
|
|
|
def leaks_credential(files: Iterable[str], root: Path, env: Mapping[str, str]) -> bool:
|
|
"""True when a drafted file holds the value of a secret-named variable."""
|
|
secrets = secret_values(env)
|
|
if not secrets:
|
|
return False
|
|
for rel in files:
|
|
text = read_in_tree(root, rel)
|
|
if text is not None and any(v in text for v in secrets):
|
|
return True
|
|
return False
|
|
|
|
|
|
def system_prompt_text(cwd: Path, guide_path: str | None) -> str | None:
|
|
"""The repository's CLAUDE.md, then the guide, each under a line naming it.
|
|
|
|
--setting-sources user keeps the PR's own .claude settings and hooks from loading,
|
|
which also stops CLAUDE.md loading; this puts it back as plain text."""
|
|
parts = []
|
|
instructions = read_in_tree(cwd, REPO_INSTRUCTIONS)
|
|
if instructions is not None:
|
|
parts.append(f"Contents of the repository's {REPO_INSTRUCTIONS}:\n\n" + instructions)
|
|
if guide_path:
|
|
guide = read_in_tree(cwd, guide_path)
|
|
if guide is not None:
|
|
parts.append(f"Contents of the documentation guide, {guide_path}:\n\n" + guide)
|
|
else:
|
|
print(f"warning: doc_guide {guide_path} is missing, a symlink or outside "
|
|
"the repository", file=sys.stderr)
|
|
return "\n\n".join(p.rstrip("\n") for p in parts) + "\n" if parts else None
|
|
|
|
|
|
def write_system_prompt(cwd: Path, guide_path: str | None,
|
|
env: Mapping[str, str]) -> Path | None:
|
|
"""The system prompt file under RUNNER_TEMP (or the system temp directory)."""
|
|
text = system_prompt_text(cwd, guide_path)
|
|
if text is None:
|
|
return None
|
|
fd, name = tempfile.mkstemp(prefix="docs-review-system-prompt-", suffix=".md",
|
|
dir=env.get("RUNNER_TEMP") or None)
|
|
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
fh.write(text)
|
|
return Path(name)
|
|
|
|
|
|
def has_claude_credential(env: Mapping[str, str]) -> bool:
|
|
return any((env.get(k) or "").strip() for k in CREDENTIAL_VARS)
|
|
|
|
|
|
def write_step_summary(result: DraftResult, env: Mapping[str, str]) -> None:
|
|
"""Print the run's cost, turns and tokens, whichever the drafter reported, and
|
|
append them to $GITHUB_STEP_SUMMARY when the runner sets it."""
|
|
lines = []
|
|
if result.drafted_by is not None:
|
|
lines.append(f"- drafted_by: {result.drafted_by}")
|
|
if result.cost_usd is not None:
|
|
lines.append(f"- total_cost_usd: {result.cost_usd:.2f}")
|
|
if result.turns is not None:
|
|
lines.append(f"- num_turns: {result.turns}")
|
|
if result.output_tokens is not None:
|
|
lines.append(f"- output_tokens: {result.output_tokens}")
|
|
if result.input_tokens is not None:
|
|
lines.append(f"- max_input_tokens: {result.input_tokens}")
|
|
if not lines:
|
|
return
|
|
print("drafter " + ", ".join(l[2:] for l in lines))
|
|
path = env.get("GITHUB_STEP_SUMMARY")
|
|
if not path:
|
|
return
|
|
try:
|
|
with open(path, "a", encoding="utf-8") as fh:
|
|
fh.write("### docs-review drafter\n\n" + "\n".join(lines) + "\n")
|
|
except OSError as err:
|
|
print(f"warning: could not write the step summary: {err}", file=sys.stderr)
|
|
|
|
|
|
def run_drafter(inputs: Inputs, prompt: str, cwd: Path, env: Mapping[str, str],
|
|
system_prompt_file: Path | None, *, local_model: str | None = None,
|
|
run_as: tuple[int, int] | None = None) -> DraftResult:
|
|
"""Run the configured drafter in cwd. `local` needs the resident model's id."""
|
|
if inputs.drafter == "local":
|
|
if local_model is None or inputs.local_url is None:
|
|
return DraftResult(False, None, None, "", "no local model to draft with")
|
|
result = local.run_local(
|
|
prompt, base_url=inputs.local_url, key=env.get(local.KEY_VAR, ""),
|
|
model=local_model, cwd=cwd, system_prompt_file=system_prompt_file, env=env,
|
|
timeout=DRAFT_TIMEOUT_S, run_as=run_as)
|
|
return dataclasses.replace(result, drafted_by=f"pi with {local_model}")
|
|
argv = claude_argv(env.get("DOCS_REVIEW_CLAUDE_BIN", "claude"), inputs.model,
|
|
str(system_prompt_file) if system_prompt_file else None)
|
|
try:
|
|
proc = subprocess.run(argv, input=prompt, cwd=cwd, env=drafter_env(env),
|
|
capture_output=True, text=True, timeout=DRAFT_TIMEOUT_S,
|
|
check=False)
|
|
except subprocess.TimeoutExpired:
|
|
return DraftResult(False, None, None, "", "timed out")
|
|
except OSError as err:
|
|
return DraftResult(False, None, None, "", f"could not start Claude: {err}")
|
|
return parse_claude_output(proc.stdout, proc.returncode)
|
|
|
|
|
|
def git_metadata(cwd: Path) -> dict[str, str]:
|
|
"""Hashes of the checkout's .git/config and of everything under .git/hooks: the
|
|
files that make a later git command run code. The drafter runs outside the
|
|
checkout, but nothing else stops it writing here."""
|
|
gitdir = cwd / ".git"
|
|
if not gitdir.is_dir() or gitdir.is_symlink():
|
|
return {".git": _entry(gitdir)}
|
|
out = {"config": _entry(gitdir / "config")}
|
|
hooks = gitdir / "hooks"
|
|
out["hooks"] = _entry(hooks)
|
|
if hooks.is_dir() and not hooks.is_symlink():
|
|
for dirpath, dirnames, filenames in os.walk(hooks):
|
|
for name in dirnames + filenames:
|
|
path = Path(dirpath) / name
|
|
out["hooks/" + path.relative_to(hooks).as_posix()] = _entry(path)
|
|
return out
|
|
|
|
|
|
def _entry(path: Path) -> str:
|
|
"""A file's or link's hash, `dir` for a directory, `missing` when absent."""
|
|
if path.is_symlink() or path.is_file():
|
|
try:
|
|
return sandbox.digest(path)
|
|
except OSError as err:
|
|
return f"unreadable:{err.errno}"
|
|
if path.is_dir():
|
|
return "dir"
|
|
return "missing" if not os.path.lexists(path) else "other"
|
|
|
|
|
|
def disallowed(change: sandbox.TreeChange, listed: frozenset[str],
|
|
patterns: tuple[str, ...], root: Path,
|
|
review_only: tuple[str, ...] = ()) -> list[str]:
|
|
"""Changed paths the drafter may not touch. A listed document may change or go; a
|
|
new file must match a docs pattern; anything written must be a regular file. Nothing
|
|
matching a review_only pattern may change, appear or go, and nothing may recreate
|
|
the pi configuration removed before drafting."""
|
|
bad = []
|
|
for p in change.paths:
|
|
ok = p in listed or (p in change.new and matches_any(p, patterns))
|
|
if ok and sandbox.is_pi_config(p):
|
|
ok = False
|
|
if ok and matches_any(p, review_only):
|
|
ok = False
|
|
if ok and p not in change.deleted and not sandbox.is_regular(root, p):
|
|
ok = False
|
|
if not ok:
|
|
bad.append(p)
|
|
bad += [name + "/" for name in sandbox.pi_config_entries(root)
|
|
if (root / name).is_dir() and not any(p.startswith(name + "/") for p in bad)]
|
|
return bad
|
|
|
|
|
|
def _short_reason(err: BaseException) -> str:
|
|
"""The first line of an error, cut to EXPORT_REASON_MAX characters."""
|
|
if isinstance(err, subprocess.TimeoutExpired):
|
|
return f"timed out after {err.timeout:g} s"
|
|
lines = str(err).strip().splitlines()
|
|
line = lines[0] if lines else type(err).__name__
|
|
return line if len(line) <= EXPORT_REASON_MAX else line[:EXPORT_REASON_MAX] + "..."
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Drafted:
|
|
result: DraftResult | None
|
|
changed: tuple[str, ...]
|
|
note: str | None # why the run failed; None when it succeeded
|
|
soft: bool = False # the drafter was unavailable: report the note, do not fail
|
|
|
|
|
|
def _local_preflight(inputs: Inputs, env: Mapping[str, str]):
|
|
"""For `local`: (model, run_as, None) or (None, None, Drafted) when it cannot run."""
|
|
if not (env.get(local.KEY_VAR) or "").strip():
|
|
return None, None, Drafted(None, (), NO_LOCAL_KEY_NOTE)
|
|
try:
|
|
run_as = local.drafter_user(env)
|
|
except local.DrafterUserError as err:
|
|
return None, None, Drafted(None, (), f"drafter failed: {err}")
|
|
found = local.probe(inputs.local_url or "", env[local.KEY_VAR])
|
|
if found.model is None:
|
|
return None, None, Drafted(None, (), found.note, soft=found.soft)
|
|
print(f"local drafter: resident model {found.model}")
|
|
return found.model, run_as, None
|
|
|
|
|
|
def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
|
|
env: Mapping[str, str]) -> Drafted:
|
|
"""Run the drafter on an export of HEAD and copy its allowed changes into cwd."""
|
|
if inputs.drafter == "claude" and not has_claude_credential(env):
|
|
return Drafted(None, (), NO_CREDENTIAL_NOTE)
|
|
model = run_as = None
|
|
if inputs.drafter == "local":
|
|
model, run_as, stop = _local_preflight(inputs, env)
|
|
if stop is not None:
|
|
return stop
|
|
if git.run(["status", "--porcelain"], cwd).strip():
|
|
return Drafted(None, (), DIRTY_NOTE)
|
|
box = prompt_file = None
|
|
try:
|
|
box = sandbox.make_sandbox(env)
|
|
try:
|
|
sandbox.export_tree(cwd, box)
|
|
except (git.GitError, subprocess.TimeoutExpired, OSError) as err:
|
|
return Drafted(None, (), EXPORT_NOTE.format(reason=_short_reason(err)))
|
|
sandbox.remove_symlinks(box)
|
|
sandbox.remove_pi_config(box)
|
|
listed = frozenset(expand_patterns(inputs.docs, box))
|
|
before = sandbox.snapshot(box)
|
|
prompt_file = write_system_prompt(box, inputs.doc_guide, env)
|
|
if run_as is not None:
|
|
local.chown_tree(box, run_as)
|
|
metadata = git_metadata(cwd)
|
|
result = run_drafter(inputs, prompt, box, env, prompt_file, local_model=model,
|
|
run_as=run_as)
|
|
write_step_summary(result, env)
|
|
# Checked before anything else, and on failure no further git command runs: a
|
|
# hook or a config change would run on the next one.
|
|
if git_metadata(cwd) != metadata:
|
|
return Drafted(result, (), GIT_METADATA_NOTE)
|
|
if not result.ok:
|
|
return Drafted(result, (), f"drafter failed: {result.error}")
|
|
change = sandbox.compare(before, sandbox.snapshot(box))
|
|
bad = disallowed(change, listed, inputs.docs, box, inputs.review_only)
|
|
if bad:
|
|
names = ", ".join(f"`{p}`" for p in bad)
|
|
where = "outside `docs`" + (" or in `review_only`" if inputs.review_only else "")
|
|
return Drafted(result, (), f"drafter failed: it changed files {where}: {names}")
|
|
if leaks_credential(change.new + change.changed, box, env):
|
|
return Drafted(result, (), CREDENTIAL_NOTE)
|
|
try:
|
|
sandbox.copy_back(change, box, cwd)
|
|
except sandbox.CopyRefused as err:
|
|
return Drafted(result, (), REFUSED_NOTE.format(path=err))
|
|
return Drafted(result, change.paths, None)
|
|
finally:
|
|
sandbox.remove(box)
|
|
if prompt_file is not None:
|
|
prompt_file.unlink(missing_ok=True)
|