From e37c8566c63ee2da5f5ecfe2c336a40d7a648623 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:46:00 -0600 Subject: [PATCH] agent queue: start runs only for commands and replay cancelled claims Every pull request comment started the verify job, which gathered state and re-ran the pull request check, so ordinary review discussion re-ran verification. Gate the verify job on comments that start with /verified and the claim job on comments that start with /. Claim runs share one concurrency group with cancel-in-progress: false. GitHub keeps one waiting run per group and cancels it when a newer run queues, so with the run deciding only its own comment, a /claim posted while another claim was being decided could be dropped without a reply. Each run now replays every command of the last lease_hours that has no bot reply, oldest first, updating labels in memory between commands; the hourly audit does the same, so a cancelled run's command is answered by the run that replaced it at the latest within the hour. Replies carry a done marker that counts only from the Actions bot. The pull request check is advisory until a live smoke test and the migration of existing issues: problems are a warning and the job passes. Tests model the concurrency group (the old event-only design loses the cancelled claim; replay answers all four commands), in-order overlap decisions, bot-only markers and the workflow triggers. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- .github/workflows/agent-claims.yml | 24 ++++- .github/workflows/agent-pr-checks.yml | 14 ++- CHANGELOG.md | 2 +- docs/coordination/agent-tasks.md | 24 ++++- scripts/agent_queue/cli.py | 13 ++- scripts/agent_queue/ghio.py | 15 ++- scripts/agent_queue/replay.py | 55 ++++++++++ tests/agent_queue/test_prcheck_summary.py | 8 ++ tests/agent_queue/test_replay.py | 126 ++++++++++++++++++++++ tests/agent_queue/test_workflows_cli.py | 37 +++++++ 10 files changed, 302 insertions(+), 16 deletions(-) create mode 100644 scripts/agent_queue/replay.py create mode 100644 tests/agent_queue/test_replay.py diff --git a/.github/workflows/agent-claims.yml b/.github/workflows/agent-claims.yml index 2cbe6bd..64f3bdb 100644 --- a/.github/workflows/agent-claims.yml +++ b/.github/workflows/agent-claims.yml @@ -4,6 +4,13 @@ name: Agent task claims # /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. +# +# Both jobs share one concurrency group, so decisions never race. GitHub keeps +# at most one pending run per group and cancels the older pending run when a +# newer one queues, so a run does not decide only its own comment: `replay` +# decides every command of the last lease_hours that has no bot reply yet, +# oldest first. The surviving run, or at the latest the hourly audit, answers +# the commands of cancelled runs. Comments that do not start with `/` start no run. on: issue_comment: @@ -16,7 +23,7 @@ permissions: {} jobs: command: - if: github.event_name == 'issue_comment' && !github.event.issue.pull_request + if: github.event_name == 'issue_comment' && !github.event.issue.pull_request && startsWith(github.event.comment.body, '/') runs-on: ubuntu-24.04-arm permissions: contents: read @@ -36,9 +43,8 @@ jobs: PYTHONPATH: scripts run: | set -eu - 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 gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/state.json" + python3 -m agent_queue replay --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json" python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json" audit: @@ -54,6 +60,16 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + - name: Decide commands whose runs were cancelled + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + PYTHONPATH: scripts + run: | + set -eu + python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/commands.json" + python3 -m agent_queue replay --state "$RUNNER_TEMP/commands.json" > "$RUNNER_TEMP/replay.json" + python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/replay.json" - name: Lapse stale claims, flag invalid tasks, write summary env: GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/agent-pr-checks.yml b/.github/workflows/agent-pr-checks.yml index 7e891a6..d5e6d95 100644 --- a/.github/workflows/agent-pr-checks.yml +++ b/.github/workflows/agent-pr-checks.yml @@ -4,6 +4,11 @@ name: Agent PR checks # 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. +# +# Advisory: problems are reported as a warning and in the run summary, but the +# check does not fail until a live smoke test and the migration of existing +# issues are done (docs/coordination/agent-tasks.md). Only a comment starting +# with /verified starts the verify job; ordinary comments start nothing. on: pull_request_target: @@ -43,10 +48,15 @@ jobs: cat "$RUNNER_TEMP/result.json" echo '```' } >> "$GITHUB_STEP_SUMMARY" - exit "$status" + # 1 means problems were found: advisory for now. Anything else is a failure of the check itself. + if [ "$status" -eq 1 ]; then + echo "::warning title=Agent PR check (advisory)::problems found; see the run summary" + elif [ "$status" -ne 0 ]; then + exit "$status" + fi verify: - if: github.event_name == 'issue_comment' && github.event.issue.pull_request + if: github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/verified') runs-on: ubuntu-24.04-arm # issues: write posts the reply; actions: write re-runs the check after a recorded verification. permissions: diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cc7b3e..4f657dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,7 +11,7 @@ remains unsupported. ### Added -- 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. +- 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. Only comments that start with a command start a run, so ordinary pull request comments never re-run verification, and each claim run decides every unanswered command in order, so commands whose pending runs GitHub cancelled are still answered. See `docs/coordination/agent-tasks.md`. Unit tests pass locally; the workflows have not run on GitHub yet, and the pull request check stays advisory (it never blocks a merge) until a live smoke test and the migration of existing issues are done. - Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet. - Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and diff --git a/docs/coordination/agent-tasks.md b/docs/coordination/agent-tasks.md index 4ca13f1..89d1e5d 100644 --- a/docs/coordination/agent-tasks.md +++ b/docs/coordination/agent-tasks.md @@ -6,7 +6,9 @@ deterministic: the rules live in `scripts/agent_queue/` (standard-library Python 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. +against the real API until the first live run. Until a live smoke test has passed and existing issues +have been migrated into the queue, the pull request check is **advisory**: it reports problems but +never blocks a merge, and it must not be made a required check. ## Areas @@ -47,6 +49,10 @@ done 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. + GitHub keeps at most one waiting run in a concurrency group and cancels it when a newer one + queues, so each run decides every command of the last `lease_hours` that has no bot reply yet, + oldest first. A command whose own run was cancelled is answered by the run that replaced it, or at + the latest by the hourly audit. Each reply carries a marker naming the comment it answers. 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 @@ -59,6 +65,9 @@ done ## Commands (issue comments) +A command must start the comment. Comments that do not start with `/` (on an issue) or with +`/verified` (on a pull request) start no workflow run. + | Command | Who | Effect | | --- | --- | --- | | `/claim` | allowed for the area | Take a ready task | @@ -80,7 +89,12 @@ machine-readable summary (counts and lists per area, priority and state). `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. +head sha>` exists. After a `/verified` comment the check is re-run automatically; other pull request +comments do not re-run it. + +The check is advisory for now: a failure is shown as a warning and in the run summary, and the job +still succeeds. It becomes blocking (fail on problems, then a required check) only after a live smoke +test on GitHub and the migration of existing issues into the queue. ## Forks and upstream sync @@ -104,7 +118,7 @@ sync report that shows upstream touching your files is the signal to re-read the - 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. +- Markers (grant, approval, answered command) 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. @@ -118,4 +132,6 @@ sh -n scripts/agent-queue.sh scripts/agent-sync.sh ``` 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. +the summary, the CLI, claim concurrency (a model of a concurrency group in which newer runs cancel +pending ones, and in-order replay of unanswered commands) and a structural check of the workflow +files, including which comments start a run. They do not exercise GitHub itself. diff --git a/scripts/agent_queue/cli.py b/scripts/agent_queue/cli.py index 2b07f6c..023e4e7 100644 --- a/scripts/agent_queue/cli.py +++ b/scripts/agent_queue/cli.py @@ -3,12 +3,12 @@ import argparse import json import sys -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from . import config as cfgmod from . import ghio from . import lease as L -from . import prcheck, queue +from . import prcheck, queue, replay from . import tasks as T from . import decide as decide_mod from .decide import decide @@ -35,6 +35,8 @@ def main(argv): 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.add_argument("--recent-commands", action="store_true", help="include comments from the last lease_hours for replay") + s = sub.add_parser("replay"); s.add_argument("--state", required=True) 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) @@ -65,13 +67,18 @@ def main(argv): 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) + since = "" + if a.recent_commands: + since = (_now(a.now) - timedelta(hours=cfg["lease_hours"])).strftime("%Y-%m-%dT%H:%M:%SZ") + st = ghio.gather(a.repo, with_prs=not a.no_prs, recent_since=since) 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 == "replay": + _out(replay.replay(_load(a.state), cfg, _now(a.now))) elif a.cmd == "apply": ghio.apply_actions(a.repo, _load(a.actions)) elif a.cmd == "audit": diff --git a/scripts/agent_queue/ghio.py b/scripts/agent_queue/ghio.py index 23274ef..8143e3c 100644 --- a/scripts/agent_queue/ghio.py +++ b/scripts/agent_queue/ghio.py @@ -27,6 +27,14 @@ def comments(repo, n): return ndjson(gh("api", "repos/%s/issues/%d/comments" % (repo, n), "--paginate", "--jq", jq)) +def recent_comments(repo, since): + """Issue and pull request comments updated since `since` (UTC ISO time), oldest first.""" + jq = ('.[] | {id: .id, user: .user.login, body: .body, created_at: .created_at, ' + 'issue: (.issue_url | split("/") | last | tonumber), pull_request: (.html_url | test("/pull/"))}') + return ndjson(gh("api", "repos/%s/issues/comments?sort=created&direction=asc&per_page=100&since=%s" % (repo, since), + "--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")) @@ -46,8 +54,9 @@ def open_prs(repo): 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.""" +def gather(repo, with_prs=True, with_comments=True, recent_since=""): + """State for decide/audit/summary/replay: open tasks plus any dependency issues they name and, + with `recent_since`, every comment since then.""" from .tasks import parse_task issues = {i["number"]: i for i in open_issues(repo)} for i in list(issues.values()): @@ -60,6 +69,8 @@ def gather(repo, with_prs=True, with_comments=True): 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) + if recent_since: + state["recent_comments"] = recent_comments(repo, recent_since) return state diff --git a/scripts/agent_queue/replay.py b/scripts/agent_queue/replay.py new file mode 100644 index 0000000..6cb785f --- /dev/null +++ b/scripts/agent_queue/replay.py @@ -0,0 +1,55 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Decides every unanswered issue command, oldest first. + +Claim runs share one concurrency group. GitHub keeps one run in progress and at most one pending in +a group, and a newly queued run cancels the pending one, so the comment that started a cancelled +run would never be decided. Each run therefore decides every recent command that has no bot reply +yet, in comment order, and applies each decision's labels to its in-memory state so later commands +see earlier grants. Every reply carries a marker naming the comment it answers.""" +import copy +import re +from datetime import timedelta + +from . import lease as L +from .decide import decide +from .tasks import label_names, parse_time + +DONE = re.compile(r"") + + +def done_marker(comment_id): + return "" % comment_id + + +def answered(comments, bots=L.BOT): + """Ids of comments a bot reply has answered. Markers from anyone else do not count.""" + return {int(m) for c in comments if c["user"] in bots for m in DONE.findall(c["body"])} + + +def _apply(state, action): + for i in state["issues"]: + if int(i["number"]) == action["issue"]: + names = [n for n in label_names(i) if n not in action["remove_labels"]] + names += [n for n in action["add_labels"] if n not in names] + i["labels"] = [{"name": n} for n in names] + + +def replay(state, cfg, now, bots=L.BOT): + """Actions for every unanswered command in state["recent_comments"] created within the lease.""" + state = copy.deepcopy(state) + since = now - timedelta(hours=cfg["lease_hours"]) + comments = state.get("recent_comments", []) + done = answered(comments, bots) + out = [] + for c in sorted(comments, key=lambda c: (parse_time(c["created_at"]), c["id"])): + if (c.get("pull_request") or c["id"] in done or c["user"] in bots + or parse_time(c["created_at"]) < since): + continue + actions = decide({"kind": "issue", "number": c["issue"], "actor": c["user"], "body": c["body"]}, state, cfg) + if not actions: + continue + actions[-1]["comment"] += "\n" + done_marker(c["id"]) + for a in actions: + _apply(state, a) + out.extend(actions) + return out diff --git a/tests/agent_queue/test_prcheck_summary.py b/tests/agent_queue/test_prcheck_summary.py index 0b3f41c..56f2796 100644 --- a/tests/agent_queue/test_prcheck_summary.py +++ b/tests/agent_queue/test_prcheck_summary.py @@ -35,6 +35,14 @@ class PRChecks(unittest.TestCase): self.assertTrue(r["ok"], r) self.assertEqual(r["verified_by"], ["qaer"]) + def test_verification_needs_no_bot_reply(self): + # A /verified whose verify run was cancelled while pending has no bot reply; the check reads + # the comments themselves, so the surviving run's re-run still counts it. + r = run(pr(), [vc("qaer"), vc("maint"), {"user": BOT, "body": "Verification of %s recorded for maint." % SHA[:12], + "created_at": "2026-01-10T11:31:00Z"}]) + self.assertTrue(r["ok"], r) + self.assertEqual(r["verified_by"], ["qaer", "maint"]) + def test_missing_link(self): r = run(pr(body="no link"), [vc("qaer")]) self.assertFalse(r["ok"]) diff --git a/tests/agent_queue/test_replay.py b/tests/agent_queue/test_replay.py new file mode 100644 index 0000000..e091976 --- /dev/null +++ b/tests/agent_queue/test_replay.py @@ -0,0 +1,126 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""Claim concurrency: one group, pending runs cancelled by newer ones, replay of unanswered commands.""" +import copy +import unittest + +from helpers import CFG, NOW, issue, state +from agent_queue import replay as R +from agent_queue.decide import decide +from agent_queue.lease import GRANT + +BOT = "github-actions[bot]" + + +def cmd(cid, user, text, n, at="2026-01-10T11:00:00Z", pr=False): + return {"id": cid, "user": user, "body": text, "created_at": at, "issue": n, "pull_request": pr} + + +def queue_state(comments): + # #1 and #2 share src/gpu/a.rs; #3 is independent. + return state(issue(1), issue(2), issue(3, files="src/gpu/b.rs"), recent_comments=comments) + + +def granted(actions): + return sorted((int(m.group(1)), m.group(2)) for a in actions for m in [GRANT.search(a["comment"])] if m) + + +def simulate(posted, run_once): + """GitHub concurrency group with cancel-in-progress: false. Each comment queues a run; while a + run is in progress one run may wait, and a newly queued run cancels the waiting one. Here every + comment arrives while the first run is still in progress. Returns the posted bot replies.""" + st = queue_state([]) + issues = st["issues"] + timeline, replies = [], [] + in_progress, pending = posted[0], None + for c in posted[1:]: + pending = c # an older pending run, if any, is cancelled here + for trigger, visible in ((in_progress, posted[:1]), (pending, posted)): + if trigger is None: + continue + view = {"issues": issues, "prs": [], "task_comments": {}, + "recent_comments": visible + timeline} + actions = run_once(trigger, view) + for a in actions: + R._apply(st, a) + timeline.append({"id": 10_000 + len(timeline), "user": BOT, "body": a["comment"], + "created_at": "2026-01-10T11:30:00Z", "issue": a["issue"], "pull_request": False}) + replies.extend(actions) + return replies + + +def event_only(trigger, view): + """The previous design: a run decides only the comment that started it.""" + return decide({"kind": "issue", "number": trigger["issue"], "actor": trigger["user"], "body": trigger["body"]}, + view, CFG) + + +def with_replay(trigger, view): + return R.replay(view, CFG, NOW) + + +POSTED = [ + cmd(1, "maint", "/claim", 3, "2026-01-10T11:00:00Z"), + cmd(2, "gpuer", "/claim", 1, "2026-01-10T11:00:01Z"), + cmd(3, "maint", "/claim", 2, "2026-01-10T11:00:02Z"), # overlaps #1 on src/gpu/a.rs + cmd(4, "gpuer", "/progress parser done", 1, "2026-01-10T11:00:03Z"), +] + + +class PendingCancellation(unittest.TestCase): + def test_deciding_only_the_trigger_loses_cancelled_commands(self): + # Runs 2 and 3 are cancelled while pending: gpuer's claim on #1 is never answered. + self.assertEqual(granted(simulate(POSTED, event_only)), [(3, "maint")]) + + def test_replay_answers_every_command_of_cancelled_runs(self): + replies = simulate(POSTED, with_replay) + self.assertEqual(granted(replies), [(1, "gpuer"), (3, "maint")]) + refused = [a for a in replies if a["issue"] == 2] + self.assertEqual(len(refused), 1) + self.assertIn("file overlap with claimed task #1", refused[0]["comment"]) + answered = R.answered([{"user": BOT, "body": a["comment"]} for a in replies]) + self.assertEqual(answered, {1, 2, 3, 4}) + + +class Replay(unittest.TestCase): + def run_replay(self, comments, st=None): + return R.replay(st or queue_state(comments), CFG, NOW) + + def test_overlapping_claims_in_one_run_are_decided_in_order(self): + actions = self.run_replay([cmd(8, "maint", "/claim", 2, "2026-01-10T11:00:05Z"), + cmd(7, "gpuer", "/claim", 1, "2026-01-10T11:00:05Z")]) + # Same second: the lower comment id is first. + self.assertEqual(granted(actions), [(1, "gpuer")]) + self.assertIn("file overlap with claimed task #1", actions[1]["comment"]) + self.assertIn(R.done_marker(8), actions[1]["comment"]) + + def test_answered_commands_are_not_decided_again(self): + first = self.run_replay([cmd(1, "gpuer", "/claim", 1)]) + st = queue_state([cmd(1, "gpuer", "/claim", 1), + {"id": 2, "user": BOT, "body": first[0]["comment"], "created_at": "2026-01-10T11:01:00Z", + "issue": 1, "pull_request": False}]) + for a in first: + R._apply(st, a) + self.assertEqual(R.replay(st, CFG, NOW), []) + + def test_done_markers_count_only_from_the_bot(self): + forged = {"id": 2, "user": "rt", "body": R.done_marker(1), "created_at": "2026-01-10T11:01:00Z", + "issue": 1, "pull_request": False} + self.assertEqual(granted(self.run_replay([cmd(1, "gpuer", "/claim", 1), forged])), [(1, "gpuer")]) + + def test_ordinary_pr_and_old_comments_start_nothing(self): + self.assertEqual(self.run_replay([ + cmd(1, "gpuer", "looks good to me", 1), + cmd(2, "gpuer", "/claim", 1, pr=True), + cmd(3, "maint", "/verified abcdef1", 1), + cmd(4, "gpuer", "/claim", 1, "2026-01-09T11:00:00Z"), # older than lease_hours + ]), []) + + def test_state_is_not_modified(self): + st = queue_state([cmd(1, "gpuer", "/claim", 1)]) + before = copy.deepcopy(st) + self.assertEqual(len(R.replay(st, CFG, NOW)), 1) + self.assertEqual(st, before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/agent_queue/test_workflows_cli.py b/tests/agent_queue/test_workflows_cli.py index cae30d6..2e5ff33 100644 --- a/tests/agent_queue/test_workflows_cli.py +++ b/tests/agent_queue/test_workflows_cli.py @@ -63,6 +63,43 @@ class Workflows(unittest.TestCase): self.assertNotRegex(text, r"github\.event\.pull_request\.head|ref:\s*\$\{\{") self.assertIn("pull_request_target", text) + def job(self, name, job): + """Text of one job block: from ` :` to the next two-space-indented key.""" + m = re.search(r"(?ms)^ %s:\n(.*?)(?=^ \S|\Z)" % re.escape(job), self.read(name)) + self.assertIsNotNone(m, "%s: job %s" % (name, job)) + return m.group(1) + + def job_if(self, name, job): + return re.search(r"(?m)^ if: (.*)$", self.job(name, job)).group(1) + + def test_only_command_comments_start_runs(self): + # Ordinary comments must not start a claim run or a verification re-run. + self.assertIn("startsWith(github.event.comment.body, '/verified')", self.job_if("agent-pr-checks.yml", "verify")) + self.assertIn("startsWith(github.event.comment.body, '/')", self.job_if("agent-claims.yml", "command")) + self.assertNotIn("issue_comment", self.job_if("agent-pr-checks.yml", "check")) + + def test_claim_jobs_share_one_group_and_replay(self): + for job in ("command", "audit"): + text = self.job("agent-claims.yml", job) + self.assertRegex(text, r"group: agent-queue\n\s+cancel-in-progress: false", job) + # Pending runs can be cancelled by newer ones, so every run replays unanswered commands. + self.assertIn("agent_queue replay", text, job) + self.assertIn("--recent-commands", text, job) + self.assertNotIn("agent_queue decide", self.job("agent-claims.yml", "command")) + + def test_verify_runs_one_at_a_time_per_pull_request(self): + text = self.job("agent-pr-checks.yml", "verify") + self.assertRegex(text, r"group: agent-verify-\$\{\{ github\.event\.issue\.number \}\}\n\s+cancel-in-progress: false") + + def test_pr_check_is_advisory(self): + # Exit status 1 (problems found) only warns until the live smoke test and issue migration. + text = self.job("agent-pr-checks.yml", "check") + found = re.search(r'if \[ "\$status" -eq 1 \]; then\n(.*?)\n\s+elif \[ "\$status" -ne 0 \]; then\n\s+exit "\$status"', text, re.S) + self.assertIsNotNone(found, text) + self.assertIn("::warning title=Agent PR check (advisory)::", found.group(1)) + self.assertNotIn("exit", found.group(1)) + self.assertEqual(text.count("exit "), 1) + def test_actions_pinned_by_sha(self): for name in QUEUE_WORKFLOWS: for use in re.findall(r"uses:\s*(\S+)", self.read(name)):