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

+1
View File
@@ -0,0 +1 @@
"""PR documentation review: stage 1 flags and the stage 2 drafter."""
+7
View File
@@ -0,0 +1,7 @@
import os
import sys
from pathlib import Path
from docs_review.cli import main
sys.exit(main(sys.argv[1:], os.environ, cwd=Path.cwd()))
+73
View File
@@ -0,0 +1,73 @@
"""Parse `git diff --name-status -M` and extract changed names from a unified diff."""
from __future__ import annotations
import posixpath
import re
from dataclasses import dataclass
MIN_NAME_LENGTH = 4
_FILE_HEADER = re.compile(r"^diff --git a/.* b/(.*)$")
_R_ASSIGN = re.compile(r"^\s*([A-Za-z.][\w.]*)\s*(?:<-|=)\s*function\b")
_R_TARGET = re.compile(r"tar_target\(\s*([A-Za-z.][\w.]*)")
_YAML_KEY = re.compile(r"^([A-Za-z_][\w.-]*)\s*:")
@dataclass(frozen=True)
class Change:
status: str # "A", "M", "D" or "R"
path: str
old_path: str | None = None
def parse_name_status(text: str) -> tuple[Change, ...]:
"""Parse name-status output. R becomes R with old_path; C and T count as M."""
changes: list[Change] = []
for line in text.splitlines():
if not line.strip():
continue
fields = line.split("\t")
code = fields[0][:1]
if code == "R" and len(fields) >= 3:
changes.append(Change("R", fields[2], fields[1]))
elif code == "C" and len(fields) >= 3:
changes.append(Change("M", fields[2], None))
elif code in ("A", "M", "D", "T") and len(fields) >= 2:
changes.append(Change("M" if code == "T" else code, fields[1], None))
else:
raise ValueError(f"unrecognized name-status line: {line!r}")
return tuple(changes)
def _names_in_line(path: str, content: str) -> list[str]:
if path.endswith(".R"):
found = []
match = _R_ASSIGN.match(content)
if match:
found.append(match.group(1))
found.extend(_R_TARGET.findall(content))
return found
if posixpath.basename(path) == "config.yml":
match = _YAML_KEY.match(content)
return [match.group(1)] if match else []
return []
def changed_names(diff_text: str) -> tuple[frozenset[str], frozenset[str]]:
"""Names net added and net removed across the diff (a name on both sides cancels)."""
added: set[str] = set()
removed: set[str] = set()
path = ""
for line in diff_text.splitlines():
header = _FILE_HEADER.match(line)
if header:
path = header.group(1)
elif line.startswith(("+++", "---")):
continue
elif line[:1] in ("+", "-"):
target = added if line[0] == "+" else removed
target.update(
n for n in _names_in_line(path, line[1:]) if len(n) >= MIN_NAME_LENGTH
)
return frozenset(added - removed), frozenset(removed - added)
+81
View File
@@ -0,0 +1,81 @@
"""Command line entry: `python3 -m docs_review {pr,closed,monthly}`."""
from __future__ import annotations
import argparse
import sys
from collections.abc import Mapping
from pathlib import Path
from docs_review.forge import ForgeError, Gitea
from docs_review.git import GitError
from docs_review.inputs import parse_inputs
from docs_review.run_monthly import run_monthly, valid_month
from docs_review.run_pr import PrArgs, docs_branch, find_docs_pr, run_pr
CLOSED_COMMENT = (
"Closed because #{n} merged or closed first. "
"The monthly pass picks up anything still needed."
)
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="docs_review")
sub = parser.add_subparsers(dest="command", required=True)
pr = sub.add_parser("pr", help="review one pull request")
pr.add_argument("--number", type=int, required=True)
pr.add_argument("--base", required=True, help="the PR's base branch")
pr.add_argument("--head-ref", required=True, help="the PR's feature branch")
pr.add_argument("--head-sha", required=True)
closed = sub.add_parser("closed", help="close the docs PR of a closed PR")
closed.add_argument("--number", type=int, required=True)
monthly = sub.add_parser("monthly", help="review the whole repository")
monthly.add_argument("--month", required=True, help="YYYY-MM")
monthly.add_argument("--base", default="main", help="the default branch")
return parser
def _build_forge(env: Mapping[str, str]) -> Gitea | None:
server = env.get("GITHUB_SERVER_URL")
repo = env.get("GITHUB_REPOSITORY")
token = env.get("DOCS_REVIEW_BOT_TOKEN")
if not (server and repo and token):
return None
return Gitea(server, repo, token, redact_env=env)
def _closed(forge, number: int) -> int:
pr = find_docs_pr(forge, number)
if pr is not None:
forge.close_pr(pr["number"], CLOSED_COMMENT.format(n=number))
return 0
def main(argv: list[str], env: Mapping[str, str], *, forge=None, cwd: Path) -> int:
try:
args = _parser().parse_args(argv)
except SystemExit as exit_:
return exit_.code if isinstance(exit_.code, int) else 2
forge = forge or _build_forge(env)
if forge is None:
print("GITHUB_SERVER_URL, GITHUB_REPOSITORY and DOCS_REVIEW_BOT_TOKEN are required",
file=sys.stderr)
return 2
try:
if args.command == "closed":
return _closed(forge, args.number)
inputs = parse_inputs(env)
if args.command == "monthly":
if not valid_month(args.month):
raise ValueError(f"--month must be YYYY-MM, got {args.month!r}")
return run_monthly(inputs, forge, env, cwd, args.month, args.base)
return run_pr(
inputs, forge, env, cwd,
PrArgs(args.number, args.base, args.head_ref, args.head_sha),
)
except ValueError as err:
print(f"usage error: {err}", file=sys.stderr)
return 2
except (GitError, ForgeError) as err:
print(f"docs_review failed: {err}", file=sys.stderr)
return 1
+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"
+163
View File
@@ -0,0 +1,163 @@
"""Running the drafter in a sandbox and taking back only the changes it may make."""
from __future__ import annotations
import os
import subprocess
import sys
import tempfile
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path
from docs_review import git, sandbox
from docs_review.draft import DraftResult, claude_argv, parse_claude_output
from docs_review.inputs import Inputs, expand_patterns, matches_any
from docs_review.secrets import secret_values
from docs_review.tree import read_in_tree
DRAFT_TIMEOUT_S = 1500
DRAFTER_ENV = frozenset({
"PATH", "HOME", "LANG", "TMPDIR", "TERM", "CLAUDE_CODE_OAUTH_TOKEN",
"ANTHROPIC_API_KEY", "DISABLE_UPDATES", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
})
REPO_INSTRUCTIONS = "CLAUDE.md"
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
REFUSED_NOTE = "drafter failed: refusing to copy back `{path}` (symlink or outside the repository)"
def drafter_env(env: Mapping[str, str]) -> dict[str, str]:
"""Only what Claude needs; the Gitea bot token and the rest stay behind."""
return {k: v for k, v in env.items() if k in DRAFTER_ENV or k.startswith("LC_")}
def leaks_credential(files: Iterable[str], root: Path, env: Mapping[str, str]) -> bool:
"""True when a drafted file holds the value of a secret-named variable."""
secrets = secret_values(env)
if not secrets:
return False
for rel in files:
text = read_in_tree(root, rel)
if text is not None and any(v in text for v in secrets):
return True
return False
def system_prompt_text(cwd: Path, guide_path: str | None) -> str | None:
"""The repository's CLAUDE.md, then the guide, each under a line naming it.
--setting-sources user keeps the PR's own .claude settings and hooks from loading,
which also stops CLAUDE.md loading; this puts it back as plain text."""
parts = []
instructions = read_in_tree(cwd, REPO_INSTRUCTIONS)
if instructions is not None:
parts.append(f"Contents of the repository's {REPO_INSTRUCTIONS}:\n\n" + instructions)
if guide_path:
guide = read_in_tree(cwd, guide_path)
if guide is not None:
parts.append(f"Contents of the documentation guide, {guide_path}:\n\n" + guide)
else:
print(f"warning: doc_guide {guide_path} is missing, a symlink or outside "
"the repository", file=sys.stderr)
return "\n\n".join(p.rstrip("\n") for p in parts) + "\n" if parts else None
def write_system_prompt(cwd: Path, guide_path: str | None,
env: Mapping[str, str]) -> Path | None:
"""The system prompt file under RUNNER_TEMP (or the system temp directory)."""
text = system_prompt_text(cwd, guide_path)
if text is None:
return None
fd, name = tempfile.mkstemp(prefix="docs-review-system-prompt-", suffix=".md",
dir=env.get("RUNNER_TEMP") or None)
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(text)
return Path(name)
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`."""
if inputs.drafter != "claude":
return DraftResult(False, None, None, "", "local drafter not built yet")
argv = claude_argv(env.get("DOCS_REVIEW_CLAUDE_BIN", "claude"), inputs.model,
str(system_prompt_file) if system_prompt_file else None)
try:
proc = subprocess.run(argv, input=prompt, cwd=cwd, env=drafter_env(env),
capture_output=True, text=True, timeout=DRAFT_TIMEOUT_S,
check=False)
except subprocess.TimeoutExpired:
return DraftResult(False, None, None, "", "timed out")
except OSError as err:
return DraftResult(False, None, None, "", f"could not start Claude: {err}")
return parse_claude_output(proc.stdout, proc.returncode)
def disallowed(change: sandbox.TreeChange, listed: frozenset[str],
patterns: tuple[str, ...], root: Path) -> list[str]:
"""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."""
bad = []
for p in change.paths:
ok = p in listed or (p in change.new and matches_any(p, patterns))
if ok and p not in change.deleted and not sandbox.is_regular(root, p):
ok = False
if not ok:
bad.append(p)
return bad
def _short_reason(err: BaseException) -> str:
"""The first line of an error, cut to EXPORT_REASON_MAX characters."""
if isinstance(err, subprocess.TimeoutExpired):
return f"timed out after {err.timeout:g} s"
lines = str(err).strip().splitlines()
line = lines[0] if lines else type(err).__name__
return line if len(line) <= EXPORT_REASON_MAX else line[:EXPORT_REASON_MAX] + "..."
@dataclass(frozen=True)
class Drafted:
result: DraftResult | None
changed: tuple[str, ...]
note: str | None # why the run failed; None when it succeeded
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 git.run(["status", "--porcelain"], cwd).strip():
return Drafted(None, (), DIRTY_NOTE)
box = prompt_file = None
try:
box = sandbox.make_sandbox(env)
try:
sandbox.export_tree(cwd, box)
except (git.GitError, subprocess.TimeoutExpired, OSError) as err:
return Drafted(None, (), EXPORT_NOTE.format(reason=_short_reason(err)))
sandbox.remove_symlinks(box)
listed = frozenset(expand_patterns(inputs.docs, box))
before = sandbox.snapshot(box)
prompt_file = write_system_prompt(box, inputs.doc_guide, env)
result = run_drafter(inputs, prompt, box, env, prompt_file)
if not result.ok:
return Drafted(result, (), f"drafter failed: {result.error}")
change = sandbox.compare(before, sandbox.snapshot(box))
bad = disallowed(change, listed, inputs.docs, box)
if bad:
names = ", ".join(f"`{p}`" for p in bad)
return Drafted(result, (), f"drafter failed: it changed files outside `docs`: {names}")
if leaks_credential(change.new + change.changed, box, env):
return Drafted(result, (), CREDENTIAL_NOTE)
try:
sandbox.copy_back(change, box, cwd)
except sandbox.CopyRefused as err:
return Drafted(result, (), REFUSED_NOTE.format(path=err))
return Drafted(result, change.paths, None)
finally:
sandbox.remove(box)
if prompt_file is not None:
prompt_file.unlink(missing_ok=True)
+196
View File
@@ -0,0 +1,196 @@
"""The five flag kinds, whole-repository mode and monthly grouping."""
from __future__ import annotations
import posixpath
from collections import Counter, defaultdict
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from docs_review.changes import Change
from docs_review.mentions import Mentions, doc_mentions
BOILERPLATE_MIN_DOCS = 3
@dataclass(frozen=True)
class Flag:
kind: str # touched, uncovered, dead, stale_generated, unguided
doc: str | None
subject: str
detail: str
def _in_source_dirs(path: str, source_dirs: tuple[str, ...]) -> bool:
return any(path.startswith(d.rstrip("/") + "/") for d in source_dirs)
def _unique_basenames(
changes: Iterable[Change], repo_files: Iterable[str] | None = None
) -> frozenset[str]:
"""Basenames carried by exactly one path among the changes and, when given, every
repository file: a basename two files share cannot say which one a doc means."""
paths = {c.path for c in changes} | {c.old_path for c in changes if c.old_path}
paths |= set(repo_files or ())
counts = Counter(posixpath.basename(p) for p in paths)
return frozenset(b for b, n in counts.items() if n == 1)
def _mentions_path(m: Mentions, path: str, unique: frozenset[str]) -> bool:
base = posixpath.basename(path)
return path in m.paths or (base in unique and base in m.basenames)
def _boilerplate_paths(
mentions: Mapping[str, Mentions], changes: tuple[Change, ...], unique: frozenset[str],
) -> frozenset[str]:
"""Modified paths more than half the documents mention, and at least
BOILERPLATE_MIN_DOCS of them: a setup line every chapter repeats says nothing about
which chapter a change to that file makes stale."""
out = set()
for c in changes:
if c.status != "M":
continue
n = sum(_mentions_path(m, c.path, unique) for m in mentions.values())
if n >= BOILERPLATE_MIN_DOCS and n * 2 > len(mentions):
out.add(c.path)
return frozenset(out)
def _path_flags(
doc: str, m: Mentions, changes: tuple[Change, ...], unique: frozenset[str],
doc_changed: bool, boilerplate: frozenset[str] = frozenset(),
) -> list[Flag]:
flags = []
for c in changes:
if c.status == "M" and (doc_changed or c.path in boilerplate):
continue
if c.status == "M" and _mentions_path(m, c.path, unique):
flags.append(Flag("touched", doc, c.path, "changed"))
elif c.status == "D" and _mentions_path(m, c.path, unique):
flags.append(Flag("dead", doc, c.path, "removed"))
elif c.status == "R" and c.old_path and _mentions_path(m, c.old_path, unique):
flags.append(Flag("dead", doc, c.old_path, f"renamed to {c.path}"))
return flags
def _changed_input_flags(
generated_texts: Mapping[str, str], changes: tuple[Change, ...],
unique: frozenset[str], changed_paths: frozenset[str],
) -> list[Flag]:
flags = []
for doc, text in generated_texts.items():
if doc in changed_paths:
continue
m = doc_mentions(text, doc)
for c in changes:
for path in (c.path, c.old_path):
if path and _mentions_path(m, path, unique):
flags.append(Flag("stale_generated", doc, path, f"input changed: {path}"))
break
return flags
def _guided_dirs(m: Mentions, guide_path: str) -> frozenset[str]:
"""Directories the guide describes as a whole: each directory it names, and the
directory of each README.md it names other than its own and the repository's."""
readme_dirs = {
posixpath.dirname(p) for p in m.paths
if posixpath.basename(p) == "README.md" and p != guide_path and posixpath.dirname(p)
}
return m.dirs | frozenset(readme_dirs)
def _unguided_flags(
doc_texts: Mapping[str, str], guide: tuple[str, str] | None,
scope: frozenset[str] | None,
) -> list[Flag]:
if guide is None:
return []
guide_path, guide_text = guide
m = doc_mentions(guide_text, guide_path)
dirs = _guided_dirs(m, guide_path)
return [
Flag("unguided", doc, doc, f"not described in {guide_path}")
for doc in doc_texts
if doc != guide_path and doc not in m.paths
and (scope is None or doc in scope)
and not any(doc.startswith(d + "/") for d in dirs)
]
def _sort_key(f: Flag) -> tuple[str, str, str]:
return (f.kind, f.doc or "", f.subject)
def compute_flags(
changes: tuple[Change, ...],
names_added: frozenset[str],
names_removed: frozenset[str],
doc_texts: Mapping[str, str],
generated_texts: Mapping[str, str],
source_dirs: tuple[str, ...],
guide: tuple[str, str] | None,
*,
repo_files: Iterable[str] | None = None,
unguided_scope: frozenset[str] | None = None,
) -> tuple[Flag, ...]:
"""All flags, sorted by kind, doc, subject. A document the change set edits gets
no touched flag; it still gets dead flags for removed or renamed paths. A modified
path most documents mention (see _boilerplate_paths) raises no touched flag. With
repo_files, a basename matches only when it is unique across the repository. With
unguided_scope, only those documents are checked for unguided; None checks all."""
changes = tuple(changes)
changed_paths = frozenset(c.path for c in changes)
unique = _unique_basenames(changes, repo_files)
changed_names = names_added | names_removed
mentions = {doc: doc_mentions(text, doc) for doc, text in doc_texts.items()}
boilerplate = _boilerplate_paths(mentions, changes, unique)
flags: list[Flag] = []
for doc, m in mentions.items():
doc_changed = doc in changed_paths
flags.extend(_path_flags(doc, m, changes, unique, doc_changed, boilerplate))
if not doc_changed:
flags.extend(
Flag("touched", doc, n, "name changed")
for n in sorted(m.names & changed_names)
)
for c in changes:
if c.status == "A" and _in_source_dirs(c.path, source_dirs):
if not any(_mentions_path(m, c.path, unique) for m in mentions.values()):
flags.append(Flag("uncovered", None, c.path, "new file"))
flags.extend(_changed_input_flags(generated_texts, changes, unique, changed_paths))
flags.extend(_unguided_flags(doc_texts, guide, unguided_scope))
return tuple(sorted(set(flags), key=_sort_key))
def whole_repo_changes(
repo_files: Iterable[str], source_dirs: tuple[str, ...]
) -> tuple[Change, ...]:
"""Treat every repository file as added, so uncovered finds all unlisted sources."""
return tuple(Change("A", p, None) for p in sorted(repo_files))
def _group_key(path: str) -> tuple[str, str]:
directory, base = posixpath.split(path)
head, sep, _ = base.partition("_")
return directory, (head + sep) if sep else base
def group_uncovered(flags: Iterable[Flag]) -> tuple[Flag, ...]:
"""Collapse uncovered files sharing a directory and filename prefix."""
groups: dict[tuple[str, str], list[Flag]] = defaultdict(list)
out: list[Flag] = []
for f in flags:
if f.kind == "uncovered":
groups[_group_key(f.subject)].append(f)
else:
out.append(f)
for (directory, prefix), members in groups.items():
if len(members) == 1:
out.append(Flag("uncovered", None, members[0].subject, "1 file"))
else:
subject = posixpath.join(directory, prefix + "*") if directory else prefix + "*"
out.append(Flag("uncovered", None, subject, f"{len(members)} files"))
return tuple(sorted(out, key=_sort_key))
+166
View File
@@ -0,0 +1,166 @@
"""Gitea REST API v1 client: comments, pull requests, issues."""
import json
import urllib.error
import urllib.request
from collections.abc import Mapping
from docs_review.secrets import redact
PAGE = 50
TIMEOUT = 30
class ForgeError(RuntimeError):
"""A Gitea request failed. Carries method, path and status; never the token."""
class Gitea:
def __init__(self, base_url: str, repo: str, token: str, *,
urlopen=urllib.request.urlopen,
redact_env: Mapping[str, str] | None = None):
self._root = base_url.rstrip("/") + "/api/v1"
self._repo = repo
self._token = token
self._urlopen = urlopen
self._identity: tuple[str, str] | None = None
# The bot's own token is always redacted, whatever redact_env holds.
self._redact_env = {**(redact_env or {}), "DOCS_REVIEW_GITEA_TOKEN": token}
def _redact(self, payload: dict) -> dict:
"""Every string field with secret values replaced; this is the one place text
leaves for Gitea."""
return {k: redact(v, self._redact_env) if isinstance(v, str) else v
for k, v in payload.items()}
def _request(self, method: str, path: str, payload: dict | None = None):
data = (None if payload is None
else json.dumps(self._redact(payload)).encode("utf-8"))
req = urllib.request.Request(
self._root + path,
data=data,
method=method,
headers={
"Authorization": f"token {self._token}",
"Content-Type": "application/json",
"Accept": "application/json",
},
)
try:
with self._urlopen(req, timeout=TIMEOUT) as resp:
raw = resp.read()
except urllib.error.HTTPError as err:
raise ForgeError(f"{method} {path} -> {err.code}") from None
except urllib.error.URLError as err:
raise ForgeError(f"{method} {path} -> {err.reason}") from None
if not raw:
return None
try:
return json.loads(raw)
except ValueError:
raise ForgeError(f"{method} {path} -> response was not JSON") from None
def _pages(self, path: str):
"""Yield every item of a paginated list, stopping at a short page."""
sep = "&" if "?" in path else "?"
page = 1
while True:
items = self._request("GET", f"{path}{sep}limit={PAGE}&page={page}")
yield from items
if len(items) < PAGE:
return
page += 1
def identity(self) -> tuple[str, str]:
if self._identity is None:
user = self._request("GET", "/user")
self._identity = (user["login"], user["email"])
return self._identity
def find_comment(self, issue: int, marker: str) -> dict | None:
"""The newest comment by the bot's login containing marker."""
login, _ = self.identity()
found = None
for c in self._pages(f"/repos/{self._repo}/issues/{issue}/comments"):
if c["user"]["login"] == login and marker in c["body"]:
found = c
return found
def upsert_comment(self, issue: int, marker: str, body: str) -> None:
existing = self.find_comment(issue, marker)
if existing:
self._request("PATCH",
f"/repos/{self._repo}/issues/comments/{existing['id']}",
{"body": body})
else:
self._request("POST", f"/repos/{self._repo}/issues/{issue}/comments",
{"body": body})
def _own_prs(self, state: str):
"""PRs opened by the bot from a branch of this repository. A PR by anyone else,
or from a fork, may carry a docs-review branch name and a forged body; it is
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:
yield pr
def find_open_pr_prefix(self, head_prefix: str) -> dict | None:
for pr in self._own_prs("open"):
if pr["head"]["ref"].startswith(head_prefix):
return pr
return None
def find_open_pr(self, head: str) -> dict | None:
"""The open PR whose head branch is exactly head."""
pr = self.find_pr(head, "open")
return pr
def find_pr(self, head: str, state: str = "all") -> dict | None:
"""The newest PR (highest number) whose head branch is exactly head."""
found = None
for pr in self._own_prs(state):
if pr["head"]["ref"] == head and (found is None or pr["number"] > found["number"]):
found = pr
return found
def open_pr(self, head: str, base: str, title: str, body: str) -> int:
pr = self._request("POST", f"/repos/{self._repo}/pulls",
{"head": head, "base": base, "title": title, "body": body})
return pr["number"]
@staticmethod
def _fields(**kw) -> dict:
return {k: v for k, v in kw.items() if v is not None}
def edit_pr(self, number: int, *, title: str | None = None,
body: str | None = None) -> None:
self._request("PATCH", f"/repos/{self._repo}/pulls/{number}",
self._fields(title=title, body=body))
def close_pr(self, number: int, comment: str) -> None:
self._request("POST", f"/repos/{self._repo}/issues/{number}/comments",
{"body": comment})
self._request("PATCH", f"/repos/{self._repo}/pulls/{number}",
{"state": "closed"})
def find_open_issue(self, marker: str) -> dict | None:
for issue in self._pages(f"/repos/{self._repo}/issues?state=open&type=issues"):
if marker in (issue.get("body") or ""):
return issue
return None
def open_issue(self, title: str, body: str) -> int:
issue = self._request("POST", f"/repos/{self._repo}/issues",
{"title": title, "body": body})
return issue["number"]
def edit_issue(self, number: int, *, title: str | None = None,
body: str | None = None) -> None:
self._request("PATCH", f"/repos/{self._repo}/issues/{number}",
self._fields(title=title, body=body))
def close_issue(self, number: int) -> None:
self._request("PATCH", f"/repos/{self._repo}/issues/{number}",
{"state": "closed"})
+128
View File
@@ -0,0 +1,128 @@
"""Thin subprocess wrappers over git. No operation here can force-push."""
import os
import subprocess
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from docs_review.secrets import scrub_env
# Precedes every revision taken from data, so a value like --output=/x is a revision
# name (and fails) rather than an option.
EOO = "--end-of-options"
# Repository config cannot swap in an external diff program or colour the output.
DIFF_FLAGS = ("--no-ext-diff", "--no-color")
class GitError(RuntimeError):
"""A git command failed; the message carries its stderr."""
@dataclass(frozen=True)
class Commit:
sha: str
author_email: str
parents: int
subject: str
def run(args: list[str], cwd: Path, extra_env: Mapping[str, str] | None = None) -> str:
"""Run git with args in cwd and return stdout; raise GitError with stderr.
git sees the process environment minus every secret-named variable, plus extra_env
for this one call."""
env = {**scrub_env(os.environ), **(extra_env or {})}
proc = subprocess.run(
["git", *args], cwd=cwd, env=env, capture_output=True, text=True, check=False
)
if proc.returncode != 0:
raise GitError(f"git {' '.join(args)} failed: {proc.stderr.strip()}")
return proc.stdout
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)
def merge(rev: str, author: tuple[str, str], cwd: Path) -> None:
"""Merge rev into the current branch without opening an editor."""
name, email = author
run(["-c", f"user.name={name}", "-c", f"user.email={email}",
"-c", "commit.gpgsign=false", "merge", "--no-edit", EOO, rev], cwd)
def merge_base(a: str, b: str, cwd: Path) -> str:
return run(["merge-base", EOO, a, b], cwd).strip()
def diff(a: str, b: str, cwd: Path) -> str:
return run(["diff", *DIFF_FLAGS, EOO, a, b], cwd)
def name_status(a: str, b: str, cwd: Path) -> str:
return run(["diff", *DIFF_FLAGS, "-M", "--name-status", EOO, a, b], cwd)
def numstat(a: str, b: str, cwd: Path) -> str:
return run(["diff", *DIFF_FLAGS, "--numstat", EOO, a, b], cwd)
def changed_worktree_files(cwd: Path) -> list[str]:
"""Paths changed in the working tree, untracked included; renames give the new path."""
out = run(["status", "--porcelain", "-z", "--untracked-files=all"], cwd)
entries = out.split("\0")
paths: list[str] = []
i = 0
while i < len(entries):
entry = entries[i]
i += 1
if len(entry) < 4:
continue
status, path = entry[:2], entry[3:]
paths.append(path)
if "R" in status or "C" in status:
i += 1 # the next field is the original path
return paths
def commits(a: str, b: str, cwd: Path) -> list[Commit]:
"""Commits in a..b, oldest first."""
out = run(["log", "--reverse", "--format=%H%x1f%ae%x1f%P%x1f%s", EOO, f"{a}..{b}"], cwd)
result = []
for line in out.splitlines():
sha, email, parents, subject = line.split("\x1f", 3)
result.append(Commit(sha, email, len(parents.split()), subject))
return result
def ls_files(cwd: Path) -> list[str]:
return [p for p in run(["ls-files"], cwd).splitlines() if p]
def commit(paths: list[str], message: str, author: tuple[str, str], cwd: Path) -> None:
name, email = author
run(["add", "--", *paths], cwd)
run(
["-c", f"user.name={name}", "-c", f"user.email={email}",
"-c", "commit.gpgsign=false", "commit", "-m", message],
cwd,
)
def push(branch: str, cwd: Path, token: str | 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."""
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",
"GIT_CONFIG_VALUE_0": f"Authorization: token {token}"}
ref = f"refs/heads/{branch}"
run(["push", "origin", f"{ref}:{ref}"], cwd, extra_env=extra)
+143
View File
@@ -0,0 +1,143 @@
"""Read the workflow's INPUT_* environment into an Inputs record."""
from __future__ import annotations
import re
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path
DRAFTERS = ("claude", "local", "none")
DEFAULT_MODEL = "claude-sonnet-5-5"
DEFAULT_WORKSTREAM = "docs"
DEFAULT_SOURCE_DIRS = ("R", "scripts")
DEFAULT_TOP_LEVEL = ("README.md",)
@dataclass(frozen=True)
class Inputs:
drafter: str
docs: tuple[str, ...]
generated: tuple[str, ...]
top_level: tuple[str, ...]
source_dirs: tuple[str, ...]
workstream: str
tracking_issue: int | None
doc_guide: str | None
model: str
def normalize_drafter(raw: str | None) -> str:
"""Return claude, local or none; anything else, including missing, is none."""
value = (raw or "").strip().lower()
return value if value in DRAFTERS else "none"
def _lines(raw: str | None) -> tuple[str, ...]:
"""Split a newline-separated input, trimming and dropping blank lines."""
return tuple(line.strip() for line in (raw or "").splitlines() if line.strip())
def _text(env: Mapping[str, str], key: str) -> str:
return (env.get(key) or "").strip()
def parse_inputs(env: Mapping[str, str]) -> Inputs:
"""Build Inputs from env. Raises ValueError when docs is missing or blank."""
docs = _lines(env.get("INPUT_DOCS"))
if not docs:
raise ValueError("input 'docs' is required: list at least one document pattern")
issue_raw = _text(env, "INPUT_TRACKING_ISSUE")
try:
tracking_issue = int(issue_raw) if issue_raw else None
except ValueError:
raise ValueError(f"input 'tracking_issue' must be an integer, got {issue_raw!r}") from None
return Inputs(
drafter=normalize_drafter(env.get("INPUT_DRAFTER")),
docs=docs,
generated=_lines(env.get("INPUT_GENERATED")),
top_level=_lines(env.get("INPUT_TOP_LEVEL")) or DEFAULT_TOP_LEVEL,
source_dirs=_lines(env.get("INPUT_SOURCE_DIRS")) or DEFAULT_SOURCE_DIRS,
workstream=_text(env, "INPUT_WORKSTREAM") or DEFAULT_WORKSTREAM,
tracking_issue=tracking_issue,
doc_guide=_text(env, "INPUT_DOC_GUIDE") or None,
model=_text(env, "INPUT_MODEL") or DEFAULT_MODEL,
)
def _glob_files(pattern: str, repo_root: Path) -> list[str]:
"""Repository-relative POSIX paths of files matching one pattern."""
return [
p.relative_to(repo_root).as_posix()
for p in repo_root.glob(pattern)
if p.is_file()
]
def expand_patterns(patterns: Iterable[str], repo_root: Path) -> tuple[str, ...]:
"""Files matching the patterns: repository-relative, sorted, de-duplicated."""
found: set[str] = set()
for pattern in patterns:
found.update(_glob_files(pattern, repo_root))
return tuple(sorted(found))
def unmatched_patterns(patterns: Iterable[str], repo_root: Path) -> tuple[str, ...]:
"""Patterns that match no file, in the order given."""
return tuple(p for p in patterns if not _glob_files(p, repo_root))
def _class(pattern: str, i: int) -> tuple[str, int] | None:
"""Translate the [...] class starting at pattern[i]; None when it never closes.
The class never matches /, so it stays inside one path segment."""
j = i + 1
negate = j < len(pattern) and pattern[j] == "!"
if negate:
j += 1
start = j
if j < len(pattern) and pattern[j] == "]":
j += 1 # a ] first in the class is literal
while j < len(pattern) and pattern[j] != "]":
j += 1
if j >= len(pattern):
return None
body = pattern[start:j].replace("\\", "\\\\").replace("^", "\\^")
if negate:
return f"[^/{body}]", j + 1
return f"(?!/)[{body}]", j + 1
def _pattern_regex(pattern: str) -> str:
"""A glob pattern as a regex: `*`, `?` and `[...]` stay inside one path segment,
and `**/` matches zero or more whole directories. A `**` not followed by `/` acts
as `*`."""
out: list[str] = []
i, n = 0, len(pattern)
while i < n:
if pattern.startswith("**/", i):
out.append("(?:[^/]+/)*")
i += 3
elif pattern.startswith("**", i):
out.append("[^/]*")
i += 2
elif pattern[i] == "*":
out.append("[^/]*")
i += 1
elif pattern[i] == "?":
out.append("[^/]")
i += 1
elif pattern[i] == "[" and (cls := _class(pattern, i)) is not None:
out.append(cls[0])
i = cls[1]
else:
out.append(re.escape(pattern[i]))
i += 1
return "".join(out)
def matches_any(path: str, patterns: Iterable[str]) -> bool:
"""True when path matches any pattern, segment-aware and consistent with
expand_patterns: wildcards never cross `/`; `**/` matches zero or more directories."""
return any(re.fullmatch(_pattern_regex(p), path) for p in patterns)
+72
View File
@@ -0,0 +1,72 @@
"""Paths and names a document mentions, resolved relative to the document."""
from __future__ import annotations
import posixpath
import re
from dataclasses import dataclass
# Each directory alternative is fixed by its first two characters (./ or ../, else an
# optional dot then a word character), so a run of ../ matches only one way and cannot
# backtrack exponentially. The optional dot keeps .gitea/ and .github/ directories.
_PATH_TOKEN = re.compile(
r"(?<![\w/.-])((?:\.\.?/|\.?[\w-][\w.-]*/)*[\w.-]+"
r"\.(?:R|r|py|sh|qmd|md|Rmd|yml|yaml|toml|sql|mjs|js|json|csv))\b"
)
# A directory is a run of segments ending in a slash, written as the whole of a code span
# or as a link target: bare prose such as "and/or" never counts. At least one segment
# must start with a word character (after an optional dot), so `../` alone is not one.
_DIR_BODY = r"((?:\.\.?/)*(?:\.?[\w-][\w.-]*/)+)"
_DIR_TOKEN = re.compile(rf"`{_DIR_BODY}`|\]\({_DIR_BODY}\)")
_BACKTICK_NAME = re.compile(r"`([A-Za-z.][\w.]{3,})(?:\(\))?`")
_CALL_NAME = re.compile(r"\b([A-Za-z.][\w.]{3,})\(")
@dataclass(frozen=True)
class Mentions:
paths: frozenset[str]
basenames: frozenset[str]
names: frozenset[str]
dirs: frozenset[str] = frozenset()
def _resolve(token: str, doc_dir: str) -> str | None:
"""Normalize a path relative to a directory; None if it leaves the repository."""
resolved = posixpath.normpath(posixpath.join(doc_dir, token))
return None if resolved == ".." or resolved.startswith("../") else resolved
def _resolve_both(token: str, doc_dir: str) -> set[str]:
"""The token as written and resolved against doc_dir, where each stays inside."""
out = set()
for base in ("", doc_dir):
resolved = _resolve(token, base)
if resolved is not None:
out.add(resolved)
return out
def doc_mentions(text: str, doc_path: str) -> Mentions:
"""What the document refers to.
Each path token counts as written (when it stays inside the repository) and as
resolved against the document's own directory. Directory tokens (a trailing slash,
in backticks or a link target) resolve the same way, without the slash; one that
resolves to the repository root is dropped. Names count only in backticks or
followed by an opening parenthesis.
"""
doc_dir = posixpath.dirname(doc_path)
paths: set[str] = set()
for token in _PATH_TOKEN.findall(text):
paths |= _resolve_both(token, doc_dir)
dirs: set[str] = set()
for code, link in _DIR_TOKEN.findall(text):
dirs |= _resolve_both(code or link, doc_dir)
dirs.discard(".")
names = set(_BACKTICK_NAME.findall(text)) | set(_CALL_NAME.findall(text))
return Mentions(
paths=frozenset(paths),
basenames=frozenset(posixpath.basename(p) for p in paths),
names=frozenset(names),
dirs=frozenset(dirs),
)
+71
View File
@@ -0,0 +1,71 @@
"""Stage 1 output: JSON, the PR comment and the monthly issue body."""
from __future__ import annotations
from collections.abc import Iterable
from docs_review.flags import Flag
STAGE1_MARKER = "<!-- docs-review:stage1 -->"
MONTHLY_MARKER = "<!-- docs-review:monthly -->"
_SECTIONS = (
("touched", "Touched",
"These documents mention code or a name this PR changes."),
("dead", "Dead",
"These documents mention a path this PR removes or renames."),
("uncovered", "Uncovered",
"These source files are not mentioned in any document."),
("stale_generated", "Stale generated",
"These generated documents depend on an input that changed."),
("unguided", "Unguided",
"These documents are not described in the documentation guide."),
)
def stage1_json(flags: Iterable[Flag], *, mode: str, head_sha: str) -> dict:
return {
"mode": mode,
"head_sha": head_sha,
"flags": [
{"kind": f.kind, "doc": f.doc, "subject": f.subject, "detail": f.detail}
for f in flags
],
}
def _line(f: Flag) -> str:
if f.doc is None:
return f"- `{f.subject}` ({f.detail})"
return f"- `{f.doc}`: `{f.subject}` ({f.detail})"
def render_sections(flags: Iterable[Flag]) -> list[str]:
flags = tuple(flags)
out: list[str] = []
for kind, title, blurb in _SECTIONS:
members = [f for f in flags if f.kind == kind]
if members:
out.append("\n".join([f"### {title}", blurb, ""] + [_line(f) for f in members]))
return out
def render_comment(
flags: Iterable[Flag], *, head_sha: str, note: str | None = None
) -> str | None:
parts = render_sections(flags)
if not parts and not note:
return None
if note:
parts.append(note)
parts.append(f"Checked at {head_sha}.")
return STAGE1_MARKER + "\n" + "\n\n".join(parts) + "\n"
def render_clean(head_sha: str) -> str:
return STAGE1_MARKER + f"Nothing flagged as of {head_sha}."
def render_issue(flags: Iterable[Flag], *, month: str) -> str:
parts = render_sections(flags) or [f"Nothing flagged as of {month}."]
return MONTHLY_MARKER + "\n" + f"Documents to review for {month}.\n\n" + "\n\n".join(parts) + "\n"
+140
View File
@@ -0,0 +1,140 @@
"""The `monthly` flow: whole-repository stage 1, then an issue or a drafted PR."""
from __future__ import annotations
import json
import re
from collections.abc import Mapping
from pathlib import Path
from docs_review import git
from docs_review.draft import build_prompt, parse_summary, render_pr_body
from docs_review.drafter import draft_in_sandbox
from docs_review.flags import Flag, compute_flags, group_uncovered, whole_repo_changes
from docs_review.inputs import Inputs, expand_patterns
from docs_review.report import MONTHLY_MARKER, render_issue, stage1_json
from docs_review.run_pr import TASK_PROMPT, read_guide, read_texts
MONTHLY_PREFIX = "docs-review/monthly-"
MONTH_PATTERN = re.compile(r"^\d{4}-(0[1-9]|1[0-2])$")
# Whole-repository mode counts every file as added and every input as changed, so only
# these two kinds mean anything.
MONTHLY_KINDS = ("uncovered", "unguided")
NO_DIFF_PAYLOAD = (
"Monthly mode has no diff. Read the repository as it stands, starting from the "
"top-level documents."
)
MOVED_NOTE = "The monthly review moved to PR #{n}."
MERGE_CONFLICT_NOTE = (
"The monthly docs branch `{branch}` no longer merges with `{base}`; "
"resolve it by hand."
)
def valid_month(month: str) -> bool:
return bool(MONTH_PATTERN.match(month))
def _stage1(inputs: Inputs, cwd: Path):
docs = expand_patterns(inputs.docs, cwd)
generated = expand_patterns(inputs.generated, cwd)
repo_files = git.ls_files(cwd)
changes = whole_repo_changes(repo_files, inputs.source_dirs)
flags = compute_flags(changes, frozenset(), frozenset(), read_texts(docs, cwd),
read_texts(generated, cwd), inputs.source_dirs,
read_guide(inputs, cwd), repo_files=repo_files)
kept = [f for f in flags if f.kind in MONTHLY_KINDS]
return group_uncovered(kept), docs
def post_issue(forge, flags: tuple[Flag, ...], month: str, note: str | None = None) -> None:
"""Open or update the one monthly issue; with nothing to say, open nothing."""
existing = forge.find_open_issue(MONTHLY_MARKER)
if not flags and not note and existing is None:
return
body = render_issue(flags, month=month)
if note:
body += "\n" + note + "\n"
title = f"docs: monthly review {month}"
if existing is not None:
forge.edit_issue(existing["number"], title=title, body=body)
else:
forge.open_issue(title, body)
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)
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.checkout_new(branch, "FETCH_HEAD", cwd)
try:
git.merge(f"origin/{base}", 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 None
return branch
def _commit_message(inputs: Inputs, month: str) -> str:
tail = f" (#{inputs.tracking_issue})" if inputs.tracking_issue else ""
return f"docs({inputs.workstream}): monthly review {month}{tail}"
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"))
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}"
if reuse is not None:
number = reuse["number"]
forge.edit_pr(number, title=title, body=body)
else:
number = forge.open_pr(head=branch, base=base, title=title, body=body)
issue = forge.find_open_issue(MONTHLY_MARKER)
if issue is not None:
forge.edit_issue(issue["number"],
body=MONTHLY_MARKER + "\n" + MOVED_NOTE.format(n=number) + "\n")
forge.close_issue(issue["number"])
def run_monthly(inputs: Inputs, forge, env: Mapping[str, str], cwd: Path,
month: str, base: str) -> int:
flags, docs = _stage1(inputs, cwd)
if inputs.drafter == "none":
post_issue(forge, flags, month)
return 0
ident = forge.identity()
reuse = forge.find_open_pr_prefix(MONTHLY_PREFIX)
branch = _checkout(base, month, reuse, ident, cwd)
if branch is None:
post_issue(forge, flags, month,
MERGE_CONFLICT_NOTE.format(branch=reuse["head"]["ref"], base=base))
return 0
flags_json = json.dumps(stage1_json(flags, mode="monthly", head_sha=month))
prompt = build_prompt(
TASK_PROMPT.read_text(encoding="utf-8"), mode="monthly", pr=None,
flags_json=flags_json, payload=NO_DIFF_PAYLOAD, docs=docs,
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_issue(forge, flags, month, drafted.note)
return 1
result, changed = drafted.result, list(drafted.changed)
if not changed:
post_issue(forge, flags, month)
return 0
_deliver(forge, inputs, base, month, branch, reuse, ident, flags, result, changed, cwd,
env)
return 0
+228
View File
@@ -0,0 +1,228 @@
"""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, 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
from docs_review.report import STAGE1_MARKER, render_clean, render_comment, stage1_json
from docs_review.tree import read_in_tree
TASK_PROMPT = Path(__file__).resolve().parent.parent / "prompts" / "task.md"
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.run(["fetch", "-q", "origin", 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"))
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
prompt = build_prompt(
TASK_PROMPT.read_text(encoding="utf-8"), mode="pr", pr=args.number,
flags_json=flags_json, payload=payload, docs=docs, 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 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
+155
View File
@@ -0,0 +1,155 @@
"""The drafter's sandbox: an export of the tracked tree with no .git, compared afterwards.
The drafter never runs in the repository. It edits a copy, and only the changes the
caller allows are copied back, so a write to .git, a hook or any other path cannot
reach the checkout the job commits from.
"""
from __future__ import annotations
import hashlib
import os
import shutil
import subprocess
import tempfile
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from docs_review.git import GitError
from docs_review.secrets import scrub_env
from docs_review.tree import inside
ARCHIVE_TIMEOUT_S = 300
def make_sandbox(env: Mapping[str, str]) -> Path:
"""A fresh empty directory under RUNNER_TEMP, or the system temp directory."""
parent = env.get("RUNNER_TEMP")
if parent:
return Path(tempfile.mkdtemp(prefix="docs-review-sandbox-", dir=parent))
return Path(tempfile.mkdtemp(prefix="docs-review-sandbox-"))
def export_tree(cwd: Path, dest: Path) -> None:
"""`git archive HEAD | tar -x -C dest`: the tracked tree at HEAD, without .git."""
env = scrub_env(os.environ)
archive = subprocess.Popen(["git", "archive", "--format=tar", "HEAD"], cwd=cwd,
env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
tar = subprocess.run(["tar", "-x", "-f", "-", "-C", str(dest)],
stdin=archive.stdout, env=env, capture_output=True,
timeout=ARCHIVE_TIMEOUT_S, check=False)
finally:
archive.stdout.close()
archive_err = archive.stderr.read().decode("utf-8", "replace")
archive.stderr.close()
archive.wait()
if archive.returncode != 0:
raise GitError(f"git archive HEAD failed: {archive_err.strip()}")
if tar.returncode != 0:
raise GitError(f"tar -x failed: {tar.stderr.decode('utf-8', 'replace').strip()}")
def remove_symlinks(root: Path) -> tuple[str, ...]:
"""Delete every symlink under root, so the drafter's Edit and Write cannot follow
one out of the sandbox. Returns the removed paths."""
removed = []
for dirpath, dirnames, filenames in os.walk(root):
base = Path(dirpath)
for name in list(filenames) + list(dirnames):
path = base / name
if path.is_symlink():
path.unlink()
removed.append(path.relative_to(root).as_posix())
dirnames[:] = [d for d in dirnames if (base / d).is_dir()]
return tuple(sorted(removed))
class CopyRefused(RuntimeError):
"""A change cannot be copied back safely; the message names the path."""
def _digest(path: Path) -> str:
"""A content hash; a symlink hashes its target text and is marked as a link."""
if path.is_symlink():
return "link:" + os.readlink(path)
h = hashlib.sha256()
with path.open("rb") as fh:
for chunk in iter(lambda: fh.read(1 << 16), b""):
h.update(chunk)
return "file:" + h.hexdigest()
def snapshot(root: Path) -> dict[str, str]:
"""Every file (and symlink) under root, as repository-relative POSIX path -> hash."""
out: dict[str, str] = {}
for dirpath, dirnames, filenames in os.walk(root):
base = Path(dirpath)
names = list(filenames) + [d for d in dirnames if (base / d).is_symlink()]
for name in names:
path = base / name
out[path.relative_to(root).as_posix()] = _digest(path)
return out
@dataclass(frozen=True)
class TreeChange:
new: tuple[str, ...]
changed: tuple[str, ...]
deleted: tuple[str, ...]
@property
def paths(self) -> tuple[str, ...]:
return tuple(sorted(self.new + self.changed + self.deleted))
def compare(before: Mapping[str, str], after: Mapping[str, str]) -> TreeChange:
return TreeChange(
new=tuple(sorted(set(after) - set(before))),
changed=tuple(sorted(p for p in set(after) & set(before) if after[p] != before[p])),
deleted=tuple(sorted(set(before) - set(after))),
)
def is_regular(sandbox: Path, rel: str) -> bool:
path = sandbox / rel
return path.is_file() and not path.is_symlink()
def _safe_target(cwd: Path, rel: str) -> Path:
"""cwd/rel, refusing .git, a symlink at or above the destination, or a destination
that resolves outside cwd."""
parts = Path(rel).parts
if not parts or ".git" in parts or ".." in parts or Path(rel).is_absolute():
raise CopyRefused(rel)
current = cwd
for part in parts:
current = current / part
if current.is_symlink():
raise CopyRefused(rel)
target = cwd / rel
if not inside(cwd, target):
raise CopyRefused(rel)
return target
def copy_back(change: TreeChange, sandbox: Path, cwd: Path) -> None:
"""Apply the sandbox's new, changed and deleted files to cwd. Every source and
target is checked before any is written, so a refusal leaves cwd untouched."""
for rel in change.new + change.changed:
if not is_regular(sandbox, rel):
raise CopyRefused(rel)
writes = [(sandbox / rel, _safe_target(cwd, rel)) for rel in change.new + change.changed]
deletes = [_safe_target(cwd, rel) for rel in change.deleted]
for source, target in writes:
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source, target)
for target in deletes:
if target.exists():
target.unlink()
def remove(path: Path | None) -> None:
if path is not None:
shutil.rmtree(path, ignore_errors=True)
+50
View File
@@ -0,0 +1,50 @@
"""Which environment variables hold secrets, and keeping their values out of text."""
from __future__ import annotations
import re
from collections.abc import Mapping
SECRET_NAME_PARTS = ("TOKEN", "KEY", "SECRET", "CREDENTIAL", "AUTHORIZATION")
# PASS and AUTH are words inside ordinary names (COMPASS, AUTHOR), so they count only at
# an underscore boundary or in a fixed spelling. ASKPASS names a credential helper.
_BOUNDED_PARTS = re.compile(
r"(?:^|_)PASS|PASSWORD|PASSWD|ASKPASS|(?:^|_)AUTH(?:_|$)|OAUTH"
)
# Names that match a part but never hold a secret: git's per-process config (the
# runner passes safe.directory this way) and the ssh agent's socket path.
NOT_SECRET_PREFIXES = ("GIT_CONFIG_",)
NOT_SECRET_NAMES = frozenset({"SSH_AUTH_SOCK"})
MIN_SECRET_LENGTH = 8
REDACTED = "***"
def is_secret_name(name: str) -> bool:
"""True when a variable name holds a secret part, ignoring case: any of
SECRET_NAME_PARTS anywhere, or PASS or AUTH at a token boundary. GIT_CONFIG_*
and SSH_AUTH_SOCK are never secret."""
upper = name.upper()
if upper in NOT_SECRET_NAMES or upper.startswith(NOT_SECRET_PREFIXES):
return False
return any(part in upper for part in SECRET_NAME_PARTS) or bool(
_BOUNDED_PARTS.search(upper))
def secret_values(env: Mapping[str, str]) -> list[str]:
"""Values of secret-named variables at least MIN_SECRET_LENGTH long, longest first
so a value containing another is replaced whole."""
values = {v for k, v in env.items()
if is_secret_name(k) and isinstance(v, str) and len(v) >= MIN_SECRET_LENGTH}
return sorted(values, key=len, reverse=True)
def redact(text: str, env: Mapping[str, str]) -> str:
"""text with every secret value from env replaced by ***."""
for value in secret_values(env):
text = text.replace(value, REDACTED)
return text
def scrub_env(env: Mapping[str, str]) -> dict[str, str]:
"""A copy of env without any secret-named variable."""
return {k: v for k, v in env.items() if not is_secret_name(k)}
+22
View File
@@ -0,0 +1,22 @@
"""Reading repository files without following a symlink out of the tree."""
from __future__ import annotations
import os
from pathlib import Path
def inside(root: Path, path: Path) -> bool:
"""True when path's real location is root's real location or below it."""
real_root = os.path.realpath(root)
real = os.path.realpath(path)
return os.path.commonpath([real_root, real]) == real_root
def read_in_tree(root: Path, rel: str) -> str | None:
"""The text of root/rel, or None when it is a symlink, not a regular file, or
resolves outside root (a symlinked parent directory included)."""
path = root / rel
if path.is_symlink() or not path.is_file() or not inside(root, path):
return None
return path.read_text(encoding="utf-8", errors="replace")