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

+40 -32
View File
@@ -2,8 +2,8 @@
`docs_review` keeps living documents current. On each Gitea pull request it flags `docs_review` keeps living documents current. On each Gitea pull request it flags
the documents the change makes stale. If the repository opts in, it also has a coding the documents the change makes stale. If the repository opts in, it also has a coding
agent draft the edits: Claude Code, or the pi agent on a model server you run. It is a Python package with no dependencies outside the standard agent draft the edits: Claude Code, or the pi agent on a model server you run. It is a
library. Python package with no dependencies outside the standard library.
## What it does ## What it does
@@ -18,10 +18,11 @@ finds, and edits that comment on later runs:
modified, where the change did not regenerate it. modified, where the change did not regenerate it.
- **unguided**: a listed document that the doc guide does not describe. - **unguided**: a listed document that the doc guide does not describe.
Stage 2 runs only with `drafter: claude` or `drafter: local`. The drafter reads the change, Stage 2 runs only with `drafter: claude` or `drafter: local`. The drafter reads the
the flags and the listed documents, and decides which documents need edits; the flags are hints, not a change, the flags and the listed documents, and decides which documents need edits; the
limit. The edits go into a second pull request into the feature branch, for the author to flags are hints, not a limit. The edits go into a second pull request into the feature
review and merge. Later runs add commits to that pull request rather than replacing it. branch, for the author to review and merge. Later runs add commits to that pull request
rather than replacing it.
The monthly pass runs on a schedule. It treats every file as new and reports the The monthly pass runs on a schedule. It treats every file as new and reports the
uncovered and unguided flags for the whole repository in one issue. With a drafter set uncovered and unguided flags for the whole repository in one issue. With a drafter set
@@ -55,34 +56,40 @@ committed, and everything posted to Gitea has credential values replaced with `*
## The local drafter ## The local drafter
`drafter: local` runs the [pi](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) `drafter: local` runs the
coding agent (a pinned version) against an OpenAI-compatible model server that you run [pi](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) coding agent (a
and that reports its loaded model the way Unsloth Studio does (below). Set `local_url` to the server's pinned version) against an OpenAI-compatible model server that you run and that reports
its loaded model the way Unsloth Studio does (below). Set `local_url` to the server's
OpenAI-compatible base URL, for example `http://model-host:8888/v1`, and the OpenAI-compatible base URL, for example `http://model-host:8888/v1`, and the
`LOCAL_MODEL_API_KEY` secret to its key. The Actions runner must be able to reach that `LOCAL_MODEL_API_KEY` secret to its key. The Actions runner must be able to reach that
address. address.
- **One model is resident at a time, and the tool uses whichever one is loaded.** Before - **One model is resident at a time, and the tool uses whichever one is loaded.**
drafting it asks the server (`GET <server>/api/inference/loaded-models`, with the key in Before drafting it asks the server (`GET <server>/api/inference/loaded-models`, with
the `Authorization` header) which model is loaded, and names exactly that one. Naming any the key in the `Authorization` header) which model is loaded, and names exactly that
other model would make the server swap it in and evict the model for every other one. Naming any other model would make the server swap it in and evict the model for
client, so the tool never does. There is no `model` input for `local`. every other client, so the tool never does. There is no `model` input for `local`. If
- **The server is only reachable while it runs.** If it cannot be reached, or has no someone loads a different model while a run is drafting, the run's remaining requests
model loaded, the run posts the stage 1 flags with the note "local drafter unavailable: load the old model back.
model server unreachable" (or "no model loaded") and succeeds. A drafter that ran and - **The server is only reachable while it runs.** If nothing answers, or the server has
failed still fails the job, as does a key the server rejects. no model loaded, the run posts the stage 1 flags with the note "local drafter
- The server must expose `/api/inference/loaded-models` returning `{"data": [{"id": ...}]}` unavailable: model server unreachable" (or "no model loaded") and succeeds. A drafter
at the root of `local_url` without its trailing `/v1`. that ran and failed still fails the job, as do a key the server rejects and an answer
that is not this server's (an HTTP error or a reply that is not the expected JSON).
- The server must expose `/api/inference/loaded-models` returning
`{"data": [{"id": ...}]}` at the root of `local_url` without its trailing `/v1`.
- Nothing is sent to Anthropic. The same material as for `claude` goes to your server. - Nothing is sent to Anthropic. The same material as for `claude` goes to your server.
pi runs with the read, list, edit and write tools only, no shell, and with every pi runs with the read, list, edit and write tools only, no shell, and with every
project-local pi file (settings, extensions, skills, prompt templates) and `AGENTS.md` project-local pi file (settings, extensions, skills, prompt templates) and `AGENTS.md`
ignored, since those come from the pull request. Its tool allowlist limits tool types, ignored, since those come from the pull request. Any top-level `.pi*` entry is also
not paths, so the workflow runs it as an unprivileged user that owns only the sandbox deleted from its working copy before it runs, and a draft that recreates one fails. Its
and pi's own temporary home; the checkout stays root-owned. The repository's tool allowlist limits tool types, not paths, so the workflow runs it as an unprivileged
`CLAUDE.md` and the doc guide reach it in the system prompt, as for `claude`. Its user that owns only the sandbox and pi's own temporary home; the checkout stays
environment is the same allowlist with `LOCAL_MODEL_API_KEY` in place of the Claude root-owned, and the tool refuses to run pi as root. The repository's `CLAUDE.md` and the
credential, and the key is written into neither its command line nor its config file. doc guide reach it in the system prompt, as for `claude`. Its environment is the same
allowlist with `LOCAL_MODEL_API_KEY` in place of the Claude credential, and the key is
written into neither its command line nor its config file.
## Install ## Install
@@ -116,8 +123,8 @@ jobs:
- `closed` in the pull request types lets the workflow close a docs pull request whose - `closed` in the pull request types lets the workflow close a docs pull request whose
feature pull request merged or closed first. feature pull request merged or closed first.
- The `concurrency` block cancels a run when the pull request is pushed again. With - The `concurrency` block cancels a run when the pull request is pushed again. With
`drafter: claude` or `local` the workflow waits three minutes between stage 1 and drafting, so a `drafter: claude` or `local` the workflow waits three minutes between stage 1 and
quick re-push cancels a run before it has spent anything. drafting, so a quick re-push cancels a run before it has spent anything.
- `tool_ref` must name the same version as the `@` in `uses:`. Gitea does not tell a - `tool_ref` must name the same version as the `@` in `uses:`. Gitea does not tell a
called workflow which ref it was called at, so the workflow fetches the tool's code at called workflow which ref it was called at, so the workflow fetches the tool's code at
`tool_ref`. `tool_ref`.
@@ -129,8 +136,9 @@ it needs no checkout action, and it installs Claude Code
Claude credential is set. With `drafter: claude` and no credential, it posts the stage 1 Claude credential is set. With `drafter: claude` and no credential, it posts the stage 1
comment with a note saying so and fails. With `drafter: local` it installs pi comment with a note saying so and fails. With `drafter: local` it installs pi
(`@earendil-works/pi-coding-agent`, a pinned version) and creates the unprivileged user (`@earendil-works/pi-coding-agent`, a pinned version) and creates the unprivileged user
when `LOCAL_MODEL_API_KEY` is set, and without it posts a note and fails in the same way. when `LOCAL_MODEL_API_KEY` is set, and without it posts a note and fails in the same
The drafter's turn count, and Claude's cost, are printed in the log and appended to way. The drafter's turn count, Claude's cost, and pi's tokens (output summed over the
run, and the largest input) are printed in the log and appended to
`$GITHUB_STEP_SUMMARY`. `$GITHUB_STEP_SUMMARY`.
The package can also be run by hand: `python3 -m docs_review pr|closed|monthly --help`. The package can also be run by hand: `python3 -m docs_review pr|closed|monthly --help`.
@@ -169,8 +177,8 @@ The package can also be run by hand: `python3 -m docs_review pr|closed|monthly -
python3 -m unittest discover -s tests -v python3 -m unittest discover -s tests -v
``` ```
The tests use only the standard library and fake `claude` and `pi` executables. They need The tests use only the standard library and fake `claude` and `pi` executables. They
Python 3.11 or later and make no network calls. need Python 3.11 or later and make no network calls.
## License ## License
+4
View File
@@ -109,6 +109,10 @@ class DraftResult:
error: str | None error: str | None
# Who drafted, for the PR body; None means Claude Code, which reports a cost. # Who drafted, for the PR body; None means Claude Code, which reports a cost.
drafted_by: str | None = None 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: 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: 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 """Print the run's cost, turns and tokens, whichever the drafter reported, and
$GITHUB_STEP_SUMMARY when the runner sets it.""" append them to $GITHUB_STEP_SUMMARY when the runner sets it."""
lines = [] lines = []
if result.drafted_by is not None:
lines.append(f"- drafted_by: {result.drafted_by}")
if result.cost_usd is not None: if result.cost_usd is not None:
lines.append(f"- total_cost_usd: {result.cost_usd:.2f}") lines.append(f"- total_cost_usd: {result.cost_usd:.2f}")
if result.turns is not None: if result.turns is not None:
lines.append(f"- num_turns: {result.turns}") 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: if not lines:
return return
print("drafter " + ", ".join(l[2:] for l in lines)) 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]: review_only: tuple[str, ...] = ()) -> list[str]:
"""Changed paths the drafter may not touch. A listed document may change or go; a """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 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 = [] bad = []
for p in change.paths: for p in change.paths:
ok = p in listed or (p in change.new and matches_any(p, patterns)) 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): if ok and matches_any(p, review_only):
ok = False ok = False
if ok and p not in change.deleted and not sandbox.is_regular(root, p): if ok and p not in change.deleted and not sandbox.is_regular(root, p):
ok = False ok = False
if not ok: if not ok:
bad.append(p) 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 return bad
@@ -233,6 +244,7 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
except (git.GitError, subprocess.TimeoutExpired, OSError) as err: except (git.GitError, subprocess.TimeoutExpired, OSError) as err:
return Drafted(None, (), EXPORT_NOTE.format(reason=_short_reason(err))) return Drafted(None, (), EXPORT_NOTE.format(reason=_short_reason(err)))
sandbox.remove_symlinks(box) sandbox.remove_symlinks(box)
sandbox.remove_pi_config(box)
listed = frozenset(expand_patterns(inputs.docs, box)) listed = frozenset(expand_patterns(inputs.docs, box))
before = sandbox.snapshot(box) before = sandbox.snapshot(box)
prompt_file = write_system_prompt(box, inputs.doc_guide, env) 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) metadata = git_metadata(cwd)
result = run_drafter(inputs, prompt, box, env, prompt_file, local_model=model, result = run_drafter(inputs, prompt, box, env, prompt_file, local_model=model,
run_as=run_as) run_as=run_as)
# Checked first, and on failure no further git command runs: a hook or a write_step_summary(result, env)
# config change would run on the next one. # 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: if git_metadata(cwd) != metadata:
return Drafted(result, (), GIT_METADATA_NOTE) return Drafted(result, (), GIT_METADATA_NOTE)
write_step_summary(result, env)
if not result.ok: if not result.ok:
return Drafted(result, (), f"drafter failed: {result.error}") return Drafted(result, (), f"drafter failed: {result.error}")
change = sandbox.compare(before, sandbox.snapshot(box)) 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 from __future__ import annotations
import errno
import json import json
import os import os
import pwd import pwd
import shutil import shutil
import socket
import subprocess import subprocess
import tempfile import tempfile
import urllib.error import urllib.error
@@ -20,6 +22,7 @@ from pathlib import Path
from typing import NamedTuple from typing import NamedTuple
from docs_review.draft import DraftResult from docs_review.draft import DraftResult
from docs_review.secrets import redact
KEY_VAR = "LOCAL_MODEL_API_KEY" KEY_VAR = "LOCAL_MODEL_API_KEY"
USER_VAR = "DOCS_REVIEW_DRAFTER_USER" 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" UNREACHABLE_NOTE = "local drafter unavailable: model server unreachable"
NO_MODEL_NOTE = "local drafter unavailable: no model loaded" NO_MODEL_NOTE = "local drafter unavailable: no model loaded"
REJECTED_NOTE = "local drafter: the model server rejected LOCAL_MODEL_API_KEY" 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): class Probe(NamedTuple):
@@ -54,7 +63,7 @@ class Probe(NamedTuple):
class DrafterUserError(RuntimeError): 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): 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 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: 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( request = urllib.request.Request(
server_root(base_url) + LOADED_MODELS_PATH, url, headers={"Authorization": f"Bearer {key}", "Accept": "application/json"})
headers={"Authorization": f"Bearer {key}", "Accept": "application/json"})
try: try:
with urlopen(request, timeout=PROBE_TIMEOUT_S) as response: with urlopen(request, timeout=PROBE_TIMEOUT_S) as response:
data = json.loads(response.read().decode("utf-8")) data = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as err: except urllib.error.HTTPError as err:
if err.code in (401, 403): if err.code in (401, 403):
return Probe(None, REJECTED_NOTE, False) return Probe(None, REJECTED_NOTE, False)
return Probe(None, UNREACHABLE_NOTE, True) return Probe(None, NOT_SERVER_NOTE.format(url=url, reason=f"HTTP {err.code}"),
except (OSError, ValueError): False)
return Probe(None, UNREACHABLE_NOTE, True) 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 models = data.get("data") if isinstance(data, dict) else None
if isinstance(models, list): if not isinstance(models, list):
for item in models: return Probe(None, NOT_SERVER_NOTE.format(url=url, reason="no `data` list"), False)
model = item.get("id") if isinstance(item, dict) else None for item in models:
if isinstance(model, str) and model.strip(): model = item.get("id") if isinstance(item, dict) else None
return Probe(model.strip(), None, True) 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) 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 return probe(base_url, key, urlopen=urlopen).model
def drafter_user(env: Mapping[str, str], *, geteuid: Callable[[], int] = os.geteuid, def drafter_user(env: Mapping[str, str], *, geteuid: Callable[[], int] | None = None,
getpwnam: Callable = pwd.getpwnam) -> tuple[int, int] | None: getpwnam: Callable | None = None) -> tuple[int, int] | None:
"""(uid, gid) to run pi as: the DOCS_REVIEW_DRAFTER_USER account when this process """(uid, gid) to run pi as. Not root: None, run as the current user. Root: the
is root and the variable is set, otherwise None (run as the current user). Raises DOCS_REVIEW_DRAFTER_USER account, and DrafterUserError when it is unset or does not
DrafterUserError when the named account does not exist.""" exist, since pi as root could write anywhere."""
name = (env.get(USER_VAR) or "").strip() geteuid = geteuid or os.geteuid
if not name or geteuid() != 0: getpwnam = getpwnam or pwd.getpwnam
if geteuid() != 0:
return None 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: try:
entry = getpwnam(name) entry = getpwnam(name)
except KeyError: 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 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]: system_prompt_file: Path | None) -> list[str]:
"""The pi command line. The task goes in as an @file, so a long prompt never lands """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.""" 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] "--thinking", THINKING, "--tools", TOOLS, *ISOLATION_FLAGS]
if system_prompt_file is not None: if system_prompt_file is not None:
argv += ["--append-system-prompt", str(system_prompt_file)] 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: 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 "" line = lines[0] if lines else ""
return line if len(line) <= ERROR_MAX else line[:ERROR_MAX] + "..." 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 """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 turn_end is a turn. Tokens: output summed over assistant messages, input as the
decides that. Nothing here raises.""" maximum (each turn's input is the whole conversation so far, so a sum would count
final, turns = None, 0 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(): for line in stdout.splitlines():
try: try:
event = json.loads(line) 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) if (event.get("type") == "message_end" and isinstance(message, dict)
and message.get("role") == "assistant"): and message.get("role") == "assistant"):
final = message 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 = "" text = ""
if final is not None and isinstance(final.get("content"), list): if final is not None and isinstance(final.get("content"), list):
text = "".join(c.get("text", "") for c in final["content"] text = "".join(c.get("text", "") for c in final["content"]
if isinstance(c, dict) and c.get("type") == "text" if isinstance(c, dict) and c.get("type") == "text"
and isinstance(c.get("text"), str)) 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"))) reason = _first_line(str(final.get("errorMessage") or final.get("stopReason")))
return DraftResult(False, None, turns, text, f"pi reported an error: {reason}") error = f"pi reported an error: {reason}"
if returncode != 0: if error is None and returncode != 0:
return DraftResult(False, None, turns, text, f"pi exited with code {returncode}") error = f"pi exited with code {returncode}"
if not text.strip(): if error is None and not text.strip():
return DraftResult(False, None, turns, text, "pi gave no final text") error = "pi gave no final text"
return DraftResult(True, None, turns, text, None) 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: 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, proc = subprocess.run(argv, cwd=cwd, env=child_env, stdin=subprocess.DEVNULL,
capture_output=True, text=True, timeout=timeout, capture_output=True, text=True, timeout=timeout,
check=False, **user) check=False, **user)
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired as err:
return DraftResult(False, None, None, "", "timed out") # 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: except OSError as err:
return DraftResult(False, None, None, "", f"could not start pi: {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: finally:
shutil.rmtree(home, ignore_errors=True) shutil.rmtree(home, ignore_errors=True)
+27
View File
@@ -66,6 +66,33 @@ def remove_symlinks(root: Path) -> tuple[str, ...]:
return tuple(sorted(removed)) 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): class CopyRefused(RuntimeError):
"""A change cannot be copied back safely; the message names the path.""" """A change cannot be copied back safely; the message names the path."""
+6 -5
View File
@@ -4,10 +4,11 @@ in these top-level documents against what is actually in the repository:
{top_level} {top_level}
An enumeration is any list of files, scripts, modules, filename prefixes, outputs or An enumeration is any list of files, scripts, modules, filename prefixes, outputs or
steps, and any stated count. Use Glob or ls to list the files each one describes. Where a list steps, and any stated count. Use Glob or ls to list the files each one describes.
or count no longer matches, correct it: add what is missing, remove what no longer Where a list or count no longer matches, correct it: add what is missing, remove what no
exists, fix the number. A list presented as complete must be complete. If a list is longer exists, fix the number.
deliberately partial, it should say so; when adding every missing item would make it A list presented as complete must be complete. If a list is deliberately partial, it
unwieldy (more than about 15 new entries), add that phrase instead. should say so; when adding every missing item would make it unwieldy (more than about 15
new entries), add that phrase instead.
Then correct anything else in these documents that no longer matches the repository. Then correct anything else in these documents that no longer matches the repository.
+5 -1
View File
@@ -10,7 +10,8 @@ models.json pi would read), task_copy (file receiving the @file task), system_co
(file receiving the --append-system-prompt file), edit (path to append a line to, (file receiving the --append-system-prompt file), edit (path to append a line to,
relative to the working directory or absolute), write (text to append instead), relative to the working directory or absolute), write (text to append instead),
fail (end on an assistant error), exit_code (exit with this code), no_text (end fail (end on an assistant error), exit_code (exit with this code), no_text (end
with an empty assistant message). with an empty assistant message), list_file (file receiving the names at the top of the
working directory).
Stdin must be /dev/null: a real pi waits on an open stdin until EOF. When it is Stdin must be /dev/null: a real pi waits on an open stdin until EOF. When it is
not, this exits 3 without printing anything. not, this exits 3 without printing anything.
@@ -51,6 +52,9 @@ if config.get("argv_file"):
Path(config["argv_file"]).write_text(json.dumps(sys.argv), encoding="utf-8") Path(config["argv_file"]).write_text(json.dumps(sys.argv), encoding="utf-8")
if config.get("cwd_file"): if config.get("cwd_file"):
Path(config["cwd_file"]).write_text(os.getcwd(), encoding="utf-8") Path(config["cwd_file"]).write_text(os.getcwd(), encoding="utf-8")
if config.get("list_file"):
Path(config["list_file"]).write_text("\n".join(sorted(os.listdir("."))),
encoding="utf-8")
if config.get("home_file"): if config.get("home_file"):
Path(config["home_file"]).write_text(os.environ.get("HOME", ""), encoding="utf-8") Path(config["home_file"]).write_text(os.environ.get("HOME", ""), encoding="utf-8")
if config.get("models_copy"): if config.get("models_copy"):
+45 -1
View File
@@ -52,7 +52,7 @@ class LocalPrTests(LocalSetup, test_cli.CliCase):
self.assertIn("Edited by the local drafter.", self.assertIn("Edited by the local drafter.",
git(self.remote, "show", f"{BRANCH}:docs/README.md")) git(self.remote, "show", f"{BRANCH}:docs/README.md"))
argv = json.loads(self.argv_file.read_text()) argv = json.loads(self.argv_file.read_text())
self.assertEqual(argv[argv.index("--model") + 1], "org/model-a") self.assertIn("--model=org/model-a", argv)
self.assertNotIn(KEY, " ".join(argv)) self.assertNotIn(KEY, " ".join(argv))
self.assertIn("Drafted by pi with org/model-a: 2 turns.", self.assertIn("Drafted by pi with org/model-a: 2 turns.",
self.fake.prs[0]["body"].splitlines()[-1]) self.fake.prs[0]["body"].splitlines()[-1])
@@ -92,6 +92,14 @@ class LocalPrTests(LocalSetup, test_cli.CliCase):
self.assertEqual(self.run_pr(self.feature_commit()), 1) self.assertEqual(self.run_pr(self.feature_commit()), 1)
self.assertIn(local.REJECTED_NOTE, self.comment_bodies()[0]) self.assertIn(local.REJECTED_NOTE, self.comment_bodies()[0])
def test_root_without_a_drafter_user_fails_hard(self):
self.pi()
self.env.pop("DOCS_REVIEW_DRAFTER_USER", None)
with up(), mock.patch.object(local.os, "geteuid", return_value=0):
self.assertEqual(self.run_pr(self.feature_commit()), 1)
self.assertIn("DOCS_REVIEW_DRAFTER_USER", self.comment_bodies()[0])
self.assertFalse(self.sentinel.exists())
def test_missing_key_fails_before_probing(self): def test_missing_key_fails_before_probing(self):
self.pi() self.pi()
self.env["LOCAL_MODEL_API_KEY"] = "" self.env["LOCAL_MODEL_API_KEY"] = ""
@@ -100,6 +108,42 @@ class LocalPrTests(LocalSetup, test_cli.CliCase):
probe.assert_not_called() probe.assert_not_called()
self.assertIn("LOCAL_MODEL_API_KEY is not set", self.comment_bodies()[0]) self.assertIn("LOCAL_MODEL_API_KEY is not set", self.comment_bodies()[0])
def test_tokens_and_turns_reach_the_step_summary(self):
summary = Path(self._tmp.name) / "step-summary.md"
self.pi(edit="docs/README.md")
with up():
self.assertEqual(self.run_pr(self.feature_commit(),
GITHUB_STEP_SUMMARY=str(summary)), 0)
text = summary.read_text()
self.assertIn("num_turns: 2", text)
self.assertIn("output_tokens: 40", text)
self.assertIn("max_input_tokens: 100", text)
self.assertNotIn("total_cost_usd", text)
def test_project_pi_config_is_removed_from_the_sandbox(self):
self.write(self.seed, ".pi/settings.json", '{"defaultModel": "other"}\n')
self.write(self.seed, ".pi/extensions/x.ts", "export default () => {}\n")
self.write(self.seed, ".pi.json", "{}\n")
listing = Path(self._tmp.name) / "listing"
self.pi(edit="docs/README.md", list_file=str(listing))
with up():
self.assertEqual(self.run_pr(self.feature_commit()), 0)
names = listing.read_text().split()
self.assertNotIn(".pi", names)
self.assertNotIn(".pi.json", names)
self.assertIn("docs", names)
self.assertEqual(len(self.fake.prs), 1)
self.assertNotIn(".pi/settings.json", git(self.remote, "show", "--stat",
"--format=", BRANCH))
def test_recreating_pi_config_is_refused(self):
self.env["INPUT_DOCS"] = "docs/*.md\n**/*.md"
self.pi(edit=".pi/notes.md")
with up():
self.assertEqual(self.run_pr(self.feature_commit()), 1)
self.assertTrue(any(".pi/notes.md" in b for b in self.comment_bodies()))
self.assertEqual(self.fake.prs, [])
def test_drafter_that_ran_and_failed_is_exit_1(self): def test_drafter_that_ran_and_failed_is_exit_1(self):
self.pi(fail=True) self.pi(fail=True)
with up(): with up():
+78 -5
View File
@@ -1,7 +1,10 @@
import errno
import io import io
import json import json
import os import os
import shutil import shutil
import socket
import ssl
import tempfile import tempfile
import unittest import unittest
import urllib.error import urllib.error
@@ -55,13 +58,16 @@ class ResidentModelTest(unittest.TestCase):
def test_errors_are_none(self): def test_errors_are_none(self):
cases = [ cases = [
(None, urllib.error.URLError("refused")), (None, urllib.error.URLError(ConnectionRefusedError(61, "refused"))),
(None, urllib.error.URLError(socket.gaierror(-2, "Name or service not known"))),
(None, TimeoutError("timed out")), (None, TimeoutError("timed out")),
(None, ConnectionResetError()), (None, ConnectionResetError()),
(None, urllib.error.HTTPError(BASE, 404, "Not Found", {}, None)),
({"data": []}, None), ({"data": []}, None),
({"nope": 1}, None), ({"nope": 1}, None),
(["x"], None), (["x"], None),
({"data": [{"name": "no id"}]}, None), ({"data": [{"name": "no id"}]}, None),
({"data": [{"id": "--api-key=x"}]}, None),
] ]
for body, error in cases: for body, error in cases:
self.assertIsNone(local.resident_model(BASE, KEY, self.assertIsNone(local.resident_model(BASE, KEY,
@@ -73,13 +79,52 @@ class ResidentModelTest(unittest.TestCase):
self.assertIsNone(local.resident_model(BASE, KEY, urlopen=urlopen)) self.assertIsNone(local.resident_model(BASE, KEY, urlopen=urlopen))
def test_probe_notes(self): def test_probe_notes(self):
p = local.probe(BASE, KEY, urlopen=self.opener(error=urllib.error.URLError("x"))) p = local.probe(BASE, KEY, urlopen=self.opener(
error=urllib.error.URLError(ConnectionRefusedError(61, "refused"))))
self.assertEqual((p.model, p.note, p.soft), (None, local.UNREACHABLE_NOTE, True)) self.assertEqual((p.model, p.note, p.soft), (None, local.UNREACHABLE_NOTE, True))
p = local.probe(BASE, KEY, urlopen=self.opener({"data": []})) p = local.probe(BASE, KEY, urlopen=self.opener({"data": []}))
self.assertEqual((p.model, p.note, p.soft), (None, local.NO_MODEL_NOTE, True)) self.assertEqual((p.model, p.note, p.soft), (None, local.NO_MODEL_NOTE, True))
p = local.probe(BASE, KEY, urlopen=self.opener({"data": [{"id": "m"}]})) p = local.probe(BASE, KEY, urlopen=self.opener({"data": [{"id": "m"}]}))
self.assertEqual((p.model, p.note), ("m", None)) self.assertEqual((p.model, p.note), ("m", None))
def test_connection_failures_are_soft(self):
for error in (urllib.error.URLError(ConnectionRefusedError(61, "refused")),
urllib.error.URLError(socket.gaierror(-2, "Name or service not known")),
urllib.error.URLError(TimeoutError("timed out")),
urllib.error.URLError(OSError(errno.EHOSTUNREACH, "no route")),
TimeoutError("timed out"), ConnectionRefusedError()):
p = local.probe(BASE, KEY, urlopen=self.opener(error=error))
self.assertEqual((p.note, p.soft), (local.UNREACHABLE_NOTE, True), error)
def test_something_else_answering_is_a_hard_failure(self):
url = "http://model-host:8888/api/inference/loaded-models"
for body, error in (
(None, urllib.error.HTTPError(BASE, 404, "Not Found", {}, None)),
(None, urllib.error.HTTPError(BASE, 500, "Server Error", {}, None)),
(None, urllib.error.HTTPError(BASE, 302, "Found", {}, None)),
({"nope": 1}, None),
(["x"], None),
(None, urllib.error.URLError(ssl.SSLError(1, "wrong version number"))),
(None, urllib.error.URLError("unknown url type: htp")),
):
p = local.probe(BASE, KEY, urlopen=self.opener(body, error))
self.assertFalse(p.soft, (body, error))
self.assertIsNone(p.model)
self.assertTrue(p.note.startswith(f"{url} does not look like the model server: "),
p.note)
def test_non_json_body_is_a_hard_failure(self):
def urlopen(request, timeout):
return FakeResponse(b"<html>")
p = local.probe(BASE, KEY, urlopen=urlopen)
self.assertFalse(p.soft)
self.assertIn("does not look like the model server", p.note)
def test_model_id_starting_with_a_dash_is_refused(self):
p = local.probe(BASE, KEY, urlopen=self.opener({"data": [{"id": "-x"}]}))
self.assertEqual((p.model, p.soft), (None, False))
self.assertIn("'-x'", p.note)
def test_rejected_key_is_a_hard_failure(self): def test_rejected_key_is_a_hard_failure(self):
err = urllib.error.HTTPError(BASE, 401, "Unauthorized", {}, None) err = urllib.error.HTTPError(BASE, 401, "Unauthorized", {}, None)
p = local.probe(BASE, KEY, urlopen=self.opener(error=err)) p = local.probe(BASE, KEY, urlopen=self.opener(error=err))
@@ -113,6 +158,22 @@ class ParseEventsTest(unittest.TestCase):
self.assertTrue(r.ok, r.error) self.assertTrue(r.ok, r.error)
self.assertEqual((r.text, r.turns, r.cost_usd, r.error), ("All done.", 2, None, None)) self.assertEqual((r.text, r.turns, r.cost_usd, r.error), ("All done.", 2, None, None))
def test_tokens_sum_output_and_take_the_max_input(self):
out = self.stream(self.said("", "toolUse", usage={"input": 900, "output": 40}),
self.said("", "toolUse", usage={"input": 1500, "output": 60}),
self.said("Done.", usage={"input": 1200, "output": 5}))
r = local.parse_pi_events(out, 0)
self.assertEqual((r.input_tokens, r.output_tokens), (1500, 105))
r = local.parse_pi_events(self.stream(self.said("Done.")), 0)
self.assertEqual((r.input_tokens, r.output_tokens), (None, None))
def test_stderr_line_joins_the_error(self):
r = local.parse_pi_events("", 1, stderr="\nboom: key abc-secret-value-1\nmore\n",
env={"LOCAL_MODEL_API_KEY": "abc-secret-value-1"})
self.assertEqual(r.error, "pi exited with code 1; stderr: boom: key ***")
ok = local.parse_pi_events(self.stream(self.said("x")), 0, stderr="warning: noise")
self.assertIsNone(ok.error)
def test_assistant_error_is_not_ok_even_at_exit_zero(self): def test_assistant_error_is_not_ok_even_at_exit_zero(self):
out = self.stream(self.said("", "error", errorMessage="Connection error.\nmore")) out = self.stream(self.said("", "error", errorMessage="Connection error.\nmore"))
r = local.parse_pi_events(out, 0) r = local.parse_pi_events(out, 0)
@@ -132,8 +193,10 @@ class DrafterUserTest(unittest.TestCase):
env = {"DOCS_REVIEW_DRAFTER_USER": "drafter"} env = {"DOCS_REVIEW_DRAFTER_USER": "drafter"}
self.assertIsNone(local.drafter_user(env, geteuid=lambda: 1000)) self.assertIsNone(local.drafter_user(env, geteuid=lambda: 1000))
def test_root_without_a_user_runs_as_root(self): def test_root_without_a_user_raises(self):
self.assertIsNone(local.drafter_user({}, geteuid=lambda: 0)) for env in ({}, {"DOCS_REVIEW_DRAFTER_USER": " "}):
with self.assertRaisesRegex(local.DrafterUserError, "DOCS_REVIEW_DRAFTER_USER"):
local.drafter_user(env, geteuid=lambda: 0)
def test_root_with_a_user(self): def test_root_with_a_user(self):
pw = mock.Mock(pw_uid=1500, pw_gid=1600) pw = mock.Mock(pw_uid=1500, pw_gid=1600)
@@ -195,7 +258,8 @@ class RunLocalTest(unittest.TestCase):
self.assertEqual(argv[1:3], ["-p", "--mode"]) self.assertEqual(argv[1:3], ["-p", "--mode"])
self.assertEqual(argv[argv.index("--mode") + 1], "json") self.assertEqual(argv[argv.index("--mode") + 1], "json")
self.assertEqual(argv[argv.index("--provider") + 1], local.PROVIDER) self.assertEqual(argv[argv.index("--provider") + 1], local.PROVIDER)
self.assertEqual(argv[argv.index("--model") + 1], "org/model-a") self.assertIn("--model=org/model-a", argv)
self.assertNotIn("--model", argv)
self.assertEqual(argv[argv.index("--thinking") + 1], "medium") self.assertEqual(argv[argv.index("--thinking") + 1], "medium")
self.assertEqual(argv[argv.index("--tools") + 1], "read,ls,edit,write") self.assertEqual(argv[argv.index("--tools") + 1], "read,ls,edit,write")
for flag in ("--no-approve", "--no-extensions", "--no-skills", "--no-context-files", for flag in ("--no-approve", "--no-extensions", "--no-skills", "--no-context-files",
@@ -268,6 +332,15 @@ class RunLocalTest(unittest.TestCase):
with mock.patch("docs_review.local.subprocess.run", with mock.patch("docs_review.local.subprocess.run",
side_effect=local.subprocess.TimeoutExpired(["pi"], 30)): side_effect=local.subprocess.TimeoutExpired(["pi"], 30)):
self.assertEqual(self.run_local().error, "timed out") self.assertEqual(self.run_local().error, "timed out")
partial = ParseEventsTest.stream(
ParseEventsTest.said("Halfway.", "toolUse", usage={"input": 70, "output": 9}))
for raw in (partial, partial.encode()):
err = local.subprocess.TimeoutExpired(["pi"], 30, output=raw, stderr=b"stuck\n")
with mock.patch("docs_review.local.subprocess.run", side_effect=err):
r = self.run_local()
self.assertFalse(r.ok)
self.assertEqual((r.turns, r.text, r.output_tokens), (1, "Halfway.", 9))
self.assertEqual(r.error, "timed out; stderr: stuck")
self.env["DOCS_REVIEW_PI_BIN"] = str(self.tmp / "absent") self.env["DOCS_REVIEW_PI_BIN"] = str(self.tmp / "absent")
r = self.run_local() r = self.run_local()
self.assertFalse(r.ok) self.assertFalse(r.ok)