Find a Gitea pull request by its branch and head however many pull requests are newer #746

Merged
lilleman merged 6 commits from item-541 into main 2026-11-27 19:59:01 +01:00
6 changed files with 66 additions and 23 deletions
+1
View File
@@ -2,6 +2,7 @@
## Unreleased
- `chunk-pr` and `chunk-preflight` find a Gitea pull request however many newer ones exist, so `chunk-pr clean` and `chunk-pr merge` no longer miss an old one.
- task-bench leaves out of a fix a change Haiku makes to a Rust test kept in a file of its own, `#[cfg(test)] mod name;` and the file it names, and plants no bug in that file.
- The technical principles ask code to read why a call failed from a status code, a documented exit code or a typed error, and not from message text.
- `chunk-preflight` reports a project whose tracked code is mostly space-indented while no `.editorconfig` or formatter setting sets the indent, and the technical principles' hard-tabs default is overridden only by such a setting plus a recorded decision.
+2
View File
@@ -948,6 +948,8 @@ class Clean(unittest.TestCase):
return f"12\t{self.merged_at}\tfalse\n" if self.merged_at else ""
if command == ["tea", "api", "repos/{owner}/{repo}/pulls?state=closed&limit=50"] and self.url == GITEA:
return json.dumps([{"number": 12, "merged": self.merged_at is not None, "head": {"ref": "refs/pull/12/head" if self.merged_at else "item-7", "label": "item-7", "sha": self.merged_at or self.head, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}])
if command == ["tea", "api", "repos/{owner}/{repo}/pulls?state=closed&limit=50&page=2"] and self.url == GITEA:
return "[]"
if command[0] != "git":
return Failure(f"the fake forge doesn't answer {command}")
done = subprocess.run(command, cwd=folder, capture_output=True, encoding="utf-8", env=isolated_env())
+3 -1
View File
@@ -193,7 +193,9 @@ def merge(number, guard):
git("update-ref", "refs/heads/main", head)
pull(number)["state"] = "merged"
opened = [found for found in state["pulls"] if found["state"] == "open"]
if forge == "tea" and args == ["api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]:
if forge == "tea" and args == ["api", "repos/{owner}/{repo}/pulls?state=open&limit=50&page=2"]:
print("[]")
elif forge == "tea" and args == ["api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]:
repo = lambda found: {"full_name": "fork/r" if found["fork"] else "o/r"}
print(json.dumps([{"number": found["number"], "head": {"ref": found["head"], "label": found["head"], "sha": sha(found), "repo": repo(found)}, "base": {"repo": {"full_name": "o/r"}}} for found in opened]))
elif forge == "gh" and args[:3] == ["pr", "list", "--head"] and args[4:6] == ["--json", "number,headRefOid,isCrossRepository"]:
+18 -9
View File
@@ -13,6 +13,8 @@ from forge.reviews import GITEA_DRAFT
POLL_SECONDS = 10
# How long checks_passed waits on Gitea for the checks before it gives up; CI took about 3 minutes in 2026-11. gh's watch waits as long as the checks run.
WAIT_SECONDS = 30 * 60
# How many pull requests pull_at asks Gitea for in a page; Gitea's default cap is 50.
PAGE_SIZE = 50
# What gh says of a pull request whose head has no check.
NO_CHECKS = "no checks reported"
@@ -40,15 +42,22 @@ def pull_at(forge: Forge, branch: str, head: str | None, state: typing.Literal["
return listed
rows = [line.split("\t") for line in listed.splitlines()]
return next((row[0] for row in rows if len(row) == 3 and row[2] == "false" and head in (None, row[1])), None)
# Gitea lists at most 50 a page; the pull request sought is among the newest. Gitea has no merged state: a merged pull request is a closed one marked merged.
pulls = gitea(run, f"repos/{{owner}}/{{repo}}/pulls?state={'open' if state == 'open' else 'closed'}&limit=50")
if isinstance(pulls, Failure):
return pulls
try:
# Match the label, not the ref: once origin deletes a merged branch, Gitea reports its ref as refs/pull/<N>/head.
return next((str(pull["number"]) for pull in pulls if pull["head"]["label"] == branch and (head is None or pull["head"]["sha"] == head) and pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"] and (state == "open" or pull["merged"] is True)), None)
except (KeyError, TypeError):
return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}")
# The pull request sought may be older than any number of others, so read pages, newest first, until one matches or the list ends: an empty page, or one that repeats the last. A short page doesn't end it, since Gitea's admin may cap a page below PAGE_SIZE. Gitea has no merged state: a merged pull request is a closed one marked merged.
last: typing.Any = None
page = 1
while True:
pulls = gitea(run, f"repos/{{owner}}/{{repo}}/pulls?state={'open' if state == 'open' else 'closed'}&limit={PAGE_SIZE}" + (f"&page={page}" if page > 1 else ""))
if isinstance(pulls, Failure):
return pulls
try:
# Match the label, not the ref: once origin deletes a merged branch, Gitea reports its ref as refs/pull/<N>/head.
found = next((str(pull["number"]) for pull in pulls if pull["head"]["label"] == branch and (head is None or pull["head"]["sha"] == head) and pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"] and (state == "open" or pull["merged"] is True)), None)
except (KeyError, TypeError):
return Failure(f"tea api listed pull requests in a shape that can't be read: {str(pulls)[:200]}")
if found or not pulls or pulls == last:
return found
last = pulls
page += 1
@dataclasses.dataclass(frozen=True)
+42 -1
View File
@@ -9,7 +9,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from forge.pulls import BEHIND, CheckFailed, checks_now, checks_passed, CONFLICTS, open_pull, other_base, Pending, POLL_SECONDS, pull_from, ready_pulls, ReadyPull, required_checks, unmergeable, WAIT_SECONDS
from forge.pulls import BEHIND, CheckFailed, checks_now, checks_passed, CONFLICTS, merged_pull, open_pull, other_base, Pending, POLL_SECONDS, pull_from, ready_pulls, ReadyPull, required_checks, unmergeable, WAIT_SECONDS
from failure import Failure
from forge.commands import forge_of, gitea, runner, url_beside
@@ -58,6 +58,47 @@ class OpenPull(unittest.TestCase):
self.assertEqual(open_pull("tea", "item-3", "abc", lambda command: LONG).reason, f"tea api listed pull requests in a shape that can't be read: {LONG[:200]}")
def gitea_pulls(newer: int, sought: dict, cap: int = 50) -> typing.Callable[[list[str]], str]:
"""A fake tea that answers the pull request list like Gitea, newest first: `newer` others, then `sought`. A page holds at most `cap`."""
def pull(number: int, label: str, sha: str, merged: bool) -> dict:
return {"number": number, "merged": merged, "head": {"label": label, "sha": sha, "repo": {"full_name": "o/r"}}, "base": {"repo": {"full_name": "o/r"}}}
everything = [pull(1000 - n, f"other-{n}", "f" * 40, True) for n in range(newer)] + [pull(sought["number"], sought["label"], sought["sha"], sought["merged"])]
def run(command: list[str]) -> str:
query = dict(part.split("=") for part in command[-1].split("?")[1].split("&"))
limit, page = min(int(query["limit"]), cap), int(query.get("page", "1"))
return json.dumps(everything[(page - 1) * limit:page * limit])
return run
class PullsBeyondTheFirstPage(unittest.TestCase):
SOUGHT = {"number": 652, "label": "item-3", "sha": "abc", "merged": True}
def test_finds_a_merged_pull_request_that_has_more_than_50_newer_ones(self):
self.assertEqual(merged_pull("tea", "item-3", "abc", gitea_pulls(120, self.SOUGHT)), "652")
def test_finds_one_that_is_the_first_after_a_full_page(self):
self.assertEqual(merged_pull("tea", "item-3", "abc", gitea_pulls(50, self.SOUGHT)), "652")
def test_finds_one_where_gitea_caps_a_page_below_the_size_asked(self):
self.assertEqual(merged_pull("tea", "item-3", "abc", gitea_pulls(70, self.SOUGHT, cap=30)), "652")
def test_finds_none_after_the_last_page_where_none_matches(self):
self.assertIsNone(merged_pull("tea", "item-9", "abc", gitea_pulls(120, self.SOUGHT)))
def test_asks_for_no_page_after_the_first_that_comes_back_empty(self):
asked = []
run = gitea_pulls(70, self.SOUGHT)
merged_pull("tea", "item-9", "abc", lambda command: asked.append(command[-1]) or run(command))
self.assertEqual([endpoint.partition("&limit=50")[2] for endpoint in asked], ["", "&page=2", "&page=3"])
def test_stops_where_gitea_answers_the_same_page_to_every_request(self):
page = json.dumps([{"number": 1, "merged": True, "head": {"label": "x", "sha": "y", "repo": {"full_name": "o/r"}}, "base": {"repo": {"full_name": "o/r"}}}])
self.assertIsNone(merged_pull("tea", "item-3", "abc", lambda command: page))
def test_finds_an_open_pull_request_the_same_way(self):
self.assertEqual(open_pull("tea", "item-3", "abc", gitea_pulls(120, {**self.SOUGHT, "merged": False})), "652")
class Unmergeable(unittest.TestCase):
def gh(self, mergeable: str, state: str) -> str | None | Failure:
commands: list[list[str]] = []
-12
View File
@@ -15,7 +15,6 @@
| 477 | 0.17.0 | | question | **Rewrite `## Goals` and `## Audience` for a setup others install and run apart from their own `~/.claude`.** | 1 | 1 | 2 | 2 | 2 | | 0.0 |
| 478 | 0.17.0 | | question | **Name the project, its repo and its two commands, today proposed as `do-release` and `do-epic`.** | 1 | 1 | 2 | 2 | 1 | | 0.0 |
| 523 | 0.17.0 | | | **Make the security pass and stability-reviewer check that a new secret's docs name its scope and its reach, such as the other repositories its account can use.** | 1 | 1 | 2 | 2 | 1 | 1.1 by 2 | 0.9 |
| 541 | 0.17.0 | | | **Find a Gitea pull request by its branch and head however many pull requests are newer, so `chunk-pr clean`, `chunk-pr merge` and `chunk-preflight` see an older one.** | 2 | 2 | 3 | 5 | 2 | 1 by 2 | 0.8 |
| 545 | 0.17.0 | | | **Have chunk-preflight name each next-release item with no `Touches:` list while others wait, and have loop-claude launch a subagent that writes the lists before it starts the next chunk.** | 3 | 2 | 3 | 6 | 6 | 1.1 by 4 | 0.6 |
| 544 | 0.17.0 | | | **Leave out of a `task-bench` fix a change Haiku makes to a PHP or JavaScript test that PHPUnit or `node --test` finds by a name `is_test` does not know.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 1 | 0.4 |
| 480 | 0.18.0 | | owner | **Resolve every path the tools use in one module: the release root (the folder the running code ships in), the config folder, the state folder and the Claude home. Then only that module names `~/.claude`, and the loop still runs from `~/.claude`.** | 3 | 2 | 3 | 6 | 6 | 1.6 by 3, code health by 3 | 2.4 |
@@ -120,17 +119,6 @@ Part of the standalone-install plan lilleman approved on 2026-11-20. Later items
An outside reviewer found it on a client project's PR that added a secret: a Gitea token documented as able to run Actions on one repository, "and nothing wider". The token reaches every repository its owning account can, so the docs had to require a dedicated account with access to that repository only. Neither `/security-review` nor stability-reviewer raised it. Where a change adds a secret or a token, ask each to check that the doc beside it states what the credential can reach, not only what the change uses it for.
### 541. Find a Gitea pull request by its branch and head however many pull requests are newer, so `chunk-pr clean`, `chunk-pr merge` and `chunk-preflight` see an older one.
Today `pull_at` in `bin/forge/pulls.py` reads only Gitea's first page of 50 pull requests, open or closed, and looks for the branch among them. A pull request with 50 newer ones in that state is missed. PR #652 here merged after 50+ newer PRs had closed, and `chunk-pr clean` then said "no merged pull request from filing-prose-reentry", leaving the worktree and branch to remove by hand. The same lookup serves `open_pull`, so `ready` and `merge` miss an old open one too, and `chunk-preflight` misses a merged chunk's worktree.
Look the pull request up so its age doesn't matter: page through the list until one matches or a page comes back short, or ask Gitea by base and head (`GET /repos/{owner}/{repo}/pulls/{base}/{head}`) where its version answers that call. Keep matching on the head's label, since Gitea reports a deleted branch's ref as `refs/pull/<N>/head`. Test it with a fake forge holding more than 50 newer pull requests.
Touches:
- `bin/forge/pulls.py`: `pull_at`
- `bin/forge/test_forge.py`
### 545. Have chunk-preflight name each next-release item with no `Touches:` list while others wait, and have loop-claude launch a subagent that writes the lists before it starts the next chunk.
In fejkdata on 2026-11-27 the loop ran one chunk for hours beside seven waiting items, because five items of the next release (one filed by the reading-cost report, four older) had no `Touches:` list, and `chunk-preflight` says only "No item may start a chunk beside item X's: its detail has no `Touches:` list". Nothing makes a session write the lists, and `rank_todo.py --check` refuses only a list it cannot read.