mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 19:30:43 +00:00
Expand the agent task queue to cpu/gpu/runtime/shared/qa with deterministic checks
The queue now has three engineering tracks plus shared and qa work. Queue rules move from shell/awk in workflows into a standard-library Python package so they are testable offline: claim decisions (dependencies, cycles, file overlap, area permission), leases renewed only by the holder, reassign and release, acceptance-command approval by hash, pull request ownership/overlap/ stale/verification checks and a machine-readable summary. Workflows apply the decisions with minimal permissions, never put user text in run blocks and never check out pull request code. The sync script fetches the real upstream so interface changes during work are reported. Not yet run on GitHub. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
This commit is contained in:
1 parent
a89f9d8d06
commit
e35df04069
28 files changed
+1822
-164
No files matched your search
@@ -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.
|
||||
"""
|
||||
@@ -0,0 +1,6 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
import sys
|
||||
|
||||
from .cli import main
|
||||
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -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
|
||||
@@ -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, [])
|
||||
@@ -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))
|
||||
@@ -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"])
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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}
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user