← Back to Pull requests

feat(life): sdlc release, the normal path to a published image (a2357) #347

Merged
fatherlinux merged 7 files (2074 lines) on Dec 04, 2026 22:46 UTC
View on GitHub
fatherlinux fatherlinux commented on Dec 04, 2026 20:40 UTC
Author

Phase 4 of docs/lifecycle.md: sdlc release, replacing josui-land-release and every hand dispatch.

Seven idempotent steps on the lifecycle runner, each in its own container with only the credentials it declares:

  • identify: origin parsed strictly (github.com/<owner>/<name>), confirmed by GET /repos; a name that does not resolve is a 2 at once. An agent (JOSUI_NAME, now passed into step containers by name) must give --item.

  • preflight: on the default branch at origin's head; version from --version, or derived from the Conventional Commits since the newest vX.Y.Z tag behind HEAD (breaking: MAJOR, MINOR before 1.0.0 per R1; feat: MINOR; else PATCH); newer than the newest tag; _bump.release_edits run on the tree so its refusal (empty Unreleased included) is seen before anything is dispatched.

  • lease: the Desk's POST /v1/releases; a 409 is ours only if GET /v1/releases shows this repo, version and item in flight, else a 1. No [desk] in the hosts file prints UNLEASED: the Desk will adopt this release.

  • dispatch: ci.yml with version, item, includes; the run is the one new workflow_dispatch run on this head that was not listed just before (no clock to skew). Two is a 2; a failed run is a 1 naming its jobs.

  • pr: the release PR by head branch ashigaru/release-X.Y.Z, this repo, into the default branch, authored by the Ashigaru App (never a title search); then the required checks (rulesets and classic protection), reading check runs and statuses. A failure is a 1 that prints resume: sdlc release --resume owner/repo#N.

  • merged: squash, pinned to the head whose checks passed. Refused (1) when the default branch moved after the cut, naming what landed, so an entry merged meanwhile never goes under a section about to be frozen.

  • image: the one push run on the merge commit passes; the tag names the merge commit (annotated tags followed); the GitHub Release exists; each image's X.Y.Z and latest are one digest that verifies against the fleet key. The last line is {"repo","version","commit","digest","release_pr"}.
  • --resume owner/repo#N reads the version from the release PR's branch, so a release started on one machine finishes on another; a closed-unmerged release PR counts as not cut.

    Tests: tests/test_life_release.py (77, fake forge and fake Desk) covers each refusal, the ambiguous-run 2, the App-author check, a failed-check stop with its resume line, the resume path, version derivation and the landing checks. tests/test_host_contract.sh pins that JOSUI_NAME reaches a step only when set.

    🤖 Generated with Claude Code

    https://claude.ai/code/session_01R7Y1jgFUuEitySo4qtRTaQ

    Ashigaru-Item: a2357

    Diff: 2074 lines (+2069 / -5) across 7 files Reviewer: fatherlinux Review duration: 126m
    All Vouch review confidence checks passed
    Residual risk 0.10 = Change Risk (0.66) × (1 − Review Confidence (0.85)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.66 · 2074 lines diff across 7 files
    0.66
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.93 · 5 substantive comment(s)
    0.93
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    84%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Real PR Conversation Timeline
    18 items
    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 20:42 UTC
    Code Review
    sdlc_jobs/life/release.py:1
    @@ -0,0 +1,744 @@
    +"""`sdlc release`: the normal path to a published image (docs/lifecycle.md).
    +
    +Replaces josui-land-release and every hand dispatch. Seven steps, each in a
    +container of its own with only the credentials it declares, and each
    +idempotent: it asks the forge whether its result is already there and goes on
    +when it is, so running the command again is how it resumes.
    +
    +    identify   origin's URL, parsed strictly, confirmed by GET /repos
    +    preflight  the default branch at origin's head, a non-empty Unreleased, a
    +               version newer than the newest tag, and `_bump.release_edits`'
    +               refusal seen here before anything is dispatched
    +    lease      the Desk's release lease, the one its own cuts take
    +    dispatch   ci.yml with version, item and includes; the one run it started
    +    pr         the App's release PR on ashigaru/release-X.Y.Z, and its
    +               required checks
    +    merged     squash, pinned to the head whose checks passed
    +    image      the push run on the merge, the tag on the merge commit, the
    +               GitHub Release, and each image's X.Y.Z and latest one signed digest
    +
    +Nothing passes from one step to the next but the forge. The version is the
    +same in every step because it is worked out the same way: `--version`; else
    +the release PR `--resume` names; else the Conventional Commits from the newest
    +vX.Y.Z tag behind this clone's HEAD to HEAD, which a tag made on the release's
    +own merge commit is never behind.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import os
    +import re
    +import subprocess
    +import tempfile
    +import time
    +import urllib.parse
    +from collections.abc import Callable, Mapping, Sequence
    +from dataclasses import dataclass
    +from datetime import UTC, datetime
    +from pathlib import Path
    +from typing import Any
    +
    +from sdlc_jobs import _bump
    +from sdlc_jobs._core import FLEET_PUBLIC_KEY, ITEM, SEMVER, CannotRunError, images, parse_includes
    +from sdlc_jobs._github import APP_LOGIN, Api, ApiError, GitHub
    +from sdlc_jobs.life import _hosts, _runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait, wait_for
    +
    +COMMAND = "release"
    +WORKFLOW = "ci.yml"
    +BRANCH = "ashigaru/release-"
    +REPO_ROOT = Path("/repo")
    +# A check passes as the Desk's cuts judge it (ashigaru automerge.PASSING).
    +PASSING = ("success", "skipped", "neutral")
    +_NOT_FOUND = 404
    +_REFUSED = (405, 409)
    +_CONFLICT = 409
    +# origin, and nothing else: github.com/<owner>/<name> over https or ssh.
    +_ORIGIN = re.compile(
    +    r"(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)"
    +    r"(?P<owner>[A-Za-z0-9][A-Za-z0-9-]*)/(?P<name>[A-Za-z0-9._-]+?)(?:\.git)?/?"
    +)
    +_TAG = re.compile(rf"v({SEMVER.pattern})")
    +# A Conventional Commit subject: type, optional scope, optional `!`, colon.
    +_SUBJECT = re.compile(r"(?P<type>[A-Za-z]+)(?:\([^)]*\))?(?P<bang>!)?:\s")
    +_BREAKING = re.compile(r"^BREAKING[ -]CHANGE:", re.MULTILINE)
    +# What a commit asks of the version, least to most.
    +_PATCH, _FEATURE, _BREAKS = 0, 1, 2
    +SKOPEO_SECONDS = 120
    +COSIGN_SECONDS = 300
    +
    +# How long each wait gives the forge, and how often it asks.
    +WAITS = {
    +    "run": (300.0, 10.0),  # the dispatch's run to appear
    +    "dispatch": (1800.0, 20.0),  # the dispatch's run to finish: the release PR
    +    "checks": (3600.0, 30.0),  # the release PR's required checks
    +    "landing": (3600.0, 30.0),  # the push run on the merge commit
    +}
    +
    +
    +# --- what a step reaches the world through; the suite replaces each -----------
    +
    +
    +def connect(run: Run) -> Api:
    +    """GitHub as the github credential sees it."""
    +    return GitHub(run.credential("github"))
    +
    +
    +def git(*args: str) -> str | None:
    +    """git's stdout in the clone bin/sdlc mounted, or None when git says no."""
    +    proc = subprocess.run(
    +        ["git", "-C", str(REPO_ROOT), *args], capture_output=True, text=True, check=False
    +    )
    +    return proc.stdout if proc.returncode == 0 else None
    +
    +
    +def desk(url: str, token: str) -> tuple[Api, str]:
    +    """The Desk's API at `url`, and the path it is served under.
    +
    +    The same REST client GitHub's calls use: one host, https only, and a
    +    redirect to another host never carries the token.
    +    """
    +    parts = urllib.parse.urlsplit(url)
    +    if parts.scheme != "https" or not parts.netloc:
    +        raise CannotRunError(f"the Desk is reached over https only, not {url}")
    +    return GitHub(token, host=parts.netloc), parts.path.rstrip("/")
    +
    +
    +def digest_of(ref: str) -> str | None:
    +    """The digest `ref` names in its registry, or None when it names nothing."""
    +    proc = subprocess.run(
    +        ["skopeo", "inspect", "--no-tags", "--format", "{{.Digest}}", f"docker://{ref}"],
    +        capture_output=True,
    +        text=True,
    +        check=False,
    +        timeout=SKOPEO_SECONDS,
    +    )
    +    if proc.returncode == 0:
    +        return proc.stdout.strip() or None
    +    if "manifest unknown" in proc.stderr or "not found" in proc.stderr.lower():
    +        return None
    +    raise CannotRunError(f"skopeo could not read {ref}: {proc.stderr.strip()[:300]}")
    +
    +
    +def signed(ref: str) -> bool:
    +    """Does `ref` (by digest) carry the fleet key's signature, as promote verifies it?"""
    +    with tempfile.TemporaryDirectory() as scratch:
    +        pub = Path(scratch) / "fleet.pub"
    +        pub.write_text(FLEET_PUBLIC_KEY)
    +        argv = ["cosign", "verify", "--insecure-ignore-tlog", "--key", str(pub), ref]
    +        proc = subprocess.run(
    +            argv, capture_output=True, text=True, check=False, timeout=COSIGN_SECONDS
    +        )
    +    return proc.returncode == 0
    +
    +
    +ENV: Mapping[str, str] = os.environ
    +TIMER: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
    +
    +
    +def today() -> str:
    +    """The CHANGELOG heading's date, UTC's, as the App's release commit writes it."""
    +    return datetime.now(UTC).date().isoformat()
    +
    +
    +# --- what every step works out the same way ------------------------------------
    +
    +
    +@dataclass
    +class Asked:
    +    """The person's arguments, checked."""
    +
    +    version: str | None
    +    item: str | None
    +    includes: list[str]
    +    resume: str | None
    +
    +
    +@dataclass
    +class Release:
    +    """What every step knows of the release, read back from the forge."""
    +
    +    api: Api
    +    repo: str
    +    default: str
    +    head: str
    +    version: str
    +    asked: Asked
    +
    +    @property
    +    def branch(self) -> str:
    +        return f"{BRANCH}{self.version}"
    +
    +    @property
    +    def tag(self) -> str:
    +        return f"v{self.version}"
    +
    +    def url(self, path: str = "") -> str:
    +        return f"https://github.com/{self.repo}{path}"
    +
    +
    +def origin_repo() -> str:
    +    """owner/name from origin's URL, parsed strictly, or a 2."""
    +    url = (git("remote", "get-url", "origin") or "").strip()
    +    m = _ORIGIN.fullmatch(url)
    +    if not m:
    +        raise CannotRunError(f"origin is not github.com/<owner>/<name>: {url or 'no origin'}")
    +    return f"{m['owner']}/{m['name']}"
    +
    +
    +def identity(api: Api) -> tuple[str, str]:
    +    """(owner/name, default branch) of origin, confirmed by GitHub, or a 2."""
    +    repo = origin_repo()
    +    try:
    +        found = api.request("GET", f"/repos/{repo}")
    +    except ApiError as err:
    +        raise CannotRunError(f"{repo} does not resolve on GitHub: {err}") from err
    +    name = (found or {}).get("full_name")
    +    default = (found or {}).get("default_branch")
    +    if not isinstance(name, str) or name.lower() != repo.lower() or not isinstance(default, str):
    +        raise CannotRunError(f"GitHub answers {name!r} for {repo}, not that repo")
    +    return name, default
    +
    +
    +def local_head() -> str:
    +    head = (git("rev-parse", "HEAD") or "").strip()
    +    if not re.fullmatch(r"[0-9a-f]{40}", head):
    +        raise CannotRunError("this clone has no HEAD commit")
    +    return head
    +
    +
    +def triple(version: str) -> tuple[int, int, int]:
    +    a, b, c = (int(p) for p in version.split("."))
    +    return a, b, c
    +
    +
    +def tags(api: Api, repo: str) -> list[str]:
    +    """Every vX.Y.Z tag's version, newest first."""
    +    names = [t.get("name") for t in api.pages(f"/repos/{repo}/tags") if isinstance(t, dict)]
    +    found = [m[1] for n in names if isinstance(n, str) and (m := _TAG.fullmatch(n))]
    +    return sorted(set(found), key=triple, reverse=True)
    +
    +
    +def bump(version: str, messages: Sequence[str]) -> str:
    +    """The next version after `version` for these commit messages (constitution R1).
    +
    +    A breaking change bumps MAJOR, or MINOR before 1.0.0; a feat bumps MINOR;
    +    anything else PATCH.
    +    """
    +    major, minor, patch = triple(version)
    +    level = _PATCH
    +    for message in messages:
    +        m = _SUBJECT.match(message)
    +        if (m and m["bang"]) or _BREAKING.search(message):
    +            level = max(level, _BREAKS)
    +        elif m and m["type"].lower() == "feat":
    +            level = max(level, _FEATURE)
    +    if level == _BREAKS and major > 0:
    +        return f"{major + 1}.0.0"
    +    if level >= _FEATURE:
    +        return f"{major}.{minor + 1}.0"
    +    return f"{major}.{minor}.{patch + 1}"
    +
    +
    +def behind_head(api: Api, repo: str, head: str) -> tuple[str, list[str]] | None:
    +    """(version, messages since it) for the newest vX.Y.Z tag HEAD has; None when it has none."""
    +    for version in tags(api, repo):

    HIGH (Performance Check): behind_head makes a separate GitHub compare request for each tag until it finds one behind HEAD. When newer tags are not reachable from the clone's HEAD, deriving a version makes a linear number of API round trips, which can become slow or hit rate limits as the tag history grows.

    Suggestion: Determine tag ancestry with a batched or local Git graph operation where possible, or use an API strategy that avoids one compare request per candidate tag.

    Evidence:

    for version in tags(api, repo):
        compared = api.request("GET", f"/repos/{repo}/compare/v{version}...{head}")
        if (compared or {}).get("status") in ("ahead", "identical"):
            commits = compared.get("commits") or []
            return version, [str((c.get("commit") or {}).get("message", "")) for c in commits]
    

    <!-- gatehouse agent=performance confidence=90 votes=2/3 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 20:42 UTC
    Reviewer

    Gatehouse found 1 issues (1 high)

    Full review.

    8 finding(s) dropped: their evidence is not in the diff.

    <!-- gatehouse review complete -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 20:52 UTC
    Code Review
    docs/lifecycle.md:1
    @@ -260,7 +260,9 @@ Replaces `josui-land-release` and every hand dispatch.
     Inputs: run from a clone of the repo. `--version X.Y.Z` (default: derived),

    HIGH (Documentation): The documented --until values omit newly supported release steps. The release step list now includes identify, preflight, lease, and dispatch, and the tests confirm that --until lease is accepted, but the inputs section still lists only pr|merged|image.

    Suggestion: Update the --until documentation to list all accepted step names, or clarify that the listed values are examples rather than an exhaustive set.

    Evidence:

    Inputs: run from a clone of the repo. `--version X.Y.Z` (default: derived),
    `--item aN`, `--includes aX,aY`, `--until pr|merged|image`.
    
    Steps (`identify`, `preflight`, `lease`, `dispatch`, `pr`, `merged`,
    `image`)
    

    <!-- gatehouse agent=docs confidence=98 votes=2/3 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 20:52 UTC
    Reviewer

    Gatehouse found 1 issues (1 high)

    Full review.

    4 finding(s) dropped: their evidence is not in the diff.

    <!-- gatehouse review complete -->

    fatherlinux fatherlinux commented on code on Dec 04, 2026 21:08 UTC
    Code Review
    docs/lifecycle.md:1
    @@ -260,7 +260,9 @@ Replaces `josui-land-release` and every hand dispatch.
     Inputs: run from a clone of the repo. `--version X.Y.Z` (default: derived),

    Fixed in 35ca946

    The release section now says --until <step> takes any step listed below, most often pr, merged or image.

    fatherlinux fatherlinux commented on code on Dec 04, 2026 21:08 UTC
    Code Review
    sdlc_jobs/life/release.py:1
    @@ -0,0 +1,744 @@
    +"""`sdlc release`: the normal path to a published image (docs/lifecycle.md).
    +
    +Replaces josui-land-release and every hand dispatch. Seven steps, each in a
    +container of its own with only the credentials it declares, and each
    +idempotent: it asks the forge whether its result is already there and goes on
    +when it is, so running the command again is how it resumes.
    +
    +    identify   origin's URL, parsed strictly, confirmed by GET /repos
    +    preflight  the default branch at origin's head, a non-empty Unreleased, a
    +               version newer than the newest tag, and `_bump.release_edits`'
    +               refusal seen here before anything is dispatched
    +    lease      the Desk's release lease, the one its own cuts take
    +    dispatch   ci.yml with version, item and includes; the one run it started
    +    pr         the App's release PR on ashigaru/release-X.Y.Z, and its
    +               required checks
    +    merged     squash, pinned to the head whose checks passed
    +    image      the push run on the merge, the tag on the merge commit, the
    +               GitHub Release, and each image's X.Y.Z and latest one signed digest
    +
    +Nothing passes from one step to the next but the forge. The version is the
    +same in every step because it is worked out the same way: `--version`; else
    +the release PR `--resume` names; else the Conventional Commits from the newest
    +vX.Y.Z tag behind this clone's HEAD to HEAD, which a tag made on the release's
    +own merge commit is never behind.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import os
    +import re
    +import subprocess
    +import tempfile
    +import time
    +import urllib.parse
    +from collections.abc import Callable, Mapping, Sequence
    +from dataclasses import dataclass
    +from datetime import UTC, datetime
    +from pathlib import Path
    +from typing import Any
    +
    +from sdlc_jobs import _bump
    +from sdlc_jobs._core import FLEET_PUBLIC_KEY, ITEM, SEMVER, CannotRunError, images, parse_includes
    +from sdlc_jobs._github import APP_LOGIN, Api, ApiError, GitHub
    +from sdlc_jobs.life import _hosts, _runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait, wait_for
    +
    +COMMAND = "release"
    +WORKFLOW = "ci.yml"
    +BRANCH = "ashigaru/release-"
    +REPO_ROOT = Path("/repo")
    +# A check passes as the Desk's cuts judge it (ashigaru automerge.PASSING).
    +PASSING = ("success", "skipped", "neutral")
    +_NOT_FOUND = 404
    +_REFUSED = (405, 409)
    +_CONFLICT = 409
    +# origin, and nothing else: github.com/<owner>/<name> over https or ssh.
    +_ORIGIN = re.compile(
    +    r"(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)"
    +    r"(?P<owner>[A-Za-z0-9][A-Za-z0-9-]*)/(?P<name>[A-Za-z0-9._-]+?)(?:\.git)?/?"
    +)
    +_TAG = re.compile(rf"v({SEMVER.pattern})")
    +# A Conventional Commit subject: type, optional scope, optional `!`, colon.
    +_SUBJECT = re.compile(r"(?P<type>[A-Za-z]+)(?:\([^)]*\))?(?P<bang>!)?:\s")
    +_BREAKING = re.compile(r"^BREAKING[ -]CHANGE:", re.MULTILINE)
    +# What a commit asks of the version, least to most.
    +_PATCH, _FEATURE, _BREAKS = 0, 1, 2
    +SKOPEO_SECONDS = 120
    +COSIGN_SECONDS = 300
    +
    +# How long each wait gives the forge, and how often it asks.
    +WAITS = {
    +    "run": (300.0, 10.0),  # the dispatch's run to appear
    +    "dispatch": (1800.0, 20.0),  # the dispatch's run to finish: the release PR
    +    "checks": (3600.0, 30.0),  # the release PR's required checks
    +    "landing": (3600.0, 30.0),  # the push run on the merge commit
    +}
    +
    +
    +# --- what a step reaches the world through; the suite replaces each -----------
    +
    +
    +def connect(run: Run) -> Api:
    +    """GitHub as the github credential sees it."""
    +    return GitHub(run.credential("github"))
    +
    +
    +def git(*args: str) -> str | None:
    +    """git's stdout in the clone bin/sdlc mounted, or None when git says no."""
    +    proc = subprocess.run(
    +        ["git", "-C", str(REPO_ROOT), *args], capture_output=True, text=True, check=False
    +    )
    +    return proc.stdout if proc.returncode == 0 else None
    +
    +
    +def desk(url: str, token: str) -> tuple[Api, str]:
    +    """The Desk's API at `url`, and the path it is served under.
    +
    +    The same REST client GitHub's calls use: one host, https only, and a
    +    redirect to another host never carries the token.
    +    """
    +    parts = urllib.parse.urlsplit(url)
    +    if parts.scheme != "https" or not parts.netloc:
    +        raise CannotRunError(f"the Desk is reached over https only, not {url}")
    +    return GitHub(token, host=parts.netloc), parts.path.rstrip("/")
    +
    +
    +def digest_of(ref: str) -> str | None:
    +    """The digest `ref` names in its registry, or None when it names nothing."""
    +    proc = subprocess.run(
    +        ["skopeo", "inspect", "--no-tags", "--format", "{{.Digest}}", f"docker://{ref}"],
    +        capture_output=True,
    +        text=True,
    +        check=False,
    +        timeout=SKOPEO_SECONDS,
    +    )
    +    if proc.returncode == 0:
    +        return proc.stdout.strip() or None
    +    if "manifest unknown" in proc.stderr or "not found" in proc.stderr.lower():
    +        return None
    +    raise CannotRunError(f"skopeo could not read {ref}: {proc.stderr.strip()[:300]}")
    +
    +
    +def signed(ref: str) -> bool:
    +    """Does `ref` (by digest) carry the fleet key's signature, as promote verifies it?"""
    +    with tempfile.TemporaryDirectory() as scratch:
    +        pub = Path(scratch) / "fleet.pub"
    +        pub.write_text(FLEET_PUBLIC_KEY)
    +        argv = ["cosign", "verify", "--insecure-ignore-tlog", "--key", str(pub), ref]
    +        proc = subprocess.run(
    +            argv, capture_output=True, text=True, check=False, timeout=COSIGN_SECONDS
    +        )
    +    return proc.returncode == 0
    +
    +
    +ENV: Mapping[str, str] = os.environ
    +TIMER: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
    +
    +
    +def today() -> str:
    +    """The CHANGELOG heading's date, UTC's, as the App's release commit writes it."""
    +    return datetime.now(UTC).date().isoformat()
    +
    +
    +# --- what every step works out the same way ------------------------------------
    +
    +
    +@dataclass
    +class Asked:
    +    """The person's arguments, checked."""
    +
    +    version: str | None
    +    item: str | None
    +    includes: list[str]
    +    resume: str | None
    +
    +
    +@dataclass
    +class Release:
    +    """What every step knows of the release, read back from the forge."""
    +
    +    api: Api
    +    repo: str
    +    default: str
    +    head: str
    +    version: str
    +    asked: Asked
    +
    +    @property
    +    def branch(self) -> str:
    +        return f"{BRANCH}{self.version}"
    +
    +    @property
    +    def tag(self) -> str:
    +        return f"v{self.version}"
    +
    +    def url(self, path: str = "") -> str:
    +        return f"https://github.com/{self.repo}{path}"
    +
    +
    +def origin_repo() -> str:
    +    """owner/name from origin's URL, parsed strictly, or a 2."""
    +    url = (git("remote", "get-url", "origin") or "").strip()
    +    m = _ORIGIN.fullmatch(url)
    +    if not m:
    +        raise CannotRunError(f"origin is not github.com/<owner>/<name>: {url or 'no origin'}")
    +    return f"{m['owner']}/{m['name']}"
    +
    +
    +def identity(api: Api) -> tuple[str, str]:
    +    """(owner/name, default branch) of origin, confirmed by GitHub, or a 2."""
    +    repo = origin_repo()
    +    try:
    +        found = api.request("GET", f"/repos/{repo}")
    +    except ApiError as err:
    +        raise CannotRunError(f"{repo} does not resolve on GitHub: {err}") from err
    +    name = (found or {}).get("full_name")
    +    default = (found or {}).get("default_branch")
    +    if not isinstance(name, str) or name.lower() != repo.lower() or not isinstance(default, str):
    +        raise CannotRunError(f"GitHub answers {name!r} for {repo}, not that repo")
    +    return name, default
    +
    +
    +def local_head() -> str:
    +    head = (git("rev-parse", "HEAD") or "").strip()
    +    if not re.fullmatch(r"[0-9a-f]{40}", head):
    +        raise CannotRunError("this clone has no HEAD commit")
    +    return head
    +
    +
    +def triple(version: str) -> tuple[int, int, int]:
    +    a, b, c = (int(p) for p in version.split("."))
    +    return a, b, c
    +
    +
    +def tags(api: Api, repo: str) -> list[str]:
    +    """Every vX.Y.Z tag's version, newest first."""
    +    names = [t.get("name") for t in api.pages(f"/repos/{repo}/tags") if isinstance(t, dict)]
    +    found = [m[1] for n in names if isinstance(n, str) and (m := _TAG.fullmatch(n))]
    +    return sorted(set(found), key=triple, reverse=True)
    +
    +
    +def bump(version: str, messages: Sequence[str]) -> str:
    +    """The next version after `version` for these commit messages (constitution R1).
    +
    +    A breaking change bumps MAJOR, or MINOR before 1.0.0; a feat bumps MINOR;
    +    anything else PATCH.
    +    """
    +    major, minor, patch = triple(version)
    +    level = _PATCH
    +    for message in messages:
    +        m = _SUBJECT.match(message)
    +        if (m and m["bang"]) or _BREAKING.search(message):
    +            level = max(level, _BREAKS)
    +        elif m and m["type"].lower() == "feat":
    +            level = max(level, _FEATURE)
    +    if level == _BREAKS and major > 0:
    +        return f"{major + 1}.0.0"
    +    if level >= _FEATURE:
    +        return f"{major}.{minor + 1}.0"
    +    return f"{major}.{minor}.{patch + 1}"
    +
    +
    +def behind_head(api: Api, repo: str, head: str) -> tuple[str, list[str]] | None:
    +    """(version, messages since it) for the newest vX.Y.Z tag HEAD has; None when it has none."""
    +    for version in tags(api, repo):

    Not a bug: the loop is not linear in tag history in practice. It walks tags newest first and stops at the first one HEAD is ahead of. The only tag that can be newer than HEAD is the one this release made on its own merge commit, so derivation costs one compare call, or two once the release has landed. It never walks the history. A local git describe would depend on the clone having fetched its tags, and the API is the forge's own answer.

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 21:10 UTC
    Reviewer

    Gatehouse found no issues.

    Reviewed 1 commit since 222c18a (incremental).

    <!-- gatehouse review complete -->

    fatherlinux fatherlinux commented on Dec 04, 2026 21:39 UTC
    Author

    Second-seat adversarial check of sdlc release at 35ca946 (read-only: sdlc_jobs/life/release.py, _runner.py, the spec in docs/lifecycle.md, compared against the Desk's cuts.refusal/_merge). Two real findings, a few low ones, and the rest held.

    Findings

    1. Re-running for a version that already shipped exits 0 as "landed" (high). preflight, lease and dispatch share done=started, and started is true once vX.Y.Z is tagged or its PR merged. So sdlc release --version 1.4.0 --item a99, where 1.4.0 is already the newest tag, skips preflight. That means the "not newer than the newest tag" refusal never runs. pr/merged skip on merged, and image re-verifies the old landing and prints the result JSON with exit 0. The commits on main since 1.4.0 (a99's change) were never released, and the command reports success. A derived version can hit the same path when a higher tag exists that HEAD isn't behind. test_preflight_version_not_newer_than_newest_tag calls the step directly, so it doesn't catch this. Suggested fix: without --resume, an existing vX.Y.Z tag or merged release PR is a 1. Resuming a landed release then requires --resume, which names the PR explicitly.

    2. It merges whatever head the App's branch carries (medium). authored() checks only who opened the PR. Anyone who can push to ashigaru/release-X.Y.Z after the cut (any writer, any seat token) can add commits. Once checks pass on the new head, merged squashes them into main without review. Pinning sha only protects against a push during the step. Nothing checks that the head commit is the App's, or that the PR touches only what _bump.release_edits moves. The Desk's cut has the same gap because it pins to the observed head, so a fix probably belongs in both: one App-authored commit, and files ⊆ release_edits.

    3. It skips refusals the Desk's cut applies (medium-low). cuts.refusal leaves a release PR for Prime when it's a draft, carries a flag label, or has changes requested. step_merged checks none of these, so a release PR someone deliberately held gets merged. The spec says "as the Desk's cut does".

    4. A double merge produces a false failure (low). The Desk's cut loop also merges a green App PR under its lease. If it wins the race, GitHub answers 405 and step_merged reports "GitHub would not merge" (exit 1) on a release that did merge. A re-run recovers. Fix: on 405/409, check merged() again before refusing.

    5. Dispatch run identification (low). the_run takes the first new run that appears. If a second ci.yml dispatch on the same sha (a hand dispatch, a different version) shows up first, it's adopted and its success is taken as ours. The damage is bounded: pr finds the PR by branch, so the worst case is a confusing refusal, not a wrong merge. Separately, if main moves between preflight and the POST, the run's head_sha ≠ rel.head, and the step waits 300s and exits 2. By then the cut has already happened, from a tree preflight never saw and with a version derived from the older commit set.

    6. Required checks ignore the ruleset's source app (low). required() drops integration_id, and verdicts() counts a commit status with the required context as a pass. If the real check-run hasn't registered yet, a success status from any writer satisfies it. GitHub enforces the source at merge time, unless the merging credential bypasses the ruleset.

    7. The TOCTOU on main (low). moved() runs before the PUT, and the merge pins only the PR head, not the base. A commit landing on main in that window gets released under a section about to be frozen. The window is narrow.

    Held (no finding)

  • Opener not the App: an exact match on ashigaru-crunchtools-com[bot]. A user named ashigaru-crunchtools-com (no [bot], which users can't take) is refused.

  • Fork or other-repo branch with the same name: pulls() filters on head.repo.full_name and base.ref.

  • Push between the checks wait and the merge: the PUT is pinned to the judged sha, so GitHub answers 409 and the step refuses.

  • Pending checks: it waits. cancelled, timed_out, stale, action_required, startup_failure, and an error/failure status are refused (1). A mixed name takes the worst verdict.

  • skipped and neutral count as pass: this matches GitHub branch protection and the Desk's PASSED. Noted, not a bug.

  • Required check missing entirely: treated as pending, so the wait expires with a 2. No required checks at all is a 1.

  • Two new dispatch runs visible at once: 2.

  • Landed checks: a tag on another commit is a 1, an annotated tag is followed, a missing GitHub Release is a 1 (drafts are invisible to /releases/tags), :latest ≠ X.Y.Z is a 1, and an unsigned digest is a 1. A repo with no images reports a null digest, by design.

  • --resume with a stale PR: the branch pattern, App author and repo are checked, and only the version is taken from the PR. Later steps re-read via pulls(). A merged one re-verifies the old landing, which is finding 1's path.

  • Lease: a 409 is ours only for the same repo, version and item, and not ended. Two item-less runs of the same version both pass the lease, then trip the two-runs check.

  • Credentials: the runner refuses any credential a step didn't declare, and only lease gets desk. Every step still receives the same write/merge github token, including the read-only identify, preflight and image. Per-step least privilege is nominal until a read-only github credential exists.
  • Ashigaru-Item: a2363

    fatherlinux fatherlinux commented on Dec 04, 2026 21:54 UTC
    Author

    Fixed in 63bf5fc

    Answers to the second-seat review (https://github.com/crunchtools/sdlc/pull/347#issuecomment-7424974391), in its order:

  • HIGH, --version for a shipped release exits 0. Fixed in 63bf5fc. Only --resume skips preflight, lease and dispatch now (done=resuming). Without it, preflight refuses (1) any release whose PR (open or merged) or tag already exists and names the --resume to use. A --resume of a PR closed unmerged is a 1. Tests: already-cut by tag, rerun with the PR open, the resume path skipping, closed-unmerged resume.

  • MEDIUM, commits on the release branch after the cut. Fixed in 63bf5fc. Before pr waits and again before merged merges, the head commit's author and committer must both be the App. Its tree must also be exactly release_edits on its sole parent, checked by phase 0's own _prs.release_of (tree equality, file for file) through the step's GitHub client. Tests cover a non-App head and a refused tree, and run the real _prs.release_of over a small tree in two cases: the App's exact cut passes, and an extra file is refused.

  • MEDIUM-LOW, the Desk's cut refusals. Fixed in 63bf5fc. A draft, a needs-human label, or a latest review per reviewer of CHANGES_REQUESTED is a 1, mirroring ashigaru desk/cuts.py refusal and automerge.FLAGS. A test asserts FLAGS == {"needs-human"}.

  • LOW, 405 "already merged". Fixed in 63bf5fc. A 405 or 409 whose PR reads back merged passes. One that does not is a 1.

  • LOW, dispatch run identification. Fixed in 63bf5fc. A run counts only if its head_sha and event match, its path ends in ci.yml, it is not among the runs listed before the dispatch, and it was created_at no earlier than the dispatch less a stated 120s clock skew. Two candidates is still a 2.

  • LOW, required checks by App. Fixed in 63bf5fc. Ruleset integration_id and classic checks[].app_id are honoured. A check of the right name from another App leaves the requirement pending.

  • LOW, the moved()/merge race. Fixed in 63bf5fc. The merge stays pinned to the head sha, and moved() runs right before it. After the merge, or after a 405 adopted as merged, as_passed requires the merge commit's tree to equal the tree of the head that passed. Otherwise it is a 1 that says the base moved under the merge. image runs as_passed again, so a merge made elsewhere is judged too. GitHub's merge API takes no base-sha precondition, so checking before and after is the available guard.
  • Suite: 99 tests in tests/test_life_release.py.

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 21:55 UTC
    Code Review
    sdlc_jobs/life/release.py:1
    @@ -0,0 +1,902 @@
    +"""`sdlc release`: the normal path to a published image (docs/lifecycle.md).
    +
    +Replaces josui-land-release and every hand dispatch. Seven steps, each in a
    +container of its own with only the credentials it declares, and each
    +idempotent: it asks the forge whether its result is already there and goes on
    +when it is, so running the command again is how it resumes.
    +
    +    identify   origin's URL, parsed strictly, confirmed by GET /repos
    +    preflight  the default branch at origin's head, a non-empty Unreleased, a
    +               version newer than the newest tag, and `_bump.release_edits`'
    +               refusal seen here before anything is dispatched
    +    lease      the Desk's release lease, the one its own cuts take
    +    dispatch   ci.yml with version, item and includes; the one run it started
    +    pr         the App's release PR on ashigaru/release-X.Y.Z, and its
    +               required checks
    +    merged     squash, pinned to the head whose checks passed
    +    image      the push run on the merge, the tag on the merge commit, the
    +               GitHub Release, and each image's X.Y.Z and latest one signed digest
    +
    +Nothing passes from one step to the next but the forge. The version is the
    +same in every step because it is worked out the same way: `--version`; else
    +the release PR `--resume` names; else the Conventional Commits from the newest
    +vX.Y.Z tag behind this clone's HEAD to HEAD, which a tag made on the release's
    +own merge commit is never behind.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import contextlib
    +import io
    +import json
    +import os
    +import re
    +import subprocess
    +import tempfile
    +import time
    +import urllib.parse
    +from collections.abc import Callable, Mapping, Sequence
    +from dataclasses import dataclass
    +from datetime import UTC, datetime, timedelta
    +from pathlib import Path
    +from typing import Any
    +
    +from sdlc_jobs import _bump, _prs
    +from sdlc_jobs._core import (
    +    FLEET_PUBLIC_KEY,
    +    ITEM,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    images,
    +    parse_includes,
    +)
    +from sdlc_jobs._github import APP_LOGIN, Api, ApiError, GitHub
    +from sdlc_jobs.life import _hosts, _runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait, wait_for
    +
    +COMMAND = "release"
    +WORKFLOW = "ci.yml"
    +BRANCH = "ashigaru/release-"
    +REPO_ROOT = Path("/repo")
    +# A check passes as the Desk's cuts judge it (ashigaru automerge.PASSING).
    +PASSING = ("success", "skipped", "neutral")
    +# A label that leaves a release PR to a person (ashigaru automerge.FLAGS).
    +FLAGS = frozenset({"needs-human"})
    +_NOT_FOUND = 404
    +_REFUSED = (405, 409)
    +_CONFLICT = 409
    +# origin, and nothing else: github.com/<owner>/<name> over https or ssh.
    +_ORIGIN = re.compile(
    +    r"(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)"
    +    r"(?P<owner>[A-Za-z0-9][A-Za-z0-9-]*)/(?P<name>[A-Za-z0-9._-]+?)(?:\.git)?/?"
    +)
    +_TAG = re.compile(rf"v({SEMVER.pattern})")
    +# A Conventional Commit subject: type, optional scope, optional `!`, colon.
    +_SUBJECT = re.compile(r"(?P<type>[A-Za-z]+)(?:\([^)]*\))?(?P<bang>!)?:\s")
    +_BREAKING = re.compile(r"^BREAKING[ -]CHANGE:", re.MULTILINE)
    +# What a commit asks of the version, least to most.
    +_PATCH, _FEATURE, _BREAKS = 0, 1, 2
    +SKOPEO_SECONDS = 120
    +# How far this machine's clock may run ahead of GitHub's when a run is matched
    +# to the dispatch that made it.
    +CLOCK_SKEW = 120
    +COSIGN_SECONDS = 300
    +
    +# How long each wait gives the forge, and how often it asks.
    +WAITS = {
    +    "run": (300.0, 10.0),  # the dispatch's run to appear
    +    "dispatch": (1800.0, 20.0),  # the dispatch's run to finish: the release PR
    +    "checks": (3600.0, 30.0),  # the release PR's required checks
    +    "landing": (3600.0, 30.0),  # the push run on the merge commit
    +}
    +
    +
    +# --- what a step reaches the world through; the suite replaces each -----------
    +
    +
    +def connect(run: Run) -> Api:
    +    """GitHub as the github credential sees it."""
    +    return GitHub(run.credential("github"))
    +
    +
    +def git(*args: str) -> str | None:
    +    """git's stdout in the clone bin/sdlc mounted, or None when git says no."""
    +    proc = subprocess.run(
    +        ["git", "-C", str(REPO_ROOT), *args], capture_output=True, text=True, check=False
    +    )
    +    return proc.stdout if proc.returncode == 0 else None
    +
    +
    +def desk(url: str, token: str) -> tuple[Api, str]:
    +    """The Desk's API at `url`, and the path it is served under.
    +
    +    The same REST client GitHub's calls use: one host, https only, and a
    +    redirect to another host never carries the token.
    +    """
    +    parts = urllib.parse.urlsplit(url)
    +    if parts.scheme != "https" or not parts.netloc:
    +        raise CannotRunError(f"the Desk is reached over https only, not {url}")
    +    return GitHub(token, host=parts.netloc), parts.path.rstrip("/")
    +
    +
    +def digest_of(ref: str) -> str | None:
    +    """The digest `ref` names in its registry, or None when it names nothing."""
    +    proc = subprocess.run(
    +        ["skopeo", "inspect", "--no-tags", "--format", "{{.Digest}}", f"docker://{ref}"],
    +        capture_output=True,
    +        text=True,
    +        check=False,
    +        timeout=SKOPEO_SECONDS,
    +    )
    +    if proc.returncode == 0:
    +        return proc.stdout.strip() or None
    +    if "manifest unknown" in proc.stderr or "not found" in proc.stderr.lower():
    +        return None
    +    raise CannotRunError(f"skopeo could not read {ref}: {proc.stderr.strip()[:300]}")
    +
    +
    +def signed(ref: str) -> bool:
    +    """Does `ref` (by digest) carry the fleet key's signature, as promote verifies it?"""
    +    with tempfile.TemporaryDirectory() as scratch:
    +        pub = Path(scratch) / "fleet.pub"
    +        pub.write_text(FLEET_PUBLIC_KEY)
    +        argv = ["cosign", "verify", "--insecure-ignore-tlog", "--key", str(pub), ref]
    +        proc = subprocess.run(
    +            argv, capture_output=True, text=True, check=False, timeout=COSIGN_SECONDS
    +        )
    +    return proc.returncode == 0
    +
    +
    +ENV: Mapping[str, str] = os.environ
    +TIMER: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
    +
    +
    +def now() -> datetime:

    CRITICAL (Documentation): The new public now function has no docstring, so its purpose and UTC behavior are undocumented.

    Suggestion: Add a brief docstring describing the value it returns, such as the current time in UTC.

    Evidence:

    def now() -> datetime:
        return datetime.now(UTC)
    

    <!-- gatehouse agent=docs confidence=94 votes=2/3 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 21:55 UTC
    Code Review
    sdlc_jobs/life/release.py:1
    @@ -0,0 +1,902 @@
    +"""`sdlc release`: the normal path to a published image (docs/lifecycle.md).
    +
    +Replaces josui-land-release and every hand dispatch. Seven steps, each in a
    +container of its own with only the credentials it declares, and each
    +idempotent: it asks the forge whether its result is already there and goes on
    +when it is, so running the command again is how it resumes.
    +
    +    identify   origin's URL, parsed strictly, confirmed by GET /repos
    +    preflight  the default branch at origin's head, a non-empty Unreleased, a
    +               version newer than the newest tag, and `_bump.release_edits`'
    +               refusal seen here before anything is dispatched
    +    lease      the Desk's release lease, the one its own cuts take
    +    dispatch   ci.yml with version, item and includes; the one run it started
    +    pr         the App's release PR on ashigaru/release-X.Y.Z, and its
    +               required checks
    +    merged     squash, pinned to the head whose checks passed
    +    image      the push run on the merge, the tag on the merge commit, the
    +               GitHub Release, and each image's X.Y.Z and latest one signed digest
    +
    +Nothing passes from one step to the next but the forge. The version is the
    +same in every step because it is worked out the same way: `--version`; else
    +the release PR `--resume` names; else the Conventional Commits from the newest
    +vX.Y.Z tag behind this clone's HEAD to HEAD, which a tag made on the release's
    +own merge commit is never behind.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import contextlib
    +import io
    +import json
    +import os
    +import re
    +import subprocess
    +import tempfile
    +import time
    +import urllib.parse
    +from collections.abc import Callable, Mapping, Sequence
    +from dataclasses import dataclass
    +from datetime import UTC, datetime, timedelta
    +from pathlib import Path
    +from typing import Any
    +
    +from sdlc_jobs import _bump, _prs
    +from sdlc_jobs._core import (
    +    FLEET_PUBLIC_KEY,
    +    ITEM,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    images,
    +    parse_includes,
    +)
    +from sdlc_jobs._github import APP_LOGIN, Api, ApiError, GitHub
    +from sdlc_jobs.life import _hosts, _runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait, wait_for
    +
    +COMMAND = "release"
    +WORKFLOW = "ci.yml"
    +BRANCH = "ashigaru/release-"
    +REPO_ROOT = Path("/repo")
    +# A check passes as the Desk's cuts judge it (ashigaru automerge.PASSING).
    +PASSING = ("success", "skipped", "neutral")
    +# A label that leaves a release PR to a person (ashigaru automerge.FLAGS).
    +FLAGS = frozenset({"needs-human"})
    +_NOT_FOUND = 404
    +_REFUSED = (405, 409)
    +_CONFLICT = 409
    +# origin, and nothing else: github.com/<owner>/<name> over https or ssh.
    +_ORIGIN = re.compile(
    +    r"(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)"
    +    r"(?P<owner>[A-Za-z0-9][A-Za-z0-9-]*)/(?P<name>[A-Za-z0-9._-]+?)(?:\.git)?/?"
    +)
    +_TAG = re.compile(rf"v({SEMVER.pattern})")
    +# A Conventional Commit subject: type, optional scope, optional `!`, colon.
    +_SUBJECT = re.compile(r"(?P<type>[A-Za-z]+)(?:\([^)]*\))?(?P<bang>!)?:\s")
    +_BREAKING = re.compile(r"^BREAKING[ -]CHANGE:", re.MULTILINE)
    +# What a commit asks of the version, least to most.
    +_PATCH, _FEATURE, _BREAKS = 0, 1, 2
    +SKOPEO_SECONDS = 120
    +# How far this machine's clock may run ahead of GitHub's when a run is matched
    +# to the dispatch that made it.
    +CLOCK_SKEW = 120
    +COSIGN_SECONDS = 300
    +
    +# How long each wait gives the forge, and how often it asks.
    +WAITS = {
    +    "run": (300.0, 10.0),  # the dispatch's run to appear
    +    "dispatch": (1800.0, 20.0),  # the dispatch's run to finish: the release PR
    +    "checks": (3600.0, 30.0),  # the release PR's required checks
    +    "landing": (3600.0, 30.0),  # the push run on the merge commit
    +}
    +
    +
    +# --- what a step reaches the world through; the suite replaces each -----------
    +
    +
    +def connect(run: Run) -> Api:
    +    """GitHub as the github credential sees it."""
    +    return GitHub(run.credential("github"))
    +
    +
    +def git(*args: str) -> str | None:
    +    """git's stdout in the clone bin/sdlc mounted, or None when git says no."""
    +    proc = subprocess.run(
    +        ["git", "-C", str(REPO_ROOT), *args], capture_output=True, text=True, check=False
    +    )
    +    return proc.stdout if proc.returncode == 0 else None
    +
    +
    +def desk(url: str, token: str) -> tuple[Api, str]:
    +    """The Desk's API at `url`, and the path it is served under.
    +
    +    The same REST client GitHub's calls use: one host, https only, and a
    +    redirect to another host never carries the token.
    +    """
    +    parts = urllib.parse.urlsplit(url)
    +    if parts.scheme != "https" or not parts.netloc:
    +        raise CannotRunError(f"the Desk is reached over https only, not {url}")
    +    return GitHub(token, host=parts.netloc), parts.path.rstrip("/")
    +
    +
    +def digest_of(ref: str) -> str | None:
    +    """The digest `ref` names in its registry, or None when it names nothing."""
    +    proc = subprocess.run(
    +        ["skopeo", "inspect", "--no-tags", "--format", "{{.Digest}}", f"docker://{ref}"],
    +        capture_output=True,
    +        text=True,
    +        check=False,
    +        timeout=SKOPEO_SECONDS,
    +    )
    +    if proc.returncode == 0:
    +        return proc.stdout.strip() or None
    +    if "manifest unknown" in proc.stderr or "not found" in proc.stderr.lower():
    +        return None
    +    raise CannotRunError(f"skopeo could not read {ref}: {proc.stderr.strip()[:300]}")
    +
    +
    +def signed(ref: str) -> bool:
    +    """Does `ref` (by digest) carry the fleet key's signature, as promote verifies it?"""
    +    with tempfile.TemporaryDirectory() as scratch:
    +        pub = Path(scratch) / "fleet.pub"
    +        pub.write_text(FLEET_PUBLIC_KEY)
    +        argv = ["cosign", "verify", "--insecure-ignore-tlog", "--key", str(pub), ref]
    +        proc = subprocess.run(
    +            argv, capture_output=True, text=True, check=False, timeout=COSIGN_SECONDS
    +        )
    +    return proc.returncode == 0
    +
    +
    +ENV: Mapping[str, str] = os.environ
    +TIMER: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
    +
    +
    +def now() -> datetime:
    +    return datetime.now(UTC)
    +
    +
    +def today() -> str:
    +    """The CHANGELOG heading's date, UTC's, as the App's release commit writes it."""
    +    return datetime.now(UTC).date().isoformat()
    +
    +
    +# --- what every step works out the same way ------------------------------------
    +
    +
    +@dataclass
    +class Asked:
    +    """The person's arguments, checked."""
    +
    +    version: str | None
    +    item: str | None
    +    includes: list[str]
    +    resume: str | None
    +
    +
    +@dataclass
    +class Release:
    +    """What every step knows of the release, read back from the forge."""
    +
    +    api: Api
    +    repo: str
    +    default: str
    +    head: str
    +    version: str
    +    asked: Asked
    +
    +    @property
    +    def branch(self) -> str:
    +        return f"{BRANCH}{self.version}"
    +
    +    @property
    +    def tag(self) -> str:
    +        return f"v{self.version}"
    +
    +    def url(self, path: str = "") -> str:
    +        return f"https://github.com/{self.repo}{path}"
    +
    +
    +def origin_repo() -> str:
    +    """owner/name from origin's URL, parsed strictly, or a 2."""
    +    url = (git("remote", "get-url", "origin") or "").strip()
    +    m = _ORIGIN.fullmatch(url)
    +    if not m:
    +        raise CannotRunError(f"origin is not github.com/<owner>/<name>: {url or 'no origin'}")
    +    return f"{m['owner']}/{m['name']}"
    +
    +
    +def identity(api: Api) -> tuple[str, str]:
    +    """(owner/name, default branch) of origin, confirmed by GitHub, or a 2."""
    +    repo = origin_repo()
    +    try:
    +        found = api.request("GET", f"/repos/{repo}")
    +    except ApiError as err:
    +        raise CannotRunError(f"{repo} does not resolve on GitHub: {err}") from err
    +    name = (found or {}).get("full_name")
    +    default = (found or {}).get("default_branch")
    +    if not isinstance(name, str) or name.lower() != repo.lower() or not isinstance(default, str):
    +        raise CannotRunError(f"GitHub answers {name!r} for {repo}, not that repo")
    +    return name, default
    +
    +
    +def local_head() -> str:
    +    head = (git("rev-parse", "HEAD") or "").strip()
    +    if not re.fullmatch(r"[0-9a-f]{40}", head):
    +        raise CannotRunError("this clone has no HEAD commit")
    +    return head
    +
    +
    +def triple(version: str) -> tuple[int, int, int]:
    +    a, b, c = (int(p) for p in version.split("."))
    +    return a, b, c
    +
    +
    +def tags(api: Api, repo: str) -> list[str]:
    +    """Every vX.Y.Z tag's version, newest first."""
    +    names = [t.get("name") for t in api.pages(f"/repos/{repo}/tags") if isinstance(t, dict)]
    +    found = [m[1] for n in names if isinstance(n, str) and (m := _TAG.fullmatch(n))]
    +    return sorted(set(found), key=triple, reverse=True)
    +
    +
    +def bump(version: str, messages: Sequence[str]) -> str:
    +    """The next version after `version` for these commit messages (constitution R1).
    +
    +    A breaking change bumps MAJOR, or MINOR before 1.0.0; a feat bumps MINOR;
    +    anything else PATCH.
    +    """
    +    major, minor, patch = triple(version)
    +    level = _PATCH
    +    for message in messages:
    +        m = _SUBJECT.match(message)
    +        if (m and m["bang"]) or _BREAKING.search(message):
    +            level = max(level, _BREAKS)
    +        elif m and m["type"].lower() == "feat":
    +            level = max(level, _FEATURE)
    +    if level == _BREAKS and major > 0:
    +        return f"{major + 1}.0.0"
    +    if level >= _FEATURE:
    +        return f"{major}.{minor + 1}.0"
    +    return f"{major}.{minor}.{patch + 1}"
    +
    +
    +def behind_head(api: Api, repo: str, head: str) -> tuple[str, list[str]] | None:
    +    """(version, messages since it) for the newest vX.Y.Z tag HEAD has; None when it has none."""
    +    for version in tags(api, repo):
    +        compared = api.request("GET", f"/repos/{repo}/compare/v{version}...{head}")
    +        if (compared or {}).get("status") in ("ahead", "identical"):
    +            commits = compared.get("commits") or []
    +            return version, [str((c.get("commit") or {}).get("message", "")) for c in commits]
    +    return None
    +
    +
    +def derived(api: Api, repo: str, head: str) -> str:
    +    since = behind_head(api, repo, head)
    +    if since is None:
    +        raise RefusedError(
    +            f"{repo} has no vX.Y.Z tag behind HEAD to derive a version from; "
    +            "name one with --version"
    +        )
    +    base, messages = since
    +    if not messages:
    +        raise RefusedError(f"nothing has landed since v{base}: there is nothing to release")
    +    return bump(base, messages)
    +
    +
    +def release_pull(api: Api, repo: str, number: int) -> dict[str, Any]:
    +    """The pull request --resume names, which must be the App's release PR, or a 1."""
    +    pull = api.request("GET", f"/repos/{repo}/pulls/{number}") or {}
    +    ref = (pull.get("head") or {}).get("ref", "")
    +    m = re.fullmatch(rf"{re.escape(BRANCH)}({SEMVER.pattern})", str(ref))
    +    if not m:
    +        raise RefusedError(f"{repo}#{number} is not on an {BRANCH}X.Y.Z branch: {ref!r}")
    +    authored(pull, f"{repo}#{number}")
    +    if pull.get("state") != "open" and not pull.get("merged_at"):
    +        raise RefusedError(f"{repo}#{number} was closed unmerged; cut the release again")
    +    return pull
    +
    +
    +def authored(pull: Mapping[str, Any], where: str) -> None:
    +    """A release PR the Ashigaru App did not write, or from another repo, is a 1."""
    +    login = (pull.get("user") or {}).get("login")
    +    if login != APP_LOGIN:
    +        raise RefusedError(f"{where} was opened by {login!r}, not the Ashigaru App ({APP_LOGIN})")
    +
    +
    +_KNOWN: dict[int, Release] = {}
    +
    +
    +def release_of(run: Run) -> Release:
    +    """What this step knows of the release, from origin, GitHub and the arguments.
    +
    +    Worked out once per run of a step: its `done` and its `run` ask the same.
    +    """
    +    if id(run) in _KNOWN:
    +        return _KNOWN[id(run)]
    +    asked = asked_of(parser().parse_args(run.argv))
    +    api = connect(run)
    +    repo, default = identity(api)
    +    head = local_head()
    +    if asked.resume is not None:
    +        named, number = _runner.parse_ref(asked.resume)
    +        if named.lower() != repo.lower():
    +            raise CannotRunError(f"--resume names {named}, and this clone is {repo}")
    +        pull = release_pull(api, repo, number)
    +        version = pull["head"]["ref"][len(BRANCH) :]
    +        if asked.version is not None and asked.version != version:
    +            raise CannotRunError(
    +                f"--version {asked.version}, and {asked.resume} releases {version}"
    +            )
    +        run.resume_ref = f"{repo}#{number}"
    +    else:
    +        version = asked.version or derived(api, repo, head)
    +    _KNOWN[id(run)] = Release(api, repo, default, head, version, asked)
    +    return _KNOWN[id(run)]
    +
    +
    +# --- the forge's answers ------------------------------------------------------
    +
    +
    +def pulls(rel: Release) -> list[dict[str, Any]]:
    +    """Every PR from this repo's ashigaru/release-X.Y.Z into the default branch; App-only."""
    +    owner = rel.repo.split("/", 1)[0]
    +    found = rel.api.request(
    +        "GET", f"/repos/{rel.repo}/pulls?head={owner}:{rel.branch}&state=all&per_page=100"
    +    )
    +    mine = [
    +        p
    +        for p in found or []
    +        if (p.get("head") or {}).get("ref") == rel.branch
    +        and ((p.get("head") or {}).get("repo") or {}).get("full_name", "").lower()
    +        == rel.repo.lower()
    +        and (p.get("base") or {}).get("ref") == rel.default
    +    ]
    +    for p in mine:
    +        authored(p, f"{rel.repo}#{p.get('number')}")
    +    return mine
    +
    +
    +def open_pull(rel: Release) -> dict[str, Any] | None:
    +    """The one open release PR, or None; two open is a 2."""
    +    found = [p for p in pulls(rel) if p.get("state") == "open"]
    +    if len(found) > 1:
    +        numbers = ", ".join(f"#{p.get('number')}" for p in found)
    +        raise CannotRunError(
    +            f"{rel.repo} has {len(found)} open release PRs for {rel.version}: {numbers}"
    +        )
    +    return found[0] if found else None
    +
    +
    +def merged_pull(rel: Release) -> dict[str, Any] | None:
    +    return next((p for p in pulls(rel) if p.get("merged_at")), None)
    +
    +
    +def merged(run: Run) -> bool:
    +    """Has the release PR merged?"""
    +    rel = release_of(run)
    +    return any(p.get("merged_at") for p in pulls(rel))
    +
    +
    +def tagged(rel: Release) -> str | None:
    +    """The commit the vX.Y.Z tag names, or None when there is no such tag."""
    +    try:
    +        ref = rel.api.request("GET", f"/repos/{rel.repo}/git/ref/tags/{rel.tag}")
    +    except ApiError as err:
    +        if err.status == _NOT_FOUND:
    +            return None
    +        raise
    +    obj = (ref or {}).get("object") or {}
    +    if obj.get("type") == "tag":  # annotated: the tag object names the commit
    +        obj = (rel.api.request("GET", f"/repos/{rel.repo}/git/tags/{obj.get('sha')}") or {}).get(
    +            "object"
    +        ) or {}
    +    return str(obj.get("sha", "")) or None
    +
    +
    +def existing(rel: Release) -> str | None:
    +    """What says this release was already cut: its open or merged PR, or its tag; else None.
    +
    +    A PR closed unmerged is a cut that was abandoned, so it is cut again.
    +    """
    +    live = [p for p in pulls(rel) if p.get("state") == "open" or p.get("merged_at")]
    +    if live:
    +        return f"{rel.repo}#{live[0].get('number')}"
    +    return rel.tag if tagged(rel) is not None else None
    +
    +
    +def resuming(run: Run) -> bool:
    +    """Is this run carrying on with the release PR --resume names?
    +
    +    Only that skips preflight, lease and dispatch: a release this run did not
    +    name is refused by preflight, never adopted as this one.
    +    """
    +    return release_of(run).asked.resume is not None
    +
    +
    +# A required check: its name, and the App that must report it (None: any).
    +Need = tuple[str, int | None]
    +
    +
    +def required(rel: Release) -> set[Need]:
    +    """The checks the default branch requires, by ruleset or classic protection, with their Apps."""
    +    branch = urllib.parse.quote(rel.default, safe="")
    +    needs: set[Need] = set()
    +    for rule in rel.api.pages(f"/repos/{rel.repo}/rules/branches/{branch}"):
    +        if isinstance(rule, dict) and rule.get("type") == "required_status_checks":
    +            for need in (rule.get("parameters") or {}).get("required_status_checks") or []:
    +                if isinstance(need, dict) and isinstance(need.get("context"), str):
    +                    app = need.get("integration_id")
    +                    needs.add((need["context"], app if isinstance(app, int) else None))
    +    found = rel.api.request("GET", f"/repos/{rel.repo}/branches/{branch}") or {}
    +    classic = (found.get("protection") or {}).get("required_status_checks") or {}
    +    for check in classic.get("checks") or []:
    +        if isinstance(check, dict) and isinstance(check.get("context"), str):
    +            app = check.get("app_id")
    +            needs.add((check["context"], app if isinstance(app, int) else None))
    +    known = {name for name, _ in needs}
    +    needs.update((c, None) for c in classic.get("contexts") or [] if c not in known)
    +    return needs
    +
    +
    +def reported(rel: Release, sha: str) -> list[tuple[str, int | None, str]]:
    +    """(name, App, verdict) for each check run and commit status on `sha`; "pending" until done."""
    +    seen: list[tuple[str, int | None, str]] = []
    +    runs = rel.api.pages(f"/repos/{rel.repo}/commits/{sha}/check-runs?filter=latest", "check_runs")
    +    for cr in runs:
    +        state = cr.get("conclusion") if cr.get("status") == "completed" else "pending"
    +        app = (cr.get("app") or {}).get("id")
    +        seen.append(
    +            (str(cr.get("name")), app if isinstance(app, int) else None, str(state or "pending"))
    +        )
    +    status = rel.api.request("GET", f"/repos/{rel.repo}/commits/{sha}/status") or {}
    +    for st in status.get("statuses") or []:
    +        state = st.get("state")
    +        verdict = (
    +            "success" if state == "success" else "pending" if state == "pending" else "failure"
    +        )
    +        seen.append((str(st.get("context")), None, verdict))
    +    return seen
    +
    +
    +def verdict(need: Need, seen: list[tuple[str, int | None, str]]) -> str:
    +    """One requirement's verdict: what its App reported under its name, combined as the Desk does.
    +
    +    Never reported is pending; any pending is pending; else any failure fails.
    +    """
    +    name, app = need
    +    states = [v for n, a, v in seen if n == name and (app is None or a == app)]
    +    if not states or "pending" in states:
    +        return "pending"
    +    return next((v for v in states if v not in PASSING), states[0])
    +
    +
    +def judged(rel: Release, pull: Mapping[str, Any]) -> bool | None:
    +    """True when every required check passed on the PR's head; None while any is pending.
    +
    +    A required check that failed is a 1 naming it.
    +    """
    +    need = required(rel)
    +    if not need:
    +        raise RefusedError(
    +            f"{rel.default} requires no checks, and release merges nothing nothing judged"
    +        )
    +    seen = reported(rel, pull["head"]["sha"])
    +    states = {n: verdict(n, seen) for n in need}
    +    failed = sorted(n[0] for n, v in states.items() if v not in (*PASSING, "pending"))
    +    if failed:
    +        raise RefusedError(
    +            "required checks failed on the release PR: "
    +            + ", ".join(failed)
    +            + f"\n{pull.get('html_url', '')}"
    +        )
    +    return True if all(v in PASSING for v in states.values()) else None
    +
    +
    +def runs(rel: Release, event: str, sha: str) -> list[dict[str, Any]]:
    +    return (
    +        rel.api.request(
    +            "GET",
    +            f"/repos/{rel.repo}/actions/workflows/{WORKFLOW}/runs"
    +            f"?event={event}&head_sha={sha}&per_page=100",
    +        ).get("workflow_runs")
    +        or []
    +    )
    +
    +
    +def finished(rel: Release, run_id: int, what: str) -> None:
    +    """Wait for run `run_id` to complete; anything but success is a 1 naming the failed jobs."""
    +    path = f"/repos/{rel.repo}/actions/runs/{run_id}"
    +    url = rel.url(f"/actions/runs/{run_id}")
    +    timeout, every = WAITS[what]
    +
    +    def probe() -> dict[str, Any] | None:
    +        got = rel.api.request("GET", path) or {}
    +        return got if got.get("status") == "completed" else None
    +
    +    done = wait_for(probe, Wait(f"the {what} run to finish", url, timeout, every), TIMER)
    +    if done.get("conclusion") != "success":
    +        jobs = rel.api.pages(f"{path}/jobs", "jobs")
    +        bad = [
    +            f"{j.get('name')} ({j.get('conclusion')})"
    +            for j in jobs
    +            if j.get("conclusion") not in PASSING
    +        ]
    +        raise RefusedError(
    +            f"the {what} run ended {done.get('conclusion')}: "
    +            f"{', '.join(bad) or 'no job failed'}\n{url}"
    +        )
    +
    +
    +def the_run(run: Run, rel: Release, which: tuple[str, str, set[object], str], what: str) -> None:
    +    """Wait for the one new run, then for it to pass.
    +
    +    `which` is (event, sha, before, after): a run of ci.yml for `event` on
    +    `sha`, not among the ids `before`, created no earlier than `after` (UTC,
    +    ISO 8601; "" for any). Two that could be it is a 2: nothing says which one
    +    is this release's.
    +    """
    +    event, sha, before, after = which
    +
    +    def probe() -> dict[str, Any] | None:
    +        new = [
    +            r
    +            for r in runs(rel, event, sha)
    +            if r.get("id") not in before
    +            and r.get("event") == event
    +            and r.get("head_sha") == sha
    +            and str(r.get("path", WORKFLOW)).endswith(WORKFLOW)
    +            and str(r.get("created_at", "")) >= after
    +        ]
    +        if len(new) > 1:
    +            urls = ", ".join(str(r.get("html_url", r.get("id"))) for r in new)
    +            raise CannotRunError(f"{len(new)} runs could be the {what} run: {urls}")
    +        return new[0] if new else None
    +
    +    timeout, every = WAITS["run"]
    +    url = rel.url(f"/actions/workflows/{WORKFLOW}")
    +    found = wait_for(probe, Wait(f"the {what} run", url, timeout, every), TIMER)
    +    run.say(f"{what} run: {found.get('html_url', found.get('id'))}")
    +    finished(rel, int(found["id"]), what)
    +
    +
    +# --- the steps ------------------------------------------------------------------
    +
    +
    +def step_identify(run: Run) -> None:
    +    if ENV.get("JOSUI_NAME") and asked_of(parser().parse_args(run.argv)).item is None:
    +        raise RefusedError(
    +            "an agent releases under a work item: pass --item aN (JOSUI_NAME is set)"
    +        )
    +    rel = release_of(run)
    +    run.say(f"{rel.repo} {rel.version}, from {rel.default} at {rel.head[:12]}")
    +
    +
    +def step_preflight(run: Run) -> None:
    +    rel = release_of(run)
    +    there = existing(rel)
    +    if there is not None:
    +        resume = f"; carry it on with --resume {there}" if "#" in there else ""
    +        raise RefusedError(f"{rel.repo} {rel.version} was already cut: {there}{resume}")
    +    branch = (git("symbolic-ref", "--quiet", "--short", "HEAD") or "").strip()
    +    if branch != rel.default:
    +        raise RefusedError(
    +            f"a release is cut from {rel.default}, and this clone is on {branch or 'no branch'}"
    +        )
    +    quoted = urllib.parse.quote(rel.default, safe="")
    +    there = (
    +        (rel.api.request("GET", f"/repos/{rel.repo}/branches/{quoted}") or {}).get("commit") or {}
    +    ).get("sha")
    +    if there != rel.head:
    +        raise RefusedError(
    +            f"this clone's {rel.default} is at {rel.head[:12]} and origin's at {str(there)[:12]}: "
    +            f"git pull, then release"
    +        )
    +    newest = tags(rel.api, rel.repo)
    +    if newest and triple(rel.version) <= triple(newest[0]):
    +        raise RefusedError(f"{rel.version} is not newer than the newest tag, v{newest[0]}")
    +
    +    def read(path: str) -> str | None:
    +        return git("show", f"HEAD:{path}")
    +
    +    try:
    +        edits = _bump.release_edits(read, rel.version, today())
    +    except _bump.ReleaseError as err:
    +        raise RefusedError(f"the release commit cannot be made: {err}") from err
    +    run.say(f"{rel.version} moves {', '.join(sorted(edits)) or 'nothing'}")
    +
    +
    +def step_lease(run: Run) -> None:
    +    rel = release_of(run)
    +    hosts = _hosts.load()
    +    if hosts.desk_url is None:
    +        run.say("UNLEASED: the Desk will adopt this release")
    +        return
    +    api, base = desk(hosts.desk_url, run.credential("desk"))
    +    body: dict[str, object] = {"repo": rel.repo, "version": rel.version}
    +    if rel.asked.item is not None:
    +        body["item"] = rel.asked.item
    +    try:
    +        api.request("POST", f"{base}/v1/releases", body)
    +    except ApiError as err:
    +        if err.status != _CONFLICT:
    +            raise CannotRunError(
    +                f"the Desk would not lease {rel.repo} {rel.version}: {err}"
    +            ) from err
    +        if not ours(rel, api, base):
    +            raise RefusedError(f"the Desk holds another release's lease: {err}") from err
    +        run.say(f"the Desk's lease on {rel.repo} is already this release's")
    +        return
    +    run.say(f"leased {rel.repo} {rel.version} on the Desk")
    +
    +
    +def ours(rel: Release, api: Api, base: str) -> bool:
    +    """Is the lease in flight on this repo for this version and item?"""
    +    leases = api.request("GET", f"{base}/v1/releases")
    +    if not isinstance(leases, list):
    +        raise CannotRunError(f"the Desk's {base}/v1/releases is not a list of leases")
    +    return any(
    +        isinstance(lease, dict)
    +        and str(lease.get("repo", "")).lower() == rel.repo.lower()
    +        and lease.get("version") == rel.version
    +        and lease.get("item") == rel.asked.item
    +        and not lease.get("ended_at")
    +        for lease in leases
    +    )
    +
    +
    +def step_dispatch(run: Run) -> None:
    +    rel = release_of(run)
    +    before = {r.get("id") for r in runs(rel, "workflow_dispatch", rel.head)}
    +    after = (now() - timedelta(seconds=CLOCK_SKEW)).strftime("%Y-%m-%dT%H:%M:%SZ")
    +    inputs = {"version": rel.version}
    +    if rel.asked.item is not None:
    +        inputs["item"] = rel.asked.item
    +    if rel.asked.includes:
    +        inputs["includes"] = ",".join(rel.asked.includes)
    +    rel.api.request(
    +        "POST",
    +        f"/repos/{rel.repo}/actions/workflows/{WORKFLOW}/dispatches",
    +        {"ref": rel.default, "inputs": inputs},
    +    )
    +    the_run(run, rel, ("workflow_dispatch", rel.head, before, after), "dispatch")
    +
    +
    +def step_pr(run: Run) -> None:
    +    rel = release_of(run)
    +    pull = open_pull(rel)
    +    if pull is None:
    +        raise RefusedError(
    +            f"the dispatch finished and {rel.repo} has no open release PR on {rel.branch}"
    +        )
    +    run.resume_ref = f"{rel.repo}#{pull['number']}"
    +    run.say(f"release PR: {pull.get('html_url', run.resume_ref)}")
    +    flagged(rel, pull)
    +    the_apps_cut(rel, pull["head"]["sha"])
    +    green(rel, pull)
    +    run.say(f"every required check passed on {pull['head']['sha'][:12]}")
    +
    +
    +def green(rel: Release, pull: Mapping[str, Any]) -> None:
    +    """Wait for every required check on the PR's head to pass; a failure is a 1."""
    +    timeout, every = WAITS["checks"]
    +    wait = Wait("the release PR's required checks", str(pull.get("html_url", "")), timeout, every)
    +    wait_for(lambda: judged(rel, pull), wait, TIMER)
    +
    +
    +def step_merged(run: Run) -> None:
    +    rel = release_of(run)
    +    pull = open_pull(rel)
    +    if pull is None:
    +        raise RefusedError(f"{rel.repo} has no open release PR on {rel.branch} to merge")
    +    run.resume_ref = f"{rel.repo}#{pull['number']}"
    +    head = pull["head"]["sha"]
    +    # This step's own read of the head: the merge is pinned to the head it judged.
    +    flagged(rel, pull)
    +    the_apps_cut(rel, head)
    +    green(rel, pull)
    +    moved(rel, head)
    +    try:
    +        rel.api.request(
    +            "PUT",
    +            f"/repos/{rel.repo}/pulls/{pull['number']}/merge",
    +            {"merge_method": "squash", "sha": head},
    +        )
    +    except ApiError as err:
    +        # 405 is also what a PR another merger (the Desk's cut) already merged answers.
    +        if err.status not in _REFUSED:
    +            raise
    +        if not (rel.api.request("GET", f"/repos/{rel.repo}/pulls/{pull['number']}") or {}).get(
    +            "merged_at"
    +        ):
    +            raise RefusedError(
    +                f"GitHub would not merge {run.resume_ref} at {head[:12]}: {err}"
    +            ) from err
    +        run.say(f"{run.resume_ref} was already merged")
    +    as_passed(rel, pull["number"], head)
    +    run.say(f"merged {run.resume_ref} at {head[:12]}")
    +
    +
    +def flagged(rel: Release, pull: Mapping[str, Any]) -> None:
    +    """The Desk's cut refusals (ashigaru desk/cuts.py `refusal`): a draft, a flag, changes asked."""
    +    where = f"{rel.repo}#{pull['number']}"
    +    if pull.get("draft"):
    +        raise RefusedError(f"{where} is a draft")
    +    labels = {
    +        str(label.get("name")) for label in pull.get("labels") or [] if isinstance(label, dict)
    +    }
    +    if FLAGS & labels:
    +        raise RefusedError(f"{where} is flagged {', '.join(sorted(FLAGS & labels))}")
    +    latest: dict[str, str] = {}
    +    for review in rel.api.pages(f"/repos/{rel.repo}/pulls/{pull['number']}/reviews"):
    +        login, state = (review.get("user") or {}).get("login"), review.get("state")
    +        if isinstance(login, str) and state in ("APPROVED", "CHANGES_REQUESTED", "DISMISSED"):
    +            latest[login] = str(state)
    +    asked = sorted(who for who, state in latest.items() if state == "CHANGES_REQUESTED")
    +    if asked:
    +        raise RefusedError(f"{where} has changes requested by {', '.join(asked)}")
    +
    +
    +class ForgeTools(Tools):
    +    """`Tools`' GitHub calls answered by an `Api`, so `_prs` judges a tree here as in CI."""
    +
    +    def __init__(self, api: Api) -> None:
    +        self.api = api
    +
    +    def http(

    CRITICAL (Documentation): The new public ForgeTools.http method has no docstring. Its interface and its handling of headers, payloads, and API errors are therefore undocumented.

    Suggestion: Add a brief docstring describing how the method translates the HTTP request to the Api call and represents API errors in its Response.

    Evidence:

    def http(
        self, method: str, url: str, headers: Mapping[str, str], payload: bytes | None = None
    ) -> Response:
        del headers  # the Api carries its own credential
        path = url.removeprefix("https://api.github.com")
        try:
            got = self.api.request(method, path, None if payload is None else json.loads(payload))
        except ApiError as err:
            return Response(err.status, str(err).encode())
        return Response(200, json.dumps(got).encode())
    

    <!-- gatehouse agent=docs confidence=88 votes=2/3 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 21:55 UTC
    Code Review
    sdlc_jobs/life/release.py:1
    @@ -0,0 +1,902 @@
    +"""`sdlc release`: the normal path to a published image (docs/lifecycle.md).
    +
    +Replaces josui-land-release and every hand dispatch. Seven steps, each in a
    +container of its own with only the credentials it declares, and each
    +idempotent: it asks the forge whether its result is already there and goes on
    +when it is, so running the command again is how it resumes.
    +
    +    identify   origin's URL, parsed strictly, confirmed by GET /repos
    +    preflight  the default branch at origin's head, a non-empty Unreleased, a
    +               version newer than the newest tag, and `_bump.release_edits`'
    +               refusal seen here before anything is dispatched
    +    lease      the Desk's release lease, the one its own cuts take
    +    dispatch   ci.yml with version, item and includes; the one run it started
    +    pr         the App's release PR on ashigaru/release-X.Y.Z, and its
    +               required checks
    +    merged     squash, pinned to the head whose checks passed
    +    image      the push run on the merge, the tag on the merge commit, the
    +               GitHub Release, and each image's X.Y.Z and latest one signed digest
    +
    +Nothing passes from one step to the next but the forge. The version is the
    +same in every step because it is worked out the same way: `--version`; else
    +the release PR `--resume` names; else the Conventional Commits from the newest
    +vX.Y.Z tag behind this clone's HEAD to HEAD, which a tag made on the release's
    +own merge commit is never behind.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import contextlib
    +import io
    +import json
    +import os
    +import re
    +import subprocess
    +import tempfile
    +import time
    +import urllib.parse
    +from collections.abc import Callable, Mapping, Sequence
    +from dataclasses import dataclass
    +from datetime import UTC, datetime, timedelta
    +from pathlib import Path
    +from typing import Any
    +
    +from sdlc_jobs import _bump, _prs
    +from sdlc_jobs._core import (
    +    FLEET_PUBLIC_KEY,
    +    ITEM,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    images,
    +    parse_includes,
    +)
    +from sdlc_jobs._github import APP_LOGIN, Api, ApiError, GitHub
    +from sdlc_jobs.life import _hosts, _runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait, wait_for
    +
    +COMMAND = "release"
    +WORKFLOW = "ci.yml"
    +BRANCH = "ashigaru/release-"
    +REPO_ROOT = Path("/repo")
    +# A check passes as the Desk's cuts judge it (ashigaru automerge.PASSING).
    +PASSING = ("success", "skipped", "neutral")
    +# A label that leaves a release PR to a person (ashigaru automerge.FLAGS).
    +FLAGS = frozenset({"needs-human"})
    +_NOT_FOUND = 404
    +_REFUSED = (405, 409)
    +_CONFLICT = 409
    +# origin, and nothing else: github.com/<owner>/<name> over https or ssh.
    +_ORIGIN = re.compile(
    +    r"(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)"
    +    r"(?P<owner>[A-Za-z0-9][A-Za-z0-9-]*)/(?P<name>[A-Za-z0-9._-]+?)(?:\.git)?/?"
    +)
    +_TAG = re.compile(rf"v({SEMVER.pattern})")
    +# A Conventional Commit subject: type, optional scope, optional `!`, colon.
    +_SUBJECT = re.compile(r"(?P<type>[A-Za-z]+)(?:\([^)]*\))?(?P<bang>!)?:\s")
    +_BREAKING = re.compile(r"^BREAKING[ -]CHANGE:", re.MULTILINE)
    +# What a commit asks of the version, least to most.
    +_PATCH, _FEATURE, _BREAKS = 0, 1, 2
    +SKOPEO_SECONDS = 120
    +# How far this machine's clock may run ahead of GitHub's when a run is matched
    +# to the dispatch that made it.
    +CLOCK_SKEW = 120
    +COSIGN_SECONDS = 300
    +
    +# How long each wait gives the forge, and how often it asks.
    +WAITS = {
    +    "run": (300.0, 10.0),  # the dispatch's run to appear
    +    "dispatch": (1800.0, 20.0),  # the dispatch's run to finish: the release PR
    +    "checks": (3600.0, 30.0),  # the release PR's required checks
    +    "landing": (3600.0, 30.0),  # the push run on the merge commit
    +}
    +
    +
    +# --- what a step reaches the world through; the suite replaces each -----------
    +
    +
    +def connect(run: Run) -> Api:
    +    """GitHub as the github credential sees it."""
    +    return GitHub(run.credential("github"))
    +
    +
    +def git(*args: str) -> str | None:
    +    """git's stdout in the clone bin/sdlc mounted, or None when git says no."""
    +    proc = subprocess.run(
    +        ["git", "-C", str(REPO_ROOT), *args], capture_output=True, text=True, check=False
    +    )
    +    return proc.stdout if proc.returncode == 0 else None
    +
    +
    +def desk(url: str, token: str) -> tuple[Api, str]:
    +    """The Desk's API at `url`, and the path it is served under.
    +
    +    The same REST client GitHub's calls use: one host, https only, and a
    +    redirect to another host never carries the token.
    +    """
    +    parts = urllib.parse.urlsplit(url)
    +    if parts.scheme != "https" or not parts.netloc:
    +        raise CannotRunError(f"the Desk is reached over https only, not {url}")
    +    return GitHub(token, host=parts.netloc), parts.path.rstrip("/")
    +
    +
    +def digest_of(ref: str) -> str | None:
    +    """The digest `ref` names in its registry, or None when it names nothing."""
    +    proc = subprocess.run(
    +        ["skopeo", "inspect", "--no-tags", "--format", "{{.Digest}}", f"docker://{ref}"],
    +        capture_output=True,
    +        text=True,
    +        check=False,
    +        timeout=SKOPEO_SECONDS,
    +    )
    +    if proc.returncode == 0:
    +        return proc.stdout.strip() or None
    +    if "manifest unknown" in proc.stderr or "not found" in proc.stderr.lower():
    +        return None
    +    raise CannotRunError(f"skopeo could not read {ref}: {proc.stderr.strip()[:300]}")
    +
    +
    +def signed(ref: str) -> bool:
    +    """Does `ref` (by digest) carry the fleet key's signature, as promote verifies it?"""
    +    with tempfile.TemporaryDirectory() as scratch:
    +        pub = Path(scratch) / "fleet.pub"
    +        pub.write_text(FLEET_PUBLIC_KEY)
    +        argv = ["cosign", "verify", "--insecure-ignore-tlog", "--key", str(pub), ref]
    +        proc = subprocess.run(
    +            argv, capture_output=True, text=True, check=False, timeout=COSIGN_SECONDS
    +        )
    +    return proc.returncode == 0
    +
    +
    +ENV: Mapping[str, str] = os.environ
    +TIMER: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
    +
    +
    +def now() -> datetime:
    +    return datetime.now(UTC)
    +
    +
    +def today() -> str:
    +    """The CHANGELOG heading's date, UTC's, as the App's release commit writes it."""
    +    return datetime.now(UTC).date().isoformat()
    +
    +
    +# --- what every step works out the same way ------------------------------------
    +
    +
    +@dataclass
    +class Asked:
    +    """The person's arguments, checked."""
    +
    +    version: str | None
    +    item: str | None
    +    includes: list[str]
    +    resume: str | None
    +
    +
    +@dataclass
    +class Release:
    +    """What every step knows of the release, read back from the forge."""
    +
    +    api: Api
    +    repo: str
    +    default: str
    +    head: str
    +    version: str
    +    asked: Asked
    +
    +    @property
    +    def branch(self) -> str:
    +        return f"{BRANCH}{self.version}"
    +
    +    @property
    +    def tag(self) -> str:
    +        return f"v{self.version}"
    +
    +    def url(self, path: str = "") -> str:
    +        return f"https://github.com/{self.repo}{path}"
    +
    +
    +def origin_repo() -> str:
    +    """owner/name from origin's URL, parsed strictly, or a 2."""
    +    url = (git("remote", "get-url", "origin") or "").strip()
    +    m = _ORIGIN.fullmatch(url)
    +    if not m:
    +        raise CannotRunError(f"origin is not github.com/<owner>/<name>: {url or 'no origin'}")
    +    return f"{m['owner']}/{m['name']}"
    +
    +
    +def identity(api: Api) -> tuple[str, str]:
    +    """(owner/name, default branch) of origin, confirmed by GitHub, or a 2."""
    +    repo = origin_repo()
    +    try:
    +        found = api.request("GET", f"/repos/{repo}")
    +    except ApiError as err:
    +        raise CannotRunError(f"{repo} does not resolve on GitHub: {err}") from err
    +    name = (found or {}).get("full_name")
    +    default = (found or {}).get("default_branch")
    +    if not isinstance(name, str) or name.lower() != repo.lower() or not isinstance(default, str):
    +        raise CannotRunError(f"GitHub answers {name!r} for {repo}, not that repo")
    +    return name, default
    +
    +
    +def local_head() -> str:
    +    head = (git("rev-parse", "HEAD") or "").strip()
    +    if not re.fullmatch(r"[0-9a-f]{40}", head):
    +        raise CannotRunError("this clone has no HEAD commit")
    +    return head
    +
    +
    +def triple(version: str) -> tuple[int, int, int]:
    +    a, b, c = (int(p) for p in version.split("."))
    +    return a, b, c
    +
    +
    +def tags(api: Api, repo: str) -> list[str]:
    +    """Every vX.Y.Z tag's version, newest first."""
    +    names = [t.get("name") for t in api.pages(f"/repos/{repo}/tags") if isinstance(t, dict)]
    +    found = [m[1] for n in names if isinstance(n, str) and (m := _TAG.fullmatch(n))]
    +    return sorted(set(found), key=triple, reverse=True)
    +
    +
    +def bump(version: str, messages: Sequence[str]) -> str:
    +    """The next version after `version` for these commit messages (constitution R1).
    +
    +    A breaking change bumps MAJOR, or MINOR before 1.0.0; a feat bumps MINOR;
    +    anything else PATCH.
    +    """
    +    major, minor, patch = triple(version)
    +    level = _PATCH
    +    for message in messages:
    +        m = _SUBJECT.match(message)
    +        if (m and m["bang"]) or _BREAKING.search(message):
    +            level = max(level, _BREAKS)
    +        elif m and m["type"].lower() == "feat":
    +            level = max(level, _FEATURE)
    +    if level == _BREAKS and major > 0:
    +        return f"{major + 1}.0.0"
    +    if level >= _FEATURE:
    +        return f"{major}.{minor + 1}.0"
    +    return f"{major}.{minor}.{patch + 1}"
    +
    +
    +def behind_head(api: Api, repo: str, head: str) -> tuple[str, list[str]] | None:
    +    """(version, messages since it) for the newest vX.Y.Z tag HEAD has; None when it has none."""
    +    for version in tags(api, repo):
    +        compared = api.request("GET", f"/repos/{repo}/compare/v{version}...{head}")
    +        if (compared or {}).get("status") in ("ahead", "identical"):
    +            commits = compared.get("commits") or []
    +            return version, [str((c.get("commit") or {}).get("message", "")) for c in commits]
    +    return None
    +
    +
    +def derived(api: Api, repo: str, head: str) -> str:
    +    since = behind_head(api, repo, head)
    +    if since is None:
    +        raise RefusedError(
    +            f"{repo} has no vX.Y.Z tag behind HEAD to derive a version from; "
    +            "name one with --version"
    +        )
    +    base, messages = since
    +    if not messages:
    +        raise RefusedError(f"nothing has landed since v{base}: there is nothing to release")
    +    return bump(base, messages)
    +
    +
    +def release_pull(api: Api, repo: str, number: int) -> dict[str, Any]:
    +    """The pull request --resume names, which must be the App's release PR, or a 1."""
    +    pull = api.request("GET", f"/repos/{repo}/pulls/{number}") or {}
    +    ref = (pull.get("head") or {}).get("ref", "")
    +    m = re.fullmatch(rf"{re.escape(BRANCH)}({SEMVER.pattern})", str(ref))
    +    if not m:
    +        raise RefusedError(f"{repo}#{number} is not on an {BRANCH}X.Y.Z branch: {ref!r}")
    +    authored(pull, f"{repo}#{number}")
    +    if pull.get("state") != "open" and not pull.get("merged_at"):
    +        raise RefusedError(f"{repo}#{number} was closed unmerged; cut the release again")
    +    return pull
    +
    +
    +def authored(pull: Mapping[str, Any], where: str) -> None:
    +    """A release PR the Ashigaru App did not write, or from another repo, is a 1."""
    +    login = (pull.get("user") or {}).get("login")
    +    if login != APP_LOGIN:
    +        raise RefusedError(f"{where} was opened by {login!r}, not the Ashigaru App ({APP_LOGIN})")
    +
    +
    +_KNOWN: dict[int, Release] = {}
    +
    +
    +def release_of(run: Run) -> Release:
    +    """What this step knows of the release, from origin, GitHub and the arguments.
    +
    +    Worked out once per run of a step: its `done` and its `run` ask the same.
    +    """
    +    if id(run) in _KNOWN:
    +        return _KNOWN[id(run)]
    +    asked = asked_of(parser().parse_args(run.argv))
    +    api = connect(run)
    +    repo, default = identity(api)
    +    head = local_head()
    +    if asked.resume is not None:
    +        named, number = _runner.parse_ref(asked.resume)
    +        if named.lower() != repo.lower():
    +            raise CannotRunError(f"--resume names {named}, and this clone is {repo}")
    +        pull = release_pull(api, repo, number)
    +        version = pull["head"]["ref"][len(BRANCH) :]
    +        if asked.version is not None and asked.version != version:
    +            raise CannotRunError(
    +                f"--version {asked.version}, and {asked.resume} releases {version}"
    +            )
    +        run.resume_ref = f"{repo}#{number}"
    +    else:
    +        version = asked.version or derived(api, repo, head)
    +    _KNOWN[id(run)] = Release(api, repo, default, head, version, asked)
    +    return _KNOWN[id(run)]
    +
    +
    +# --- the forge's answers ------------------------------------------------------
    +
    +
    +def pulls(rel: Release) -> list[dict[str, Any]]:
    +    """Every PR from this repo's ashigaru/release-X.Y.Z into the default branch; App-only."""
    +    owner = rel.repo.split("/", 1)[0]
    +    found = rel.api.request(
    +        "GET", f"/repos/{rel.repo}/pulls?head={owner}:{rel.branch}&state=all&per_page=100"
    +    )
    +    mine = [
    +        p
    +        for p in found or []
    +        if (p.get("head") or {}).get("ref") == rel.branch
    +        and ((p.get("head") or {}).get("repo") or {}).get("full_name", "").lower()
    +        == rel.repo.lower()
    +        and (p.get("base") or {}).get("ref") == rel.default
    +    ]
    +    for p in mine:
    +        authored(p, f"{rel.repo}#{p.get('number')}")
    +    return mine
    +
    +
    +def open_pull(rel: Release) -> dict[str, Any] | None:
    +    """The one open release PR, or None; two open is a 2."""
    +    found = [p for p in pulls(rel) if p.get("state") == "open"]
    +    if len(found) > 1:
    +        numbers = ", ".join(f"#{p.get('number')}" for p in found)
    +        raise CannotRunError(
    +            f"{rel.repo} has {len(found)} open release PRs for {rel.version}: {numbers}"
    +        )
    +    return found[0] if found else None
    +
    +
    +def merged_pull(rel: Release) -> dict[str, Any] | None:
    +    return next((p for p in pulls(rel) if p.get("merged_at")), None)
    +
    +
    +def merged(run: Run) -> bool:
    +    """Has the release PR merged?"""
    +    rel = release_of(run)
    +    return any(p.get("merged_at") for p in pulls(rel))
    +
    +
    +def tagged(rel: Release) -> str | None:
    +    """The commit the vX.Y.Z tag names, or None when there is no such tag."""
    +    try:
    +        ref = rel.api.request("GET", f"/repos/{rel.repo}/git/ref/tags/{rel.tag}")
    +    except ApiError as err:
    +        if err.status == _NOT_FOUND:
    +            return None
    +        raise
    +    obj = (ref or {}).get("object") or {}
    +    if obj.get("type") == "tag":  # annotated: the tag object names the commit
    +        obj = (rel.api.request("GET", f"/repos/{rel.repo}/git/tags/{obj.get('sha')}") or {}).get(
    +            "object"
    +        ) or {}
    +    return str(obj.get("sha", "")) or None
    +
    +
    +def existing(rel: Release) -> str | None:
    +    """What says this release was already cut: its open or merged PR, or its tag; else None.
    +
    +    A PR closed unmerged is a cut that was abandoned, so it is cut again.
    +    """
    +    live = [p for p in pulls(rel) if p.get("state") == "open" or p.get("merged_at")]
    +    if live:
    +        return f"{rel.repo}#{live[0].get('number')}"
    +    return rel.tag if tagged(rel) is not None else None
    +
    +
    +def resuming(run: Run) -> bool:
    +    """Is this run carrying on with the release PR --resume names?
    +
    +    Only that skips preflight, lease and dispatch: a release this run did not
    +    name is refused by preflight, never adopted as this one.
    +    """
    +    return release_of(run).asked.resume is not None
    +
    +
    +# A required check: its name, and the App that must report it (None: any).
    +Need = tuple[str, int | None]
    +
    +
    +def required(rel: Release) -> set[Need]:
    +    """The checks the default branch requires, by ruleset or classic protection, with their Apps."""
    +    branch = urllib.parse.quote(rel.default, safe="")
    +    needs: set[Need] = set()
    +    for rule in rel.api.pages(f"/repos/{rel.repo}/rules/branches/{branch}"):
    +        if isinstance(rule, dict) and rule.get("type") == "required_status_checks":
    +            for need in (rule.get("parameters") or {}).get("required_status_checks") or []:
    +                if isinstance(need, dict) and isinstance(need.get("context"), str):
    +                    app = need.get("integration_id")
    +                    needs.add((need["context"], app if isinstance(app, int) else None))
    +    found = rel.api.request("GET", f"/repos/{rel.repo}/branches/{branch}") or {}
    +    classic = (found.get("protection") or {}).get("required_status_checks") or {}
    +    for check in classic.get("checks") or []:
    +        if isinstance(check, dict) and isinstance(check.get("context"), str):
    +            app = check.get("app_id")
    +            needs.add((check["context"], app if isinstance(app, int) else None))
    +    known = {name for name, _ in needs}
    +    needs.update((c, None) for c in classic.get("contexts") or [] if c not in known)
    +    return needs
    +
    +
    +def reported(rel: Release, sha: str) -> list[tuple[str, int | None, str]]:
    +    """(name, App, verdict) for each check run and commit status on `sha`; "pending" until done."""
    +    seen: list[tuple[str, int | None, str]] = []
    +    runs = rel.api.pages(f"/repos/{rel.repo}/commits/{sha}/check-runs?filter=latest", "check_runs")
    +    for cr in runs:
    +        state = cr.get("conclusion") if cr.get("status") == "completed" else "pending"
    +        app = (cr.get("app") or {}).get("id")
    +        seen.append(
    +            (str(cr.get("name")), app if isinstance(app, int) else None, str(state or "pending"))
    +        )
    +    status = rel.api.request("GET", f"/repos/{rel.repo}/commits/{sha}/status") or {}
    +    for st in status.get("statuses") or []:
    +        state = st.get("state")
    +        verdict = (
    +            "success" if state == "success" else "pending" if state == "pending" else "failure"
    +        )
    +        seen.append((str(st.get("context")), None, verdict))
    +    return seen
    +
    +
    +def verdict(need: Need, seen: list[tuple[str, int | None, str]]) -> str:
    +    """One requirement's verdict: what its App reported under its name, combined as the Desk does.
    +
    +    Never reported is pending; any pending is pending; else any failure fails.
    +    """
    +    name, app = need
    +    states = [v for n, a, v in seen if n == name and (app is None or a == app)]
    +    if not states or "pending" in states:
    +        return "pending"
    +    return next((v for v in states if v not in PASSING), states[0])
    +
    +
    +def judged(rel: Release, pull: Mapping[str, Any]) -> bool | None:
    +    """True when every required check passed on the PR's head; None while any is pending.
    +
    +    A required check that failed is a 1 naming it.
    +    """
    +    need = required(rel)
    +    if not need:
    +        raise RefusedError(
    +            f"{rel.default} requires no checks, and release merges nothing nothing judged"
    +        )
    +    seen = reported(rel, pull["head"]["sha"])
    +    states = {n: verdict(n, seen) for n in need}
    +    failed = sorted(n[0] for n, v in states.items() if v not in (*PASSING, "pending"))
    +    if failed:
    +        raise RefusedError(
    +            "required checks failed on the release PR: "
    +            + ", ".join(failed)
    +            + f"\n{pull.get('html_url', '')}"
    +        )
    +    return True if all(v in PASSING for v in states.values()) else None
    +
    +
    +def runs(rel: Release, event: str, sha: str) -> list[dict[str, Any]]:
    +    return (
    +        rel.api.request(
    +            "GET",
    +            f"/repos/{rel.repo}/actions/workflows/{WORKFLOW}/runs"
    +            f"?event={event}&head_sha={sha}&per_page=100",
    +        ).get("workflow_runs")
    +        or []
    +    )
    +
    +
    +def finished(rel: Release, run_id: int, what: str) -> None:
    +    """Wait for run `run_id` to complete; anything but success is a 1 naming the failed jobs."""
    +    path = f"/repos/{rel.repo}/actions/runs/{run_id}"
    +    url = rel.url(f"/actions/runs/{run_id}")
    +    timeout, every = WAITS[what]
    +
    +    def probe() -> dict[str, Any] | None:
    +        got = rel.api.request("GET", path) or {}
    +        return got if got.get("status") == "completed" else None
    +
    +    done = wait_for(probe, Wait(f"the {what} run to finish", url, timeout, every), TIMER)
    +    if done.get("conclusion") != "success":
    +        jobs = rel.api.pages(f"{path}/jobs", "jobs")
    +        bad = [
    +            f"{j.get('name')} ({j.get('conclusion')})"
    +            for j in jobs
    +            if j.get("conclusion") not in PASSING
    +        ]
    +        raise RefusedError(
    +            f"the {what} run ended {done.get('conclusion')}: "
    +            f"{', '.join(bad) or 'no job failed'}\n{url}"
    +        )
    +
    +
    +def the_run(run: Run, rel: Release, which: tuple[str, str, set[object], str], what: str) -> None:
    +    """Wait for the one new run, then for it to pass.
    +
    +    `which` is (event, sha, before, after): a run of ci.yml for `event` on
    +    `sha`, not among the ids `before`, created no earlier than `after` (UTC,
    +    ISO 8601; "" for any). Two that could be it is a 2: nothing says which one
    +    is this release's.
    +    """
    +    event, sha, before, after = which
    +
    +    def probe() -> dict[str, Any] | None:
    +        new = [
    +            r
    +            for r in runs(rel, event, sha)
    +            if r.get("id") not in before
    +            and r.get("event") == event
    +            and r.get("head_sha") == sha
    +            and str(r.get("path", WORKFLOW)).endswith(WORKFLOW)
    +            and str(r.get("created_at", "")) >= after
    +        ]
    +        if len(new) > 1:
    +            urls = ", ".join(str(r.get("html_url", r.get("id"))) for r in new)
    +            raise CannotRunError(f"{len(new)} runs could be the {what} run: {urls}")
    +        return new[0] if new else None
    +
    +    timeout, every = WAITS["run"]
    +    url = rel.url(f"/actions/workflows/{WORKFLOW}")
    +    found = wait_for(probe, Wait(f"the {what} run", url, timeout, every), TIMER)
    +    run.say(f"{what} run: {found.get('html_url', found.get('id'))}")
    +    finished(rel, int(found["id"]), what)
    +
    +
    +# --- the steps ------------------------------------------------------------------
    +
    +
    +def step_identify(run: Run) -> None:
    +    if ENV.get("JOSUI_NAME") and asked_of(parser().parse_args(run.argv)).item is None:
    +        raise RefusedError(
    +            "an agent releases under a work item: pass --item aN (JOSUI_NAME is set)"
    +        )
    +    rel = release_of(run)
    +    run.say(f"{rel.repo} {rel.version}, from {rel.default} at {rel.head[:12]}")
    +
    +
    +def step_preflight(run: Run) -> None:
    +    rel = release_of(run)
    +    there = existing(rel)
    +    if there is not None:
    +        resume = f"; carry it on with --resume {there}" if "#" in there else ""
    +        raise RefusedError(f"{rel.repo} {rel.version} was already cut: {there}{resume}")
    +    branch = (git("symbolic-ref", "--quiet", "--short", "HEAD") or "").strip()
    +    if branch != rel.default:
    +        raise RefusedError(
    +            f"a release is cut from {rel.default}, and this clone is on {branch or 'no branch'}"
    +        )
    +    quoted = urllib.parse.quote(rel.default, safe="")
    +    there = (
    +        (rel.api.request("GET", f"/repos/{rel.repo}/branches/{quoted}") or {}).get("commit") or {}
    +    ).get("sha")
    +    if there != rel.head:
    +        raise RefusedError(
    +            f"this clone's {rel.default} is at {rel.head[:12]} and origin's at {str(there)[:12]}: "
    +            f"git pull, then release"
    +        )
    +    newest = tags(rel.api, rel.repo)
    +    if newest and triple(rel.version) <= triple(newest[0]):
    +        raise RefusedError(f"{rel.version} is not newer than the newest tag, v{newest[0]}")
    +
    +    def read(path: str) -> str | None:
    +        return git("show", f"HEAD:{path}")
    +
    +    try:
    +        edits = _bump.release_edits(read, rel.version, today())
    +    except _bump.ReleaseError as err:
    +        raise RefusedError(f"the release commit cannot be made: {err}") from err
    +    run.say(f"{rel.version} moves {', '.join(sorted(edits)) or 'nothing'}")
    +
    +
    +def step_lease(run: Run) -> None:
    +    rel = release_of(run)
    +    hosts = _hosts.load()
    +    if hosts.desk_url is None:
    +        run.say("UNLEASED: the Desk will adopt this release")
    +        return
    +    api, base = desk(hosts.desk_url, run.credential("desk"))
    +    body: dict[str, object] = {"repo": rel.repo, "version": rel.version}
    +    if rel.asked.item is not None:
    +        body["item"] = rel.asked.item
    +    try:
    +        api.request("POST", f"{base}/v1/releases", body)
    +    except ApiError as err:
    +        if err.status != _CONFLICT:
    +            raise CannotRunError(
    +                f"the Desk would not lease {rel.repo} {rel.version}: {err}"
    +            ) from err
    +        if not ours(rel, api, base):
    +            raise RefusedError(f"the Desk holds another release's lease: {err}") from err
    +        run.say(f"the Desk's lease on {rel.repo} is already this release's")
    +        return
    +    run.say(f"leased {rel.repo} {rel.version} on the Desk")
    +
    +
    +def ours(rel: Release, api: Api, base: str) -> bool:
    +    """Is the lease in flight on this repo for this version and item?"""
    +    leases = api.request("GET", f"{base}/v1/releases")
    +    if not isinstance(leases, list):
    +        raise CannotRunError(f"the Desk's {base}/v1/releases is not a list of leases")
    +    return any(
    +        isinstance(lease, dict)
    +        and str(lease.get("repo", "")).lower() == rel.repo.lower()
    +        and lease.get("version") == rel.version
    +        and lease.get("item") == rel.asked.item
    +        and not lease.get("ended_at")
    +        for lease in leases
    +    )
    +
    +
    +def step_dispatch(run: Run) -> None:
    +    rel = release_of(run)
    +    before = {r.get("id") for r in runs(rel, "workflow_dispatch", rel.head)}
    +    after = (now() - timedelta(seconds=CLOCK_SKEW)).strftime("%Y-%m-%dT%H:%M:%SZ")
    +    inputs = {"version": rel.version}
    +    if rel.asked.item is not None:
    +        inputs["item"] = rel.asked.item
    +    if rel.asked.includes:
    +        inputs["includes"] = ",".join(rel.asked.includes)
    +    rel.api.request(
    +        "POST",
    +        f"/repos/{rel.repo}/actions/workflows/{WORKFLOW}/dispatches",
    +        {"ref": rel.default, "inputs": inputs},
    +    )
    +    the_run(run, rel, ("workflow_dispatch", rel.head, before, after), "dispatch")
    +
    +
    +def step_pr(run: Run) -> None:
    +    rel = release_of(run)
    +    pull = open_pull(rel)
    +    if pull is None:
    +        raise RefusedError(
    +            f"the dispatch finished and {rel.repo} has no open release PR on {rel.branch}"
    +        )
    +    run.resume_ref = f"{rel.repo}#{pull['number']}"
    +    run.say(f"release PR: {pull.get('html_url', run.resume_ref)}")
    +    flagged(rel, pull)
    +    the_apps_cut(rel, pull["head"]["sha"])
    +    green(rel, pull)
    +    run.say(f"every required check passed on {pull['head']['sha'][:12]}")
    +
    +
    +def green(rel: Release, pull: Mapping[str, Any]) -> None:
    +    """Wait for every required check on the PR's head to pass; a failure is a 1."""
    +    timeout, every = WAITS["checks"]
    +    wait = Wait("the release PR's required checks", str(pull.get("html_url", "")), timeout, every)
    +    wait_for(lambda: judged(rel, pull), wait, TIMER)
    +
    +
    +def step_merged(run: Run) -> None:
    +    rel = release_of(run)
    +    pull = open_pull(rel)
    +    if pull is None:
    +        raise RefusedError(f"{rel.repo} has no open release PR on {rel.branch} to merge")
    +    run.resume_ref = f"{rel.repo}#{pull['number']}"
    +    head = pull["head"]["sha"]
    +    # This step's own read of the head: the merge is pinned to the head it judged.
    +    flagged(rel, pull)
    +    the_apps_cut(rel, head)
    +    green(rel, pull)
    +    moved(rel, head)
    +    try:
    +        rel.api.request(
    +            "PUT",
    +            f"/repos/{rel.repo}/pulls/{pull['number']}/merge",
    +            {"merge_method": "squash", "sha": head},
    +        )
    +    except ApiError as err:
    +        # 405 is also what a PR another merger (the Desk's cut) already merged answers.
    +        if err.status not in _REFUSED:
    +            raise
    +        if not (rel.api.request("GET", f"/repos/{rel.repo}/pulls/{pull['number']}") or {}).get(
    +            "merged_at"
    +        ):
    +            raise RefusedError(
    +                f"GitHub would not merge {run.resume_ref} at {head[:12]}: {err}"
    +            ) from err
    +        run.say(f"{run.resume_ref} was already merged")
    +    as_passed(rel, pull["number"], head)
    +    run.say(f"merged {run.resume_ref} at {head[:12]}")
    +
    +
    +def flagged(rel: Release, pull: Mapping[str, Any]) -> None:
    +    """The Desk's cut refusals (ashigaru desk/cuts.py `refusal`): a draft, a flag, changes asked."""
    +    where = f"{rel.repo}#{pull['number']}"
    +    if pull.get("draft"):
    +        raise RefusedError(f"{where} is a draft")
    +    labels = {
    +        str(label.get("name")) for label in pull.get("labels") or [] if isinstance(label, dict)
    +    }
    +    if FLAGS & labels:
    +        raise RefusedError(f"{where} is flagged {', '.join(sorted(FLAGS & labels))}")
    +    latest: dict[str, str] = {}
    +    for review in rel.api.pages(f"/repos/{rel.repo}/pulls/{pull['number']}/reviews"):
    +        login, state = (review.get("user") or {}).get("login"), review.get("state")
    +        if isinstance(login, str) and state in ("APPROVED", "CHANGES_REQUESTED", "DISMISSED"):
    +            latest[login] = str(state)
    +    asked = sorted(who for who, state in latest.items() if state == "CHANGES_REQUESTED")
    +    if asked:
    +        raise RefusedError(f"{where} has changes requested by {', '.join(asked)}")
    +
    +
    +class ForgeTools(Tools):
    +    """`Tools`' GitHub calls answered by an `Api`, so `_prs` judges a tree here as in CI."""
    +
    +    def __init__(self, api: Api) -> None:
    +        self.api = api
    +
    +    def http(
    +        self, method: str, url: str, headers: Mapping[str, str], payload: bytes | None = None
    +    ) -> Response:
    +        del headers  # the Api carries its own credential
    +        path = url.removeprefix("https://api.github.com")
    +        try:
    +            got = self.api.request(method, path, None if payload is None else json.loads(payload))
    +        except ApiError as err:
    +            return Response(err.status, str(err).encode())
    +        return Response(200, json.dumps(got).encode())
    +
    +
    +def the_apps_cut(rel: Release, head: str) -> None:
    +    """A 1 unless `head` is the App's one release commit, exactly `release_edits` on its parent.
    +
    +    The same tree equality phase 0 trusts in CI (`_prs.release_of`): a commit
    +    pushed onto the release branch after the cut, or a hand-made branch, is
    +    not what the App cut and is merged by hand or not at all.
    +    """
    +    commit = rel.api.request("GET", f"/repos/{rel.repo}/commits/{head}") or {}
    +    who = {str((commit.get(role) or {}).get("login")) for role in ("author", "committer")}
    +    if who != {APP_LOGIN}:
    +        raise RefusedError(
    +            f"the release PR's head {head[:12]} is by {', '.join(sorted(who))}, not the App alone"
    +        )
    +    said = io.StringIO()

    MEDIUM (General Review): the_apps_cut captures _prs.release_of's stdout and parses its human-readable text to construct a refusal reason. This couples control flow to diagnostic wording and uses process-wide stdout redirection, making the check harder to maintain and unsafe to compose with concurrent output.

    Suggestion: Expose a structured result or error reason from _prs.release_of (or a dedicated validation function) and use that directly instead of redirecting and parsing stdout.

    Evidence:

        said = io.StringIO()
        with contextlib.redirect_stdout(said):
            parent = _prs.release_of(ForgeTools(rel.api), {}, rel.repo, head, rel.version)
        if parent is None:
            why = said.getvalue().strip().removeprefix("gates: ").removesuffix(": gating")
    

    <!-- gatehouse agent=general confidence=92 votes=1/1 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 21:55 UTC
    Reviewer

    Gatehouse found 3 issues (2 critical, 1 medium)

    Reviewed 1 commit since 35ca946 (incremental).

    5 finding(s) dropped: their evidence is not in the diff.

    <!-- gatehouse review complete -->

    fatherlinux fatherlinux commented on code on Dec 04, 2026 22:17 UTC
    Code Review
    sdlc_jobs/life/release.py:1
    @@ -0,0 +1,902 @@
    +"""`sdlc release`: the normal path to a published image (docs/lifecycle.md).
    +
    +Replaces josui-land-release and every hand dispatch. Seven steps, each in a
    +container of its own with only the credentials it declares, and each
    +idempotent: it asks the forge whether its result is already there and goes on
    +when it is, so running the command again is how it resumes.
    +
    +    identify   origin's URL, parsed strictly, confirmed by GET /repos
    +    preflight  the default branch at origin's head, a non-empty Unreleased, a
    +               version newer than the newest tag, and `_bump.release_edits`'
    +               refusal seen here before anything is dispatched
    +    lease      the Desk's release lease, the one its own cuts take
    +    dispatch   ci.yml with version, item and includes; the one run it started
    +    pr         the App's release PR on ashigaru/release-X.Y.Z, and its
    +               required checks
    +    merged     squash, pinned to the head whose checks passed
    +    image      the push run on the merge, the tag on the merge commit, the
    +               GitHub Release, and each image's X.Y.Z and latest one signed digest
    +
    +Nothing passes from one step to the next but the forge. The version is the
    +same in every step because it is worked out the same way: `--version`; else
    +the release PR `--resume` names; else the Conventional Commits from the newest
    +vX.Y.Z tag behind this clone's HEAD to HEAD, which a tag made on the release's
    +own merge commit is never behind.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import contextlib
    +import io
    +import json
    +import os
    +import re
    +import subprocess
    +import tempfile
    +import time
    +import urllib.parse
    +from collections.abc import Callable, Mapping, Sequence
    +from dataclasses import dataclass
    +from datetime import UTC, datetime, timedelta
    +from pathlib import Path
    +from typing import Any
    +
    +from sdlc_jobs import _bump, _prs
    +from sdlc_jobs._core import (
    +    FLEET_PUBLIC_KEY,
    +    ITEM,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    images,
    +    parse_includes,
    +)
    +from sdlc_jobs._github import APP_LOGIN, Api, ApiError, GitHub
    +from sdlc_jobs.life import _hosts, _runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait, wait_for
    +
    +COMMAND = "release"
    +WORKFLOW = "ci.yml"
    +BRANCH = "ashigaru/release-"
    +REPO_ROOT = Path("/repo")
    +# A check passes as the Desk's cuts judge it (ashigaru automerge.PASSING).
    +PASSING = ("success", "skipped", "neutral")
    +# A label that leaves a release PR to a person (ashigaru automerge.FLAGS).
    +FLAGS = frozenset({"needs-human"})
    +_NOT_FOUND = 404
    +_REFUSED = (405, 409)
    +_CONFLICT = 409
    +# origin, and nothing else: github.com/<owner>/<name> over https or ssh.
    +_ORIGIN = re.compile(
    +    r"(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)"
    +    r"(?P<owner>[A-Za-z0-9][A-Za-z0-9-]*)/(?P<name>[A-Za-z0-9._-]+?)(?:\.git)?/?"
    +)
    +_TAG = re.compile(rf"v({SEMVER.pattern})")
    +# A Conventional Commit subject: type, optional scope, optional `!`, colon.
    +_SUBJECT = re.compile(r"(?P<type>[A-Za-z]+)(?:\([^)]*\))?(?P<bang>!)?:\s")
    +_BREAKING = re.compile(r"^BREAKING[ -]CHANGE:", re.MULTILINE)
    +# What a commit asks of the version, least to most.
    +_PATCH, _FEATURE, _BREAKS = 0, 1, 2
    +SKOPEO_SECONDS = 120
    +# How far this machine's clock may run ahead of GitHub's when a run is matched
    +# to the dispatch that made it.
    +CLOCK_SKEW = 120
    +COSIGN_SECONDS = 300
    +
    +# How long each wait gives the forge, and how often it asks.
    +WAITS = {
    +    "run": (300.0, 10.0),  # the dispatch's run to appear
    +    "dispatch": (1800.0, 20.0),  # the dispatch's run to finish: the release PR
    +    "checks": (3600.0, 30.0),  # the release PR's required checks
    +    "landing": (3600.0, 30.0),  # the push run on the merge commit
    +}
    +
    +
    +# --- what a step reaches the world through; the suite replaces each -----------
    +
    +
    +def connect(run: Run) -> Api:
    +    """GitHub as the github credential sees it."""
    +    return GitHub(run.credential("github"))
    +
    +
    +def git(*args: str) -> str | None:
    +    """git's stdout in the clone bin/sdlc mounted, or None when git says no."""
    +    proc = subprocess.run(
    +        ["git", "-C", str(REPO_ROOT), *args], capture_output=True, text=True, check=False
    +    )
    +    return proc.stdout if proc.returncode == 0 else None
    +
    +
    +def desk(url: str, token: str) -> tuple[Api, str]:
    +    """The Desk's API at `url`, and the path it is served under.
    +
    +    The same REST client GitHub's calls use: one host, https only, and a
    +    redirect to another host never carries the token.
    +    """
    +    parts = urllib.parse.urlsplit(url)
    +    if parts.scheme != "https" or not parts.netloc:
    +        raise CannotRunError(f"the Desk is reached over https only, not {url}")
    +    return GitHub(token, host=parts.netloc), parts.path.rstrip("/")
    +
    +
    +def digest_of(ref: str) -> str | None:
    +    """The digest `ref` names in its registry, or None when it names nothing."""
    +    proc = subprocess.run(
    +        ["skopeo", "inspect", "--no-tags", "--format", "{{.Digest}}", f"docker://{ref}"],
    +        capture_output=True,
    +        text=True,
    +        check=False,
    +        timeout=SKOPEO_SECONDS,
    +    )
    +    if proc.returncode == 0:
    +        return proc.stdout.strip() or None
    +    if "manifest unknown" in proc.stderr or "not found" in proc.stderr.lower():
    +        return None
    +    raise CannotRunError(f"skopeo could not read {ref}: {proc.stderr.strip()[:300]}")
    +
    +
    +def signed(ref: str) -> bool:
    +    """Does `ref` (by digest) carry the fleet key's signature, as promote verifies it?"""
    +    with tempfile.TemporaryDirectory() as scratch:
    +        pub = Path(scratch) / "fleet.pub"
    +        pub.write_text(FLEET_PUBLIC_KEY)
    +        argv = ["cosign", "verify", "--insecure-ignore-tlog", "--key", str(pub), ref]
    +        proc = subprocess.run(
    +            argv, capture_output=True, text=True, check=False, timeout=COSIGN_SECONDS
    +        )
    +    return proc.returncode == 0
    +
    +
    +ENV: Mapping[str, str] = os.environ
    +TIMER: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
    +
    +
    +def now() -> datetime:

    Fixed in 1d38cca

    now() has a docstring: this machine's time in UTC, used to match a dispatch to its run.

    fatherlinux fatherlinux commented on code on Dec 04, 2026 22:17 UTC
    Code Review
    sdlc_jobs/life/release.py:1
    @@ -0,0 +1,902 @@
    +"""`sdlc release`: the normal path to a published image (docs/lifecycle.md).
    +
    +Replaces josui-land-release and every hand dispatch. Seven steps, each in a
    +container of its own with only the credentials it declares, and each
    +idempotent: it asks the forge whether its result is already there and goes on
    +when it is, so running the command again is how it resumes.
    +
    +    identify   origin's URL, parsed strictly, confirmed by GET /repos
    +    preflight  the default branch at origin's head, a non-empty Unreleased, a
    +               version newer than the newest tag, and `_bump.release_edits`'
    +               refusal seen here before anything is dispatched
    +    lease      the Desk's release lease, the one its own cuts take
    +    dispatch   ci.yml with version, item and includes; the one run it started
    +    pr         the App's release PR on ashigaru/release-X.Y.Z, and its
    +               required checks
    +    merged     squash, pinned to the head whose checks passed
    +    image      the push run on the merge, the tag on the merge commit, the
    +               GitHub Release, and each image's X.Y.Z and latest one signed digest
    +
    +Nothing passes from one step to the next but the forge. The version is the
    +same in every step because it is worked out the same way: `--version`; else
    +the release PR `--resume` names; else the Conventional Commits from the newest
    +vX.Y.Z tag behind this clone's HEAD to HEAD, which a tag made on the release's
    +own merge commit is never behind.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import contextlib
    +import io
    +import json
    +import os
    +import re
    +import subprocess
    +import tempfile
    +import time
    +import urllib.parse
    +from collections.abc import Callable, Mapping, Sequence
    +from dataclasses import dataclass
    +from datetime import UTC, datetime, timedelta
    +from pathlib import Path
    +from typing import Any
    +
    +from sdlc_jobs import _bump, _prs
    +from sdlc_jobs._core import (
    +    FLEET_PUBLIC_KEY,
    +    ITEM,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    images,
    +    parse_includes,
    +)
    +from sdlc_jobs._github import APP_LOGIN, Api, ApiError, GitHub
    +from sdlc_jobs.life import _hosts, _runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait, wait_for
    +
    +COMMAND = "release"
    +WORKFLOW = "ci.yml"
    +BRANCH = "ashigaru/release-"
    +REPO_ROOT = Path("/repo")
    +# A check passes as the Desk's cuts judge it (ashigaru automerge.PASSING).
    +PASSING = ("success", "skipped", "neutral")
    +# A label that leaves a release PR to a person (ashigaru automerge.FLAGS).
    +FLAGS = frozenset({"needs-human"})
    +_NOT_FOUND = 404
    +_REFUSED = (405, 409)
    +_CONFLICT = 409
    +# origin, and nothing else: github.com/<owner>/<name> over https or ssh.
    +_ORIGIN = re.compile(
    +    r"(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)"
    +    r"(?P<owner>[A-Za-z0-9][A-Za-z0-9-]*)/(?P<name>[A-Za-z0-9._-]+?)(?:\.git)?/?"
    +)
    +_TAG = re.compile(rf"v({SEMVER.pattern})")
    +# A Conventional Commit subject: type, optional scope, optional `!`, colon.
    +_SUBJECT = re.compile(r"(?P<type>[A-Za-z]+)(?:\([^)]*\))?(?P<bang>!)?:\s")
    +_BREAKING = re.compile(r"^BREAKING[ -]CHANGE:", re.MULTILINE)
    +# What a commit asks of the version, least to most.
    +_PATCH, _FEATURE, _BREAKS = 0, 1, 2
    +SKOPEO_SECONDS = 120
    +# How far this machine's clock may run ahead of GitHub's when a run is matched
    +# to the dispatch that made it.
    +CLOCK_SKEW = 120
    +COSIGN_SECONDS = 300
    +
    +# How long each wait gives the forge, and how often it asks.
    +WAITS = {
    +    "run": (300.0, 10.0),  # the dispatch's run to appear
    +    "dispatch": (1800.0, 20.0),  # the dispatch's run to finish: the release PR
    +    "checks": (3600.0, 30.0),  # the release PR's required checks
    +    "landing": (3600.0, 30.0),  # the push run on the merge commit
    +}
    +
    +
    +# --- what a step reaches the world through; the suite replaces each -----------
    +
    +
    +def connect(run: Run) -> Api:
    +    """GitHub as the github credential sees it."""
    +    return GitHub(run.credential("github"))
    +
    +
    +def git(*args: str) -> str | None:
    +    """git's stdout in the clone bin/sdlc mounted, or None when git says no."""
    +    proc = subprocess.run(
    +        ["git", "-C", str(REPO_ROOT), *args], capture_output=True, text=True, check=False
    +    )
    +    return proc.stdout if proc.returncode == 0 else None
    +
    +
    +def desk(url: str, token: str) -> tuple[Api, str]:
    +    """The Desk's API at `url`, and the path it is served under.
    +
    +    The same REST client GitHub's calls use: one host, https only, and a
    +    redirect to another host never carries the token.
    +    """
    +    parts = urllib.parse.urlsplit(url)
    +    if parts.scheme != "https" or not parts.netloc:
    +        raise CannotRunError(f"the Desk is reached over https only, not {url}")
    +    return GitHub(token, host=parts.netloc), parts.path.rstrip("/")
    +
    +
    +def digest_of(ref: str) -> str | None:
    +    """The digest `ref` names in its registry, or None when it names nothing."""
    +    proc = subprocess.run(
    +        ["skopeo", "inspect", "--no-tags", "--format", "{{.Digest}}", f"docker://{ref}"],
    +        capture_output=True,
    +        text=True,
    +        check=False,
    +        timeout=SKOPEO_SECONDS,
    +    )
    +    if proc.returncode == 0:
    +        return proc.stdout.strip() or None
    +    if "manifest unknown" in proc.stderr or "not found" in proc.stderr.lower():
    +        return None
    +    raise CannotRunError(f"skopeo could not read {ref}: {proc.stderr.strip()[:300]}")
    +
    +
    +def signed(ref: str) -> bool:
    +    """Does `ref` (by digest) carry the fleet key's signature, as promote verifies it?"""
    +    with tempfile.TemporaryDirectory() as scratch:
    +        pub = Path(scratch) / "fleet.pub"
    +        pub.write_text(FLEET_PUBLIC_KEY)
    +        argv = ["cosign", "verify", "--insecure-ignore-tlog", "--key", str(pub), ref]
    +        proc = subprocess.run(
    +            argv, capture_output=True, text=True, check=False, timeout=COSIGN_SECONDS
    +        )
    +    return proc.returncode == 0
    +
    +
    +ENV: Mapping[str, str] = os.environ
    +TIMER: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
    +
    +
    +def now() -> datetime:
    +    return datetime.now(UTC)
    +
    +
    +def today() -> str:
    +    """The CHANGELOG heading's date, UTC's, as the App's release commit writes it."""
    +    return datetime.now(UTC).date().isoformat()
    +
    +
    +# --- what every step works out the same way ------------------------------------
    +
    +
    +@dataclass
    +class Asked:
    +    """The person's arguments, checked."""
    +
    +    version: str | None
    +    item: str | None
    +    includes: list[str]
    +    resume: str | None
    +
    +
    +@dataclass
    +class Release:
    +    """What every step knows of the release, read back from the forge."""
    +
    +    api: Api
    +    repo: str
    +    default: str
    +    head: str
    +    version: str
    +    asked: Asked
    +
    +    @property
    +    def branch(self) -> str:
    +        return f"{BRANCH}{self.version}"
    +
    +    @property
    +    def tag(self) -> str:
    +        return f"v{self.version}"
    +
    +    def url(self, path: str = "") -> str:
    +        return f"https://github.com/{self.repo}{path}"
    +
    +
    +def origin_repo() -> str:
    +    """owner/name from origin's URL, parsed strictly, or a 2."""
    +    url = (git("remote", "get-url", "origin") or "").strip()
    +    m = _ORIGIN.fullmatch(url)
    +    if not m:
    +        raise CannotRunError(f"origin is not github.com/<owner>/<name>: {url or 'no origin'}")
    +    return f"{m['owner']}/{m['name']}"
    +
    +
    +def identity(api: Api) -> tuple[str, str]:
    +    """(owner/name, default branch) of origin, confirmed by GitHub, or a 2."""
    +    repo = origin_repo()
    +    try:
    +        found = api.request("GET", f"/repos/{repo}")
    +    except ApiError as err:
    +        raise CannotRunError(f"{repo} does not resolve on GitHub: {err}") from err
    +    name = (found or {}).get("full_name")
    +    default = (found or {}).get("default_branch")
    +    if not isinstance(name, str) or name.lower() != repo.lower() or not isinstance(default, str):
    +        raise CannotRunError(f"GitHub answers {name!r} for {repo}, not that repo")
    +    return name, default
    +
    +
    +def local_head() -> str:
    +    head = (git("rev-parse", "HEAD") or "").strip()
    +    if not re.fullmatch(r"[0-9a-f]{40}", head):
    +        raise CannotRunError("this clone has no HEAD commit")
    +    return head
    +
    +
    +def triple(version: str) -> tuple[int, int, int]:
    +    a, b, c = (int(p) for p in version.split("."))
    +    return a, b, c
    +
    +
    +def tags(api: Api, repo: str) -> list[str]:
    +    """Every vX.Y.Z tag's version, newest first."""
    +    names = [t.get("name") for t in api.pages(f"/repos/{repo}/tags") if isinstance(t, dict)]
    +    found = [m[1] for n in names if isinstance(n, str) and (m := _TAG.fullmatch(n))]
    +    return sorted(set(found), key=triple, reverse=True)
    +
    +
    +def bump(version: str, messages: Sequence[str]) -> str:
    +    """The next version after `version` for these commit messages (constitution R1).
    +
    +    A breaking change bumps MAJOR, or MINOR before 1.0.0; a feat bumps MINOR;
    +    anything else PATCH.
    +    """
    +    major, minor, patch = triple(version)
    +    level = _PATCH
    +    for message in messages:
    +        m = _SUBJECT.match(message)
    +        if (m and m["bang"]) or _BREAKING.search(message):
    +            level = max(level, _BREAKS)
    +        elif m and m["type"].lower() == "feat":
    +            level = max(level, _FEATURE)
    +    if level == _BREAKS and major > 0:
    +        return f"{major + 1}.0.0"
    +    if level >= _FEATURE:
    +        return f"{major}.{minor + 1}.0"
    +    return f"{major}.{minor}.{patch + 1}"
    +
    +
    +def behind_head(api: Api, repo: str, head: str) -> tuple[str, list[str]] | None:
    +    """(version, messages since it) for the newest vX.Y.Z tag HEAD has; None when it has none."""
    +    for version in tags(api, repo):
    +        compared = api.request("GET", f"/repos/{repo}/compare/v{version}...{head}")
    +        if (compared or {}).get("status") in ("ahead", "identical"):
    +            commits = compared.get("commits") or []
    +            return version, [str((c.get("commit") or {}).get("message", "")) for c in commits]
    +    return None
    +
    +
    +def derived(api: Api, repo: str, head: str) -> str:
    +    since = behind_head(api, repo, head)
    +    if since is None:
    +        raise RefusedError(
    +            f"{repo} has no vX.Y.Z tag behind HEAD to derive a version from; "
    +            "name one with --version"
    +        )
    +    base, messages = since
    +    if not messages:
    +        raise RefusedError(f"nothing has landed since v{base}: there is nothing to release")
    +    return bump(base, messages)
    +
    +
    +def release_pull(api: Api, repo: str, number: int) -> dict[str, Any]:
    +    """The pull request --resume names, which must be the App's release PR, or a 1."""
    +    pull = api.request("GET", f"/repos/{repo}/pulls/{number}") or {}
    +    ref = (pull.get("head") or {}).get("ref", "")
    +    m = re.fullmatch(rf"{re.escape(BRANCH)}({SEMVER.pattern})", str(ref))
    +    if not m:
    +        raise RefusedError(f"{repo}#{number} is not on an {BRANCH}X.Y.Z branch: {ref!r}")
    +    authored(pull, f"{repo}#{number}")
    +    if pull.get("state") != "open" and not pull.get("merged_at"):
    +        raise RefusedError(f"{repo}#{number} was closed unmerged; cut the release again")
    +    return pull
    +
    +
    +def authored(pull: Mapping[str, Any], where: str) -> None:
    +    """A release PR the Ashigaru App did not write, or from another repo, is a 1."""
    +    login = (pull.get("user") or {}).get("login")
    +    if login != APP_LOGIN:
    +        raise RefusedError(f"{where} was opened by {login!r}, not the Ashigaru App ({APP_LOGIN})")
    +
    +
    +_KNOWN: dict[int, Release] = {}
    +
    +
    +def release_of(run: Run) -> Release:
    +    """What this step knows of the release, from origin, GitHub and the arguments.
    +
    +    Worked out once per run of a step: its `done` and its `run` ask the same.
    +    """
    +    if id(run) in _KNOWN:
    +        return _KNOWN[id(run)]
    +    asked = asked_of(parser().parse_args(run.argv))
    +    api = connect(run)
    +    repo, default = identity(api)
    +    head = local_head()
    +    if asked.resume is not None:
    +        named, number = _runner.parse_ref(asked.resume)
    +        if named.lower() != repo.lower():
    +            raise CannotRunError(f"--resume names {named}, and this clone is {repo}")
    +        pull = release_pull(api, repo, number)
    +        version = pull["head"]["ref"][len(BRANCH) :]
    +        if asked.version is not None and asked.version != version:
    +            raise CannotRunError(
    +                f"--version {asked.version}, and {asked.resume} releases {version}"
    +            )
    +        run.resume_ref = f"{repo}#{number}"
    +    else:
    +        version = asked.version or derived(api, repo, head)
    +    _KNOWN[id(run)] = Release(api, repo, default, head, version, asked)
    +    return _KNOWN[id(run)]
    +
    +
    +# --- the forge's answers ------------------------------------------------------
    +
    +
    +def pulls(rel: Release) -> list[dict[str, Any]]:
    +    """Every PR from this repo's ashigaru/release-X.Y.Z into the default branch; App-only."""
    +    owner = rel.repo.split("/", 1)[0]
    +    found = rel.api.request(
    +        "GET", f"/repos/{rel.repo}/pulls?head={owner}:{rel.branch}&state=all&per_page=100"
    +    )
    +    mine = [
    +        p
    +        for p in found or []
    +        if (p.get("head") or {}).get("ref") == rel.branch
    +        and ((p.get("head") or {}).get("repo") or {}).get("full_name", "").lower()
    +        == rel.repo.lower()
    +        and (p.get("base") or {}).get("ref") == rel.default
    +    ]
    +    for p in mine:
    +        authored(p, f"{rel.repo}#{p.get('number')}")
    +    return mine
    +
    +
    +def open_pull(rel: Release) -> dict[str, Any] | None:
    +    """The one open release PR, or None; two open is a 2."""
    +    found = [p for p in pulls(rel) if p.get("state") == "open"]
    +    if len(found) > 1:
    +        numbers = ", ".join(f"#{p.get('number')}" for p in found)
    +        raise CannotRunError(
    +            f"{rel.repo} has {len(found)} open release PRs for {rel.version}: {numbers}"
    +        )
    +    return found[0] if found else None
    +
    +
    +def merged_pull(rel: Release) -> dict[str, Any] | None:
    +    return next((p for p in pulls(rel) if p.get("merged_at")), None)
    +
    +
    +def merged(run: Run) -> bool:
    +    """Has the release PR merged?"""
    +    rel = release_of(run)
    +    return any(p.get("merged_at") for p in pulls(rel))
    +
    +
    +def tagged(rel: Release) -> str | None:
    +    """The commit the vX.Y.Z tag names, or None when there is no such tag."""
    +    try:
    +        ref = rel.api.request("GET", f"/repos/{rel.repo}/git/ref/tags/{rel.tag}")
    +    except ApiError as err:
    +        if err.status == _NOT_FOUND:
    +            return None
    +        raise
    +    obj = (ref or {}).get("object") or {}
    +    if obj.get("type") == "tag":  # annotated: the tag object names the commit
    +        obj = (rel.api.request("GET", f"/repos/{rel.repo}/git/tags/{obj.get('sha')}") or {}).get(
    +            "object"
    +        ) or {}
    +    return str(obj.get("sha", "")) or None
    +
    +
    +def existing(rel: Release) -> str | None:
    +    """What says this release was already cut: its open or merged PR, or its tag; else None.
    +
    +    A PR closed unmerged is a cut that was abandoned, so it is cut again.
    +    """
    +    live = [p for p in pulls(rel) if p.get("state") == "open" or p.get("merged_at")]
    +    if live:
    +        return f"{rel.repo}#{live[0].get('number')}"
    +    return rel.tag if tagged(rel) is not None else None
    +
    +
    +def resuming(run: Run) -> bool:
    +    """Is this run carrying on with the release PR --resume names?
    +
    +    Only that skips preflight, lease and dispatch: a release this run did not
    +    name is refused by preflight, never adopted as this one.
    +    """
    +    return release_of(run).asked.resume is not None
    +
    +
    +# A required check: its name, and the App that must report it (None: any).
    +Need = tuple[str, int | None]
    +
    +
    +def required(rel: Release) -> set[Need]:
    +    """The checks the default branch requires, by ruleset or classic protection, with their Apps."""
    +    branch = urllib.parse.quote(rel.default, safe="")
    +    needs: set[Need] = set()
    +    for rule in rel.api.pages(f"/repos/{rel.repo}/rules/branches/{branch}"):
    +        if isinstance(rule, dict) and rule.get("type") == "required_status_checks":
    +            for need in (rule.get("parameters") or {}).get("required_status_checks") or []:
    +                if isinstance(need, dict) and isinstance(need.get("context"), str):
    +                    app = need.get("integration_id")
    +                    needs.add((need["context"], app if isinstance(app, int) else None))
    +    found = rel.api.request("GET", f"/repos/{rel.repo}/branches/{branch}") or {}
    +    classic = (found.get("protection") or {}).get("required_status_checks") or {}
    +    for check in classic.get("checks") or []:
    +        if isinstance(check, dict) and isinstance(check.get("context"), str):
    +            app = check.get("app_id")
    +            needs.add((check["context"], app if isinstance(app, int) else None))
    +    known = {name for name, _ in needs}
    +    needs.update((c, None) for c in classic.get("contexts") or [] if c not in known)
    +    return needs
    +
    +
    +def reported(rel: Release, sha: str) -> list[tuple[str, int | None, str]]:
    +    """(name, App, verdict) for each check run and commit status on `sha`; "pending" until done."""
    +    seen: list[tuple[str, int | None, str]] = []
    +    runs = rel.api.pages(f"/repos/{rel.repo}/commits/{sha}/check-runs?filter=latest", "check_runs")
    +    for cr in runs:
    +        state = cr.get("conclusion") if cr.get("status") == "completed" else "pending"
    +        app = (cr.get("app") or {}).get("id")
    +        seen.append(
    +            (str(cr.get("name")), app if isinstance(app, int) else None, str(state or "pending"))
    +        )
    +    status = rel.api.request("GET", f"/repos/{rel.repo}/commits/{sha}/status") or {}
    +    for st in status.get("statuses") or []:
    +        state = st.get("state")
    +        verdict = (
    +            "success" if state == "success" else "pending" if state == "pending" else "failure"
    +        )
    +        seen.append((str(st.get("context")), None, verdict))
    +    return seen
    +
    +
    +def verdict(need: Need, seen: list[tuple[str, int | None, str]]) -> str:
    +    """One requirement's verdict: what its App reported under its name, combined as the Desk does.
    +
    +    Never reported is pending; any pending is pending; else any failure fails.
    +    """
    +    name, app = need
    +    states = [v for n, a, v in seen if n == name and (app is None or a == app)]
    +    if not states or "pending" in states:
    +        return "pending"
    +    return next((v for v in states if v not in PASSING), states[0])
    +
    +
    +def judged(rel: Release, pull: Mapping[str, Any]) -> bool | None:
    +    """True when every required check passed on the PR's head; None while any is pending.
    +
    +    A required check that failed is a 1 naming it.
    +    """
    +    need = required(rel)
    +    if not need:
    +        raise RefusedError(
    +            f"{rel.default} requires no checks, and release merges nothing nothing judged"
    +        )
    +    seen = reported(rel, pull["head"]["sha"])
    +    states = {n: verdict(n, seen) for n in need}
    +    failed = sorted(n[0] for n, v in states.items() if v not in (*PASSING, "pending"))
    +    if failed:
    +        raise RefusedError(
    +            "required checks failed on the release PR: "
    +            + ", ".join(failed)
    +            + f"\n{pull.get('html_url', '')}"
    +        )
    +    return True if all(v in PASSING for v in states.values()) else None
    +
    +
    +def runs(rel: Release, event: str, sha: str) -> list[dict[str, Any]]:
    +    return (
    +        rel.api.request(
    +            "GET",
    +            f"/repos/{rel.repo}/actions/workflows/{WORKFLOW}/runs"
    +            f"?event={event}&head_sha={sha}&per_page=100",
    +        ).get("workflow_runs")
    +        or []
    +    )
    +
    +
    +def finished(rel: Release, run_id: int, what: str) -> None:
    +    """Wait for run `run_id` to complete; anything but success is a 1 naming the failed jobs."""
    +    path = f"/repos/{rel.repo}/actions/runs/{run_id}"
    +    url = rel.url(f"/actions/runs/{run_id}")
    +    timeout, every = WAITS[what]
    +
    +    def probe() -> dict[str, Any] | None:
    +        got = rel.api.request("GET", path) or {}
    +        return got if got.get("status") == "completed" else None
    +
    +    done = wait_for(probe, Wait(f"the {what} run to finish", url, timeout, every), TIMER)
    +    if done.get("conclusion") != "success":
    +        jobs = rel.api.pages(f"{path}/jobs", "jobs")
    +        bad = [
    +            f"{j.get('name')} ({j.get('conclusion')})"
    +            for j in jobs
    +            if j.get("conclusion") not in PASSING
    +        ]
    +        raise RefusedError(
    +            f"the {what} run ended {done.get('conclusion')}: "
    +            f"{', '.join(bad) or 'no job failed'}\n{url}"
    +        )
    +
    +
    +def the_run(run: Run, rel: Release, which: tuple[str, str, set[object], str], what: str) -> None:
    +    """Wait for the one new run, then for it to pass.
    +
    +    `which` is (event, sha, before, after): a run of ci.yml for `event` on
    +    `sha`, not among the ids `before`, created no earlier than `after` (UTC,
    +    ISO 8601; "" for any). Two that could be it is a 2: nothing says which one
    +    is this release's.
    +    """
    +    event, sha, before, after = which
    +
    +    def probe() -> dict[str, Any] | None:
    +        new = [
    +            r
    +            for r in runs(rel, event, sha)
    +            if r.get("id") not in before
    +            and r.get("event") == event
    +            and r.get("head_sha") == sha
    +            and str(r.get("path", WORKFLOW)).endswith(WORKFLOW)
    +            and str(r.get("created_at", "")) >= after
    +        ]
    +        if len(new) > 1:
    +            urls = ", ".join(str(r.get("html_url", r.get("id"))) for r in new)
    +            raise CannotRunError(f"{len(new)} runs could be the {what} run: {urls}")
    +        return new[0] if new else None
    +
    +    timeout, every = WAITS["run"]
    +    url = rel.url(f"/actions/workflows/{WORKFLOW}")
    +    found = wait_for(probe, Wait(f"the {what} run", url, timeout, every), TIMER)
    +    run.say(f"{what} run: {found.get('html_url', found.get('id'))}")
    +    finished(rel, int(found["id"]), what)
    +
    +
    +# --- the steps ------------------------------------------------------------------
    +
    +
    +def step_identify(run: Run) -> None:
    +    if ENV.get("JOSUI_NAME") and asked_of(parser().parse_args(run.argv)).item is None:
    +        raise RefusedError(
    +            "an agent releases under a work item: pass --item aN (JOSUI_NAME is set)"
    +        )
    +    rel = release_of(run)
    +    run.say(f"{rel.repo} {rel.version}, from {rel.default} at {rel.head[:12]}")
    +
    +
    +def step_preflight(run: Run) -> None:
    +    rel = release_of(run)
    +    there = existing(rel)
    +    if there is not None:
    +        resume = f"; carry it on with --resume {there}" if "#" in there else ""
    +        raise RefusedError(f"{rel.repo} {rel.version} was already cut: {there}{resume}")
    +    branch = (git("symbolic-ref", "--quiet", "--short", "HEAD") or "").strip()
    +    if branch != rel.default:
    +        raise RefusedError(
    +            f"a release is cut from {rel.default}, and this clone is on {branch or 'no branch'}"
    +        )
    +    quoted = urllib.parse.quote(rel.default, safe="")
    +    there = (
    +        (rel.api.request("GET", f"/repos/{rel.repo}/branches/{quoted}") or {}).get("commit") or {}
    +    ).get("sha")
    +    if there != rel.head:
    +        raise RefusedError(
    +            f"this clone's {rel.default} is at {rel.head[:12]} and origin's at {str(there)[:12]}: "
    +            f"git pull, then release"
    +        )
    +    newest = tags(rel.api, rel.repo)
    +    if newest and triple(rel.version) <= triple(newest[0]):
    +        raise RefusedError(f"{rel.version} is not newer than the newest tag, v{newest[0]}")
    +
    +    def read(path: str) -> str | None:
    +        return git("show", f"HEAD:{path}")
    +
    +    try:
    +        edits = _bump.release_edits(read, rel.version, today())
    +    except _bump.ReleaseError as err:
    +        raise RefusedError(f"the release commit cannot be made: {err}") from err
    +    run.say(f"{rel.version} moves {', '.join(sorted(edits)) or 'nothing'}")
    +
    +
    +def step_lease(run: Run) -> None:
    +    rel = release_of(run)
    +    hosts = _hosts.load()
    +    if hosts.desk_url is None:
    +        run.say("UNLEASED: the Desk will adopt this release")
    +        return
    +    api, base = desk(hosts.desk_url, run.credential("desk"))
    +    body: dict[str, object] = {"repo": rel.repo, "version": rel.version}
    +    if rel.asked.item is not None:
    +        body["item"] = rel.asked.item
    +    try:
    +        api.request("POST", f"{base}/v1/releases", body)
    +    except ApiError as err:
    +        if err.status != _CONFLICT:
    +            raise CannotRunError(
    +                f"the Desk would not lease {rel.repo} {rel.version}: {err}"
    +            ) from err
    +        if not ours(rel, api, base):
    +            raise RefusedError(f"the Desk holds another release's lease: {err}") from err
    +        run.say(f"the Desk's lease on {rel.repo} is already this release's")
    +        return
    +    run.say(f"leased {rel.repo} {rel.version} on the Desk")
    +
    +
    +def ours(rel: Release, api: Api, base: str) -> bool:
    +    """Is the lease in flight on this repo for this version and item?"""
    +    leases = api.request("GET", f"{base}/v1/releases")
    +    if not isinstance(leases, list):
    +        raise CannotRunError(f"the Desk's {base}/v1/releases is not a list of leases")
    +    return any(
    +        isinstance(lease, dict)
    +        and str(lease.get("repo", "")).lower() == rel.repo.lower()
    +        and lease.get("version") == rel.version
    +        and lease.get("item") == rel.asked.item
    +        and not lease.get("ended_at")
    +        for lease in leases
    +    )
    +
    +
    +def step_dispatch(run: Run) -> None:
    +    rel = release_of(run)
    +    before = {r.get("id") for r in runs(rel, "workflow_dispatch", rel.head)}
    +    after = (now() - timedelta(seconds=CLOCK_SKEW)).strftime("%Y-%m-%dT%H:%M:%SZ")
    +    inputs = {"version": rel.version}
    +    if rel.asked.item is not None:
    +        inputs["item"] = rel.asked.item
    +    if rel.asked.includes:
    +        inputs["includes"] = ",".join(rel.asked.includes)
    +    rel.api.request(
    +        "POST",
    +        f"/repos/{rel.repo}/actions/workflows/{WORKFLOW}/dispatches",
    +        {"ref": rel.default, "inputs": inputs},
    +    )
    +    the_run(run, rel, ("workflow_dispatch", rel.head, before, after), "dispatch")
    +
    +
    +def step_pr(run: Run) -> None:
    +    rel = release_of(run)
    +    pull = open_pull(rel)
    +    if pull is None:
    +        raise RefusedError(
    +            f"the dispatch finished and {rel.repo} has no open release PR on {rel.branch}"
    +        )
    +    run.resume_ref = f"{rel.repo}#{pull['number']}"
    +    run.say(f"release PR: {pull.get('html_url', run.resume_ref)}")
    +    flagged(rel, pull)
    +    the_apps_cut(rel, pull["head"]["sha"])
    +    green(rel, pull)
    +    run.say(f"every required check passed on {pull['head']['sha'][:12]}")
    +
    +
    +def green(rel: Release, pull: Mapping[str, Any]) -> None:
    +    """Wait for every required check on the PR's head to pass; a failure is a 1."""
    +    timeout, every = WAITS["checks"]
    +    wait = Wait("the release PR's required checks", str(pull.get("html_url", "")), timeout, every)
    +    wait_for(lambda: judged(rel, pull), wait, TIMER)
    +
    +
    +def step_merged(run: Run) -> None:
    +    rel = release_of(run)
    +    pull = open_pull(rel)
    +    if pull is None:
    +        raise RefusedError(f"{rel.repo} has no open release PR on {rel.branch} to merge")
    +    run.resume_ref = f"{rel.repo}#{pull['number']}"
    +    head = pull["head"]["sha"]
    +    # This step's own read of the head: the merge is pinned to the head it judged.
    +    flagged(rel, pull)
    +    the_apps_cut(rel, head)
    +    green(rel, pull)
    +    moved(rel, head)
    +    try:
    +        rel.api.request(
    +            "PUT",
    +            f"/repos/{rel.repo}/pulls/{pull['number']}/merge",
    +            {"merge_method": "squash", "sha": head},
    +        )
    +    except ApiError as err:
    +        # 405 is also what a PR another merger (the Desk's cut) already merged answers.
    +        if err.status not in _REFUSED:
    +            raise
    +        if not (rel.api.request("GET", f"/repos/{rel.repo}/pulls/{pull['number']}") or {}).get(
    +            "merged_at"
    +        ):
    +            raise RefusedError(
    +                f"GitHub would not merge {run.resume_ref} at {head[:12]}: {err}"
    +            ) from err
    +        run.say(f"{run.resume_ref} was already merged")
    +    as_passed(rel, pull["number"], head)
    +    run.say(f"merged {run.resume_ref} at {head[:12]}")
    +
    +
    +def flagged(rel: Release, pull: Mapping[str, Any]) -> None:
    +    """The Desk's cut refusals (ashigaru desk/cuts.py `refusal`): a draft, a flag, changes asked."""
    +    where = f"{rel.repo}#{pull['number']}"
    +    if pull.get("draft"):
    +        raise RefusedError(f"{where} is a draft")
    +    labels = {
    +        str(label.get("name")) for label in pull.get("labels") or [] if isinstance(label, dict)
    +    }
    +    if FLAGS & labels:
    +        raise RefusedError(f"{where} is flagged {', '.join(sorted(FLAGS & labels))}")
    +    latest: dict[str, str] = {}
    +    for review in rel.api.pages(f"/repos/{rel.repo}/pulls/{pull['number']}/reviews"):
    +        login, state = (review.get("user") or {}).get("login"), review.get("state")
    +        if isinstance(login, str) and state in ("APPROVED", "CHANGES_REQUESTED", "DISMISSED"):
    +            latest[login] = str(state)
    +    asked = sorted(who for who, state in latest.items() if state == "CHANGES_REQUESTED")
    +    if asked:
    +        raise RefusedError(f"{where} has changes requested by {', '.join(asked)}")
    +
    +
    +class ForgeTools(Tools):
    +    """`Tools`' GitHub calls answered by an `Api`, so `_prs` judges a tree here as in CI."""
    +
    +    def __init__(self, api: Api) -> None:
    +        self.api = api
    +
    +    def http(

    Fixed in 1d38cca

    ForgeTools.http now has a docstring. It answers the URL's path through the Api as a 200 with JSON and turns an ApiError into its status. Headers are dropped because the Api carries its own credential.

    fatherlinux fatherlinux commented on code on Dec 04, 2026 22:17 UTC
    Code Review
    sdlc_jobs/life/release.py:1
    @@ -0,0 +1,902 @@
    +"""`sdlc release`: the normal path to a published image (docs/lifecycle.md).
    +
    +Replaces josui-land-release and every hand dispatch. Seven steps, each in a
    +container of its own with only the credentials it declares, and each
    +idempotent: it asks the forge whether its result is already there and goes on
    +when it is, so running the command again is how it resumes.
    +
    +    identify   origin's URL, parsed strictly, confirmed by GET /repos
    +    preflight  the default branch at origin's head, a non-empty Unreleased, a
    +               version newer than the newest tag, and `_bump.release_edits`'
    +               refusal seen here before anything is dispatched
    +    lease      the Desk's release lease, the one its own cuts take
    +    dispatch   ci.yml with version, item and includes; the one run it started
    +    pr         the App's release PR on ashigaru/release-X.Y.Z, and its
    +               required checks
    +    merged     squash, pinned to the head whose checks passed
    +    image      the push run on the merge, the tag on the merge commit, the
    +               GitHub Release, and each image's X.Y.Z and latest one signed digest
    +
    +Nothing passes from one step to the next but the forge. The version is the
    +same in every step because it is worked out the same way: `--version`; else
    +the release PR `--resume` names; else the Conventional Commits from the newest
    +vX.Y.Z tag behind this clone's HEAD to HEAD, which a tag made on the release's
    +own merge commit is never behind.
    +"""
    +
    +from __future__ import annotations
    +
    +import argparse
    +import contextlib
    +import io
    +import json
    +import os
    +import re
    +import subprocess
    +import tempfile
    +import time
    +import urllib.parse
    +from collections.abc import Callable, Mapping, Sequence
    +from dataclasses import dataclass
    +from datetime import UTC, datetime, timedelta
    +from pathlib import Path
    +from typing import Any
    +
    +from sdlc_jobs import _bump, _prs
    +from sdlc_jobs._core import (
    +    FLEET_PUBLIC_KEY,
    +    ITEM,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    images,
    +    parse_includes,
    +)
    +from sdlc_jobs._github import APP_LOGIN, Api, ApiError, GitHub
    +from sdlc_jobs.life import _hosts, _runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait, wait_for
    +
    +COMMAND = "release"
    +WORKFLOW = "ci.yml"
    +BRANCH = "ashigaru/release-"
    +REPO_ROOT = Path("/repo")
    +# A check passes as the Desk's cuts judge it (ashigaru automerge.PASSING).
    +PASSING = ("success", "skipped", "neutral")
    +# A label that leaves a release PR to a person (ashigaru automerge.FLAGS).
    +FLAGS = frozenset({"needs-human"})
    +_NOT_FOUND = 404
    +_REFUSED = (405, 409)
    +_CONFLICT = 409
    +# origin, and nothing else: github.com/<owner>/<name> over https or ssh.
    +_ORIGIN = re.compile(
    +    r"(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)"
    +    r"(?P<owner>[A-Za-z0-9][A-Za-z0-9-]*)/(?P<name>[A-Za-z0-9._-]+?)(?:\.git)?/?"
    +)
    +_TAG = re.compile(rf"v({SEMVER.pattern})")
    +# A Conventional Commit subject: type, optional scope, optional `!`, colon.
    +_SUBJECT = re.compile(r"(?P<type>[A-Za-z]+)(?:\([^)]*\))?(?P<bang>!)?:\s")
    +_BREAKING = re.compile(r"^BREAKING[ -]CHANGE:", re.MULTILINE)
    +# What a commit asks of the version, least to most.
    +_PATCH, _FEATURE, _BREAKS = 0, 1, 2
    +SKOPEO_SECONDS = 120
    +# How far this machine's clock may run ahead of GitHub's when a run is matched
    +# to the dispatch that made it.
    +CLOCK_SKEW = 120
    +COSIGN_SECONDS = 300
    +
    +# How long each wait gives the forge, and how often it asks.
    +WAITS = {
    +    "run": (300.0, 10.0),  # the dispatch's run to appear
    +    "dispatch": (1800.0, 20.0),  # the dispatch's run to finish: the release PR
    +    "checks": (3600.0, 30.0),  # the release PR's required checks
    +    "landing": (3600.0, 30.0),  # the push run on the merge commit
    +}
    +
    +
    +# --- what a step reaches the world through; the suite replaces each -----------
    +
    +
    +def connect(run: Run) -> Api:
    +    """GitHub as the github credential sees it."""
    +    return GitHub(run.credential("github"))
    +
    +
    +def git(*args: str) -> str | None:
    +    """git's stdout in the clone bin/sdlc mounted, or None when git says no."""
    +    proc = subprocess.run(
    +        ["git", "-C", str(REPO_ROOT), *args], capture_output=True, text=True, check=False
    +    )
    +    return proc.stdout if proc.returncode == 0 else None
    +
    +
    +def desk(url: str, token: str) -> tuple[Api, str]:
    +    """The Desk's API at `url`, and the path it is served under.
    +
    +    The same REST client GitHub's calls use: one host, https only, and a
    +    redirect to another host never carries the token.
    +    """
    +    parts = urllib.parse.urlsplit(url)
    +    if parts.scheme != "https" or not parts.netloc:
    +        raise CannotRunError(f"the Desk is reached over https only, not {url}")
    +    return GitHub(token, host=parts.netloc), parts.path.rstrip("/")
    +
    +
    +def digest_of(ref: str) -> str | None:
    +    """The digest `ref` names in its registry, or None when it names nothing."""
    +    proc = subprocess.run(
    +        ["skopeo", "inspect", "--no-tags", "--format", "{{.Digest}}", f"docker://{ref}"],
    +        capture_output=True,
    +        text=True,
    +        check=False,
    +        timeout=SKOPEO_SECONDS,
    +    )
    +    if proc.returncode == 0:
    +        return proc.stdout.strip() or None
    +    if "manifest unknown" in proc.stderr or "not found" in proc.stderr.lower():
    +        return None
    +    raise CannotRunError(f"skopeo could not read {ref}: {proc.stderr.strip()[:300]}")
    +
    +
    +def signed(ref: str) -> bool:
    +    """Does `ref` (by digest) carry the fleet key's signature, as promote verifies it?"""
    +    with tempfile.TemporaryDirectory() as scratch:
    +        pub = Path(scratch) / "fleet.pub"
    +        pub.write_text(FLEET_PUBLIC_KEY)
    +        argv = ["cosign", "verify", "--insecure-ignore-tlog", "--key", str(pub), ref]
    +        proc = subprocess.run(
    +            argv, capture_output=True, text=True, check=False, timeout=COSIGN_SECONDS
    +        )
    +    return proc.returncode == 0
    +
    +
    +ENV: Mapping[str, str] = os.environ
    +TIMER: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
    +
    +
    +def now() -> datetime:
    +    return datetime.now(UTC)
    +
    +
    +def today() -> str:
    +    """The CHANGELOG heading's date, UTC's, as the App's release commit writes it."""
    +    return datetime.now(UTC).date().isoformat()
    +
    +
    +# --- what every step works out the same way ------------------------------------
    +
    +
    +@dataclass
    +class Asked:
    +    """The person's arguments, checked."""
    +
    +    version: str | None
    +    item: str | None
    +    includes: list[str]
    +    resume: str | None
    +
    +
    +@dataclass
    +class Release:
    +    """What every step knows of the release, read back from the forge."""
    +
    +    api: Api
    +    repo: str
    +    default: str
    +    head: str
    +    version: str
    +    asked: Asked
    +
    +    @property
    +    def branch(self) -> str:
    +        return f"{BRANCH}{self.version}"
    +
    +    @property
    +    def tag(self) -> str:
    +        return f"v{self.version}"
    +
    +    def url(self, path: str = "") -> str:
    +        return f"https://github.com/{self.repo}{path}"
    +
    +
    +def origin_repo() -> str:
    +    """owner/name from origin's URL, parsed strictly, or a 2."""
    +    url = (git("remote", "get-url", "origin") or "").strip()
    +    m = _ORIGIN.fullmatch(url)
    +    if not m:
    +        raise CannotRunError(f"origin is not github.com/<owner>/<name>: {url or 'no origin'}")
    +    return f"{m['owner']}/{m['name']}"
    +
    +
    +def identity(api: Api) -> tuple[str, str]:
    +    """(owner/name, default branch) of origin, confirmed by GitHub, or a 2."""
    +    repo = origin_repo()
    +    try:
    +        found = api.request("GET", f"/repos/{repo}")
    +    except ApiError as err:
    +        raise CannotRunError(f"{repo} does not resolve on GitHub: {err}") from err
    +    name = (found or {}).get("full_name")
    +    default = (found or {}).get("default_branch")
    +    if not isinstance(name, str) or name.lower() != repo.lower() or not isinstance(default, str):
    +        raise CannotRunError(f"GitHub answers {name!r} for {repo}, not that repo")
    +    return name, default
    +
    +
    +def local_head() -> str:
    +    head = (git("rev-parse", "HEAD") or "").strip()
    +    if not re.fullmatch(r"[0-9a-f]{40}", head):
    +        raise CannotRunError("this clone has no HEAD commit")
    +    return head
    +
    +
    +def triple(version: str) -> tuple[int, int, int]:
    +    a, b, c = (int(p) for p in version.split("."))
    +    return a, b, c
    +
    +
    +def tags(api: Api, repo: str) -> list[str]:
    +    """Every vX.Y.Z tag's version, newest first."""
    +    names = [t.get("name") for t in api.pages(f"/repos/{repo}/tags") if isinstance(t, dict)]
    +    found = [m[1] for n in names if isinstance(n, str) and (m := _TAG.fullmatch(n))]
    +    return sorted(set(found), key=triple, reverse=True)
    +
    +
    +def bump(version: str, messages: Sequence[str]) -> str:
    +    """The next version after `version` for these commit messages (constitution R1).
    +
    +    A breaking change bumps MAJOR, or MINOR before 1.0.0; a feat bumps MINOR;
    +    anything else PATCH.
    +    """
    +    major, minor, patch = triple(version)
    +    level = _PATCH
    +    for message in messages:
    +        m = _SUBJECT.match(message)
    +        if (m and m["bang"]) or _BREAKING.search(message):
    +            level = max(level, _BREAKS)
    +        elif m and m["type"].lower() == "feat":
    +            level = max(level, _FEATURE)
    +    if level == _BREAKS and major > 0:
    +        return f"{major + 1}.0.0"
    +    if level >= _FEATURE:
    +        return f"{major}.{minor + 1}.0"
    +    return f"{major}.{minor}.{patch + 1}"
    +
    +
    +def behind_head(api: Api, repo: str, head: str) -> tuple[str, list[str]] | None:
    +    """(version, messages since it) for the newest vX.Y.Z tag HEAD has; None when it has none."""
    +    for version in tags(api, repo):
    +        compared = api.request("GET", f"/repos/{repo}/compare/v{version}...{head}")
    +        if (compared or {}).get("status") in ("ahead", "identical"):
    +            commits = compared.get("commits") or []
    +            return version, [str((c.get("commit") or {}).get("message", "")) for c in commits]
    +    return None
    +
    +
    +def derived(api: Api, repo: str, head: str) -> str:
    +    since = behind_head(api, repo, head)
    +    if since is None:
    +        raise RefusedError(
    +            f"{repo} has no vX.Y.Z tag behind HEAD to derive a version from; "
    +            "name one with --version"
    +        )
    +    base, messages = since
    +    if not messages:
    +        raise RefusedError(f"nothing has landed since v{base}: there is nothing to release")
    +    return bump(base, messages)
    +
    +
    +def release_pull(api: Api, repo: str, number: int) -> dict[str, Any]:
    +    """The pull request --resume names, which must be the App's release PR, or a 1."""
    +    pull = api.request("GET", f"/repos/{repo}/pulls/{number}") or {}
    +    ref = (pull.get("head") or {}).get("ref", "")
    +    m = re.fullmatch(rf"{re.escape(BRANCH)}({SEMVER.pattern})", str(ref))
    +    if not m:
    +        raise RefusedError(f"{repo}#{number} is not on an {BRANCH}X.Y.Z branch: {ref!r}")
    +    authored(pull, f"{repo}#{number}")
    +    if pull.get("state") != "open" and not pull.get("merged_at"):
    +        raise RefusedError(f"{repo}#{number} was closed unmerged; cut the release again")
    +    return pull
    +
    +
    +def authored(pull: Mapping[str, Any], where: str) -> None:
    +    """A release PR the Ashigaru App did not write, or from another repo, is a 1."""
    +    login = (pull.get("user") or {}).get("login")
    +    if login != APP_LOGIN:
    +        raise RefusedError(f"{where} was opened by {login!r}, not the Ashigaru App ({APP_LOGIN})")
    +
    +
    +_KNOWN: dict[int, Release] = {}
    +
    +
    +def release_of(run: Run) -> Release:
    +    """What this step knows of the release, from origin, GitHub and the arguments.
    +
    +    Worked out once per run of a step: its `done` and its `run` ask the same.
    +    """
    +    if id(run) in _KNOWN:
    +        return _KNOWN[id(run)]
    +    asked = asked_of(parser().parse_args(run.argv))
    +    api = connect(run)
    +    repo, default = identity(api)
    +    head = local_head()
    +    if asked.resume is not None:
    +        named, number = _runner.parse_ref(asked.resume)
    +        if named.lower() != repo.lower():
    +            raise CannotRunError(f"--resume names {named}, and this clone is {repo}")
    +        pull = release_pull(api, repo, number)
    +        version = pull["head"]["ref"][len(BRANCH) :]
    +        if asked.version is not None and asked.version != version:
    +            raise CannotRunError(
    +                f"--version {asked.version}, and {asked.resume} releases {version}"
    +            )
    +        run.resume_ref = f"{repo}#{number}"
    +    else:
    +        version = asked.version or derived(api, repo, head)
    +    _KNOWN[id(run)] = Release(api, repo, default, head, version, asked)
    +    return _KNOWN[id(run)]
    +
    +
    +# --- the forge's answers ------------------------------------------------------
    +
    +
    +def pulls(rel: Release) -> list[dict[str, Any]]:
    +    """Every PR from this repo's ashigaru/release-X.Y.Z into the default branch; App-only."""
    +    owner = rel.repo.split("/", 1)[0]
    +    found = rel.api.request(
    +        "GET", f"/repos/{rel.repo}/pulls?head={owner}:{rel.branch}&state=all&per_page=100"
    +    )
    +    mine = [
    +        p
    +        for p in found or []
    +        if (p.get("head") or {}).get("ref") == rel.branch
    +        and ((p.get("head") or {}).get("repo") or {}).get("full_name", "").lower()
    +        == rel.repo.lower()
    +        and (p.get("base") or {}).get("ref") == rel.default
    +    ]
    +    for p in mine:
    +        authored(p, f"{rel.repo}#{p.get('number')}")
    +    return mine
    +
    +
    +def open_pull(rel: Release) -> dict[str, Any] | None:
    +    """The one open release PR, or None; two open is a 2."""
    +    found = [p for p in pulls(rel) if p.get("state") == "open"]
    +    if len(found) > 1:
    +        numbers = ", ".join(f"#{p.get('number')}" for p in found)
    +        raise CannotRunError(
    +            f"{rel.repo} has {len(found)} open release PRs for {rel.version}: {numbers}"
    +        )
    +    return found[0] if found else None
    +
    +
    +def merged_pull(rel: Release) -> dict[str, Any] | None:
    +    return next((p for p in pulls(rel) if p.get("merged_at")), None)
    +
    +
    +def merged(run: Run) -> bool:
    +    """Has the release PR merged?"""
    +    rel = release_of(run)
    +    return any(p.get("merged_at") for p in pulls(rel))
    +
    +
    +def tagged(rel: Release) -> str | None:
    +    """The commit the vX.Y.Z tag names, or None when there is no such tag."""
    +    try:
    +        ref = rel.api.request("GET", f"/repos/{rel.repo}/git/ref/tags/{rel.tag}")
    +    except ApiError as err:
    +        if err.status == _NOT_FOUND:
    +            return None
    +        raise
    +    obj = (ref or {}).get("object") or {}
    +    if obj.get("type") == "tag":  # annotated: the tag object names the commit
    +        obj = (rel.api.request("GET", f"/repos/{rel.repo}/git/tags/{obj.get('sha')}") or {}).get(
    +            "object"
    +        ) or {}
    +    return str(obj.get("sha", "")) or None
    +
    +
    +def existing(rel: Release) -> str | None:
    +    """What says this release was already cut: its open or merged PR, or its tag; else None.
    +
    +    A PR closed unmerged is a cut that was abandoned, so it is cut again.
    +    """
    +    live = [p for p in pulls(rel) if p.get("state") == "open" or p.get("merged_at")]
    +    if live:
    +        return f"{rel.repo}#{live[0].get('number')}"
    +    return rel.tag if tagged(rel) is not None else None
    +
    +
    +def resuming(run: Run) -> bool:
    +    """Is this run carrying on with the release PR --resume names?
    +
    +    Only that skips preflight, lease and dispatch: a release this run did not
    +    name is refused by preflight, never adopted as this one.
    +    """
    +    return release_of(run).asked.resume is not None
    +
    +
    +# A required check: its name, and the App that must report it (None: any).
    +Need = tuple[str, int | None]
    +
    +
    +def required(rel: Release) -> set[Need]:
    +    """The checks the default branch requires, by ruleset or classic protection, with their Apps."""
    +    branch = urllib.parse.quote(rel.default, safe="")
    +    needs: set[Need] = set()
    +    for rule in rel.api.pages(f"/repos/{rel.repo}/rules/branches/{branch}"):
    +        if isinstance(rule, dict) and rule.get("type") == "required_status_checks":
    +            for need in (rule.get("parameters") or {}).get("required_status_checks") or []:
    +                if isinstance(need, dict) and isinstance(need.get("context"), str):
    +                    app = need.get("integration_id")
    +                    needs.add((need["context"], app if isinstance(app, int) else None))
    +    found = rel.api.request("GET", f"/repos/{rel.repo}/branches/{branch}") or {}
    +    classic = (found.get("protection") or {}).get("required_status_checks") or {}
    +    for check in classic.get("checks") or []:
    +        if isinstance(check, dict) and isinstance(check.get("context"), str):
    +            app = check.get("app_id")
    +            needs.add((check["context"], app if isinstance(app, int) else None))
    +    known = {name for name, _ in needs}
    +    needs.update((c, None) for c in classic.get("contexts") or [] if c not in known)
    +    return needs
    +
    +
    +def reported(rel: Release, sha: str) -> list[tuple[str, int | None, str]]:
    +    """(name, App, verdict) for each check run and commit status on `sha`; "pending" until done."""
    +    seen: list[tuple[str, int | None, str]] = []
    +    runs = rel.api.pages(f"/repos/{rel.repo}/commits/{sha}/check-runs?filter=latest", "check_runs")
    +    for cr in runs:
    +        state = cr.get("conclusion") if cr.get("status") == "completed" else "pending"
    +        app = (cr.get("app") or {}).get("id")
    +        seen.append(
    +            (str(cr.get("name")), app if isinstance(app, int) else None, str(state or "pending"))
    +        )
    +    status = rel.api.request("GET", f"/repos/{rel.repo}/commits/{sha}/status") or {}
    +    for st in status.get("statuses") or []:
    +        state = st.get("state")
    +        verdict = (
    +            "success" if state == "success" else "pending" if state == "pending" else "failure"
    +        )
    +        seen.append((str(st.get("context")), None, verdict))
    +    return seen
    +
    +
    +def verdict(need: Need, seen: list[tuple[str, int | None, str]]) -> str:
    +    """One requirement's verdict: what its App reported under its name, combined as the Desk does.
    +
    +    Never reported is pending; any pending is pending; else any failure fails.
    +    """
    +    name, app = need
    +    states = [v for n, a, v in seen if n == name and (app is None or a == app)]
    +    if not states or "pending" in states:
    +        return "pending"
    +    return next((v for v in states if v not in PASSING), states[0])
    +
    +
    +def judged(rel: Release, pull: Mapping[str, Any]) -> bool | None:
    +    """True when every required check passed on the PR's head; None while any is pending.
    +
    +    A required check that failed is a 1 naming it.
    +    """
    +    need = required(rel)
    +    if not need:
    +        raise RefusedError(
    +            f"{rel.default} requires no checks, and release merges nothing nothing judged"
    +        )
    +    seen = reported(rel, pull["head"]["sha"])
    +    states = {n: verdict(n, seen) for n in need}
    +    failed = sorted(n[0] for n, v in states.items() if v not in (*PASSING, "pending"))
    +    if failed:
    +        raise RefusedError(
    +            "required checks failed on the release PR: "
    +            + ", ".join(failed)
    +            + f"\n{pull.get('html_url', '')}"
    +        )
    +    return True if all(v in PASSING for v in states.values()) else None
    +
    +
    +def runs(rel: Release, event: str, sha: str) -> list[dict[str, Any]]:
    +    return (
    +        rel.api.request(
    +            "GET",
    +            f"/repos/{rel.repo}/actions/workflows/{WORKFLOW}/runs"
    +            f"?event={event}&head_sha={sha}&per_page=100",
    +        ).get("workflow_runs")
    +        or []
    +    )
    +
    +
    +def finished(rel: Release, run_id: int, what: str) -> None:
    +    """Wait for run `run_id` to complete; anything but success is a 1 naming the failed jobs."""
    +    path = f"/repos/{rel.repo}/actions/runs/{run_id}"
    +    url = rel.url(f"/actions/runs/{run_id}")
    +    timeout, every = WAITS[what]
    +
    +    def probe() -> dict[str, Any] | None:
    +        got = rel.api.request("GET", path) or {}
    +        return got if got.get("status") == "completed" else None
    +
    +    done = wait_for(probe, Wait(f"the {what} run to finish", url, timeout, every), TIMER)
    +    if done.get("conclusion") != "success":
    +        jobs = rel.api.pages(f"{path}/jobs", "jobs")
    +        bad = [
    +            f"{j.get('name')} ({j.get('conclusion')})"
    +            for j in jobs
    +            if j.get("conclusion") not in PASSING
    +        ]
    +        raise RefusedError(
    +            f"the {what} run ended {done.get('conclusion')}: "
    +            f"{', '.join(bad) or 'no job failed'}\n{url}"
    +        )
    +
    +
    +def the_run(run: Run, rel: Release, which: tuple[str, str, set[object], str], what: str) -> None:
    +    """Wait for the one new run, then for it to pass.
    +
    +    `which` is (event, sha, before, after): a run of ci.yml for `event` on
    +    `sha`, not among the ids `before`, created no earlier than `after` (UTC,
    +    ISO 8601; "" for any). Two that could be it is a 2: nothing says which one
    +    is this release's.
    +    """
    +    event, sha, before, after = which
    +
    +    def probe() -> dict[str, Any] | None:
    +        new = [
    +            r
    +            for r in runs(rel, event, sha)
    +            if r.get("id") not in before
    +            and r.get("event") == event
    +            and r.get("head_sha") == sha
    +            and str(r.get("path", WORKFLOW)).endswith(WORKFLOW)
    +            and str(r.get("created_at", "")) >= after
    +        ]
    +        if len(new) > 1:
    +            urls = ", ".join(str(r.get("html_url", r.get("id"))) for r in new)
    +            raise CannotRunError(f"{len(new)} runs could be the {what} run: {urls}")
    +        return new[0] if new else None
    +
    +    timeout, every = WAITS["run"]
    +    url = rel.url(f"/actions/workflows/{WORKFLOW}")
    +    found = wait_for(probe, Wait(f"the {what} run", url, timeout, every), TIMER)
    +    run.say(f"{what} run: {found.get('html_url', found.get('id'))}")
    +    finished(rel, int(found["id"]), what)
    +
    +
    +# --- the steps ------------------------------------------------------------------
    +
    +
    +def step_identify(run: Run) -> None:
    +    if ENV.get("JOSUI_NAME") and asked_of(parser().parse_args(run.argv)).item is None:
    +        raise RefusedError(
    +            "an agent releases under a work item: pass --item aN (JOSUI_NAME is set)"
    +        )
    +    rel = release_of(run)
    +    run.say(f"{rel.repo} {rel.version}, from {rel.default} at {rel.head[:12]}")
    +
    +
    +def step_preflight(run: Run) -> None:
    +    rel = release_of(run)
    +    there = existing(rel)
    +    if there is not None:
    +        resume = f"; carry it on with --resume {there}" if "#" in there else ""
    +        raise RefusedError(f"{rel.repo} {rel.version} was already cut: {there}{resume}")
    +    branch = (git("symbolic-ref", "--quiet", "--short", "HEAD") or "").strip()
    +    if branch != rel.default:
    +        raise RefusedError(
    +            f"a release is cut from {rel.default}, and this clone is on {branch or 'no branch'}"
    +        )
    +    quoted = urllib.parse.quote(rel.default, safe="")
    +    there = (
    +        (rel.api.request("GET", f"/repos/{rel.repo}/branches/{quoted}") or {}).get("commit") or {}
    +    ).get("sha")
    +    if there != rel.head:
    +        raise RefusedError(
    +            f"this clone's {rel.default} is at {rel.head[:12]} and origin's at {str(there)[:12]}: "
    +            f"git pull, then release"
    +        )
    +    newest = tags(rel.api, rel.repo)
    +    if newest and triple(rel.version) <= triple(newest[0]):
    +        raise RefusedError(f"{rel.version} is not newer than the newest tag, v{newest[0]}")
    +
    +    def read(path: str) -> str | None:
    +        return git("show", f"HEAD:{path}")
    +
    +    try:
    +        edits = _bump.release_edits(read, rel.version, today())
    +    except _bump.ReleaseError as err:
    +        raise RefusedError(f"the release commit cannot be made: {err}") from err
    +    run.say(f"{rel.version} moves {', '.join(sorted(edits)) or 'nothing'}")
    +
    +
    +def step_lease(run: Run) -> None:
    +    rel = release_of(run)
    +    hosts = _hosts.load()
    +    if hosts.desk_url is None:
    +        run.say("UNLEASED: the Desk will adopt this release")
    +        return
    +    api, base = desk(hosts.desk_url, run.credential("desk"))
    +    body: dict[str, object] = {"repo": rel.repo, "version": rel.version}
    +    if rel.asked.item is not None:
    +        body["item"] = rel.asked.item
    +    try:
    +        api.request("POST", f"{base}/v1/releases", body)
    +    except ApiError as err:
    +        if err.status != _CONFLICT:
    +            raise CannotRunError(
    +                f"the Desk would not lease {rel.repo} {rel.version}: {err}"
    +            ) from err
    +        if not ours(rel, api, base):
    +            raise RefusedError(f"the Desk holds another release's lease: {err}") from err
    +        run.say(f"the Desk's lease on {rel.repo} is already this release's")
    +        return
    +    run.say(f"leased {rel.repo} {rel.version} on the Desk")
    +
    +
    +def ours(rel: Release, api: Api, base: str) -> bool:
    +    """Is the lease in flight on this repo for this version and item?"""
    +    leases = api.request("GET", f"{base}/v1/releases")
    +    if not isinstance(leases, list):
    +        raise CannotRunError(f"the Desk's {base}/v1/releases is not a list of leases")
    +    return any(
    +        isinstance(lease, dict)
    +        and str(lease.get("repo", "")).lower() == rel.repo.lower()
    +        and lease.get("version") == rel.version
    +        and lease.get("item") == rel.asked.item
    +        and not lease.get("ended_at")
    +        for lease in leases
    +    )
    +
    +
    +def step_dispatch(run: Run) -> None:
    +    rel = release_of(run)
    +    before = {r.get("id") for r in runs(rel, "workflow_dispatch", rel.head)}
    +    after = (now() - timedelta(seconds=CLOCK_SKEW)).strftime("%Y-%m-%dT%H:%M:%SZ")
    +    inputs = {"version": rel.version}
    +    if rel.asked.item is not None:
    +        inputs["item"] = rel.asked.item
    +    if rel.asked.includes:
    +        inputs["includes"] = ",".join(rel.asked.includes)
    +    rel.api.request(
    +        "POST",
    +        f"/repos/{rel.repo}/actions/workflows/{WORKFLOW}/dispatches",
    +        {"ref": rel.default, "inputs": inputs},
    +    )
    +    the_run(run, rel, ("workflow_dispatch", rel.head, before, after), "dispatch")
    +
    +
    +def step_pr(run: Run) -> None:
    +    rel = release_of(run)
    +    pull = open_pull(rel)
    +    if pull is None:
    +        raise RefusedError(
    +            f"the dispatch finished and {rel.repo} has no open release PR on {rel.branch}"
    +        )
    +    run.resume_ref = f"{rel.repo}#{pull['number']}"
    +    run.say(f"release PR: {pull.get('html_url', run.resume_ref)}")
    +    flagged(rel, pull)
    +    the_apps_cut(rel, pull["head"]["sha"])
    +    green(rel, pull)
    +    run.say(f"every required check passed on {pull['head']['sha'][:12]}")
    +
    +
    +def green(rel: Release, pull: Mapping[str, Any]) -> None:
    +    """Wait for every required check on the PR's head to pass; a failure is a 1."""
    +    timeout, every = WAITS["checks"]
    +    wait = Wait("the release PR's required checks", str(pull.get("html_url", "")), timeout, every)
    +    wait_for(lambda: judged(rel, pull), wait, TIMER)
    +
    +
    +def step_merged(run: Run) -> None:
    +    rel = release_of(run)
    +    pull = open_pull(rel)
    +    if pull is None:
    +        raise RefusedError(f"{rel.repo} has no open release PR on {rel.branch} to merge")
    +    run.resume_ref = f"{rel.repo}#{pull['number']}"
    +    head = pull["head"]["sha"]
    +    # This step's own read of the head: the merge is pinned to the head it judged.
    +    flagged(rel, pull)
    +    the_apps_cut(rel, head)
    +    green(rel, pull)
    +    moved(rel, head)
    +    try:
    +        rel.api.request(
    +            "PUT",
    +            f"/repos/{rel.repo}/pulls/{pull['number']}/merge",
    +            {"merge_method": "squash", "sha": head},
    +        )
    +    except ApiError as err:
    +        # 405 is also what a PR another merger (the Desk's cut) already merged answers.
    +        if err.status not in _REFUSED:
    +            raise
    +        if not (rel.api.request("GET", f"/repos/{rel.repo}/pulls/{pull['number']}") or {}).get(
    +            "merged_at"
    +        ):
    +            raise RefusedError(
    +                f"GitHub would not merge {run.resume_ref} at {head[:12]}: {err}"
    +            ) from err
    +        run.say(f"{run.resume_ref} was already merged")
    +    as_passed(rel, pull["number"], head)
    +    run.say(f"merged {run.resume_ref} at {head[:12]}")
    +
    +
    +def flagged(rel: Release, pull: Mapping[str, Any]) -> None:
    +    """The Desk's cut refusals (ashigaru desk/cuts.py `refusal`): a draft, a flag, changes asked."""
    +    where = f"{rel.repo}#{pull['number']}"
    +    if pull.get("draft"):
    +        raise RefusedError(f"{where} is a draft")
    +    labels = {
    +        str(label.get("name")) for label in pull.get("labels") or [] if isinstance(label, dict)
    +    }
    +    if FLAGS & labels:
    +        raise RefusedError(f"{where} is flagged {', '.join(sorted(FLAGS & labels))}")
    +    latest: dict[str, str] = {}
    +    for review in rel.api.pages(f"/repos/{rel.repo}/pulls/{pull['number']}/reviews"):
    +        login, state = (review.get("user") or {}).get("login"), review.get("state")
    +        if isinstance(login, str) and state in ("APPROVED", "CHANGES_REQUESTED", "DISMISSED"):
    +            latest[login] = str(state)
    +    asked = sorted(who for who, state in latest.items() if state == "CHANGES_REQUESTED")
    +    if asked:
    +        raise RefusedError(f"{where} has changes requested by {', '.join(asked)}")
    +
    +
    +class ForgeTools(Tools):
    +    """`Tools`' GitHub calls answered by an `Api`, so `_prs` judges a tree here as in CI."""
    +
    +    def __init__(self, api: Api) -> None:
    +        self.api = api
    +
    +    def http(
    +        self, method: str, url: str, headers: Mapping[str, str], payload: bytes | None = None
    +    ) -> Response:
    +        del headers  # the Api carries its own credential
    +        path = url.removeprefix("https://api.github.com")
    +        try:
    +            got = self.api.request(method, path, None if payload is None else json.loads(payload))
    +        except ApiError as err:
    +            return Response(err.status, str(err).encode())
    +        return Response(200, json.dumps(got).encode())
    +
    +
    +def the_apps_cut(rel: Release, head: str) -> None:
    +    """A 1 unless `head` is the App's one release commit, exactly `release_edits` on its parent.
    +
    +    The same tree equality phase 0 trusts in CI (`_prs.release_of`): a commit
    +    pushed onto the release branch after the cut, or a hand-made branch, is
    +    not what the App cut and is merged by hand or not at all.
    +    """
    +    commit = rel.api.request("GET", f"/repos/{rel.repo}/commits/{head}") or {}
    +    who = {str((commit.get(role) or {}).get("login")) for role in ("author", "committer")}
    +    if who != {APP_LOGIN}:
    +        raise RefusedError(
    +            f"the release PR's head {head[:12]} is by {', '.join(sorted(who))}, not the App alone"
    +        )
    +    said = io.StringIO()

    Fixed in 1d38cca

    the_apps_cut no longer redirects stdout or parses _prs.release_of's words. It refuses on the function's None alone, and the function's own diagnostic line prints unchanged as the reason. Phase 0's function is left as CI uses it.

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 22:18 UTC
    Reviewer

    Gatehouse found no issues.

    Reviewed 1 commit since 63bf5fc (incremental).

    1 finding(s) dropped: their evidence is not in the diff.

    1 finding(s) not re-raised: already answered on this PR.

    <!-- gatehouse review complete -->

    Reviewers
    Assignees
    fatherlinux fatherlinux
    Labels
    risk: low confidence: 84.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 65.8% (HIGH) · Higher = larger blast radius
    65.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 84.5% · Lower = rushed or shallow review
    84.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 10.2% · Safe to merge
    10.2%