"""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 pathlib import Path 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 PROMPTS = Path(__file__).resolve().parent.parent / "prompts" MODES = ("pr", "monthly") DIFF_CAP_BYTES = 200_000 LAST_HEAD = "" _LAST_HEAD_RE = re.compile(r"") 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." REVIEW_ONLY_NOTE = ( "\nDocuments you may read but not edit:\n\n{paths}\n\n" "If one of them is stale, do not edit it; add an entry to the summary's `declined` " "list, with its path as `flag`, saying what is stale.\n" ) def load_template(mode: str) -> str: """prompts/task.md with this mode's instructions, prompts/mode-.md, in place of its {mode_text} field.""" if mode not in MODES: raise ValueError(f"unknown mode {mode!r}; expected one of {', '.join(MODES)}") task = (PROMPTS / "task.md").read_text(encoding="utf-8") mode_text = (PROMPTS / f"mode-{mode}.md").read_text(encoding="utf-8") return task.replace("{mode_text}", mode_text, 1) 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, review_only: tuple[str, ...] = (), ) -> str: """Fill the template's named fields. Only the template is parsed for braces. `docs` are the documents the drafter may edit; `review_only` the listed documents it may only read, rendered as their own section or, when there are none, as nothing.""" note = GUIDE_NOTE.format(path=guide_path) if guide_path else NO_GUIDE_NOTE read_only = REVIEW_ONLY_NOTE.format(paths="\n".join(review_only)) if review_only else "" 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, "review_only": read_only, }) 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 # 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: """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 if result.drafted_by is not None: parts.append(f"Drafted by {result.drafted_by}: {turns} turns.") else: 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"