Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
feat(contrib): publish an accurate issue claim board (#1917)
Alpamys Makazhane892f72da77a
diff --git a/.github/workflows/claim-board.yml b/.github/workflows/claim-board.ymlnew file mode 100644index 00000000..1166fab4--- /dev/null+++ b/.github/workflows/claim-board.yml@@ -0,0 +1,45 @@+# Regenerate the claim board: the body of the pinned, locked issue #1945.+#+# scripts/claim_board.py reads the open issues labelled `help wanted`, `claimed` or+# `infra-blocked`, their comments and the open pull requests through `gh api`, and renders one+# markdown table. Each title goes inside a code span with `|` and backticks replaced, so issue+# text cannot add links, mentions or markup to the board.+#+# Why an issue and not a file: main requires status checks, and the workflow token cannot push+# past them; editing an issue body needs no write access to the code and adds no commits.+#+# Security: the token can read contents and pull requests and write issues, nothing else.+# Nothing an issue author wrote reaches a shell command: no expression is interpolated into+# `run`. Checkout is the default branch, pinned by commit, and the token is not kept.+name: claim board++on:+ schedule:+ - cron: "17 5 * * *"+ workflow_dispatch:++permissions:+ contents: read+ issues: write+ pull-requests: read++jobs:+ board:+ if: github.repository == 'MakazhanAlpamys/Soup'+ runs-on: ubuntu-latest+ timeout-minutes: 10+ # A manual run and the daily one never overlap, and neither cancels the other.+ concurrency:+ group: claim-board+ cancel-in-progress: false+ steps:+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4+ with:+ persist-credentials: false+ - name: Rewrite the board issue+ env:+ GH_TOKEN: ${{ github.token }}+ BOARD_ISSUE: "1945"+ run: |+ python3 scripts/claim_board.py --write claim-board.md+ gh issue edit "$BOARD_ISSUE" --repo MakazhanAlpamys/Soup --body-file claim-board.mddiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 7215f40b..bf73bc07 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -346,6 +346,9 @@ Comment on it saying you are taking it. GitHub only lets us set the formalassignee badge for repo collaborators, so the comment **is** the claim — it willlook unassigned either way, and we treat the thread as the record.+The current board is the pinned issue+[#1945](https://github.com/MakazhanAlpamys/Soup/issues/1945), regenerated daily.+Two commitments in return:- **If a maintainer ends up doing the work instead, you get told, in the thread,diff --git a/changelog.d/0.76.0/1917.added.md b/changelog.d/0.76.0/1917.added.mdnew file mode 100644index 00000000..55eb2318--- /dev/null+++ b/changelog.d/0.76.0/1917.added.md@@ -0,0 +1 @@+- A claim board, the pinned issue #1945 regenerated daily by `scripts/claim_board.py`, shows which `help wanted` issues are free, claimed or blocked (#1917)diff --git a/scripts/claim_board.py b/scripts/claim_board.pynew file mode 100644index 00000000..e740e2ec--- /dev/null+++ b/scripts/claim_board.py@@ -0,0 +1,338 @@+"""Render the claim board: which open issues are free, claimed, or blocked.++Reads the open issues labelled ``help wanted``, ``claimed`` or ``infra-blocked`` through+``gh api`` (stdlib only) and writes one plain-markdown table. The board is not committed:+it is the body of the pinned, locked issue #1945, which a scheduled job rewrites with+``gh issue edit 1945 --body-file <file>``. The claim rules are in CONTRIBUTING.md ("How+work is queued"); this page only reports them.++ python scripts/claim_board.py # print to stdout+ python scripts/claim_board.py --write board.md # write the page to a file+ python scripts/claim_board.py --check board.md # exit 1 when the file differs++The generation-time line is ignored by ``--check``. Exit codes: 0 ok, 1 stale file, 2 an+API or usage error.+"""++from __future__ import annotations++import argparse+import json+import re+import subprocess+import sys+from datetime import datetime, timezone+from pathlib import Path++REPO = "MakazhanAlpamys/Soup"+MAINTAINER = "MakazhanAlpamys"+LABELS = ("help wanted", "claimed", "infra-blocked")+BOARD_ISSUE = 1945+GUIDE_URL = f"https://github.com/{REPO}/blob/main/CONTRIBUTING.md#how-work-is-queued"+TITLE_WIDTH = 60+GENERATED_PREFIX = "Generated: "++_CONFIRM_RE = re.compile(r"^\s*confirmed\b|\b(?:is|are) yours\b", re.IGNORECASE | re.MULTILINE)+_NAMED_CONFIRM_RE = re.compile(r"^\s*confirmed\s*[,!:]?\s*@([a-z0-9-]+)\b", re.IGNORECASE)+_LEADING_LOGIN_RE = re.compile(r"^\s*@([a-z0-9-]+)\b([^@\n]*)", re.IGNORECASE)+_DIRECT_CONFIRM_RE = re.compile(+ r"^\s*(?:confirmed(?:[,.!]|$)|(?:it|this) is yours\b)", re.IGNORECASE+)+_TAKE_RE = re.compile(+ r"\b(?:i'd like to take|i would like to take|i'll take|i will take|take this"+ r"|claim this|i claim)\b",+ re.IGNORECASE,+)+_LINK_WORDS = r"(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?|refs?|part of)"+_AFTER_RE = re.compile(r"\bafter\s+#(\d+)", re.IGNORECASE)+_DIFFICULTY_RE = re.compile(r"^difficulty:(\d+)$")+++class BoardError(Exception):+ """An API or usage problem; main() turns it into exit code 2."""+++def label_names(issue: dict) -> list[str]:+ return [lab["name"] if isinstance(lab, dict) else lab for lab in issue.get("labels", [])]+++def difficulty(issue: dict) -> int | None:+ for name in label_names(issue):+ match = _DIFFICULTY_RE.match(name)+ if match:+ return int(match.group(1))+ return None+++def parse_time(text: str) -> datetime:+ return datetime.fromisoformat(text.replace("Z", "+00:00"))+++def _login(comment: dict) -> str:+ return (comment.get("user") or {}).get("login", "")+++def _named_confirmation(body: str, issue_number: int) -> tuple[str, bool] | None:+ """Return the addressee and whether their acceptance states ownership."""+ named = _NAMED_CONFIRM_RE.match(body)+ if named:+ acceptance = body[named.end() :].split("@", 1)[0].split("\n", 1)[0]+ owns = bool(re.search(r"\b(?:is|are) yours\b", acceptance, re.IGNORECASE))+ return named.group(1), owns+ leading = _LEADING_LOGIN_RE.match(body)+ if leading and re.search(+ rf"(?:#{issue_number}\b|\bthis issue)\s+is yours\b", leading.group(2), re.IGNORECASE+ ):+ return leading.group(1), True+ return None+++def find_claimant(comments: list[dict], issue_number: int) -> tuple[str | None, str | None, bool]:+ """Return (login, since date, confirmed).++ Prefer the latest direct acceptance, binding a named login to an API author.+ A generic acceptance needs the preceding contributor's own take request.+ Ambiguous claim evidence returns (None, None, True), for "claimed (see thread)".+ Without acceptance, retain the first take request as unconfirmed.+ """+ ordered = sorted(comments, key=lambda item: item["created_at"])+ for index in range(len(ordered) - 1, -1, -1):+ comment = ordered[index]+ body = comment.get("body", "")+ if _login(comment) != MAINTAINER or not _CONFIRM_RE.search(body):+ continue+ earlier = [item for item in ordered[:index] if _login(item) not in (MAINTAINER, "")]+ named = _named_confirmation(body, issue_number)+ if named is not None:+ login, owns = named+ matches = [item for item in earlier if _login(item).casefold() == login.casefold()]+ if not owns and not any(_TAKE_RE.search(item.get("body", "")) for item in matches):+ continue+ if matches:+ item = matches[-1]+ return _login(item), item["created_at"][:10], True+ return None, None, True+ if _DIRECT_CONFIRM_RE.match(body) and earlier:+ previous = earlier[-1]+ if _TAKE_RE.search(previous.get("body", "")):+ return _login(previous), previous["created_at"][:10], True+ if any(_TAKE_RE.search(item.get("body", "")) for item in earlier):+ return None, None, True+ for comment in ordered:+ if _login(comment) not in (MAINTAINER, "") and _TAKE_RE.search(comment.get("body", "")):+ return _login(comment), comment["created_at"][:10], False+ return None, None, False+++def _always_open(number: int) -> bool:+ return True+++def blocker(issue: dict, comments: list[dict], is_open=_always_open) -> str | None:+ """`infra-blocked` label, or 'after #N' (N still open) in the last maintainer comment."""+ if "infra-blocked" in label_names(issue):+ return "infra-blocked"+ for comment in sorted(comments, key=lambda item: item["created_at"], reverse=True):+ if _login(comment) == MAINTAINER:+ match = _AFTER_RE.search(comment.get("body", ""))+ if match and is_open(int(match.group(1))):+ return f"after #{match.group(1)}"+ return None+ return None+++def quiet_days(comments: list[dict], login: str | None, now: datetime) -> int | None:+ if not login:+ return None+ times = [parse_time(c["created_at"]) for c in comments if _login(c) == login]+ if not times:+ return None+ return max((now - max(times)).days, 0)+++def find_pr(prs: list[dict], issue_number: int, login: str | None) -> int | None:+ """Lowest open PR by `login` whose body closes or refs the issue (not "see also")."""+ if not login:+ return None+ hits = []+ for pr in prs:+ if (pr.get("user") or {}).get("login") != login:+ continue+ link = re.compile(rf"\b{_LINK_WORDS}:?\s+#{issue_number}\b", re.IGNORECASE)+ if link.search(pr.get("body") or ""):+ hits.append(pr["number"])+ return min(hits) if hits else None+++def classify(+ issue: dict, comments: list[dict], prs: list[dict], now: datetime, is_open=_always_open+) -> dict:+ labels = label_names(issue)+ login, since, confirmed = find_claimant(comments, issue["number"])+ block = blocker(issue, comments, is_open)+ claimed = "claimed" in labels or confirmed+ if block:+ kind, state = "blocked", f"blocked: {block}"+ elif claimed and login:+ kind = "claimed"+ # The login sits in a code span: the board names the claimant without a mention, so+ # a daily rewrite of the issue never notifies anyone.+ state = f"claimed by `@{login}` since {since}" + ("" if confirmed else " (unconfirmed)")+ elif claimed:+ kind, state = "claimed", "claimed (see thread)"+ else:+ kind, state = "free", "free"+ return {+ "number": issue["number"],+ "title": issue["title"],+ "difficulty": difficulty(issue),+ "kind": kind,+ "state": state,+ "pr": find_pr(prs, issue["number"], login) if kind != "free" else None,+ "quiet": quiet_days(comments, login, now) if kind != "free" else None,+ }+++def sort_rows(rows: list[dict]) -> list[dict]:+ order = {"free": 0, "claimed": 1, "blocked": 2}++ def key(row: dict) -> tuple:+ diff = row["difficulty"] if row["difficulty"] is not None else 99+ quiet = -(row["quiet"] if row["quiet"] is not None else -1)+ if row["kind"] == "free":+ return (0, diff, row["number"])+ return (order[row["kind"]], quiet, row["number"])++ return sorted(rows, key=key)+++def short_title(title: str) -> str:+ """Untrusted text: one backtick code span, so no link, tag, mention or issue ref renders."""+ title = " ".join(title.replace("|", "/").replace("`", "'").split())+ if len(title) > TITLE_WIDTH:+ title = title[: TITLE_WIDTH - 3] + "..."+ return f"`{title}`"+++def render(rows: list[dict], now: datetime) -> str:+ stamp = now.strftime("%Y-%m-%d %H:%M UTC")+ lines = [+ "# Claim board",+ "",+ f"{GENERATED_PREFIX}{stamp}",+ "",+ "Open issues labelled `help wanted`, `claimed` or `infra-blocked`. To claim one, "+ "comment on that issue itself; this issue is locked. A maintainer confirms the claim. "+ "A claim with no pull request and no word from the claimant for 7 days gets a "+ "check-in; 7 more quiet days release it. A pull request waiting on its author for 14 "+ f"days gets a ping, and 7 more days close it. See [How work is queued]({GUIDE_URL}). "+ "This issue body is regenerated daily by `scripts/claim_board.py`; an edit made here "+ "is overwritten.",+ "",+ "| Issue | Title | Difficulty | State | PR | Quiet |",+ "|-------|-------|------------|-------|----|-------|",+ ]+ for row in sort_rows(rows):+ diff = str(row["difficulty"]) if row["difficulty"] is not None else "-"+ pr = f"#{row['pr']}" if row["pr"] else "-"+ quiet = f"quiet {row['quiet']} d" if row["quiet"] is not None else "-"+ lines.append(+ f"| #{row['number']} | {short_title(row['title'])} | {diff} | "+ f"{row['state']} | {pr} | {quiet} |"+ )+ if not rows:+ lines.append("| - | No open issues carry these labels | - | - | - | - |")+ return "\n".join(lines) + "\n"+++def strip_stamp(text: str) -> str:+ return "\n".join(line for line in text.splitlines() if not line.startswith(GENERATED_PREFIX))+++def gh_json(args: list[str]) -> list[dict]:+ try:+ proc = subprocess.run(+ ["gh", "api", *args], capture_output=True, text=True, check=False, timeout=300+ )+ except (OSError, subprocess.TimeoutExpired) as exc:+ raise BoardError(f"could not run gh: {exc}") from exc+ if proc.returncode != 0:+ raise BoardError(f"gh api {args[0]} failed: {proc.stderr.strip() or proc.returncode}")+ text = proc.stdout.strip()+ items: list[dict] = []+ try:+ # --paginate prints one JSON array per page, back to back.+ decoder, pos = json.JSONDecoder(), 0+ while pos < len(text):+ value, pos = decoder.raw_decode(text, pos)+ items.extend(value if isinstance(value, list) else [value])+ while pos < len(text) and text[pos].isspace():+ pos += 1+ except ValueError as exc:+ raise BoardError(f"gh api {args[0]} returned invalid JSON: {exc}") from exc+ return items+++def fetch(now: datetime) -> list[dict]:+ issues: dict[int, dict] = {}+ for label in LABELS:+ query = label.replace(" ", "%20")+ found = gh_json(+ [f"repos/{REPO}/issues?state=open&per_page=100&labels={query}", "--paginate"]+ )+ for item in found:+ if "pull_request" not in item:+ issues[item["number"]] = item+ prs = gh_json([f"repos/{REPO}/pulls?state=open&per_page=100", "--paginate"])+ states: dict[int, bool] = {}++ def is_open(number: int) -> bool:+ if number not in states:+ found_one = gh_json([f"repos/{REPO}/issues/{number}"])+ states[number] = bool(found_one) and found_one[0].get("state") == "open"+ return states[number]++ rows = []+ for number in sorted(issues):+ comments = gh_json([f"repos/{REPO}/issues/{number}/comments?per_page=100", "--paginate"])+ rows.append(classify(issues[number], comments, prs, now, is_open))+ return rows+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description="Render the claim board page.")+ mode = parser.add_mutually_exclusive_group()+ mode.add_argument("--write", metavar="PATH", help="write the page to this file")+ mode.add_argument(+ "--check",+ metavar="PATH",+ help="write nothing; exit 1 when this file differs from the live board (time line ignored)",+ )+ args = parser.parse_args(argv)+ now = datetime.now(timezone.utc)+ try:+ page = render(fetch(now), now)+ except BoardError as exc:+ print(f"claim_board: {exc}", file=sys.stderr)+ return 2+ if args.write:+ Path(args.write).write_text(page, encoding="utf-8", newline="\n")+ print(f"wrote {args.write}")+ return 0+ if args.check:+ path = Path(args.check)+ existing = path.read_text(encoding="utf-8") if path.exists() else None+ if existing is None or strip_stamp(existing) != strip_stamp(page):+ print(+ f"{args.check} is stale. Run `python scripts/claim_board.py --write "+ f"{args.check}` to rewrite it."+ )+ return 1+ print(f"{args.check} is up to date.")+ return 0+ sys.stdout.write(page)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/test_claim_board.py b/tests/test_claim_board.pynew file mode 100644index 00000000..8ed9d6d6--- /dev/null+++ b/tests/test_claim_board.py@@ -0,0 +1,470 @@+"""scripts/claim_board.py: classification, ordering and rendering with fake API data."""++import importlib.util+import re+import sys+from datetime import datetime, timezone+from pathlib import Path+from urllib.parse import parse_qs, urlsplit++import pytest++_ROOT = Path(__file__).resolve().parents[1]+_PATH = _ROOT / "scripts" / "claim_board.py"+_SPEC = importlib.util.spec_from_file_location("claim_board", _PATH)+board = importlib.util.module_from_spec(_SPEC)+sys.modules["claim_board"] = board+_SPEC.loader.exec_module(board)++NOW = datetime(2026, 10, 14, 12, 0, tzinfo=timezone.utc)+++def issue(number, labels=("help wanted",), title="Some title"):+ return {"number": number, "title": title, "labels": [{"name": n} for n in labels]}+++def comment(login, body, created):+ return {"user": {"login": login}, "body": body, "created_at": created}+++def pull(number, login, body):+ return {"number": number, "user": {"login": login}, "title": "x", "body": body}+++def test_free():+ row = board.classify(issue(5, ("help wanted", "difficulty:3")), [], [], NOW)+ assert row["kind"] == "free" and row["state"] == "free" and row["difficulty"] == 3+ assert row["pr"] is None and row["quiet"] is None+++def test_claimed_confirmed_with_pr_and_quiet_days():+ comments = [+ comment("alice", "I'd like to take this", "2026-10-01T10:00:00Z"),+ comment("MakazhanAlpamys", "Confirmed, it is yours", "2026-10-02T10:00:00Z"),+ comment("alice", "working on it", "2026-10-04T12:00:00Z"),+ ]+ prs = [pull(90, "bob", "Fixes #7"), pull(91, "alice", "Refs #7")]+ row = board.classify(issue(7, ("claimed",)), comments, prs, NOW)+ assert row["state"] == "claimed by `@alice` since 2026-10-01"+ assert row["pr"] == 91+ assert row["quiet"] == 10+++def test_claimed_unconfirmed_is_labelled():+ comments = [comment("carol", "Can I claim this?", "2026-10-10T00:00:00Z")]+ row = board.classify(issue(8, ("claimed",)), comments, [], NOW)+ assert row["state"] == "claimed by `@carol` since 2026-10-10 (unconfirmed)"+++def test_the_rendered_board_mentions_nobody():+ # The board is an issue body rewritten every day: a bare @login would notify the claimant.+ comments = [+ comment("alice", "I'd like to take this", "2026-10-01T10:00:00Z"),+ comment("MakazhanAlpamys", "Confirmed, it is yours", "2026-10-02T10:00:00Z"),+ ]+ page = board.render([board.classify(issue(7, ("claimed",)), comments, [], NOW)], NOW)+ assert "`@alice`" in page+ assert "@" not in re.sub(r"`[^`]*`", "", page)+++def test_claimed_label_without_nameable_claimant():+ row = board.classify(issue(9, ("claimed",)), [], [], NOW)+ assert row["state"] == "claimed (see thread)"++[email protected]("labels", [("help wanted",), ("help wanted", "claimed")])+def test_an_offer_on_other_issues_does_not_confirm_the_fallback(labels):+ """#1878: #1881 carries the issue; #1895's author is offered other work."""+ comments = [+ comment("Nari-Ab", "I'd like to claim this issue.", "2026-10-14T11:02:12Z"),+ comment(+ board.MAINTAINER,+ "Thanks @Nari-Ab. @Fire162 opened #1881 for this issue; it carries the issue. "+ "Your #1895 waits behind it as the fallback.",+ "2026-10-14T12:33:25Z",+ ),+ comment(+ "Nari-Ab",+ "#1895 is a draft fallback. Could you suggest a different issue?",+ "2026-10-14T12:40:23Z",+ ),+ comment(+ board.MAINTAINER,+ "Thanks @Nari-Ab. Three free issues: #1887, #1884, #1888. "+ "Post your plan on the issue you choose and the claim is yours now.",+ "2026-10-14T14:11:01Z",+ ),+ ]+ prs = [pull(1881, "Fire162", "Fixes #1878"), pull(1895, "Nari-Ab", "Fixes #1878")]+ row = board.classify(issue(1878, labels), comments, prs, NOW)+ assert row["kind"] == "claimed"+ assert row["state"] == "claimed (see thread)"+ assert row["pr"] is None and row["quiet"] is None+++def test_latest_named_confirmation_replaces_a_completed_claim():+ """#1199: fix 3 was completed/released before fix 2 was confirmed again."""+ comments = [+ comment("yunaremaia", "I am taking proposed fix 3.", "2026-10-03T10:45:32Z"),+ comment(+ board.MAINTAINER,+ "Confirmed, @yunaremaia: proposed fix 3 is yours.",+ "2026-10-04T15:52:21Z",+ ),+ comment(+ board.MAINTAINER,+ "Fix 3 merged. The claim covered fix 3, which is now done, so I have taken "+ "`claimed` off: the two remaining fixes are free to take.",+ "2026-10-07T20:35:31Z",+ ),+ comment("Faisal-Fayaz", "Taking fix 2.", "2026-10-08T06:34:19Z"),+ comment(+ board.MAINTAINER,+ "Confirmed, @Faisal-Fayaz: fix 2 is yours. Marked the issue claimed again. "+ "Fix 1 stays unclaimed.",+ "2026-10-08T06:37:04Z",+ ),+ ]+ prs = [pull(1600, "yunaremaia", "Refs #1199"), pull(1700, "Faisal-Fayaz", "Refs #1199")]+ row = board.classify(issue(1199, ("help wanted", "claimed")), comments, prs, NOW)+ assert row["state"] == "claimed by `@Faisal-Fayaz` since 2026-10-08"+ assert row["pr"] == 1700 and row["quiet"] == 6+++ "confirmation",+ [+ "Confirmed, @alice: it is yours.",+ "Confirmed, @alice: go ahead.",+ ],+)+def test_named_confirmation_binds_its_author_despite_an_interleaved_reply(confirmation):+ comments = [+ comment("alice", "I'll take this", "2026-10-01T10:00:00Z"),+ comment("bob", "I can provide a fallback if needed.", "2026-10-02T09:00:00Z"),+ comment(+ board.MAINTAINER,+ confirmation,+ "2026-10-02T10:00:00Z",+ ),+ ]+ row = board.classify(issue(7), comments, [pull(91, "alice", "Refs #7")], NOW)+ assert row["state"] == "claimed by `@alice` since 2026-10-01"+ assert row["pr"] == 91++[email protected]("subject", ["#7", "this issue"])+def test_leading_named_same_issue_acceptance_excludes_a_rejected_fallback(subject):+ """The ordinary #1915 form addresses the winner before mentioning a fallback."""+ comments = [+ comment("alice", "I'll take this", "2026-10-01T10:00:00Z"),+ comment("bob", "I can provide a fallback if needed.", "2026-10-02T09:00:00Z"),+ comment(+ board.MAINTAINER,+ f"@alice, thanks for the plan: {subject} is yours. @bob, please wait.",+ "2026-10-02T10:00:00Z",+ ),+ ]+ row = board.classify(issue(7), comments, [pull(91, "alice", "Refs #7")], NOW)+ assert row["state"] == "claimed by `@alice` since 2026-10-01"+ assert row["pr"] == 91++[email protected]("confirmation", ["Confirmed", "Confirmed, go ahead", "it is yours"])+def test_direct_confirmation_after_a_same_issue_take_request_still_names_it(confirmation):+ comments = [+ comment("alice", "I'll take this", "2026-10-01T10:00:00Z"),+ comment(board.MAINTAINER, confirmation, "2026-10-02T10:00:00Z"),+ ]+ row = board.classify(issue(7), comments, [], NOW)+ assert row["state"] == "claimed by `@alice` since 2026-10-01"+++def test_generic_confirmation_after_a_side_question_does_not_name_its_author():+ comments = [+ comment("alice", "I'll take this", "2026-10-01T10:00:00Z"),+ comment("bob", "Which other issue is free?", "2026-10-02T09:00:00Z"),+ comment(board.MAINTAINER, "Confirmed", "2026-10-02T10:00:00Z"),+ ]+ row = board.classify(issue(7), comments, [], NOW)+ assert row["state"] == "claimed (see thread)"+ assert row["pr"] is None and row["quiet"] is None+++def test_a_named_confirmation_does_not_invent_an_author_from_public_text():+ comments = [+ comment("alice", "I'll take this", "2026-10-01T10:00:00Z"),+ comment(+ board.MAINTAINER,+ "Confirmed, @someone-else: it is yours.",+ "2026-10-02T10:00:00Z",+ ),+ ]+ row = board.classify(issue(7), comments, [], NOW)+ assert row["state"] == "claimed (see thread)"+ assert row["pr"] is None and row["quiet"] is None++[email protected]("with_reporter", [False, True])+ "confirmation",+ [+ "Confirmed on main: reproduced the bug.",+ "Confirmed, @alice: reproduced the bug.",+ ],+)+def test_confirming_bug_evidence_without_a_take_request_keeps_the_issue_free(+ with_reporter,+ confirmation,+):+ comments = (+ [comment("alice", "Here is the failing traceback.", "2026-10-01T10:00:00Z")]+ if with_reporter+ else []+ )+ comments.append(+ comment(+ board.MAINTAINER,+ confirmation,+ "2026-10-02T10:00:00Z",+ )+ )+ row = board.classify(issue(7), comments, [], NOW)+ assert row["kind"] == "free" and row["state"] == "free"+ assert row["pr"] is None and row["quiet"] is None+++def test_blocked_by_label():+ row = board.classify(issue(10, ("help wanted", "infra-blocked")), [], [], NOW)+ assert row["kind"] == "blocked" and row["state"] == "blocked: infra-blocked"+++def test_blocked_after_issue_uses_last_maintainer_comment_only():+ comments = [+ comment("MakazhanAlpamys", "Start after #11", "2026-10-01T00:00:00Z"),+ comment("MakazhanAlpamys", "Unblocked now", "2026-10-05T00:00:00Z"),+ ]+ assert board.classify(issue(12), comments, [], NOW)["kind"] == "free"+ comments[1]["body"] = "Please wait, after #13 lands"+ assert board.classify(issue(12), comments, [], NOW)["state"] == "blocked: after #13"+++def test_quiet_days_fixed_now():+ comments = [comment("dan", "hi", "2026-10-14T11:00:00Z")]+ assert board.quiet_days(comments, "dan", NOW) == 0+ assert board.quiet_days(comments, "eve", NOW) is None+ assert board.quiet_days(comments, None, NOW) is None+++def test_ordering_is_deterministic():+ rows = [+ {"number": 4, "difficulty": 5, "kind": "blocked", "quiet": None},+ {"number": 3, "difficulty": 2, "kind": "claimed", "quiet": 3},+ {"number": 2, "difficulty": 4, "kind": "claimed", "quiet": 9},+ {"number": 6, "difficulty": 4, "kind": "free", "quiet": None},+ {"number": 1, "difficulty": 1, "kind": "free", "quiet": None},+ ]+ assert [r["number"] for r in board.sort_rows(rows)] == [1, 6, 2, 3, 4]+ assert board.sort_rows(rows) == board.sort_rows(list(reversed(rows)))+++def _cell(page):+ return page.splitlines()[-1].split("|")[2].strip()+++def test_render_is_plain_markdown_and_truncates():+ row = board.classify(issue(1, title="x" * 100), [], [], NOW)+ page = board.render([row], NOW)+ assert "\x1b" not in page+ assert "Generated: 2026-10-14 12:00 UTC" in page+ assert board.GUIDE_URL in page and "](../" not in page+ cell = _cell(page)+ assert len(cell) == board.TITLE_WIDTH + 2 and cell.endswith("...`")+ assert not re.search("[\\u0400-\\u04FF]", page)+++def test_pipe_in_title_becomes_slash():+ page = board.render([board.classify(issue(1, title="a|b"), [], [], NOW)], NOW)+ assert _cell(page) == "`a/b`"+ assert len(page.splitlines()[-1].split("|")) == 8+++def test_title_cannot_form_markdown_or_mention():+ title = "[link](x) <b> @user #1 back`tick \\ end"+ page = board.render([board.classify(issue(1, title=title), [], [], NOW)], NOW)+ cell = _cell(page)+ assert cell == "`[link](x) <b> @user #1 back'tick \\ end`"+ assert cell.count("`") == 2+++def test_newlines_in_a_title_cannot_start_a_new_row_or_block():+ title = "a\n| x | y |\n# H\r\n- item\u2028z\u2029y\x85w"+ page = board.render([board.classify(issue(1, title=title), [], [], NOW)], NOW)+ assert page.count("\n") == board.render([], NOW).count("\n")+ assert _cell(page) == "`a / x / y / # H - item z y w`"+ assert len(page.splitlines()[-1].split("|")) == 8+++def test_blocked_outranks_claimed():+ comments = [+ comment("alice", "I'll take this", "2026-10-01T10:00:00Z"),+ comment("MakazhanAlpamys", "Confirmed", "2026-10-02T10:00:00Z"),+ ]+ row = board.classify(issue(3, ("claimed", "infra-blocked")), comments, [], NOW)+ assert row["kind"] == "blocked" and row["state"] == "blocked: infra-blocked"+ later = comments + [comment("MakazhanAlpamys", "after #99 lands", "2026-10-03T10:00:00Z")]+ row = board.classify(issue(3, ("claimed",)), later, [], NOW)+ assert row["kind"] == "blocked" and row["state"] == "blocked: after #99"+++def test_confirm_regex_cases():+ assert not board._CONFIRM_RE.search("CI confirmed green")+ assert not board._CONFIRM_RE.search("this is not yours")+ assert board._CONFIRM_RE.search("Confirmed, go ahead")+ assert board._CONFIRM_RE.search("ok\nConfirmed")+ assert board._CONFIRM_RE.search("it is yours")+ assert board._CONFIRM_RE.search("they are yours")+++def test_take_regex_cases():+ for text in ("unclaimed", "claimed by bob", "I claimed it"):+ assert not board._TAKE_RE.search(text), text+ for text in ("I'd like to take", "I'll take it", "take this", "claim this", "I claim"):+ assert board._TAKE_RE.search(text), text+++def test_after_blocker_only_when_target_open():+ comments = [comment("MakazhanAlpamys", "after #20", "2026-10-01T00:00:00Z")]+ closed = board.classify(issue(4), comments, [], NOW, lambda n: False)+ assert closed["kind"] == "free"+ opened = board.classify(issue(4), comments, [], NOW, lambda n: True)+ assert opened["state"] == "blocked: after #20"+++def test_pr_linking_needs_closing_keyword_and_claimant():+ comments = [comment("alice", "I'll take this", "2026-10-01T00:00:00Z")]+ prs = [+ pull(50, "alice", "see also #6"),+ pull(51, "bob", "Closes #6"),+ pull(52, "alice", "Part of #6"),+ pull(53, "alice", "Resolves #66"),+ ]+ assert board.classify(issue(6, ("claimed",)), comments, prs, NOW)["pr"] == 52+ assert board.classify(issue(6, ("claimed",)), comments, prs[:2], NOW)["pr"] is None+++def test_pr_link_needs_the_whole_issue_number_and_picks_the_lowest():+ comments = [comment("alice", "I'll take this", "2026-10-01T00:00:00Z")]+ prs = [+ pull(49, "alice", "Resolves #66"),+ pull(54, "alice", "Fixes #6"),+ pull(52, "alice", "Part of #6"),+ ]+ assert board.classify(issue(6, ("claimed",)), comments, prs, NOW)["pr"] == 52+++def test_fetch_asks_for_open_issues_of_each_label_and_skips_pull_requests(monkeypatch):+ asked = []++ def fake(args):+ path = args[0]+ asked.append(path)+ if "/issues?" in path:+ label = parse_qs(urlsplit(path).query)["labels"][0]+ return {+ "help wanted": [issue(1), dict(issue(2), pull_request={})],+ "claimed": [issue(1), issue(3, ("claimed",))],+ "infra-blocked": [issue(4, ("infra-blocked",))],+ }[label]+ if "/pulls?" in path or path.endswith("/comments?per_page=100"):+ return []+ raise AssertionError(path)++ monkeypatch.setattr(board, "gh_json", fake)+ rows = board.fetch(NOW)+ assert [row["number"] for row in rows] == [1, 3, 4]+ assert [row["kind"] for row in rows] == ["free", "claimed", "blocked"]+ queries = [parse_qs(urlsplit(path).query) for path in asked if "/issues?" in path]+ assert len(queries) == 3+ assert {query["labels"][0] for query in queries} == {"help wanted", "claimed", "infra-blocked"}+ assert all(query["state"] == ["open"] for query in queries)+++def test_strip_stamp_ignores_generation_time_only():+ first = board.render([], NOW)+ later = board.render([], datetime(2026, 10, 15, tzinfo=timezone.utc))+ assert first != later and board.strip_stamp(first) == board.strip_stamp(later)+++def test_api_error_exits_2(monkeypatch, capsys):+ def boom(args):+ raise board.BoardError("nope")++ monkeypatch.setattr(board, "gh_json", boom)+ assert board.main([]) == 2+ assert "claim_board: nope" in capsys.readouterr().err+++def _stub_fetch(monkeypatch):+ rows = [board.classify(issue(1), [], [], NOW)]+ monkeypatch.setattr(board, "fetch", lambda now: rows)+ return board.render(rows, NOW)+++def test_check_detects_drift_and_match(monkeypatch, tmp_path, capsys):+ page = _stub_fetch(monkeypatch)+ path = tmp_path / "board.md"+ path.write_text(page, encoding="utf-8")+ assert board.main(["--check", str(path)]) == 0+ path.write_text(page.replace("Some title", "Other"), encoding="utf-8")+ assert board.main(["--check", str(path)]) == 1+ assert "is stale" in capsys.readouterr().out+++def test_write_keeps_existing_file_when_gh_fails(monkeypatch, tmp_path):+ def boom(now):+ raise board.BoardError("gh down")++ monkeypatch.setattr(board, "fetch", boom)+ path = tmp_path / "board.md"+ path.write_bytes(b"old page\n")+ assert board.main(["--write", str(path)]) == 2+ assert path.read_bytes() == b"old page\n"+++def test_page_is_an_issue_body_regenerated_daily():+ page = board.render([], NOW)+ assert "regenerated daily by `scripts/claim_board.py`" in page+ assert "comment on that issue itself" in page+ assert "docs/" not in page and "by hand" not in page+++def test_write_puts_the_page_at_the_given_path(monkeypatch, tmp_path, capsys):+ page = _stub_fetch(monkeypatch)+ path = tmp_path / "board.md"+ assert board.main(["--write", str(path)]) == 0+ written = path.read_bytes()+ assert b"\r" not in written and written.startswith(b"# Claim board\n")+ assert board.strip_stamp(written.decode("utf-8")) == board.strip_stamp(page)+ assert f"wrote {path}" in capsys.readouterr().out+++def test_check_calls_a_missing_file_stale(monkeypatch, tmp_path, capsys):+ _stub_fetch(monkeypatch)+ assert board.main(["--check", str(tmp_path / "board.md")]) == 1+ assert "is stale" in capsys.readouterr().out+++def test_check_needs_a_path(capsys):+ with pytest.raises(SystemExit) as stopped:+ board.main(["--check"])+ assert stopped.value.code == 2+ assert "--check: expected one argument" in capsys.readouterr().err+++def test_contributing_points_at_the_pinned_issue_not_a_docs_page():+ flat = " ".join((_ROOT / "CONTRIBUTING.md").read_text(encoding="utf-8").split())+ link = f"[#{board.BOARD_ISSUE}](https://github.com/{board.REPO}/issues/{board.BOARD_ISSUE})"+ assert link in flat+ assert "claims.md" not in flat+ assert not (_ROOT / "docs" / "claims.md").exists(), "the board is an issue body, not a file"diff --git a/tests/test_claim_board_workflow.py b/tests/test_claim_board_workflow.pynew file mode 100644index 00000000..2f4b7c86--- /dev/null+++ b/tests/test_claim_board_workflow.py@@ -0,0 +1,97 @@+"""The daily claim-board workflow (.github/workflows/claim-board.yml).++It runs with a write token on a schedule, so its shape is pinned here: what triggers it, what+the token may do, which action it runs and how, and that no expression reaches a shell.+"""++from __future__ import annotations++import re+from pathlib import Path++import pytest+import yaml++ROOT = Path(__file__).resolve().parent.parent+WORKFLOW = ROOT / ".github" / "workflows" / "claim-board.yml"+CONTRIBUTING = ROOT / "CONTRIBUTING.md"++[email protected](scope="module")+def text() -> str:+ return WORKFLOW.read_text(encoding="utf-8")++[email protected](scope="module")+def workflow(text: str) -> dict:+ return yaml.safe_load(text)++[email protected](scope="module")+def steps(workflow: dict) -> list[dict]:+ return [step for job in workflow["jobs"].values() for step in job["steps"]]+++def test_it_runs_daily_or_by_hand_and_on_nothing_else(workflow: dict) -> None:+ triggers = workflow[True] # YAML 1.1 reads the key `on` as the boolean True+ assert set(triggers) == {"schedule", "workflow_dispatch"}+ assert triggers["schedule"] == [{"cron": "17 5 * * *"}]+++def test_the_token_reads_code_and_writes_only_issues(workflow: dict) -> None:+ assert workflow["permissions"] == {+ "contents": "read",+ "issues": "write",+ "pull-requests": "read",+ }+ for name, job in workflow["jobs"].items():+ assert "permissions" not in job, name+++def test_the_workflow_uses_the_workflow_token_and_no_secret(text: str, steps: list[dict]) -> None:+ step = next(step for step in steps if "claim_board.py" in step.get("run", ""))+ assert step["env"]["GH_TOKEN"] == "${{ github.token }}"+ assert not re.search(r"\bsecrets\s*(?:\.|\[)", text)+++def test_it_never_runs_in_a_fork(workflow: dict) -> None:+ for name, job in workflow["jobs"].items():+ assert job["if"] == "github.repository == 'MakazhanAlpamys/Soup'", name+++def test_the_only_action_is_checkout_pinned_by_commit(text: str, steps: list[dict]) -> None:+ uses = re.findall(r"^\s*(?:-\s*)?uses:\s*(\S+)", text, flags=re.MULTILINE)+ assert len(uses) == 1+ assert re.fullmatch(r"actions/checkout@[0-9a-f]{40}", uses[0]), uses[0]+ checkout = next(step for step in steps if "uses" in step)+ assert checkout["with"] == {"persist-credentials": False}+++def test_no_expression_is_interpolated_into_a_shell_command(steps: list[dict]) -> None:+ runs = [step["run"] for step in steps if "run" in step]+ assert runs+ for run in runs:+ assert "${{" not in run, run+++def test_no_issue_text_is_read_by_the_workflow_itself(text: str) -> None:+ for forbidden in ("issue.title", "issue.body", "comment.body", "head_ref", "event.inputs"):+ assert forbidden not in text, forbidden+++def test_runs_never_overlap_or_cancel_each_other(workflow: dict) -> None:+ for name, job in workflow["jobs"].items():+ assert job["concurrency"] == {"group": "claim-board", "cancel-in-progress": False}, name+ assert job["timeout-minutes"] <= 10, name+++def test_it_rewrites_the_issue_contributing_points_to(steps: list[dict]) -> None:+ step = next(step for step in steps if "claim_board.py" in step.get("run", ""))+ board = step["env"]["BOARD_ISSUE"]+ assert board.isdigit()+ assert 'gh issue edit "$BOARD_ISSUE"' in step["run"]+ assert "--body-file claim-board.md" in step["run"]+ assert "--write claim-board.md" in step["run"]+ assert f"https://github.com/MakazhanAlpamys/Soup/issues/{board}" in CONTRIBUTING.read_text(+ encoding="utf-8"+ )