feat: reusable review workflow
tests / unittest (push) Successful in 19s

Callers use Civilytics/docs-review/.gitea/workflows/review.yml@v1 with secrets: inherit.
Stage 1 on every pull request; for drafter: claude, a 180-second wait and then the sandboxed
drafter; closed pull requests close their docs PR; schedule and dispatch run the monthly
pass. Tested live against Gitea 28.3 (drafter none, a misspelled drafter, claude, close).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-12 15:12:57 -05:00
1 parent ade847ba5b
commit f39409e62c
11 files changed
+466 -26

No files matched your search

+30
View File
@@ -26,6 +26,8 @@ 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)"
@@ -78,6 +80,31 @@ def write_system_prompt(cwd: Path, guide_path: str | None,
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`."""
@@ -129,6 +156,8 @@ class Drafted:
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
@@ -143,6 +172,7 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
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))
+4 -2
View File
@@ -102,8 +102,10 @@ class Gitea:
never trusted."""
login, _ = self.identity()
for pr in self._pages(f"/repos/{self._repo}/pulls?state={state}"):
head_repo = (pr["head"].get("repo") or {}).get("full_name")
if (pr.get("user") or {}).get("login") == login and head_repo == self._repo:
head_repo = (pr["head"].get("repo") or {}).get("full_name") or ""
# Gitea owner and repository names are case-insensitive.
if ((pr.get("user") or {}).get("login") == login
and head_repo.lower() == self._repo.lower()):
yield pr
def find_open_pr_prefix(self, head_prefix: str) -> dict | None:
+30 -7
View File
@@ -43,8 +43,16 @@ def run(args: list[str], cwd: Path, extra_env: Mapping[str, str] | None = None)
def checkout_new(branch: str, rev: str, cwd: Path) -> None:
"""Create or reset branch at rev and switch to it."""
run(["checkout", "-q", "-B", branch, EOO, rev], cwd)
"""Create or reset branch at rev and switch to it.
git before 2.43 reads a revision after --end-of-options in checkout as a pathspec
("Cannot update paths and switch to branch"), and node:22 ships 2.39. So an
option-like branch or rev is refused here instead, and the trailing -- keeps rev a
revision."""
for value in (branch, rev):
if not value or value.startswith("-"):
raise GitError(f"refusing to check out {value!r}")
run(["checkout", "-q", "-B", branch, rev, "--"], cwd)
def merge(rev: str, author: tuple[str, str], cwd: Path) -> None:
@@ -54,6 +62,12 @@ def merge(rev: str, author: tuple[str, str], cwd: Path) -> None:
"-c", "commit.gpgsign=false", "merge", "--no-edit", EOO, rev], cwd)
def fetch(branch: str, cwd: Path) -> None:
"""Fetch one branch from origin into FETCH_HEAD; the branch can never read as an
option."""
run(["fetch", "-q", "origin", EOO, branch], cwd)
def merge_base(a: str, b: str, cwd: Path) -> str:
return run(["merge-base", EOO, a, b], cwd).strip()
@@ -112,17 +126,26 @@ def commit(paths: list[str], message: str, author: tuple[str, str], cwd: Path) -
)
def push(branch: str, cwd: Path, token: str | None) -> None:
def header_key(server: str | None) -> str:
"""The config key for the auth header: scoped to the Gitea server when it is known,
so the header is never sent to any other host."""
if server:
return f"http.{server.rstrip('/')}/.extraHeader"
return "http.extraHeader"
def push(branch: str, cwd: Path, token: str | None, server: str | None = None) -> None:
"""Push branch to origin under an explicit refspec, never forced.
The token travels as an http.extraHeader set through GIT_CONFIG_* variables on this
call only, so it never reaches argv or .git/config. A branch starting with + or -
could force the push or read as an option, so it is refused."""
The token travels as an extraHeader set through GIT_CONFIG_* variables on this call
only, so it never reaches argv or .git/config; with server (GITHUB_SERVER_URL) the
header is scoped to that URL. A branch starting with + or - could force the push or
read as an option, so it is refused."""
if not branch or branch.startswith(("+", "-")):
raise GitError(f"refusing to push branch {branch!r}")
extra = None
if token:
extra = {"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "http.extraHeader",
extra = {"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": header_key(server),
"GIT_CONFIG_VALUE_0": f"Authorization: token {token}"}
ref = f"refs/heads/{branch}"
run(["push", "origin", f"{ref}:{ref}"], cwd, extra_env=extra)
+4 -3
View File
@@ -64,13 +64,13 @@ def post_issue(forge, flags: tuple[Flag, ...], month: str, note: str | None = No
def _checkout(base: str, month: str, reuse: dict | None, ident, cwd: Path) -> str | None:
"""The branch to draft on, or None when a reused branch no longer merges."""
git.run(["fetch", "-q", "origin", base], cwd)
git.fetch(base, cwd)
if reuse is None:
branch = f"{MONTHLY_PREFIX}{month}"
git.checkout_new(branch, f"origin/{base}", cwd)
return branch
branch = reuse["head"]["ref"]
git.run(["fetch", "-q", "origin", branch], cwd)
git.fetch(branch, cwd)
git.checkout_new(branch, "FETCH_HEAD", cwd)
try:
git.merge(f"origin/{base}", ident, cwd)
@@ -92,7 +92,8 @@ def _commit_message(inputs: Inputs, month: str) -> str:
def _deliver(forge, inputs, base, month, branch, reuse, ident, flags, result, changed, cwd,
env):
git.commit(changed, _commit_message(inputs, month), ident, cwd)
git.push(branch, cwd, env.get("DOCS_REVIEW_BOT_TOKEN"))
git.push(branch, cwd, env.get("DOCS_REVIEW_BOT_TOKEN"),
env.get("GITHUB_SERVER_URL"))
head = git.run(["rev-parse", "HEAD"], cwd).strip()
body = render_pr_body(parse_summary(result.text), result, flags, head, changed)
title = f"docs: monthly review {month}"
+3 -2
View File
@@ -117,7 +117,7 @@ def _checkout_docs_branch(resume: bool, args: PrArgs, ident, cwd: Path) -> bool:
if not resume:
git.checkout_new(branch, args.head_sha, cwd)
return True
git.run(["fetch", "-q", "origin", branch], cwd)
git.fetch(branch, cwd)
git.checkout_new(branch, "FETCH_HEAD", cwd)
try:
git.merge(args.head_sha, ident, cwd)
@@ -135,7 +135,8 @@ def _deliver(forge, inputs, args, docs_pr, ident, flags, result, changed, cwd, e
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"))
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)