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>
This commit is contained in:
elforeign committed 2026-11-24 00:46:21 -06:00
1 parent 98bbe57471
commit e37c8566c6
10 files changed
+302 -16

No files matched your search

+10 -3
View File
@@ -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":
+13 -2
View File
@@ -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
+55
View File
@@ -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"<!-- agent-queue:done comment=(\d+) -->")
def done_marker(comment_id):
return "<!-- agent-queue:done comment=%d -->" % 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