Compare commits

...
2 Commits
Author SHA1 Message Date
jaredandClaude Opus 5.5 9771f638b9 feat: reusable review workflow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:36:55 -05:00
jaredandClaude Opus 5.5 a1f061ca6c fix: credential check, step summary, fetch hardening, case-insensitive repo match
- drafter: claude with neither CLAUDE_CODE_OAUTH_TOKEN nor ANTHROPIC_API_KEY set posts
  the stage 1 flags with the note 'drafter: claude but no Claude credential is set' and
  fails, without starting Claude.
- total_cost_usd and num_turns are printed and appended to GITHUB_STEP_SUMMARY.
- git.fetch puts --end-of-options before the branch; run_pr and run_monthly use it.
- The bot's own PRs match head.repo.full_name case-insensitively.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 14:35:42 -05:00
10 changed files with 345 additions and 6 deletions

No files matched your search

+233
View File
@@ -0,0 +1,233 @@
# The reusable docs-review workflow. A repository calls it from its own workflow with
# `uses: Civilytics/docs-review/.gitea/workflows/review.yml@v1`; README.md has the
# caller and the inputs.
#
# Secrets reach only the steps that need them. The bot token is in the clone step and
# the two steps that run the tool. The Claude credentials are in the drafting step only,
# and that step runs only when `drafter` normalizes to `claude`. Every `if:` reads the
# normalized drafter, never the raw input.
name: docs-review
on:
workflow_call:
inputs:
drafter:
description: "claude, local or none; anything else behaves as none"
type: string
required: false
default: none
docs:
description: "Newline-separated paths or globs of the living documents"
type: string
required: true
generated:
description: "Newline-separated paths of documents that are rebuilt, never hand-edited"
type: string
required: false
default: ""
top_level:
description: "The subset of docs the monthly pass re-reads in full"
type: string
required: false
default: README.md
source_dirs:
description: "Newline-separated directories whose new files count toward uncovered"
type: string
required: false
default: "R\nscripts"
workstream:
description: "Scope in draft commit messages, docs(<workstream>): ..."
type: string
required: false
default: docs
tracking_issue:
description: "Issue number the monthly pass's commits cite"
type: string
required: false
default: ""
doc_guide:
description: "Path to the document naming each listed document's reader and purpose"
type: string
required: false
default: ""
model:
description: "Model for drafter: claude"
type: string
required: false
default: claude-sonnet-5-5
tool_ref:
description: "Branch or tag of docs-review to run; keep it equal to the @ref in uses:"
type: string
required: false
default: v1
secrets:
DOCS_REVIEW_BOT_TOKEN:
required: false
CLAUDE_CODE_OAUTH_TOKEN:
required: false
ANTHROPIC_API_KEY:
required: false
defaults:
run:
shell: bash
jobs:
review:
runs-on: ubuntu-latest
# node:22 carries python3 (3.11) and git, and npm for the Claude Code install.
container: node:22
# The drafter's own timeout is 25 minutes; the debounce adds 3.
timeout-minutes: 40
env:
TOOL_REPO: Civilytics/docs-review
TOOL_REF: ${{ inputs.tool_ref }}
EVENT: ${{ github.event_name }}
ACTION: ${{ github.event.action }}
PR: ${{ github.event.pull_request.number }}
BASE: ${{ github.event.pull_request.base.ref }}
HEAD_REF: ${{ github.event.pull_request.head.ref }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
INPUT_DRAFTER: ${{ inputs.drafter }}
INPUT_DOCS: ${{ inputs.docs }}
INPUT_GENERATED: ${{ inputs.generated }}
INPUT_TOP_LEVEL: ${{ inputs.top_level }}
INPUT_SOURCE_DIRS: ${{ inputs.source_dirs }}
INPUT_WORKSTREAM: ${{ inputs.workstream }}
INPUT_TRACKING_ISSUE: ${{ inputs.tracking_issue }}
INPUT_DOC_GUIDE: ${{ inputs.doc_guide }}
INPUT_MODEL: ${{ inputs.model }}
# The calling repository's files are untrusted. Every python3 call takes -P, so
# Python imports nothing from the working directory and a docs_review/ or os.py in
# a pull request cannot replace the tool.
steps:
- name: Versions
env:
PROBE_WORKFLOW_REF: ${{ github.workflow_ref }}
PROBE_JOB_WORKFLOW_SHA: ${{ github.job_workflow_sha }}
PROBE_JOB_WORKFLOW_REF: ${{ github.job_workflow_ref }}
run: |
python3 --version
git --version
node --version
echo "probe workflow_ref=[$PROBE_WORKFLOW_REF]"
echo "probe job_workflow_sha=[$PROBE_JOB_WORKFLOW_SHA]"
echo "probe job_workflow_ref=[$PROBE_JOB_WORKFLOW_REF]"
echo "probe RUNNER_TEMP=[${RUNNER_TEMP:-}]"
env | grep -E '^GITHUB_' | grep -viE 'TOKEN' | sort | sed 's/^/probe /'
- name: Fetch docs-review
run: |
set -eu
tool="$RUNNER_TEMP/docs-review"
git clone -q --depth 1 --branch "$TOOL_REF" -- \
"$GITHUB_SERVER_URL/$TOOL_REPO.git" "$tool"
echo "docs-review $TOOL_REF at $(git -C "$tool" rev-parse --short HEAD)"
echo "PYTHONPATH=$tool" >> "$GITHUB_ENV"
- name: Normalize the drafter
id: drafter
run: |
set -eu
drafter="$(python3 -P -c 'import os; from docs_review.inputs import normalize_drafter; print(normalize_drafter(os.environ.get("INPUT_DRAFTER")))')"
echo "drafter: ${INPUT_DRAFTER:-<unset>} -> $drafter"
echo "drafter=$drafter" >> "$GITHUB_OUTPUT"
# Full history, so merge bases and the docs branch's ancestry resolve. The token
# travels as an http.extraHeader in this command's environment, so it is never
# written to .git/config or a remote URL.
- name: Clone the calling repository
if: github.event_name != 'pull_request' || github.event.action != 'closed'
env:
DOCS_REVIEW_BOT_TOKEN: ${{ secrets.DOCS_REVIEW_BOT_TOKEN }}
run: |
set -eu
if [ -z "$DOCS_REVIEW_BOT_TOKEN" ]; then
echo "::error::the DOCS_REVIEW_BOT_TOKEN secret is not set"
exit 1
fi
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader \
GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN"
src="$(mktemp -d)"
git clone -q -- "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" "$src"
cd "$src"
if [ "$EVENT" = "pull_request" ]; then
git fetch -q origin "refs/pull/$PR/head"
git fetch -q origin "+refs/heads/$BASE:refs/remotes/origin/$BASE"
git checkout -q --detach "$HEAD_SHA"
fi
git log --oneline -1
cd - >/dev/null
cp -a "$src/." . && rm -rf "$src"
- name: Close the docs PR of a closed pull request
if: github.event_name == 'pull_request' && github.event.action == 'closed'
env:
DOCS_REVIEW_BOT_TOKEN: ${{ secrets.DOCS_REVIEW_BOT_TOKEN }}
run: python3 -P -m docs_review closed --number "$PR"
# Stage 1 runs on every PR event. With drafter none it is the whole run and posts
# the comment; otherwise it only checks that the flags compute, and the drafting
# step after the debounce posts.
- name: Stage 1
if: >-
(github.event_name == 'pull_request' && github.event.action != 'closed')
|| ((github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')
&& steps.drafter.outputs.drafter == 'none')
env:
DOCS_REVIEW_BOT_TOKEN: ${{ secrets.DOCS_REVIEW_BOT_TOKEN }}
DOCS_REVIEW_STAGE: "1"
run: |
set -eu
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader \
GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN"
if [ "$EVENT" = "pull_request" ]; then
python3 -P -m docs_review pr --number "$PR" --base "$BASE" \
--head-ref "$HEAD_REF" --head-sha "$HEAD_SHA"
else
base="$(git rev-parse --abbrev-ref origin/HEAD)"
python3 -P -m docs_review monthly --month "$(date -u +%Y-%m)" --base "${base#origin/}"
fi
# A re-push inside this wait cancels the run (the caller's concurrency group)
# before anything is spent.
- name: Debounce
if: >-
github.event_name == 'pull_request' && github.event.action != 'closed'
&& steps.drafter.outputs.drafter != 'none'
run: sleep 180
# `local` runs here too, without the Claude credentials and without the install.
- name: Draft
if: >-
steps.drafter.outputs.drafter != 'none'
&& (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
|| (github.event_name == 'pull_request' && github.event.action != 'closed'))
env:
DRAFTER: ${{ steps.drafter.outputs.drafter }}
DOCS_REVIEW_BOT_TOKEN: ${{ secrets.DOCS_REVIEW_BOT_TOKEN }}
CLAUDE_CODE_OAUTH_TOKEN: ${{ steps.drafter.outputs.drafter == 'claude' && secrets.CLAUDE_CODE_OAUTH_TOKEN || '' }}
ANTHROPIC_API_KEY: ${{ steps.drafter.outputs.drafter == 'claude' && secrets.ANTHROPIC_API_KEY || '' }}
CLAUDE_CODE_VERSION: 2.1.322
DISABLE_UPDATES: "1"
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1"
run: |
set -eu
# A fresh HOME, so no settings, credentials or history from the image reach
# Claude Code.
export HOME="$(mktemp -d "$RUNNER_TEMP/home.XXXXXX")"
# With no credential the tool posts the flags with a note and fails, so the
# install would be wasted.
if [ "$DRAFTER" = "claude" ] && [ -n "$CLAUDE_CODE_OAUTH_TOKEN$ANTHROPIC_API_KEY" ]; then
npm install -g --no-fund --no-audit "@anthropic-ai/claude-code@$CLAUDE_CODE_VERSION"
claude --version
fi
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader \
GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN"
if [ "$EVENT" = "pull_request" ]; then
python3 -P -m docs_review pr --number "$PR" --base "$BASE" \
--head-ref "$HEAD_REF" --head-sha "$HEAD_SHA"
else
base="$(git rev-parse --abbrev-ref origin/HEAD)"
python3 -P -m docs_review monthly --month "$(date -u +%Y-%m)" --base "${base#origin/}"
fi
+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" DIRTY_NOTE = "working tree not clean before drafting"
EXPORT_NOTE = "drafter failed: could not export the tree for drafting: {reason}" EXPORT_NOTE = "drafter failed: could not export the tree for drafting: {reason}"
EXPORT_REASON_MAX = 200 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)" 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) 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], def run_drafter(inputs: Inputs, prompt: str, cwd: Path, env: Mapping[str, str],
system_prompt_file: Path | None) -> DraftResult: system_prompt_file: Path | None) -> DraftResult:
"""Run the configured drafter in cwd. Task 12 adds `local`.""" """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, def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
env: Mapping[str, str]) -> Drafted: env: Mapping[str, str]) -> Drafted:
"""Run the drafter on an export of HEAD and copy its allowed changes into cwd.""" """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(): if git.run(["status", "--porcelain"], cwd).strip():
return Drafted(None, (), DIRTY_NOTE) return Drafted(None, (), DIRTY_NOTE)
box = prompt_file = None box = prompt_file = None
@@ -143,6 +172,7 @@ def draft_in_sandbox(inputs: Inputs, prompt: str, cwd: Path,
before = sandbox.snapshot(box) before = sandbox.snapshot(box)
prompt_file = write_system_prompt(box, inputs.doc_guide, env) prompt_file = write_system_prompt(box, inputs.doc_guide, env)
result = run_drafter(inputs, prompt, box, env, prompt_file) result = run_drafter(inputs, prompt, box, env, prompt_file)
write_step_summary(result, env)
if not result.ok: if not result.ok:
return Drafted(result, (), f"drafter failed: {result.error}") return Drafted(result, (), f"drafter failed: {result.error}")
change = sandbox.compare(before, sandbox.snapshot(box)) change = sandbox.compare(before, sandbox.snapshot(box))
+4 -2
View File
@@ -102,8 +102,10 @@ class Gitea:
never trusted.""" never trusted."""
login, _ = self.identity() login, _ = self.identity()
for pr in self._pages(f"/repos/{self._repo}/pulls?state={state}"): for pr in self._pages(f"/repos/{self._repo}/pulls?state={state}"):
head_repo = (pr["head"].get("repo") or {}).get("full_name") head_repo = (pr["head"].get("repo") or {}).get("full_name") or ""
if (pr.get("user") or {}).get("login") == login and head_repo == self._repo: # 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 yield pr
def find_open_pr_prefix(self, head_prefix: str) -> dict | None: def find_open_pr_prefix(self, head_prefix: str) -> dict | None:
+6
View File
@@ -54,6 +54,12 @@ def merge(rev: str, author: tuple[str, str], cwd: Path) -> None:
"-c", "commit.gpgsign=false", "merge", "--no-edit", EOO, rev], cwd) "-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: def merge_base(a: str, b: str, cwd: Path) -> str:
return run(["merge-base", EOO, a, b], cwd).strip() return run(["merge-base", EOO, a, b], cwd).strip()
+2 -2
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: 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.""" """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: if reuse is None:
branch = f"{MONTHLY_PREFIX}{month}" branch = f"{MONTHLY_PREFIX}{month}"
git.checkout_new(branch, f"origin/{base}", cwd) git.checkout_new(branch, f"origin/{base}", cwd)
return branch return branch
branch = reuse["head"]["ref"] branch = reuse["head"]["ref"]
git.run(["fetch", "-q", "origin", branch], cwd) git.fetch(branch, cwd)
git.checkout_new(branch, "FETCH_HEAD", cwd) git.checkout_new(branch, "FETCH_HEAD", cwd)
try: try:
git.merge(f"origin/{base}", ident, cwd) git.merge(f"origin/{base}", ident, cwd)
+1 -1
View File
@@ -117,7 +117,7 @@ def _checkout_docs_branch(resume: bool, args: PrArgs, ident, cwd: Path) -> bool:
if not resume: if not resume:
git.checkout_new(branch, args.head_sha, cwd) git.checkout_new(branch, args.head_sha, cwd)
return True return True
git.run(["fetch", "-q", "origin", branch], cwd) git.fetch(branch, cwd)
git.checkout_new(branch, "FETCH_HEAD", cwd) git.checkout_new(branch, "FETCH_HEAD", cwd)
try: try:
git.merge(args.head_sha, ident, cwd) git.merge(args.head_sha, ident, cwd)
+42
View File
@@ -54,6 +54,7 @@ class CliCase(unittest.TestCase):
"DOCS_REVIEW_CLAUDE_BIN": str(self.fake_claude), "DOCS_REVIEW_CLAUDE_BIN": str(self.fake_claude),
"DOCS_REVIEW_BOT_TOKEN": "bot-token-value-123456", "DOCS_REVIEW_BOT_TOKEN": "bot-token-value-123456",
"RUNNER_TEMP": str(tmp), "RUNNER_TEMP": str(tmp),
"ANTHROPIC_API_KEY": "test-api-key-value-123456",
} }
def claude(self, **config): def claude(self, **config):
@@ -221,6 +222,47 @@ class ClaudeDrafterTests(CliCase):
self.assertEqual(len(self.comment_bodies()), 1) self.assertEqual(len(self.comment_bodies()), 1)
class CredentialAndSummaryTests(CliCase):
def setUp(self):
super().setUp()
self.claude(edit="docs/README.md")
def test_missing_credential_posts_stage1_note_and_fails(self):
sha = self.feature_commit()
env = {k: v for k, v in self.env.items()
if k not in ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_API_KEY")}
self.env = env
self.assertEqual(self.run_pr(sha, CLAUDE_CODE_OAUTH_TOKEN="", ANTHROPIC_API_KEY=""), 1)
bodies = self.comment_bodies()
self.assertEqual(len(bodies), 1)
self.assertIn("drafter: claude but no Claude credential is set", bodies[0])
self.assertIn("Touched", bodies[0])
self.assertFalse(self.sentinel.exists())
self.assertEqual(self.fake.prs, [])
def test_oauth_token_alone_is_enough(self):
sha = self.feature_commit()
self.env.pop("ANTHROPIC_API_KEY")
self.assertEqual(self.run_pr(sha, CLAUDE_CODE_OAUTH_TOKEN="oauth-token-value-1"), 0)
self.assertEqual(len(self.fake.prs), 1)
def test_cost_and_turns_reach_the_step_summary(self):
summary = Path(self.env["RUNNER_TEMP"]) / "step-summary.md"
summary.write_text("earlier step\n", encoding="utf-8")
sha = self.feature_commit()
self.assertEqual(self.run_pr(sha, GITHUB_STEP_SUMMARY=str(summary)), 0)
text = summary.read_text(encoding="utf-8")
self.assertTrue(text.startswith("earlier step\n"))
self.assertIn("total_cost_usd: 0.12", text)
self.assertIn("num_turns: 3", text)
def test_no_summary_file_without_the_variable(self):
sha = self.feature_commit()
self.env.pop("GITHUB_STEP_SUMMARY", None)
self.assertEqual(self.run_pr(sha), 0)
self.assertFalse((Path(self.env["RUNNER_TEMP"]) / "step-summary.md").exists())
class DocsPrLifecycleTests(CliCase): class DocsPrLifecycleTests(CliCase):
def setUp(self): def setUp(self):
super().setUp() super().setUp()
+2 -1
View File
@@ -22,7 +22,8 @@ class ExportFailureTest(unittest.TestCase):
tmp = Path(self._tmp.name) tmp = Path(self._tmp.name)
self.repo = make_repo(tmp / "repo") self.repo = make_repo(tmp / "repo")
(tmp / "runner").mkdir() (tmp / "runner").mkdir()
self.env = {"RUNNER_TEMP": str(tmp / "runner"), "PATH": "/usr/bin:/bin"} self.env = {"RUNNER_TEMP": str(tmp / "runner"), "PATH": "/usr/bin:/bin",
"ANTHROPIC_API_KEY": "test-api-key-value-123456"}
def draft_with(self, err): def draft_with(self, err):
made = [] made = []
+7
View File
@@ -174,6 +174,13 @@ class TestPrsAndIssues(unittest.TestCase):
self.assertIsNone(g.find_open_pr("docs-review/pr-12")) self.assertIsNone(g.find_open_pr("docs-review/pr-12"))
self.assertIsNone(g.find_open_pr_prefix("docs-review/")) self.assertIsNone(g.find_open_pr_prefix("docs-review/"))
def test_head_repo_matches_ignoring_case(self):
routes = {("GET", BASE + "/api/v1/user"): USER,
("GET", API + "/pulls?state=all&limit=50&page=1"):
[pr(5, "docs-review/pr-12", repo="O/R")]}
g, _ = client(routes)
self.assertEqual(g.find_pr("docs-review/pr-12")["number"], 5)
def test_open_pr_and_edit(self): def test_open_pr_and_edit(self):
g, f = client({ g, f = client({
("POST", API + "/pulls"): {"number": 12}, ("POST", API + "/pulls"): {"number": 12},
+18
View File
@@ -136,6 +136,24 @@ class TestGitHardening(unittest.TestCase):
git.run(["status"], self.repo) git.run(["status"], self.repo)
self.assertNotIn("GIT_CONFIG_COUNT", calls[-1][1]) self.assertNotIn("GIT_CONFIG_COUNT", calls[-1][1])
def test_fetch_ends_options_before_the_branch(self):
git.run(["push", "-q", "origin", "main"], self.repo)
calls = self._record()
git.fetch("main", self.repo)
argv, _ = calls[-1]
self.assertEqual(argv[-2:], [git.EOO, "main"])
self.assertEqual(git.run(["rev-parse", "FETCH_HEAD"], self.repo).strip(),
git.run(["rev-parse", "main"], self.repo).strip())
out = Path(self._tmp.name) / "x"
with self.assertRaises(git.GitError):
git.fetch(f"--upload-pack=touch {out}", self.repo)
self.assertFalse(out.exists())
def test_flows_fetch_only_through_the_helper(self):
from docs_review import run_monthly, run_pr
for module in (run_pr, run_monthly):
self.assertNotIn('["fetch"', inspect.getsource(module))
def test_push_without_token_adds_no_header(self): def test_push_without_token_adds_no_header(self):
calls = self._record() calls = self._record()
git.push("main", self.repo, None) git.push("main", self.repo, None)