Initial public release: PR documentation review for Gitea
tests / unittest (push) Failing after 13s

Stage 1 flags the living documents a pull request makes stale (no model, nothing sent).
Stage 2, on repositories that opt in with drafter: claude, has Claude Code draft the edits
in a sandboxed copy of the tree and opens them as a pull request into the feature branch.
A monthly pass re-reads the top-level documents against the whole repository.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jaredandClaude Opus 5.5 committed 2026-11-12 14:20:22 -05:00
commit ade847ba5b
38 files changed
+4286

No files matched your search

+189
View File
@@ -0,0 +1,189 @@
"""The drafter contract: prompt, diff payload, Claude argv and result, summary, skip rule."""
from __future__ import annotations
import json
import re
from collections.abc import Iterable
from dataclasses import dataclass
from docs_review.flags import Flag
from docs_review.git import Commit
from docs_review.inputs import matches_any
from docs_review.report import render_sections
DIFF_CAP_BYTES = 200_000
LAST_HEAD = "<!-- docs-review:last-head={sha} -->"
_LAST_HEAD_RE = re.compile(r"<!-- docs-review:last-head=([0-9a-f]{40}) -->")
TOOLS = "Read,Glob,Grep,Edit,Write"
# Each tool scoped to the working directory. Bare names under --allowedTools let Claude
# read and write outside it; these rules confine it under dontAsk (spike S3, 2026-11-12).
ALLOWED_TOOLS = tuple(f"{t}(./**)" for t in TOOLS.split(","))
DISALLOWED_TOOLS = "Bash"
MAX_TURNS = "25"
MAX_BUDGET_USD = "2.00"
PERMISSION_MODE = "dontAsk"
SETTING_SOURCES = "user" # a PR cannot run hooks from its own .claude/settings.json
GUIDE_NOTE = (
"The guide appended to your system prompt, {path}, names each document's reader and "
"purpose; write each edit for that reader."
)
NO_GUIDE_NOTE = "No guide is set; make the smallest edit and match the surrounding document's voice."
def diff_payload(diff_text: str, numstat: str) -> str:
"""The diff itself, or above the cap a file list with per-file line counts."""
if len(diff_text.encode("utf-8")) <= DIFF_CAP_BYTES:
return diff_text
return (
f"The diff is over the {DIFF_CAP_BYTES:,}-byte cap, so it is given as a file list "
"with per-file line counts (added, removed, path). Open files as needed to read "
"what changed.\n\n" + numstat
)
def build_prompt(
template: str, *, mode: str, pr: int | None, flags_json: str, payload: str,
docs: tuple[str, ...], top_level: tuple[str, ...], guide_path: str | None,
) -> str:
"""Fill the template's named fields. Only the template is parsed for braces."""
note = GUIDE_NOTE.format(path=guide_path) if guide_path else NO_GUIDE_NOTE
return template.format_map({
"mode": mode,
"pr": "none" if pr is None else pr,
"flags_json": flags_json,
"payload": payload,
"docs": "\n".join(docs),
"top_level": "\n".join(top_level),
"guide_note": note,
})
def claude_argv(binary: str, model: str, system_prompt_file: str | None) -> list[str]:
"""The Claude Code command line; the prompt goes on stdin. system_prompt_file holds
the repository's CLAUDE.md and the guide, appended to the system prompt."""
argv = [
binary, "-p", "--model", model, "--output-format", "json",
"--max-turns", MAX_TURNS, "--max-budget-usd", MAX_BUDGET_USD,
"--tools", TOOLS, "--allowedTools", *ALLOWED_TOOLS,
"--disallowedTools", DISALLOWED_TOOLS,
"--permission-mode", PERMISSION_MODE, "--no-session-persistence",
"--setting-sources", SETTING_SOURCES,
]
if system_prompt_file:
argv += ["--append-system-prompt-file", system_prompt_file]
return argv
@dataclass(frozen=True)
class DraftResult:
ok: bool
cost_usd: float | None
turns: int | None
text: str
error: str | None
def parse_claude_output(stdout: str, returncode: int) -> DraftResult:
"""Read Claude's JSON result. Missing keys become None; nothing here raises."""
try:
data = json.loads(stdout)
except ValueError:
data = None
if not isinstance(data, dict):
return DraftResult(False, None, None, "", "output was not JSON")
text = data.get("result")
text = text if isinstance(text, str) else ""
cost, turns = data.get("total_cost_usd"), data.get("num_turns")
cost = float(cost) if isinstance(cost, (int, float)) and not isinstance(cost, bool) else None
turns = turns if isinstance(turns, int) and not isinstance(turns, bool) else None
if data.get("is_error"):
return DraftResult(False, cost, turns, text, text or "Claude reported an error")
subtype = data.get("subtype")
if subtype is not None and subtype != "success":
return DraftResult(False, cost, turns, text, f"Claude stopped early: {subtype}")
if returncode != 0:
return DraftResult(False, cost, turns, text, f"exit code {returncode}")
return DraftResult(True, cost, turns, text, None)
@dataclass(frozen=True)
class Summary:
edits: tuple[tuple[str, str], ...]
declined: tuple[tuple[str, str], ...]
_FENCE_RE = re.compile(r"```json[ \t]*\n(.*?)\n[ \t]*```", re.DOTALL)
def _pairs(items: object, a: str, b: str) -> tuple[tuple[str, str], ...] | None:
if not isinstance(items, list):
return None
pairs = []
for item in items:
if not isinstance(item, dict):
return None
pairs.append((str(item.get(a, "")), str(item.get(b, ""))))
return tuple(pairs)
def parse_summary(text: str) -> Summary | None:
"""The last fenced json block that has `edits` and `declined`; None if there is none."""
for block in reversed(_FENCE_RE.findall(text)):
try:
data = json.loads(block)
except ValueError:
continue
if not isinstance(data, dict) or "edits" not in data or "declined" not in data:
continue
edits = _pairs(data["edits"], "path", "why")
declined = _pairs(data["declined"], "flag", "reason")
if edits is not None and declined is not None:
return Summary(edits, declined)
return None
def outside_docs(changed: Iterable[str], docs_patterns: tuple[str, ...]) -> list[str]:
"""Changed paths that match none of the document patterns."""
return [p for p in changed if not matches_any(p, docs_patterns)]
def parse_last_head(body: str) -> str | None:
m = _LAST_HEAD_RE.search(body)
return m.group(1) if m else None
def should_skip(commits: list[Commit], bot_email: str, pr: int) -> bool:
"""True when every new commit is the bot's, or the merge of this PR's docs branch."""
if not commits:
return False
branch = re.compile(rf"docs-review/pr-{pr}(?!\d)")
return all(
c.author_email == bot_email or (c.parents >= 2 and branch.search(c.subject))
for c in commits
)
def render_pr_body(
summary: Summary | None, result: DraftResult, flags: Iterable[Flag],
head_sha: str, changed: list[str],
) -> str:
"""The docs PR description. The first line records the head the draft was made at."""
parts = [LAST_HEAD.format(sha=head_sha)]
if summary is None:
files = "\n".join(f"- `{p}`" for p in changed)
parts.append("### Proposed edits\nThe drafter gave no summary. Files changed:\n\n" + files)
else:
edits = "\n".join(f"- `{p}`: {why}" for p, why in summary.edits) or "None."
parts.append("### Proposed edits\n" + edits)
declined = "\n".join(f"- {f}: {r}" for f, r in summary.declined) or "None."
parts.append("### Flags not acted on\n" + declined)
stage1 = render_sections(flags)
if stage1:
parts.append("### Flags from stage 1\n\n" + "\n\n".join(stage1))
turns = "unknown" if result.turns is None else result.turns
cost = "unknown" if result.cost_usd is None else f"{result.cost_usd:.2f}"
parts.append(f"Drafted by Claude Code: {turns} turns, ${cost} estimated.")
return "\n\n".join(parts) + "\n"