fix: local drafter review round 1

- Refuse to run pi as root when DOCS_REVIEW_DRAFTER_USER is unset.
- Keep a record of the run: parse partial output on timeout, add the first
  redacted stderr line to failures, and report summed output and peak
  input tokens with turns in the log and step summary.
- Delete top-level .pi* entries from the sandbox before drafting and
  refuse a draft that recreates one.
- Probe: an HTTP error, redirect or non-JSON answer is a hard failure;
  only connection failures and an empty model list are soft. Refuse model
  ids starting with "-" and pass --model=<id>.
- README: mid-run model swap note, hard-failure cases, rewrap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-12 16:42:10 -05:00
1 parent 28b993cb23
commit 7095db060e
9 files changed
+330 -86

No files matched your search

+4
View File
@@ -109,6 +109,10 @@ class DraftResult:
error: str | None
# Who drafted, for the PR body; None means Claude Code, which reports a cost.
drafted_by: str | None = None
# Tokens from the local drafter's event stream: the largest input (the peak
# context) and the summed output. Claude reports a cost instead.
input_tokens: int | None = None
output_tokens: int | None = None
def parse_claude_output(stdout: str, returncode: int) -> DraftResult:
+18 -6
View File
@@ -88,13 +88,19 @@ def has_claude_credential(env: Mapping[str, str]) -> bool:
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."""
"""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))
@@ -168,16 +174,21 @@ def disallowed(change: sandbox.TreeChange, listed: frozenset[str],
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."""
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
@@ -233,6 +244,7 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
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)
@@ -241,11 +253,11 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
metadata = git_metadata(cwd)
result = run_drafter(inputs, prompt, box, env, prompt_file, local_model=model,
run_as=run_as)
# Checked first, and on failure no further git command runs: a hook or a
# config change would run on the next one.
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)
write_step_summary(result, env)
if not result.ok:
return Drafted(result, (), f"drafter failed: {result.error}")
change = sandbox.compare(before, sandbox.snapshot(box))
+107 -36
View File
@@ -7,10 +7,12 @@ drafter always asks which model is loaded and uses exactly that one.
from __future__ import annotations
import errno
import json
import os
import pwd
import shutil
import socket
import subprocess
import tempfile
import urllib.error
@@ -20,6 +22,7 @@ from pathlib import Path
from typing import NamedTuple
from docs_review.draft import DraftResult
from docs_review.secrets import redact
KEY_VAR = "LOCAL_MODEL_API_KEY"
USER_VAR = "DOCS_REVIEW_DRAFTER_USER"
@@ -45,6 +48,12 @@ INSTRUCTION = ("Your task is in the attached file {path}. Read and follow it; "
UNREACHABLE_NOTE = "local drafter unavailable: model server unreachable"
NO_MODEL_NOTE = "local drafter unavailable: no model loaded"
REJECTED_NOTE = "local drafter: the model server rejected LOCAL_MODEL_API_KEY"
NOT_SERVER_NOTE = "{url} does not look like the model server: {reason}"
BAD_ID_NOTE = "local drafter: the model server reported an unusable model id {model!r}"
# Failures to reach anything at all. Anything else that answers is the wrong server.
_UNREACHABLE = (ConnectionError, TimeoutError, socket.timeout, socket.gaierror)
_UNREACHABLE_ERRNOS = frozenset({errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ENETDOWN,
errno.EHOSTDOWN})
class Probe(NamedTuple):
@@ -54,7 +63,7 @@ class Probe(NamedTuple):
class DrafterUserError(RuntimeError):
"""DOCS_REVIEW_DRAFTER_USER names a user that does not exist."""
"""Running as root without an existing DOCS_REVIEW_DRAFTER_USER account."""
class _NoRedirect(urllib.request.HTTPRedirectHandler):
@@ -73,26 +82,49 @@ def server_root(base_url: str) -> str:
return url[: -len("/v1")] if url.endswith("/v1") else url
def _unreachable(err: BaseException) -> bool:
"""True when nothing answered: refused, reset, timed out or a name that does not
resolve. URLError wraps the socket error in .reason."""
reason = err.reason if isinstance(err, urllib.error.URLError) else err
if isinstance(reason, _UNREACHABLE):
return True
return isinstance(reason, OSError) and reason.errno in _UNREACHABLE_ERRNOS
def probe(base_url: str, key: str, *, urlopen: Callable = _OPENER.open) -> Probe:
"""Ask the server which model is resident. The key travels in a header only."""
"""Ask the server which model is resident. The key travels in a header only.
Nothing answering, or no model loaded, is soft; a rejected key, or an answer that
is not this server's (an HTTP error, a redirect, a body that is not the expected
JSON), is a hard failure."""
url = server_root(base_url) + LOADED_MODELS_PATH
request = urllib.request.Request(
server_root(base_url) + LOADED_MODELS_PATH,
headers={"Authorization": f"Bearer {key}", "Accept": "application/json"})
url, headers={"Authorization": f"Bearer {key}", "Accept": "application/json"})
try:
with urlopen(request, timeout=PROBE_TIMEOUT_S) as response:
data = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as err:
if err.code in (401, 403):
return Probe(None, REJECTED_NOTE, False)
return Probe(None, UNREACHABLE_NOTE, True)
except (OSError, ValueError):
return Probe(None, UNREACHABLE_NOTE, True)
return Probe(None, NOT_SERVER_NOTE.format(url=url, reason=f"HTTP {err.code}"),
False)
except ValueError:
return Probe(None, NOT_SERVER_NOTE.format(url=url, reason="the reply is not JSON"),
False)
except OSError as err:
if _unreachable(err):
return Probe(None, UNREACHABLE_NOTE, True)
return Probe(None, NOT_SERVER_NOTE.format(url=url, reason=type(err).__name__),
False)
models = data.get("data") if isinstance(data, dict) else None
if isinstance(models, list):
for item in models:
model = item.get("id") if isinstance(item, dict) else None
if isinstance(model, str) and model.strip():
return Probe(model.strip(), None, True)
if not isinstance(models, list):
return Probe(None, NOT_SERVER_NOTE.format(url=url, reason="no `data` list"), False)
for item in models:
model = item.get("id") if isinstance(item, dict) else None
if isinstance(model, str) and model.strip():
model = model.strip()
if model.startswith("-"):
return Probe(None, BAD_ID_NOTE.format(model=model), False)
return Probe(model, None, True)
return Probe(None, NO_MODEL_NOTE, True)
@@ -102,18 +134,24 @@ def resident_model(base_url: str, key: str, *,
return probe(base_url, key, urlopen=urlopen).model
def drafter_user(env: Mapping[str, str], *, geteuid: Callable[[], int] = os.geteuid,
getpwnam: Callable = pwd.getpwnam) -> tuple[int, int] | None:
"""(uid, gid) to run pi as: the DOCS_REVIEW_DRAFTER_USER account when this process
is root and the variable is set, otherwise None (run as the current user). Raises
DrafterUserError when the named account does not exist."""
name = (env.get(USER_VAR) or "").strip()
if not name or geteuid() != 0:
def drafter_user(env: Mapping[str, str], *, geteuid: Callable[[], int] | None = None,
getpwnam: Callable | None = None) -> tuple[int, int] | None:
"""(uid, gid) to run pi as. Not root: None, run as the current user. Root: the
DOCS_REVIEW_DRAFTER_USER account, and DrafterUserError when it is unset or does not
exist, since pi as root could write anywhere."""
geteuid = geteuid or os.geteuid
getpwnam = getpwnam or pwd.getpwnam
if geteuid() != 0:
return None
name = (env.get(USER_VAR) or "").strip()
if not name:
raise DrafterUserError(f"running as root and {USER_VAR} is not set; "
"refusing to run pi as root")
try:
entry = getpwnam(name)
except KeyError:
raise DrafterUserError(f"drafter user {name!r} does not exist") from None
raise DrafterUserError(f"drafter user {name!r} ({USER_VAR}) does not exist") \
from None
return entry.pw_uid, entry.pw_gid
@@ -142,7 +180,7 @@ def pi_argv(binary: str, model: str, task_file: Path,
system_prompt_file: Path | None) -> list[str]:
"""The pi command line. The task goes in as an @file, so a long prompt never lands
in argv; the key is never in it."""
argv = [binary, "-p", "--mode", "json", "--provider", PROVIDER, "--model", model,
argv = [binary, "-p", "--mode", "json", "--provider", PROVIDER, f"--model={model}",
"--thinking", THINKING, "--tools", TOOLS, *ISOLATION_FLAGS]
if system_prompt_file is not None:
argv += ["--append-system-prompt", str(system_prompt_file)]
@@ -157,16 +195,33 @@ def pi_env(env: Mapping[str, str], home: Path) -> dict[str, str]:
def _first_line(text: str) -> str:
lines = text.strip().splitlines()
"""The first non-blank line, cut to ERROR_MAX characters."""
lines = [l.strip() for l in text.splitlines() if l.strip()]
line = lines[0] if lines else ""
return line if len(line) <= ERROR_MAX else line[:ERROR_MAX] + "..."
def parse_pi_events(stdout: str, returncode: int) -> DraftResult:
def _text(raw: str | bytes | None) -> str:
if raw is None:
return ""
return raw.decode("utf-8", "replace") if isinstance(raw, bytes) else raw
def _count(usage: object, key: str) -> int | None:
value = usage.get(key) if isinstance(usage, dict) else None
return value if isinstance(value, int) and not isinstance(value, bool) else None
def parse_pi_events(stdout: str, returncode: int | None, *, stderr: str = "",
env: Mapping[str, str] | None = None,
error: str | None = None) -> DraftResult:
"""Read pi's JSON event stream: the last assistant message is the answer, and each
turn_end is a turn. pi exits 0 after a model error, so the message's stopReason
decides that. Nothing here raises."""
final, turns = None, 0
turn_end is a turn. Tokens: output summed over assistant messages, input as the
maximum (each turn's input is the whole conversation so far, so a sum would count
it many times). pi exits 0 after a model error, so the message's stopReason decides
that. `error` (a timeout) fails the run whatever the stream says; the first stderr
line, credential values redacted, joins any failure. Nothing here raises."""
final, turns, tokens_in, tokens_out = None, 0, None, None
for line in stdout.splitlines():
try:
event = json.loads(line)
@@ -180,19 +235,31 @@ def parse_pi_events(stdout: str, returncode: int) -> DraftResult:
if (event.get("type") == "message_end" and isinstance(message, dict)
and message.get("role") == "assistant"):
final = message
usage = message.get("usage")
used_in, used_out = _count(usage, "input"), _count(usage, "output")
if used_in is not None:
tokens_in = max(tokens_in or 0, used_in)
if used_out is not None:
tokens_out = (tokens_out or 0) + used_out
text = ""
if final is not None and isinstance(final.get("content"), list):
text = "".join(c.get("text", "") for c in final["content"]
if isinstance(c, dict) and c.get("type") == "text"
and isinstance(c.get("text"), str))
if final is not None and final.get("stopReason") in ("error", "aborted"):
if error is None and final is not None and final.get("stopReason") in ("error",
"aborted"):
reason = _first_line(str(final.get("errorMessage") or final.get("stopReason")))
return DraftResult(False, None, turns, text, f"pi reported an error: {reason}")
if returncode != 0:
return DraftResult(False, None, turns, text, f"pi exited with code {returncode}")
if not text.strip():
return DraftResult(False, None, turns, text, "pi gave no final text")
return DraftResult(True, None, turns, text, None)
error = f"pi reported an error: {reason}"
if error is None and returncode != 0:
error = f"pi exited with code {returncode}"
if error is None and not text.strip():
error = "pi gave no final text"
if error is not None:
line = _first_line(redact(stderr, env or {}))
if line:
error += f"; stderr: {line}"
return DraftResult(error is None, None, turns, text, error,
input_tokens=tokens_in, output_tokens=tokens_out)
def _write(path: Path, text: str) -> None:
@@ -229,10 +296,14 @@ def run_local(prompt: str, *, base_url: str, key: str, model: str, cwd: Path,
proc = subprocess.run(argv, cwd=cwd, env=child_env, stdin=subprocess.DEVNULL,
capture_output=True, text=True, timeout=timeout,
check=False, **user)
except subprocess.TimeoutExpired:
return DraftResult(False, None, None, "", "timed out")
except subprocess.TimeoutExpired as err:
# Whatever pi streamed before the kill: the turns, the last message and
# the tokens survive in the record.
return parse_pi_events(_text(err.stdout), None, stderr=_text(err.stderr),
env=child_env, error="timed out")
except OSError as err:
return DraftResult(False, None, None, "", f"could not start pi: {err}")
return parse_pi_events(proc.stdout, proc.returncode)
return parse_pi_events(proc.stdout, proc.returncode, stderr=proc.stderr,
env=child_env)
finally:
shutil.rmtree(home, ignore_errors=True)
+27
View File
@@ -66,6 +66,33 @@ def remove_symlinks(root: Path) -> tuple[str, ...]:
return tuple(sorted(removed))
PI_CONFIG_PREFIX = ".pi"
def is_pi_config(rel: str) -> bool:
"""True for a path under a top-level entry named .pi*: pi's project settings,
extensions and model config, or a config file beside them."""
return Path(rel).parts[0].startswith(PI_CONFIG_PREFIX) if rel else False
def pi_config_entries(root: Path) -> tuple[str, ...]:
"""Top-level names under root that start with .pi."""
return tuple(sorted(n for n in os.listdir(root) if n.startswith(PI_CONFIG_PREFIX)))
def remove_pi_config(root: Path) -> tuple[str, ...]:
"""Delete every top-level .pi* entry, so a pull request's pi settings or model
config cannot load whatever flags pi is given. Returns the removed names."""
removed = pi_config_entries(root)
for name in removed:
path = root / name
if path.is_dir() and not path.is_symlink():
shutil.rmtree(path)
else:
path.unlink()
return removed
class CopyRefused(RuntimeError):
"""A change cannot be copied back safely; the message names the path."""