Files
docs-review/docs_review/run_pr.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

231 lines
8.9 KiB
Python

"""The `pr` flow: stage 1, then the drafter and delivery of its edits."""
from __future__ import annotations
import json
import sys
import tempfile
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from docs_review import git
from docs_review.changes import changed_names, parse_name_status
from docs_review.draft import (
DraftResult, build_prompt, diff_payload, load_template, parse_last_head,
parse_summary, render_pr_body, should_skip,
)
from docs_review.drafter import draft_in_sandbox
from docs_review.flags import Flag, compute_flags
from docs_review.inputs import Inputs, expand_patterns, split_review_only
from docs_review.report import STAGE1_MARKER, render_clean, render_comment, stage1_json
from docs_review.tree import read_in_tree
CLOSED_BRANCH_NOTE = (
"docs-review/pr-{n} was closed without merging; delete that branch to get new drafts."
)
MERGE_CONFLICT_NOTE = (
"docs branch no longer merges; resolve docs-review/pr-{n} by hand"
)
@dataclass(frozen=True)
class PrArgs:
number: int
base: str
head_ref: str
head_sha: str
def docs_branch(number: int) -> str:
return f"docs-review/pr-{number}"
def find_docs_pr(forge, number: int) -> dict | None:
"""The open docs PR for this number."""
branch = docs_branch(number)
return forge.find_open_pr(branch)
POINTER = "Proposed edits are in #{n}."
def read_texts(paths: tuple[str, ...], cwd: Path) -> dict[str, str]:
"""Each path's text; a symlink or a file outside the tree is left out unread."""
texts = {}
for p in paths:
text = read_in_tree(cwd, p)
if text is None:
print(f"warning: skipping {p}: a symlink or outside the repository",
file=sys.stderr)
else:
texts[p] = text
return texts
def read_guide(inputs: Inputs, cwd: Path) -> tuple[str, str] | None:
if not inputs.doc_guide:
return None
text = read_in_tree(cwd, inputs.doc_guide)
if text is None:
print(f"warning: doc_guide {inputs.doc_guide} is missing, a symlink or outside "
"the repository", file=sys.stderr)
return None
return inputs.doc_guide, text
def post_stage1(forge, number: int, flags, head_sha: str, note: str | None = None,
docs_pr: int | None = None) -> None:
"""Upsert the stage 1 comment; with nothing to say, only rewrite an existing one.
With an open docs PR, the comment keeps pointing at it."""
pointer = "" if docs_pr is None else POINTER.format(n=docs_pr)
body = render_comment(flags, head_sha=head_sha, note=note)
if body is not None:
forge.upsert_comment(number, STAGE1_MARKER,
body + (f"\n{pointer}\n" if pointer else ""))
elif forge.find_comment(number, STAGE1_MARKER):
clean = render_clean(head_sha)
forge.upsert_comment(number, STAGE1_MARKER, f"{clean} {pointer}" if pointer else clean)
def _write_stage1(flags, head_sha: str, env: Mapping[str, str]) -> str:
out = Path(env.get("RUNNER_TEMP") or tempfile.gettempdir()) / "docs-review-stage1.json"
payload = stage1_json(flags, mode="pr", head_sha=head_sha)
out.write_text(json.dumps(payload), encoding="utf-8")
return json.dumps(payload)
def _skip_drafting(docs_pr: dict, bot_email: str, args: PrArgs, cwd: Path) -> bool:
last_head = parse_last_head(docs_pr.get("body") or "")
if last_head is None:
return False
try:
new = git.commits(last_head, args.head_sha, cwd)
except git.GitError:
return False
return should_skip(new, bot_email, args.number)
def _remote_branch_exists(branch: str, cwd: Path) -> bool:
return bool(git.run(["ls-remote", "--heads", "origin", branch], cwd).strip())
def _checkout_docs_branch(resume: bool, args: PrArgs, ident, cwd: Path) -> bool:
"""Check out the docs branch with the feature head merged in; False on conflict."""
branch = docs_branch(args.number)
if not resume:
git.checkout_new(branch, args.head_sha, cwd)
return True
git.fetch(branch, cwd)
git.checkout_new(branch, "FETCH_HEAD", cwd)
try:
git.merge(args.head_sha, ident, cwd)
except git.GitError:
try:
git.run(["rev-parse", "-q", "--verify", "MERGE_HEAD"], cwd)
except git.GitError:
raise # not a conflict: nothing to abort
git.run(["merge", "--abort"], cwd)
return False
return True
def _deliver(forge, inputs, args, docs_pr, ident, flags, result, changed, cwd, env) -> None:
branch = docs_branch(args.number)
git.commit(changed, f"docs({inputs.workstream}): proposed edits (#{args.number})",
ident, cwd)
git.push(branch, cwd, env.get("DOCS_REVIEW_BOT_TOKEN"),
env.get("GITHUB_SERVER_URL"))
body = render_pr_body(parse_summary(result.text), result, flags, args.head_sha, changed)
if docs_pr is not None:
forge.edit_pr(docs_pr["number"], body=body)
number = docs_pr["number"]
else:
number = forge.open_pr(head=branch, base=args.head_ref,
title=f"docs: proposed edits for #{args.number}", body=body)
if forge.find_comment(args.number, STAGE1_MARKER):
forge.upsert_comment(args.number, STAGE1_MARKER,
STAGE1_MARKER + POINTER.format(n=number))
def _no_edits_note(result: DraftResult) -> str:
summary = parse_summary(result.text)
if summary is None or not summary.declined:
return "The drafter proposed no edits."
lines = "\n".join(f"- {f}: {r}" for f, r in summary.declined)
return "The drafter proposed no edits. Flags not acted on:\n\n" + lines
def added_paths(changes) -> frozenset[str]:
"""Paths the PR adds, counting a rename's new path: the only documents a PR is
asked to describe in the guide."""
return frozenset(c.path for c in changes if c.status in ("A", "R"))
def _stage1(inputs: Inputs, args: PrArgs, cwd: Path):
mb = git.merge_base(f"origin/{args.base}", args.head_sha, cwd)
changes = parse_name_status(git.name_status(mb, args.head_sha, cwd))
diff_text = git.diff(mb, args.head_sha, cwd)
added, removed = changed_names(diff_text)
docs = expand_patterns(inputs.docs, cwd)
generated = expand_patterns(inputs.generated, cwd)
flags = compute_flags(changes, added, removed, read_texts(docs, cwd),
read_texts(generated, cwd), inputs.source_dirs,
read_guide(inputs, cwd), repo_files=git.ls_files(cwd),
unguided_scope=added_paths(changes))
payload = diff_payload(diff_text, git.numstat(mb, args.head_sha, cwd))
return flags, payload, docs
def run_pr(inputs: Inputs, forge, env: Mapping[str, str], cwd: Path, args: PrArgs) -> int:
if docs_branch(args.number) == args.head_ref:
print(f"refusing to review {args.head_ref}: it is this PR's own docs branch",
file=sys.stderr)
return 1
ident = forge.identity()
flags, payload, docs = _stage1(inputs, args, cwd)
flags_json = _write_stage1(flags, args.head_sha, env)
if inputs.drafter == "none":
post_stage1(forge, args.number, flags, args.head_sha)
return 0
if env.get("DOCS_REVIEW_STAGE") == "1":
return 0
branch = docs_branch(args.number)
latest = forge.find_pr(branch)
docs_pr = latest if latest is not None and latest["state"] == "open" else None
pr_no = docs_pr["number"] if docs_pr is not None else None
if latest is not None and _skip_drafting(latest, ident[1], args, cwd):
post_stage1(forge, args.number, flags, args.head_sha, docs_pr=pr_no)
return 0
remote = _remote_branch_exists(branch, cwd)
resume = docs_pr is not None or (remote and bool(latest and latest.get("merged")))
if remote and not resume:
post_stage1(forge, args.number, flags, args.head_sha,
CLOSED_BRANCH_NOTE.format(n=args.number))
return 0
if not _checkout_docs_branch(resume, args, ident, cwd):
post_stage1(forge, args.number, flags, args.head_sha,
MERGE_CONFLICT_NOTE.format(n=args.number), docs_pr=pr_no)
return 0
editable, read_only = split_review_only(docs, inputs.review_only)
prompt = build_prompt(
load_template("pr"), mode="pr", pr=args.number,
flags_json=flags_json, payload=payload, docs=editable, review_only=read_only,
top_level=inputs.top_level,
guide_path=inputs.doc_guide,
)
drafted = draft_in_sandbox(inputs, prompt, cwd, env)
if drafted.note is not None:
post_stage1(forge, args.number, flags, args.head_sha, drafted.note, docs_pr=pr_no)
return 0 if drafted.soft else 1
result, changed = drafted.result, list(drafted.changed)
if not changed:
if flags:
post_stage1(forge, args.number, flags, args.head_sha, _no_edits_note(result),
docs_pr=pr_no)
return 0
_deliver(forge, inputs, args, docs_pr, ident, flags, result, changed, cwd, env)
return 0