An open source, non-profit web search engine
Run Claude on GitHub Actions to plan and implement labelled issues
Daoud Clarkec21eb2e1590a
diff --git a/.github/claude/implement-issue.md b/.github/claude/implement-issue.mdnew file mode 100644index 0000000..94afaa9--- /dev/null+++ b/.github/claude/implement-issue.md@@ -0,0 +1,85 @@+# Implement the next part of an issue++You are Claude Code running in GitHub Actions on a fresh checkout of `main`, with the+project installed and a test database running. Your job is to produce **one** pull+request: the next unbuilt part of one issue, verified green before you open it.++`ISSUE_NUMBER` is in the prompt; `$N` below means that number.++## 1. Stop if work is already in flight++```+gh pr list --state open --json headRefName --jq '.[].headRefName' | grep "^claude/issue-$N-"+```++If that matches, a part of this issue is still in review. Print what you found and stop+without changing anything — parts are merged one at a time.++## 2. Decide what to build++Read `AGENTS.md` and `gh issue view $N --comments` first.++- **If `docs/plans/issue-$N-*.md` exists**, take the **first** `## PR k:` heading that is+ not marked `(Done)`. Build exactly that section — not the next one, not a bit of the+ next one. Note whether it is the last unfinished section in the file.+- **Otherwise** implement the whole issue in this one pull request. If it cannot be done+ in about 500 added lines, do not start: write a plan file instead, following sections 2+ and 3 of `.github/claude/plan-issue.md`, and stop there. The next run implements its+ first section.++## 3. Build it++Branch off `main`: `git checkout -b claude/issue-$N-pr-<k>`, where `<k>` is the section+number, or `1` when there is no plan.++Write the code the way the surrounding code is written, and follow `AGENTS.md`. Add tests+under `test/` alongside the behaviour they cover.++## 4. Both gates must pass before you open a pull request++```+make check+uv run pytest+```++`DATABASE_URL` and `DJANGO_SETTINGS_MODULE` are already set for you. Iterate until both+are green. If something is genuinely beyond this change to fix, say exactly what fails+and why in the pull request body — never describe a run as green when it is not.++## 5. Check the size budget++```+git diff --numstat origin/main...HEAD+```++Sum the added lines, ignoring `uv.lock`, `poetry.lock`, `devdata/`, `front-end/` build+output and `docs/plans/`. If the total is over 500, cut the change back to the part that+stands on its own, and — when there is a plan — add a follow-up section to it for the+remainder rather than silently dropping the work.++## 6. Update the plan in the same commit++- Not the last unfinished section: append ` (Done)` to that section's heading, so it+ reads `## PR k: <title> (Done)`. Change nothing else in the plan.+- The last unfinished section: `git rm` the whole plan file. The issue is finished.+- No plan at all: nothing to update.++## 7. Open the pull request++```+git commit -m "<section title>"+git push -u origin claude/issue-$N-pr-<k>+gh pr create --title "<section title>" --body "<body>"+```++The body says what changed and why, how you verified it (the actual `make check` and+`uv run pytest` results), and ends with `Part of #$N` — or `Closes #$N` when this was the+last section, so merging it closes the issue.++## Rules++- **Never modify anything under `.github/`.** That is the automation's own configuration.+- One section per run. Never bundle two sections into one pull request.+- Do not merge anything, do not change labels.+- If you cannot finish, push nothing and explain in the log. A half-finished branch or a+ pull request that does not build blocks every later part of the issue.diff --git a/.github/claude/plan-issue.md b/.github/claude/plan-issue.mdnew file mode 100644index 0000000..31a9aa8--- /dev/null+++ b/.github/claude/plan-issue.md@@ -0,0 +1,62 @@+# Plan an issue++You are Claude Code running in GitHub Actions on a fresh checkout of `main`. Your job is+to turn one issue into a written plan, delivered as a pull request that adds exactly one+file. **Write no application code in this run.**++`ISSUE_NUMBER` is in the prompt; `$N` below means that number.++## 1. Understand the issue++- `gh issue view $N --comments` — read the whole thread, including what people have+ ruled out.+- Read `AGENTS.md` for the project's commands and conventions.+- Explore the code the issue touches before deciding anything. Search for functions,+ models and helpers that already do part of the job: a plan that reuses what exists is+ worth far more than one that invents a parallel implementation.+- If the issue is too vague to plan without guessing, do not guess. Post a comment with+ the specific questions that block you (`gh issue comment $N`), and stop — no branch,+ no pull request.+- If `docs/plans/issue-$N-*.md` already exists, the issue has a plan. Stop and do+ nothing.++## 2. Write the plan++Write one file, `docs/plans/issue-$N-<slug>.md`, where `<slug>` is a two-to-four word+kebab-case summary. Follow the format in `docs/plans/README.md` exactly — the workflow+parses those headings to decide what to build next, so a malformed heading stalls the+issue.++Rules for the breakdown:++- Every `## PR k:` section must be at most **500 added lines**, tests included, excluding+ lockfiles and generated data. Estimate honestly and split anything close to the limit.+- Sections are implemented and merged strictly in order, one pull request each. Each one+ must be independently mergeable and must leave `main` working and green.+- The first section should be the smallest slice that works end to end, not scaffolding.+- Tests belong in the section that adds the behaviour they cover. Never make a section+ that is only "add tests" or only "refactor for later".+- Name the concrete files, functions and models each section touches, and the existing+ code it should reuse.+- Give each section acceptance criteria a reviewer can check.+- Keep it short. A plan is a sequence of decisions, not a restatement of the codebase.++## 3. Open the pull request++```+git checkout -b claude/issue-$N-plan+git add docs/plans/issue-$N-<slug>.md+git commit -m "Plan issue #$N: <issue title>"+git push -u origin claude/issue-$N-plan+gh pr create --title "Plan: <issue title>" --body "<body>"+```++The body: one paragraph on the approach and why it is split this way, then the list of+sections with their line estimates, then `Part of #$N`. Merging this pull request is what+starts implementation, so make the trade-offs easy to review.++## Rules++- **Never modify anything under `.github/`.** That is the automation's own configuration.+- The pull request adds exactly one file. If you changed anything else, revert it.+- Do not merge anything, do not close the issue, do not change labels.diff --git a/.github/scripts/select-claude-work.sh b/.github/scripts/select-claude-work.shnew file mode 100755index 0000000..818b254--- /dev/null+++ b/.github/scripts/select-claude-work.sh@@ -0,0 +1,108 @@+#!/usr/bin/env bash+#+# Pick the issues that the Claude issue-automation workflow should act on.+#+# The queues are derived entirely from repository and issue state, never from a label+# the automation itself has to remember to change, so a rerun after a failed job is+# harmless and a human can redirect the work by editing a plan file:+#+# implement the issue has a plan under docs/plans/ with a section not marked (Done),+# or it is labelled "ready to code" and has no plan at all+# plan the issue is labelled "ready to plan" and has no plan yet+#+# An issue with an open claude/issue-<N>-* pull request is skipped in both queues. That+# is what enforces "one PR at a time per issue": the next part cannot start until the+# previous one is merged (or closed).+#+# Writes plan_matrix/implement_matrix (and has_plan/has_implement) to $GITHUB_OUTPUT, or+# to stdout when that is unset, so the selection can be dry-run locally with:+#+# GH_TOKEN=$(gh auth token) bash .github/scripts/select-claude-work.sh++set -euo pipefail++readonly plan_dir="docs/plans"+readonly max_items="${CLAUDE_MAX_ITEMS:-3}"+readonly only_issue="${CLAUDE_ONLY_ISSUE:-}"++open_issues=$(gh issue list --state open --limit 200 --json number,title,labels)+open_branches=$(gh pr list --state open --limit 200 --json headRefName --jq '.[].headRefName')++# An open PR on a claude/issue-<N>-* branch means part <k> of issue <N> is still in+# review; nothing new may start for that issue.+has_open_pull_request() {+ grep -qE "^claude/issue-$1-" <<<"$open_branches"+}++plan_file_for() {+ local candidate+ for candidate in "$plan_dir"/issue-"$1"-*.md; do+ if [[ -f $candidate ]]; then+ printf '%s\n' "$candidate"+ return+ fi+ done+}++# A plan is unfinished while it still has a "## PR <k>: ..." heading without the (Done)+# suffix that the implementing PR appends.+has_pending_section() {+ local total done_count+ total=$(grep -cE '^## PR [0-9]+:' "$1" || true)+ done_count=$(grep -cE '^## PR [0-9]+:.*\(Done\)[[:space:]]*$' "$1" || true)+ ((total > done_count))+}++plan_items=()+implement_items=()++while IFS=$'\t' read -r number title labels; do+ if [[ -n $only_issue && $number != "$only_issue" ]]; then+ continue+ fi+ if has_open_pull_request "$number"; then+ echo "issue #$number: skipped, a claude/issue-$number-* pull request is still open" >&2+ continue+ fi++ plan_file=$(plan_file_for "$number")+ item=$(jq -nc --argjson issue "$number" --arg title "$title" '{issue: $issue, title: $title}')++ if [[ -n $plan_file ]]; then+ if has_pending_section "$plan_file"; then+ implement_items+=("$item")+ else+ echo "issue #$number: $plan_file has no pending section but was not deleted" >&2+ fi+ elif [[ ,$labels, == *,"ready to code",* ]]; then+ implement_items+=("$item")+ elif [[ ,$labels, == *,"ready to plan",* ]]; then+ plan_items+=("$item")+ fi+done < <(jq -r '.[] | [.number, .title, ([.labels[].name] | join(","))] | @tsv' <<<"$open_issues")++# Finishing work already under way beats starting more of it, so implement items take+# the budget first.+selected_implement=("${implement_items[@]:0:max_items}")+remaining=$((max_items - ${#selected_implement[@]}))+selected_plan=("${plan_items[@]:0:remaining}")++as_matrix() {+ if (($# == 0)); then+ echo '{"item":[]}'+ else+ printf '%s\n' "$@" | jq -sc '{item: .}'+ fi+}++plan_matrix=$(as_matrix ${selected_plan+"${selected_plan[@]}"})+implement_matrix=$(as_matrix ${selected_implement+"${selected_implement[@]}"})++output() {+ printf '%s=%s\n' "$1" "$2" >>"${GITHUB_OUTPUT:-/dev/stdout}"+}++output plan_matrix "$plan_matrix"+output implement_matrix "$implement_matrix"+output has_plan "$([[ $plan_matrix == '{"item":[]}' ]] && echo false || echo true)"+output has_implement "$([[ $implement_matrix == '{"item":[]}' ]] && echo false || echo true)"diff --git a/.github/workflows/claude-issues.yml b/.github/workflows/claude-issues.ymlnew file mode 100644index 0000000..1771caf--- /dev/null+++ b/.github/workflows/claude-issues.yml@@ -0,0 +1,162 @@+name: Claude issue automation++# Turns triaged issues into pull requests, hourly.+#+# "ready to plan" -> a PR adding docs/plans/issue-<N>-<slug>.md and nothing else+# "ready to code" -> a PR implementing the issue (or a plan, if it is too big for one)+# a plan on main -> one PR per unfinished "## PR <k>:" section, in order+#+# Only one claude/issue-<N>-* pull request is ever open per issue: the next part starts+# after the previous one is merged. See .github/claude/*.md for what Claude is told, and+# docs/plans/README.md for the plan format.+#+# Note that an issue only enters these queues once someone with write access labels it,+# so untriaged issue text never reaches a run.++on:+ schedule:+ # Hourly, off the hour: runs at :00 queue behind everyone else's.+ - cron: "17 * * * *"+ workflow_dispatch:+ inputs:+ issue:+ description: "Act on this issue number only (blank = every eligible issue)"+ required: false+ type: string++permissions:+ contents: write+ pull-requests: write+ issues: write+ id-token: write # OIDC exchange for the Claude GitHub App+ actions: read++env:+ # How many issues may be worked on in one run, implement items first.+ CLAUDE_MAX_ITEMS: "3"++jobs:+ select:+ runs-on: ubuntu-latest+ outputs:+ plan_matrix: ${{ steps.select.outputs.plan_matrix }}+ implement_matrix: ${{ steps.select.outputs.implement_matrix }}+ has_plan: ${{ steps.select.outputs.has_plan }}+ has_implement: ${{ steps.select.outputs.has_implement }}+ steps:+ - name: Check out repository+ uses: actions/checkout@v4+ # Read-only listing, so the default workflow token is enough here.+ - name: Select the issues to act on+ id: select+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ CLAUDE_ONLY_ISSUE: ${{ inputs.issue }}+ run: .github/scripts/select-claude-work.sh++ plan:+ needs: select+ if: needs.select.outputs.has_plan == 'true'+ runs-on: ubuntu-latest+ timeout-minutes: 30+ strategy:+ fail-fast: false+ matrix: ${{ fromJSON(needs.select.outputs.plan_matrix) }}+ # Never two runs on one issue at once; a queued duplicate exits early when it sees+ # the pull request the first one opened.+ concurrency:+ group: claude-issue-${{ matrix.item.issue }}+ cancel-in-progress: false+ name: "plan #${{ matrix.item.issue }}"+ steps:+ # Full history: the instructions diff the branch against main.+ - name: Check out repository+ uses: actions/checkout@v4+ with:+ fetch-depth: 0+ # No github_token input: the action then authenticates as the Claude GitHub App,+ # which sets GH_TOKEN and the git credentials for Claude and, unlike the workflow+ # token, lets CI run on the pull requests it pushes.+ - name: Write the plan+ uses: anthropics/claude-code-action@v1+ with:+ anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}+ prompt: |+ Follow the instructions in .github/claude/plan-issue.md exactly.++ ISSUE_NUMBER: ${{ matrix.item.issue }}+ ISSUE_TITLE: ${{ matrix.item.title }}+ REPOSITORY: ${{ github.repository }}+ claude_args: |+ --model claude-opus-5+ --max-turns 60+ --allowedTools "Read,Glob,Grep,Edit,Write,TodoWrite,Bash(git:*),Bash(gh:*),Bash(ls:*),Bash(cat:*),Bash(head:*),Bash(tail:*),Bash(wc:*),Bash(find:*),Bash(grep:*),Bash(rg:*),Bash(mkdir:*)"++ implement:+ needs: select+ if: needs.select.outputs.has_implement == 'true'+ runs-on: ubuntu-latest+ timeout-minutes: 60+ strategy:+ fail-fast: false+ matrix: ${{ fromJSON(needs.select.outputs.implement_matrix) }}+ concurrency:+ group: claude-issue-${{ matrix.item.issue }}+ cancel-in-progress: false+ name: "implement #${{ matrix.item.issue }}"++ # The environment below is the test job of ci.yml: Claude has to get the same gates+ # green before it opens a pull request, so it needs the same database and toolchain.+ services:+ postgres:+ image: postgres:15+ env:+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: test_mwmbl+ options: >-+ --health-cmd pg_isready+ --health-interval 10s+ --health-timeout 5s+ --health-retries 5+ ports:+ - 5432:5432++ steps:+ - name: Check out repository+ uses: actions/checkout@v4+ with:+ fetch-depth: 0+ - name: Set up python+ uses: actions/setup-python@v4+ with:+ python-version: '3.11.12'+ - name: Install uv+ uses: astral-sh/setup-uv@v5+ with:+ enable-cache: true+ cache-dependency-glob: "uv.lock"+ - name: Install Rust toolchain+ uses: dtolnay/rust-toolchain@stable+ - name: Install dependencies+ run: uv sync --group dev+ - name: Install project with maturin+ run: uv run maturin develop+ - name: Create test directories and files+ run: mkdir -p /tmp/test_mwmbl_data+ - name: Implement the next part+ uses: anthropics/claude-code-action@v1+ env:+ DATABASE_URL: postgres://postgres:postgres@localhost:5432/test_mwmbl+ DJANGO_SETTINGS_MODULE: mwmbl.settings_test+ with:+ anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}+ prompt: |+ Follow the instructions in .github/claude/implement-issue.md exactly.++ ISSUE_NUMBER: ${{ matrix.item.issue }}+ ISSUE_TITLE: ${{ matrix.item.title }}+ REPOSITORY: ${{ github.repository }}+ claude_args: |+ --model claude-opus-5+ --max-turns 100+ --allowedTools "Read,Glob,Grep,Edit,Write,TodoWrite,Bash(git:*),Bash(gh:*),Bash(make:*),Bash(uv:*),Bash(python:*),Bash(ls:*),Bash(cat:*),Bash(head:*),Bash(tail:*),Bash(wc:*),Bash(find:*),Bash(grep:*),Bash(rg:*),Bash(mkdir:*),Bash(sed:*),Bash(diff:*)"diff --git a/.gitignore b/.gitignoreindex 42bc25e..ccd77dc 100644--- a/.gitignore+++ b/.gitignore@@ -202,8 +202,9 @@ devdata/ss_judge_matrix*devdata/ss_judge_queries.txtdevdata/super_search_xgb/-# AI planning documents-plans/+# Local AI planning documents. Anchored to the root so that docs/plans/, which the+# Claude issue automation writes and reads, stays tracked.+/plans/# Claude Code configuration.claude/diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000..c549e09--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,58 @@+# Working on Mwmbl++Mwmbl is a non-profit, open source web search engine: a Django application serving search+and curation, plus a distributed crawler run by volunteers. This file is the context a+coding agent gets; see `README.md` for the project itself and+[book.mwmbl.org](https://book.mwmbl.org) for the full developer guide.++## Commands++Use `uv` for everything — never a bare `python` or `pip`.++```sh+make check # ruff format --check, ruff check, ty — exactly what CI gates on+make fix # ruff format + ruff check --fix+make test # the full pytest suite+make test-file FILE=test/test_auth.py+uv run manage.py <command> --settings=mwmbl.settings_dev+```++`make test` and `make migrate` need `DATABASE_URL` in the environment, for example+`DATABASE_URL="postgres://user@/mwmbl_test"`. Tests use `mwmbl.settings_test`.++`make check` and `make test` are the two gates. Both must pass before you open a pull+request, and `.pre-commit-config.yaml` runs the first of them on every commit.++## Layout++- `mwmbl/` — the Django project. `crawler/` (crawl queue and batches), `indexer/` (the+ index and its update pipeline), `moderation/`, `platform/`, `evaluation/` and+ `rankeval/` (ranking quality), `api.py` (django-ninja endpoints), `models.py`,+ `settings_*.py` per environment.+- `mwmbl_rank/` — the Rust ranking extension, built with maturin. Changing it means+ `uv run maturin develop` before the tests will see it.+- `test/` — pytest suite, one file per area.+- `front-end/` — the JS build; leave it alone unless the change is about the UI.+- `scripts/`, `analyse/` — one-off analysis and evaluation tools, not application code.+- `devdata/` — generated data artifacts, mostly gitignored. Never commit large files here.+- `docs/plans/` — implementation plans for issues being built one pull request at a time;+ see `docs/plans/README.md`.++## Style++- No defensive programming. Let it fail loudly rather than papering over a missing+ setting or an unexpected shape — no `getattr(settings, "X", default)`, no bare+ `except`, no "just in case" fallbacks.+- Name intermediate results instead of nesting expressions. A well-named local is the+ cheapest documentation there is.+- Imports go at the top of the file.+- Comments explain *why*, not *what*. Skip the comment that restates the line below it.+- Match the surrounding code's naming and idiom over any general preference.+- Tests live next to the behaviour they cover, in `test/`, and are part of the same+ change — not a follow-up.++## Pull requests++Keep them small: at most about 500 added lines, tests included. Say what changed, why,+and how it was verified. Reference the issue with `Part of #<N>`, or `Closes #<N>` when+it finishes the issue.diff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 100644index 0000000..dc366f8--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1 @@+See @AGENTS.md.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 9292c5b..003a2e7 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -4,3 +4,18 @@ Please join the discussion at https://matrix.to/#/#mwmbl:matrix.org and let us kSee https://book.mwmbl.org/page/developers/ for a guide to development.++Automated issue work+--------------------++Two labels hand an issue to the Claude automation in+`.github/workflows/claude-issues.yml`, which runs hourly:++- **ready to plan** — it opens a pull request adding an implementation plan under+ `docs/plans/`. Merging that pull request starts the work, one pull request per section.+- **ready to code** — it opens a single pull request implementing the issue, or writes a+ plan first if the issue is too big for one.++Only one automated pull request is open per issue at a time, so the next part waits for+you to merge the previous one. See `docs/plans/README.md` for the plan format and+`AGENTS.md` for the conventions the automation follows.diff --git a/docs/plans/README.md b/docs/plans/README.mdnew file mode 100644index 0000000..2e02e1f--- /dev/null+++ b/docs/plans/README.md@@ -0,0 +1,54 @@+# Implementation plans++A plan in this directory is the agreed breakdown of one issue into a sequence of small+pull requests. The Claude issue automation+(`.github/workflows/claude-issues.yml`) writes them, reads them to decide what to build+next, and deletes them when the issue is finished — so the format below is load-bearing.+You are welcome to edit a plan by hand while it is in flight; keep the headings intact.++## Lifecycle++1. An issue is labelled **ready to plan**. The next run opens a pull request adding+ `issue-<N>-<slug>.md` here, and nothing else.+2. You review and merge that pull request. Merging it is what starts the work.+3. Each later run implements the first section not marked `(Done)`, appends `(Done)` to+ that heading in the same commit, and opens one pull request for it. Nothing else+ starts on that issue until you merge it.+4. The pull request for the last section deletes this file and says `Closes #<N>`, so+ merging it closes the issue.++An issue labelled **ready to code** skips step 1 and goes straight to a single pull+request — unless it turns out to need more than about 500 lines, in which case the run+writes a plan here instead.++## Format++```markdown+# Issue #123: Rebuild the crawler's retry backoff++One paragraph: the problem, and what the code looks like when this is finished.++## PR 1: Record retry attempts on CrawlAttempt+**Estimated added lines:** ~180+**Files:** mwmbl/crawler/models.py, mwmbl/crawler/retry.py, test/test_retry.py++What to change and which existing code to reuse.++- Acceptance criterion+- Acceptance criterion++## PR 2: Back off exponentially on 5xx+...+```++What the automation parses, and what a hand edit must therefore preserve:++- A section heading matches `## PR <k>: <title>` exactly, numbered from 1, in the order+ they are to be built.+- A finished section's heading ends with ` (Done)` and nothing after it.+- The file is named `issue-<N>-<slug>.md`, where `<N>` is the issue number.+- The file is deleted by the last pull request. A plan whose sections are all `(Done)`+ but which still exists is reported as a warning by the selector and blocks nothing.++Each section must be at most **500 added lines** including tests, must be independently+mergeable, and must leave `main` working.