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
7 changed files with 45 additions and 146 deletions

No files matched your search

+15 -13
View File
@@ -55,9 +55,6 @@ on:
type: string type: string
required: false required: false
default: claude-sonnet-5-5 default: claude-sonnet-5-5
# Gitea 28.3 does not tell a called workflow its own ref (github.workflow_ref and
# job_workflow_sha are empty, and GITHUB_WORKFLOW_SHA is the caller's commit), so
# the caller names the tool version twice.
tool_ref: tool_ref:
description: "Branch or tag of docs-review to run; keep it equal to the @ref in uses:" description: "Branch or tag of docs-review to run; keep it equal to the @ref in uses:"
type: string type: string
@@ -105,10 +102,19 @@ jobs:
# a pull request cannot replace the tool. # a pull request cannot replace the tool.
steps: steps:
- name: Versions - 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: | run: |
python3 --version python3 --version
git --version git --version
node --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 - name: Fetch docs-review
run: | run: |
@@ -128,8 +134,8 @@ jobs:
echo "drafter=$drafter" >> "$GITHUB_OUTPUT" echo "drafter=$drafter" >> "$GITHUB_OUTPUT"
# Full history, so merge bases and the docs branch's ancestry resolve. The token # Full history, so merge bases and the docs branch's ancestry resolve. The token
# travels as an http.<server>/.extraHeader in this command's environment, so it is # travels as an http.extraHeader in this command's environment, so it is never
# sent only to the Gitea server and never written to .git/config or a remote URL. # written to .git/config or a remote URL.
- name: Clone the calling repository - name: Clone the calling repository
if: github.event_name != 'pull_request' || github.event.action != 'closed' if: github.event_name != 'pull_request' || github.event.action != 'closed'
env: env:
@@ -140,14 +146,10 @@ jobs:
echo "::error::the DOCS_REVIEW_BOT_TOKEN secret is not set" echo "::error::the DOCS_REVIEW_BOT_TOKEN secret is not set"
exit 1 exit 1
fi fi
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="http.${GITHUB_SERVER_URL}/.extraHeader" \ export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader \
GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN" GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN"
src="$(mktemp -d)" src="$(mktemp -d)"
if ! git clone -q -- "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" "$src"; then git clone -q -- "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git" "$src"
echo "::error::the bot token could not clone $GITHUB_REPOSITORY; it needs the" \
"write:repository scope and write access to the repository"
exit 1
fi
cd "$src" cd "$src"
if [ "$EVENT" = "pull_request" ]; then if [ "$EVENT" = "pull_request" ]; then
git fetch -q origin "refs/pull/$PR/head" git fetch -q origin "refs/pull/$PR/head"
@@ -177,7 +179,7 @@ jobs:
DOCS_REVIEW_STAGE: "1" DOCS_REVIEW_STAGE: "1"
run: | run: |
set -eu set -eu
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="http.${GITHUB_SERVER_URL}/.extraHeader" \ export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader \
GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN" GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN"
if [ "$EVENT" = "pull_request" ]; then if [ "$EVENT" = "pull_request" ]; then
python3 -P -m docs_review pr --number "$PR" --base "$BASE" \ python3 -P -m docs_review pr --number "$PR" --base "$BASE" \
@@ -220,7 +222,7 @@ jobs:
npm install -g --no-fund --no-audit "@anthropic-ai/claude-code@$CLAUDE_CODE_VERSION" npm install -g --no-fund --no-audit "@anthropic-ai/claude-code@$CLAUDE_CODE_VERSION"
claude --version claude --version
fi fi
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="http.${GITHUB_SERVER_URL}/.extraHeader" \ export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader \
GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN" GIT_CONFIG_VALUE_0="Authorization: token $DOCS_REVIEW_BOT_TOKEN"
if [ "$EVENT" = "pull_request" ]; then if [ "$EVENT" = "pull_request" ]; then
python3 -P -m docs_review pr --number "$PR" --base "$BASE" \ python3 -P -m docs_review pr --number "$PR" --base "$BASE" \
+11 -56
View File
@@ -5,6 +5,12 @@ the documents the change makes stale. If the repository opts in, it also has Cla
Code draft the edits. It is a Python package with no dependencies outside the standard Code draft the edits. It is a Python package with no dependencies outside the standard
library. library.
## Status
The Python package and its tests are published here. The reusable Gitea Actions
workflow is not yet published, so the install snippet below is provisional and may
change.
## What it does ## What it does
Stage 1 compares the pull request's changes with the documents you list. It uses no model Stage 1 compares the pull request's changes with the documents you list. It uses no model
@@ -34,11 +40,6 @@ uncovered and unguided flags for the whole repository in one issue. With
- It never merges anything. - It never merges anything.
- It posts nothing when nothing is flagged. - It posts nothing when nothing is flagged.
For a pull request from a branch of the same repository, Gitea runs the caller workflow
from the pull request's head, so anyone who can push a branch can change the caller's
inputs. The safeguards in this README bound what the pull request's content can do, not
what an edited caller workflow file can do.
## What is sent to Anthropic ## What is sent to Anthropic
Nothing is sent unless the repository sets `drafter: claude`. With it, the drafter Nothing is sent unless the repository sets `drafter: claude`. With it, the drafter
@@ -54,73 +55,27 @@ committed, and everything posted to Gitea has credential values replaced with `*
## Install ## Install
Add a workflow to the repository you want reviewed, at `.gitea/workflows/docs-review.yml`: Install instructions will be added with the reusable workflow. Until then, the package
can be run by hand: `python3 -m docs_review pr|closed|monthly --help`.
```yaml
name: docs-review
on:
pull_request:
branches: [main]
types: [opened, synchronize, reopened, closed]
schedule:
- cron: "0 9 1 * *" # the monthly pass, on the first of the month
workflow_dispatch:
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
docs:
uses: Civilytics/docs-review/.gitea/workflows/review.yml@v1
with:
tool_ref: v1
drafter: none
docs: |
README.md
docs/*.md
doc_guide: docs/README.md
secrets: inherit
```
- `closed` in the pull request types lets the workflow close a docs pull request whose
feature pull request merged or closed first.
- The `concurrency` block cancels a run when the pull request is pushed again. With
`drafter: claude` the workflow waits three minutes between stage 1 and drafting, so a
quick re-push cancels a run before it has spent anything.
- `tool_ref` must name the same version as the `@` in `uses:`. Gitea does not tell a
called workflow which ref it was called at, so the workflow fetches the tool's code at
`tool_ref`.
- A `workflow_dispatch` run is the monthly pass for the current month.
The job runs in the `node:22` image. It clones the repository with the bot token, so
it needs no checkout action, and it installs Claude Code
(`@anthropic-ai/claude-code`, a pinned version) only when `drafter` is `claude` and a
Claude credential is set. With `drafter: claude` and no credential, it posts the stage 1
comment with a note saying so and fails. The drafter's cost and turn count are printed
in the log and appended to `$GITHUB_STEP_SUMMARY`.
The package can also be run by hand: `python3 -m docs_review pr|closed|monthly --help`.
## Inputs ## Inputs
| Input | Default | Meaning | | Input | Default | Meaning |
|---|---|---| |---|---|---|
| `drafter` | `none` | `none` flags only. `claude` also drafts edits. `local` is accepted but not yet built: it fails the job with "local drafter not built yet". Any other value, including a misspelling, behaves as `none`. | | `drafter` | `none` | `none` flags only. `claude` also drafts edits. `local` is accepted but not yet built. |
| `docs` | required | Newline-separated patterns for the living documents. | | `docs` | required | Newline-separated patterns for the living documents. |
| `generated` | none | Patterns for generated files. | | `generated` | none | Patterns for generated files. |
| `top_level` | `README.md` | The subset of `docs` the monthly pass re-reads in full. | | `top_level` | `README.md` | The subset of `docs` the monthly pass re-reads in full. |
| `source_dirs` | `R` and `scripts` | Newline-separated directories whose files count as source. | | `source_dirs` | `R scripts` | Directories whose files count as source. |
| `workstream` | `docs` | Scope in draft commit messages, as `docs(<workstream>): ...`. | | `workstream` | `docs` | Scope in draft commit messages, as `docs(<workstream>): ...`. |
| `tracking_issue` | none | Issue number the monthly pass's commit messages cite. | | `tracking_issue` | none | Issue number the monthly pass's commit messages cite. |
| `doc_guide` | none | Path to the document that says who reads each listed document and what it is for. The drafter writes for that reader. | | `doc_guide` | none | Path to the document that says who reads each listed document and what it is for. The drafter writes for that reader. |
| `model` | `claude-sonnet-5-5` | Model used when `drafter` is `claude`. | | `model` | `claude-sonnet-5-5` | Model used when `drafter` is `claude`. |
| `tool_ref` | `v1` | The docs-review branch or tag to run; the same as the `@` in `uses:`. |
## Secrets ## Secrets
- `DOCS_REVIEW_BOT_TOKEN` is required. It is a token for a Gitea bot account with - `DOCS_REVIEW_BOT_TOKEN` is required. It is a token for a Gitea bot account with
write access to the repository and the token scopes `write:repository`, repository write, issue write and user read permissions.
`write:issue` and `read:user`. An organization secret serves every repository in the
organization.
- `CLAUDE_CODE_OAUTH_TOKEN` or `ANTHROPIC_API_KEY` is needed only for - `CLAUDE_CODE_OAUTH_TOKEN` or `ANTHROPIC_API_KEY` is needed only for
`drafter: claude`. `drafter: claude`.
+7 -24
View File
@@ -43,16 +43,8 @@ def run(args: list[str], cwd: Path, extra_env: Mapping[str, str] | None = None)
def checkout_new(branch: str, rev: str, cwd: Path) -> None: def checkout_new(branch: str, rev: str, cwd: Path) -> None:
"""Create or reset branch at rev and switch to it. """Create or reset branch at rev and switch to it."""
run(["checkout", "-q", "-B", branch, EOO, rev], cwd)
git before 2.43 reads a revision after --end-of-options in checkout as a pathspec
("Cannot update paths and switch to branch"), and node:22 ships 2.39. So an
option-like branch or rev is refused here instead, and the trailing -- keeps rev a
revision."""
for value in (branch, rev):
if not value or value.startswith("-"):
raise GitError(f"refusing to check out {value!r}")
run(["checkout", "-q", "-B", branch, rev, "--"], cwd)
def merge(rev: str, author: tuple[str, str], cwd: Path) -> None: def merge(rev: str, author: tuple[str, str], cwd: Path) -> None:
@@ -126,26 +118,17 @@ def commit(paths: list[str], message: str, author: tuple[str, str], cwd: Path) -
) )
def header_key(server: str | None) -> str: def push(branch: str, cwd: Path, token: str | None) -> None:
"""The config key for the auth header: scoped to the Gitea server when it is known,
so the header is never sent to any other host."""
if server:
return f"http.{server.rstrip('/')}/.extraHeader"
return "http.extraHeader"
def push(branch: str, cwd: Path, token: str | None, server: str | None = None) -> None:
"""Push branch to origin under an explicit refspec, never forced. """Push branch to origin under an explicit refspec, never forced.
The token travels as an extraHeader set through GIT_CONFIG_* variables on this call The token travels as an http.extraHeader set through GIT_CONFIG_* variables on this
only, so it never reaches argv or .git/config; with server (GITHUB_SERVER_URL) the call only, so it never reaches argv or .git/config. A branch starting with + or -
header is scoped to that URL. A branch starting with + or - could force the push or could force the push or read as an option, so it is refused."""
read as an option, so it is refused."""
if not branch or branch.startswith(("+", "-")): if not branch or branch.startswith(("+", "-")):
raise GitError(f"refusing to push branch {branch!r}") raise GitError(f"refusing to push branch {branch!r}")
extra = None extra = None
if token: if token:
extra = {"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": header_key(server), extra = {"GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "http.extraHeader",
"GIT_CONFIG_VALUE_0": f"Authorization: token {token}"} "GIT_CONFIG_VALUE_0": f"Authorization: token {token}"}
ref = f"refs/heads/{branch}" ref = f"refs/heads/{branch}"
run(["push", "origin", f"{ref}:{ref}"], cwd, extra_env=extra) run(["push", "origin", f"{ref}:{ref}"], cwd, extra_env=extra)
+1 -2
View File
@@ -92,8 +92,7 @@ def _commit_message(inputs: Inputs, month: str) -> str:
def _deliver(forge, inputs, base, month, branch, reuse, ident, flags, result, changed, cwd, def _deliver(forge, inputs, base, month, branch, reuse, ident, flags, result, changed, cwd,
env): env):
git.commit(changed, _commit_message(inputs, month), ident, cwd) git.commit(changed, _commit_message(inputs, month), ident, cwd)
git.push(branch, cwd, env.get("DOCS_REVIEW_BOT_TOKEN"), git.push(branch, cwd, env.get("DOCS_REVIEW_BOT_TOKEN"))
env.get("GITHUB_SERVER_URL"))
head = git.run(["rev-parse", "HEAD"], cwd).strip() head = git.run(["rev-parse", "HEAD"], cwd).strip()
body = render_pr_body(parse_summary(result.text), result, flags, head, changed) body = render_pr_body(parse_summary(result.text), result, flags, head, changed)
title = f"docs: monthly review {month}" title = f"docs: monthly review {month}"
+1 -2
View File
@@ -135,8 +135,7 @@ def _deliver(forge, inputs, args, docs_pr, ident, flags, result, changed, cwd, e
branch = docs_branch(args.number) branch = docs_branch(args.number)
git.commit(changed, f"docs({inputs.workstream}): proposed edits (#{args.number})", git.commit(changed, f"docs({inputs.workstream}): proposed edits (#{args.number})",
ident, cwd) ident, cwd)
git.push(branch, cwd, env.get("DOCS_REVIEW_BOT_TOKEN"), git.push(branch, cwd, env.get("DOCS_REVIEW_BOT_TOKEN"))
env.get("GITHUB_SERVER_URL"))
body = render_pr_body(parse_summary(result.text), result, flags, args.head_sha, changed) body = render_pr_body(parse_summary(result.text), result, flags, args.head_sha, changed)
if docs_pr is not None: if docs_pr is not None:
forge.edit_pr(docs_pr["number"], body=body) forge.edit_pr(docs_pr["number"], body=body)
+6 -23
View File
@@ -4,7 +4,6 @@ import shutil
import subprocess import subprocess
import tempfile import tempfile
import unittest import unittest
from unittest import mock
from pathlib import Path from pathlib import Path
from docs_review.cli import main from docs_review.cli import main
@@ -170,28 +169,6 @@ class ClaudeDrafterTests(CliCase):
self.fake.email) self.fake.email)
self.assertEqual(self.comment_bodies(), []) self.assertEqual(self.comment_bodies(), [])
def test_resume_fetches_with_end_of_options_and_scoped_push(self):
self.assertEqual(self.run_pr(self.feature_commit()), 0)
calls = []
real = subprocess.run
def record(argv, **kw):
calls.append((list(argv), kw.get("env") or {}))
return real(argv, **kw)
server = "https://gitea.example.org"
sha = self.feature_commit()
with mock.patch("docs_review.git.subprocess.run", side_effect=record):
self.assertEqual(self.run_pr(sha, GITHUB_SERVER_URL=server), 0)
# The harness's own `git fetch -q origin` (run_pr's setup) names no branch.
fetches = [a for a, _ in calls if a[:2] == ["git", "fetch"] and a[-1] != "origin"]
self.assertTrue(fetches)
for argv in fetches:
self.assertEqual(argv[-2:], ["--end-of-options", BRANCH])
pushes = [e for a, e in calls if a[:2] == ["git", "push"]]
self.assertEqual(len(pushes), 1)
self.assertEqual(pushes[0]["GIT_CONFIG_KEY_0"], f"http.{server}/.extraHeader")
def test_rerun_appends_and_keeps_hand_edit(self): def test_rerun_appends_and_keeps_hand_edit(self):
self.assertEqual(self.run_pr(self.feature_commit()), 0) self.assertEqual(self.run_pr(self.feature_commit()), 0)
git(self.seed, "fetch", "-q", "origin", BRANCH) git(self.seed, "fetch", "-q", "origin", BRANCH)
@@ -279,6 +256,12 @@ class CredentialAndSummaryTests(CliCase):
self.assertIn("total_cost_usd: 0.12", text) self.assertIn("total_cost_usd: 0.12", text)
self.assertIn("num_turns: 3", 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):
+4 -26
View File
@@ -49,20 +49,6 @@ class TestGit(unittest.TestCase):
call() call()
self.assertFalse(out.exists()) self.assertFalse(out.exists())
def test_checkout_new_creates_branch_at_rev(self):
git.checkout_new("docs-review/pr-3", "HEAD~1", self.repo)
self.assertEqual(git.run(["rev-parse", "--abbrev-ref", "HEAD"], self.repo).strip(),
"docs-review/pr-3")
self.assertEqual(git.run(["rev-parse", "HEAD"], self.repo).strip(),
git.run(["rev-parse", "main~1"], self.repo).strip())
def test_checkout_new_refuses_option_like_values(self):
out = Path(self._tmp.name) / "x"
for branch, rev in (("b", f"--output={out}"), ("-b", "HEAD"), ("b", "")):
with self.assertRaises(git.GitError):
git.checkout_new(branch, rev, self.repo)
self.assertFalse(out.exists())
def test_merge_base_and_ls_files(self): def test_merge_base_and_ls_files(self):
head = git.run(["rev-parse", "HEAD"], self.repo).strip() head = git.run(["rev-parse", "HEAD"], self.repo).strip()
self.assertEqual(git.merge_base("HEAD", "HEAD~1", self.repo), self.assertEqual(git.merge_base("HEAD", "HEAD~1", self.repo),
@@ -163,18 +149,10 @@ class TestGitHardening(unittest.TestCase):
git.fetch(f"--upload-pack=touch {out}", self.repo) git.fetch(f"--upload-pack=touch {out}", self.repo)
self.assertFalse(out.exists()) self.assertFalse(out.exists())
def test_push_scopes_header_to_the_server(self): def test_flows_fetch_only_through_the_helper(self):
calls = self._record() from docs_review import run_monthly, run_pr
git.run(["checkout", "-q", "-b", "docs-review/pr-4"], self.repo) for module in (run_pr, run_monthly):
git.push("docs-review/pr-4", self.repo, self.TOKEN, "https://gitea.example.org/") self.assertNotIn('["fetch"', inspect.getsource(module))
env = calls[-1][1]
self.assertEqual(env["GIT_CONFIG_KEY_0"], "http.https://gitea.example.org/.extraHeader")
self.assertEqual(env["GIT_CONFIG_VALUE_0"], f"Authorization: token {self.TOKEN}")
def test_header_key_falls_back_to_unscoped(self):
self.assertEqual(git.header_key(None), "http.extraHeader")
self.assertEqual(git.header_key(""), "http.extraHeader")
self.assertEqual(git.header_key("https://h.example"), "http.https://h.example/.extraHeader")
def test_push_without_token_adds_no_header(self): def test_push_without_token_adds_no_header(self):
calls = self._record() calls = self._record()