Answer security round 1: 0 🔴, 1 🟡 (0 misread); take only origin's own pull request at the branch's head and merge it pinned to that head

This commit is contained in:
2026-11-08 10:47:36 +01:00
parent 29b986ca42
commit f6e96da675
7 changed files with 122 additions and 58 deletions
+1 -1
View File
@@ -128,7 +128,7 @@ Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with py
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. The non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool.
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path.
- `deploy_release` imports `chunk_preflight`'s forge commands, which list a branch's open pull request with `gh` or `tea`, and `release_standing.py`, which says whether the next release is ready to cut.
- `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_standing.py`, which says whether the next release is ready to cut.
- `judge_replay` imports `loop_claude`'s judge.
- `larv_review` imports `rank_todo.py`'s ranking.
- `loop_claude` runs `chunk-preflight` as a process of its own.
+14 -18
View File
@@ -7,14 +7,14 @@ import re
import shutil
import tempfile
from chunk_preflight.choices import forge_of
from deploy_release import forge
from release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned
from git_repo import default_ref, git
from deploy_release.deploy import deploy
from failure import Failure
from git_repo import default_ref, git
from release import newest_tag, Release, version
from release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned
from deploy_release import forge
from chunk_preflight.choices import forge_of
from todo_table import items
from release import newest_tag, Release, version
def cut(clone: str, checkout: str) -> str | Failure:
@@ -92,27 +92,23 @@ def land(clone: str, ref: str, named: str, title: str) -> Failure | None:
if isinstance(url, Failure):
return url
on, run, branch, base = forge_of(url), forge.runner(clone), f"release-{named}", ref.removeprefix("origin/")
number = forge.open_pull(on, branch, run)
if isinstance(number, Failure):
return number
head = branch_head(branch, clone)
if head is None:
if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title), Failure):
return pushed
head = branch_head(branch, clone) or Failure(f"pushed {branch}, but origin holds no such branch")
if isinstance(head, Failure):
return head
number = forge.open_pull(on, branch, head, run)
if number is None:
if head is None:
if isinstance(pushed := push_cut_commit(clone, ref, branch, named, title), Failure):
return pushed
if isinstance(created := forge.create_pull(on, branch, base, title, run), Failure):
return created
number = forge.open_pull(on, branch, run)
if number is None or isinstance(number, Failure):
return number or Failure(f"opened a pull request for {branch}, but the forge lists none")
head = branch_head(branch, clone)
if head is None or isinstance(head, Failure):
return head or Failure(f"origin holds no branch {branch}")
number = forge.open_pull(on, branch, head, run) or Failure(f"opened a pull request for {branch}, but the forge lists none from origin at {head[:12]}")
if isinstance(number, Failure):
return number
if isinstance(passed := forge.checks_passed(on, number, head, run), Failure):
return passed
return forge.merge(on, number, run)
return forge.merge(on, number, head, run)
def branch_head(branch: str, clone: str) -> str | None | Failure:
+48 -21
View File
@@ -1,12 +1,14 @@
"""A cut's pull request steps on the forge origin lives on: gh on GitHub, tea elsewhere, as chunk_preflight tells them apart."""
"""A cut's pull request steps on the forge origin lives on: gh on GitHub, tea elsewhere, as chunk_preflight tells them apart.
Each step is pinned to head, the commit origin's release branch points at: the cut takes only a pull request from origin itself whose head is that commit, and the forge merges it only while its head is still that commit. So a fork's pull request from a branch of the same name, or a push to the branch after its checks passed, is never merged.
"""
import json
import subprocess
import time
import typing
from chunk_preflight.choices import Forge, pulls_command
from chunk_preflight.facts import open_pulls
from failure import Failure
from chunk_preflight.choices import Forge
# How long tea waits between two reads of the pull request's checks.
POLL_SECONDS = 10
@@ -27,13 +29,36 @@ def runner(cwd: str) -> Run:
return run
def open_pull(forge: Forge, branch: str, run: Run) -> str | None | Failure:
"""The number of branch's open pull request; None where it has none."""
listed = run(pulls_command(forge, branch))
if isinstance(listed, Failure):
return listed
found = open_pulls(listed, forge, branch)
return found[0].split()[0].removeprefix("#") if found else None
def gitea(run: Run, endpoint: str, *fields: str) -> typing.Any | Failure:
"""What Gitea's API answered at endpoint, parsed; with fields, `key=value` strings, a POST of them. tea api exits 0 on an HTTP error too, so an answer holding only Gitea's `message` is a Failure."""
answered = run(["tea", "api", *(["--method", "POST"] if fields else []), *[word for field in fields for word in ("--field", field)], endpoint])
if isinstance(answered, Failure) or not answered.strip():
return answered
try:
parsed = json.loads(answered)
except ValueError:
return Failure(f"tea api {endpoint} printed no JSON: {answered.strip()[:200]}")
if isinstance(parsed, dict) and "message" in parsed:
return Failure(f"tea api {endpoint}: {parsed['message']}")
return parsed
def open_pull(forge: Forge, branch: str, head: str, run: Run) -> str | None | Failure:
"""The number of the open pull request from origin's own branch whose head is head; None where there is none."""
if forge == "gh":
listed = run(["gh", "pr", "list", "--head", branch, "--json", "number,headRefOid,isCrossRepository", "--template", "{{range .}}{{.number}}\t{{.headRefOid}}\t{{.isCrossRepository}}\n{{end}}"])
if isinstance(listed, Failure):
return listed
rows = [line.split("\t") for line in listed.splitlines()]
return next((row[0] for row in rows if row[1:] == [head, "false"]), None)
# Gitea lists at most 50 a page; a release's pull request is among the newest.
pulls = gitea(run, "repos/{owner}/{repo}/pulls?state=open&limit=50")
if isinstance(pulls, Failure):
return pulls
try:
return next((str(pull["number"]) for pull in pulls if pull["head"]["ref"] == branch and pull["head"]["sha"] == head and pull["head"]["repo"]["full_name"] == pull["base"]["repo"]["full_name"]), None)
except (KeyError, TypeError):
return Failure(f"tea api listed pull requests in a shape the cut doesn't read: {str(pulls)[:200]}")
def create_pull(forge: Forge, branch: str, base: str, title: str, run: Run) -> Failure | None:
@@ -51,15 +76,14 @@ def checks_passed(forge: Forge, number: str, head: str, run: Run, sleep: typing.
return watched
return None
while True:
read = run(["tea", "api", f"repos/{{owner}}/{{repo}}/commits/{head}/status"])
if isinstance(read, Failure):
return read
# Gitea reads a commit with no status as pending, with total_count 0.
status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status")
if isinstance(status, Failure):
return status
try:
status = json.loads(read)
count, state = status["total_count"], status["state"]
except (ValueError, KeyError, TypeError):
return Failure(f"tea api printed no commit status for {head}: {read.strip()[:200]}")
except (KeyError, TypeError):
return Failure(f"tea api printed no commit status for {head}: {str(status)[:200]}")
# Gitea reads a commit with no status as pending, with total_count 0.
if count == 0 or state == "success":
return None
if state != "pending":
@@ -67,8 +91,11 @@ def checks_passed(forge: Forge, number: str, head: str, run: Run, sleep: typing.
sleep(POLL_SECONDS)
def merge(forge: Forge, number: str, run: Run) -> Failure | None:
# GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title.
command = ["gh", "pr", "merge", number, "--rebase"] if forge == "gh" else ["tea", "pulls", "merge", "--style", "fast-forward-only", number]
merged = run(command)
def merge(forge: Forge, number: str, head: str, run: Run) -> Failure | None:
"""Merge pull request number fast-forward only, refused by the forge where its head is no longer head."""
if forge == "gh":
# GitHub has no fast-forward-only merge. A rebase merge of a branch already on top of main is the nearest, though it may give the commit a new hash, so the cut finds it on main by its title.
merged = run(["gh", "pr", "merge", number, "--rebase", "--match-head-commit", head])
else:
merged = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", "Do=fast-forward-only", f"head_commit_id={head}")
return merged if isinstance(merged, Failure) else None
+56 -15
View File
@@ -156,24 +156,30 @@ def git(*words):
return subprocess.run(["git", "--git-dir", state["origin"], *words], capture_output=True, text=True)
def pull(number):
return next(found for found in state["pulls"] if str(found["number"]) == number)
def merge(number):
head = git("rev-parse", "refs/heads/" + pull(number)["head"]).stdout.strip()
def merge(number, guard):
head = pull(number)["sha"]
if head != guard:
save()
sys.exit("head commit changed")
if git("merge-base", "--is-ancestor", "refs/heads/main", head).returncode:
save()
sys.exit("Not possible to fast-forward")
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 == ["pulls", "list", "--fields", "index,head,url", "--output", "tsv"]:
print("index\thead\turl")
for found in opened:
print(f"{found['number']}\t{found['head']}\thttps://forge/pulls/{found['number']}")
elif forge == "gh" and args[:3] == ["pr", "list", "--head"]:
if 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"], "sha": found["sha"], "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"]:
for found in opened:
if found["head"] == args[3]:
print(f"{found['number']}\thttps://forge/pull/{found['number']}")
print(f"{found['number']}\t{found['sha']}\t{str(found['fork']).lower()}")
elif args[:2] in (["pulls", "create"], ["pr", "create"]):
state["pulls"].append({"number": len(state["pulls"]) + 1, "head": args[args.index("--head") + 1], "state": "open"})
head = args[args.index("--head") + 1]
if any(found["head"] == head and not found["fork"] for found in opened):
save()
sys.exit("pull request already exists for these targets")
state["pulls"].append({"number": len(state["pulls"]) + 1, "head": head, "sha": git("rev-parse", "refs/heads/" + head).stdout.strip(), "fork": False, "state": "open"})
elif forge == "tea" and args[0] == "api" and args[1].endswith("/status"):
checks = state["checks"]
print(json.dumps({"state": "pending" if checks == "none" else checks, "total_count": 0 if checks == "none" else 1}))
@@ -184,10 +190,14 @@ elif forge == "gh" and args[:2] == ["pr", "checks"]:
if state["checks"] == "failure":
save()
sys.exit("lint\tfail")
elif args[:3] == ["pulls", "merge", "--style"] and args[3] == "fast-forward-only":
merge(args[4])
elif args[:2] == ["pr", "merge"] and args[3] == "--rebase":
merge(args[2])
elif forge == "tea" and args[:5] == ["api", "--method", "POST", "--field", "Do=fast-forward-only"] and args[5] == "--field" and args[7].endswith("/merge"):
try:
merge(args[7].split("/")[-2], args[6].removeprefix("head_commit_id="))
except SystemExit as refused:
# Gitea answers an error with a message, and tea api exits 0 all the same.
print(json.dumps({"message": str(refused)}))
elif args[:2] == ["pr", "merge"] and args[3:5] == ["--rebase", "--match-head-commit"]:
merge(args[2], args[5])
else:
save()
sys.exit("unexpected call")
@@ -264,7 +274,7 @@ class Cut(unittest.TestCase):
self.assertIn("v0.2.0", ran.stdout)
calls = self.forge_state()["calls"]
self.assertIn(["tea", "pulls", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls])
self.assertIn(["tea", "pulls", "merge", "--style", "fast-forward-only", "1"], calls)
self.assertIn("Do=fast-forward-only", [word for call in calls if call[-1].endswith("/pulls/1/merge") for word in call])
self.assertEqual(self.git(self.clone, "rev-parse", "HEAD"), head, "the clone's own checkout stays where it was")
self.assertEqual(self.git(self.clone, "status", "--porcelain"), "")
@@ -275,7 +285,7 @@ class Cut(unittest.TestCase):
self.assert_cut(ran)
calls = self.forge_state()["calls"]
self.assertIn(["gh", "pr", "create", "--head", "release-0.2.0", "--base", "main"], [call[:7] for call in calls])
self.assertIn(["gh", "pr", "merge", "1", "--rebase"], calls)
self.assertIn(["gh", "pr", "merge", "1", "--rebase"], [call[:5] for call in calls])
def test_refuses_changing_nothing_while_the_next_release_holds_an_item(self):
self.commit({"todo.md": TODO + ROW.format(id=1, release="0.2.0") + ROW.format(id=2, release="0.3.0")}, "Plan item 1 again")
@@ -332,6 +342,37 @@ class Cut(unittest.TestCase):
self.assert_cut(self.cut())
self.assertEqual(len(self.forge_state()["pulls"]), 1, "the rerun finds the merged commit, so it opens no second pull request")
def test_merges_only_origins_own_pull_request_where_a_fork_opened_one_from_a_branch_of_the_same_name(self):
for forge_name in ("tea", "gh"):
with self.subTest(forge_name):
self.setUp()
if forge_name == "gh":
self.git(self.clone, "remote", "set-url", "origin", "https://github.com/o/r.git")
self.git(self.clone, "config", f"url.{self.origin}.insteadOf", "https://github.com/o/r.git")
self.set_checks("failure")
self.cut()
self.git(self.clone, "switch", "-q", "-c", "fork", "origin/release-0.2.0")
self.commit({"settings.json": "{\"hooks\": \"evil\"}\n"}, "Cut release 0.2.0")
self.git(self.clone, "push", "-q", "origin", "fork:refs/forks/release-0.2.0")
self.git(self.clone, "switch", "-q", "main")
state = self.forge_state()
fork = {"number": 9, "head": "release-0.2.0", "sha": self.git(self.clone, "rev-parse", "fork").strip(), "fork": True, "state": "open"}
self.forge_state({**state, "pulls": [fork, *state["pulls"]], "checks": "success"})
self.assert_cut(self.cut())
self.assertEqual([found["state"] for found in self.forge_state()["pulls"]], ["open", "merged"])
self.assertNotIn("evil", self.origin_git("show", "main:settings.json") if "settings.json" in self.origin_git("ls-tree", "--name-only", "main") else "")
def test_stops_where_origins_open_pull_request_has_another_head_than_the_branch(self):
self.set_checks("failure")
self.cut()
state = self.forge_state()
state["pulls"][0]["sha"] = "0" * 40
self.forge_state({**state, "checks": "success"})
ran = self.cut()
self.assertEqual(ran.returncode, 1)
self.assertIn("already exists", ran.stderr)
self.assertEqual(self.origin_git("log", "-1", "--format=%s", "main").strip(), "Release review of 0.2.0")
class ChecksPassed(unittest.TestCase):
def test_waits_on_tea_while_a_check_is_pending_and_takes_none_as_passed(self):
+1 -1
View File
@@ -6,8 +6,8 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from release import newest_tag, tagged
from test_env import isolated_env
from release import newest_tag, tagged
class NewestTag(unittest.TestCase):
+1 -1
View File
@@ -34,7 +34,7 @@ The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the
## deploy: `deploy-release --cut` cuts a release through a pull request merged fast-forward only, then tags the merged commit and moves `~/.claude` to it; the human runs it
2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. `main` on the remote takes no push and merges only by fast-forward, so a cut that commits on `main` and pushes no longer works. The tool cuts only the release `chunk-preflight` would call ready to cut, through `bin/release_standing.py`, so the two never disagree on which release is next or whether it is ready; the version is that release's, never the tool's choice. It builds the cut commit in a worktree of its own, so the clone's checkout stays as it is. It finds the merged commit on `main` by its title, `Cut release <version>`, since GitHub's nearest merge, a rebase merge, may give the commit a new hash. Each step first checks whether an earlier run did it, so a rerun continues. Releases stay the human's, so the human runs it, and the forge credentials stay theirs. Valid while `main` takes changes only through a pull request.
2026-11-08, lilleman, todo item 271. Serves goal 1.5 and goal 2. `main` on the remote takes no push and merges only by fast-forward, so a cut that commits on `main` and pushes no longer works. The tool cuts only the release `chunk-preflight` would call ready to cut, through `bin/release_standing.py`, so the two never disagree on which release is next or whether it is ready; the version is that release's, never the tool's choice. It builds the cut commit in a worktree of its own, so the clone's checkout stays as it is. It finds the merged commit on `main` by its title, `Cut release <version>`, since GitHub's nearest merge, a rebase merge, may give the commit a new hash. It takes only a pull request from origin's own branch whose head is the commit that branch points at, and has the forge merge it only while its head is still that commit, so a fork's pull request from a branch of the same name, or a push after the checks passed, is never merged and deployed. Each step first checks whether an earlier run did it, so a rerun continues. Releases stay the human's, so the human runs it, and the forge credentials stay theirs. Valid while `main` takes changes only through a pull request.
## larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything
+1 -1
View File
@@ -142,7 +142,7 @@ DRY, in `principles/technical-principles.md`: the list is copied by hand, and se
On 2026-11-08 the human answered yes, with a reserved list: a worker takes its own recommendation on a choice no rule reserves for the human, records it in the item or a decision, and interrupts only for a reserved choice or an ask it has no recommendation for. The reserved choices are a release, a change to the ladder or its steps, and a goal, listed in one place.
92 of the 255 interrupts in loop-claude's archive, on 2026-11-08, carry the worker's recommendation, such as "I recommend shipping". The judge answered 16 asks itself, as `Verdict: quoted`, from the records. A finished chunk with an interrupt took a median 7.1 h, against 0.44 h without one. The change touches the interrupt contract in `CLAUDE.md` → "Ask, don't guess" and the judge's prompt in `bin/loop_claude/cycle/judge.py`. Watch goal 1.2's counter-signal afterwards: decisions the human reverses.
92 of the 255 interrupts in loop-claude's archive, on 2026-11-08, carry the worker's recommendation, such as "I recommend shipping". The judge answered 16 asks itself, as `Verdict: quoted`, from the records. A finished chunk with an interrupt took a median 7.1 h, against 0.44 h without one. The change touches the interrupt contract in `CLAUDE.md` → "Working loop", "Ask, don't guess" and the judge's prompt in `bin/loop_claude/cycle/judge.py`. Watch goal 1.2's counter-signal afterwards: decisions the human reverses.
### 105. Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.