"""Running the drafter in a sandbox and taking back only the changes it may make.""" from __future__ import annotations 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, 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") 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 and turns, whichever Claude reported, and append them to $GITHUB_STEP_SUMMARY when the runner sets it.""" lines = [] 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 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) -> DraftResult: """Run the configured drafter in cwd. Task 12 adds `local`.""" if inputs.drafter != "claude": return DraftResult(False, None, None, "", "local drafter not built yet") 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 disallowed(change: sandbox.TreeChange, listed: frozenset[str], patterns: tuple[str, ...], root: Path) -> 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.""" bad = [] for p in change.paths: ok = p in listed or (p in change.new and matches_any(p, patterns)) if ok and p not in change.deleted and not sandbox.is_regular(root, p): ok = False if not ok: bad.append(p) 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 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) 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) listed = frozenset(expand_patterns(inputs.docs, box)) before = sandbox.snapshot(box) prompt_file = write_system_prompt(box, inputs.doc_guide, env) result = run_drafter(inputs, prompt, box, env, prompt_file) write_step_summary(result, env) 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) if bad: names = ", ".join(f"`{p}`" for p in bad) return Drafted(result, (), f"drafter failed: it changed files outside `docs`: {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)