A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Guard nightly cleanup by release ID and retry pending Latest recovery (#1972)
Eyal Golan10fb48386444
diff --git a/changelog.d/nightly-release-id-recovery.md b/changelog.d/nightly-release-id-recovery.mdnew file mode 100644index 000000000..ee8f9c4b9--- /dev/null+++ b/changelog.d/nightly-release-id-recovery.md@@ -0,0 +1 @@+Record the nightly draft release ID before uploads, refuse cleanup of a different release, and retry a recorded failed Latest recovery before the next run proceeds.diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex a2bcf8087..b32065c0e 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -189,7 +189,9 @@ The gates, in order. The first one that fails ends the night as REFUSED, and not1. Preflight: `origin/main` differs from the last published nightly (otherwise the night is SKIPPED), at least 40 GBfree, no `EXCLUSIVE-WINDOW` file, the Unity licence, editor and slot script present, and no release already holdingtonight's tag, and no local or remote git tag of that name. First delete a stranded draft only when its tag- matches this job's saved `open_draft`, then check availability. Foreign drafts and published releases refuse.+ matches this job's saved `open_draft` and its release ID matches `open_draft_id`, then check availability.+ Foreign drafts and published releases refuse. Old state with an `open_draft` but no ID still loads; a same-tag+ draft refuses with "check by hand" and is never deleted without an ID match.With `--no-publish`, leave the draft and state alone and refuse the collision.2. `build-sim`, then `scripts/check.sh origin/main` (`check`) and `scripts/oss/release_gate.sh` (`release-gate`), thesame bar as a release.@@ -219,22 +221,35 @@ nightly; without the line, an increase beyond 2% refuses the night. The new sizelast nightly (the tag points at the commit the night started from, even if `main` moves during the build), the assetschecked against the local zips, the itch push when enabled (checked by build id and a fetch of the live files, androlled back to the previous build if publication or its verification fails), the release made public with `--latest` and checked for-`isPrerelease: false` and Latest, then `site.yml` started and the demo checked for the new version. Creation also uses-`--latest`, without `--prerelease`. Right before create, the tag is checked again (no release, no local or remote git-tag), so a release made during the build is refused and not touched; only then is ownership recorded and saved. A-create that fails after leaving a draft (an asset upload failing) has that draft cleaned; rollback deletes only that-run's unpublished draft, and only while GitHub shows it as a draft. Ownership is by tag: a draft someone else creates-with the same tag in the second between that check and create would be treated as this run's. Owning a draft by its-release ID, and retrying a failed Latest restore on the next run, are tracked in #1917. A saved stranded draft is cleaned before the next-attempt; it never reaches `/demo/`, because `site.yml` skips drafts.+`isPrerelease: false` and Latest, then `site.yml` started and the demo checked for the new version. Creation uses+`gh api` through the same job runner, with `draft: true`, `prerelease: false` and `make_latest: "true"`.+Right before create, the tag is checked again (no release, no local or remote git tag), so a release made during the+build is refused and not touched. The create response's numeric release ID is saved as `open_draft_id` alongside+`open_draft` before `gh release upload` starts. A failed upload can therefore clean its own draft. Cleanup and+rollback first check that the tag still resolves to that ID and is still a draft, then delete through+`gh api repos/<repo>/releases/<id> --method DELETE`, preserving git tags. A different or unknown ID refuses with+"check by hand"; a replacement with the same tag is never the deletion target. If creation fails without returning+a usable ID, ownership is not guessed and any stranded draft requires a check by hand. A saved draft with a matching+ID is cleaned before the next attempt; it never reaches `/demo/`, because `site.yml` skips drafts. These ID ownership+and persisted recovery guarantees complete the two hardening steps deferred from #1916 to #1917.Before publishing, read the current Latest separately from the previous nightly asset baseline and record it in`latest-before-publish.txt`. On any later failure, including publication verification or both site attempts, and onlywhile the failed release is still Latest, restore that previous tag with `gh release edit <previous> --latest` andverify it; a Latest someone else set in the meantime is left alone and reported. The REFUSED line and`latest-rollback.log` name the previous Latest and the recovery result. With no previous Latest, explicitly report-that fact and remove the failed release's Latest mark; report any failed recovery for manual repair. Published+that fact and remove the failed release's Latest mark. Before attempting recovery, save+`latest_recovery_pending: {"failed": "<tag>", "previous": "<previous Latest>"}` in `state.json`; `previous` is null+when there was no Latest. A failed or unverified recovery keeps this record and reports "check by hand". At the+start of the next publishing run, before preflight, the no-change skip or a pending site deploy, retry through the+same guarded `restore_latest`. Only while the failed tag is still Latest may it edit Latest. A different Latest,+including no Latest, is left alone and the record is cleared; a verified recovery also clears it. A failed retry+keeps the record and refuses the run before anything publishes. Each outcome is logged and notified, including+success and leaving Latest alone. `--no-publish` leaves pending recovery and state untouched and refuses until a+publishing run can handle it. Old state files without the pending field load with no recovery pending. Publishedreleases and tags are preserved. A site-only failure retains the new itch build and the public release, recordsthe site deploy as pending, and restores the previous Latest after the second attempt.+If the ownership checkpoint cannot be saved, refuse before upload and attempt only guarded cleanup of the known draft ID. If recovery state cannot be saved, still attempt the guarded Latest repair, then refuse before site dispatch or publication and report "check by hand". An unwritable state file cannot promise a durable retry record; preserve the saved file and report the unsaved-state error.+Numeric tag components accept leading zeros: `v0.03.1` ties with `v0.3.1` and yields the normalized next tag `v0.3.2`.The no-change skip compares `state.json`'s last published SHA with `origin/main`, regardless of its saved tag name.diff --git a/tools/nightly.py b/tools/nightly.pyindex 5b65e7c50..9fe1e5a53 100644--- a/tools/nightly.py+++ b/tools/nightly.py@@ -32,7 +32,7 @@ import nightly_checksimport unity_postmergefrom nightly_publish import (GitHub, Itch, demo_serves, itch_frame_url, release_notes, sha256_lines, sha256_of,unzip_to)-from nightly_state import (JOB, TZ, Config, Missed, Published, Refused, Runner, Skipped, State, Stop,+from nightly_state import (JOB, TZ, Config, LatestRecovery, Missed, Published, Refused, Runner, Skipped, State, Stop,enable_itch, late_start, load_config, load_state, log_line, missed_days, night_of,notify, record, run_lock, save_state, tag_for)from web_check import find_chrome@@ -205,8 +205,9 @@ def preflight(cfg: Config, state: State, runner: Runner, gh: GitHub, *, job: Pattag = tag_for(version)if gh.release_state(tag) == "draft" and state.open_draft == tag:if not no_publish: # --no-publish makes no store write, not even this cleanup- gh.delete_draft(tag) # this job's own draft from an earlier run+ gh.delete_draft(tag, state.open_draft_id) # refuses old state with no ID, or a replacement draftstate.open_draft = None+ state.open_draft_id = Nonegh.ensure_tag_available(tag)run_dir = job / "runs" / f"{now.astimezone(TZ):%Y%m%d-%H%M%S}"manifest = (clone / "sim/Statecraft.Sim.Tests/golden/manifest.txt").read_text(encoding="utf-8")@@ -574,9 +575,10 @@ def _drop_draft(night: Night, state: State, gh: GitHub) -> None:try:present = gh.release_state(night.tag)if present == "draft":- gh.delete_draft(night.tag)+ gh.delete_draft(night.tag, state.open_draft_id)if present != "published":state.open_draft = None+ state.open_draft_id = Noneexcept Exception as e:print(f"could not delete the draft {night.tag}: {e}", file=sys.stderr) # open_draft stays, so a rerun cleans it@@ -603,22 +605,49 @@ def _itch_rollback(night: Night, itch, folder: Path, version: str) -> str:return note-def _restore_latest(night: Night, gh: GitHub, previous: str | None) -> str:+def _recover_latest(state: State, gh: GitHub, failed: str, previous: str | None,+ save: Callable[[], bool | None]) -> tuple[bool, str]:+ """Checkpoint recovery before trying it. Only a verified result clears it; every outcome is reported."""target = f"previous Latest {previous}" if previous is not None else "no previous Latest"+ state.latest_recovery_pending = LatestRecovery(failed, previous)try:- acted, current = gh.restore_latest(previous, night.tag)+ checkpoint_saved = save() is not False+ except Exception as e:+ checkpoint_saved = False+ print(f"could not checkpoint Latest recovery: {_detail(e)}", file=sys.stderr)+ recovered = False+ try:+ acted, current = gh.restore_latest(previous, failed)if acted:note = (f"restored {target}" if previous is not None else"no previous Latest; removed the failed release's Latest mark")elif current is None:- note = f"there is no Latest now, so {night.tag} is not Latest: left alone"+ note = f"there is no Latest now, so {failed} is not Latest: left alone"elif current == previous:- note = f"{target} still stands; nothing to restore"+ note = f"{target} still stands; left alone"else:- note = f"Latest is now {current}, not {night.tag}: left alone"+ note = f"Latest is now {current}, not {failed}: left alone"+ state.latest_recovery_pending = None+ recovered = Trueexcept Exception as e:note = f"Latest recovery failed ({target}): {_detail(e)}; check by hand"+ try:+ result_saved = save() is not False+ except Exception as e:+ result_saved = False+ print(f"could not save Latest recovery result: {_detail(e)}", file=sys.stderr)+ if not checkpoint_saved or not result_saved:+ note += "; recovery state could not be saved; check by hand"+ recovered = False+ note = f"{failed} ({target}): {note}"print(note, file=sys.stderr)+ notify("Nightly Latest recovery", note[:200])+ return recovered, note+++def _restore_latest(night: Night, state: State, gh: GitHub, previous: str | None,+ save: Callable[[], bool | None]) -> str:+ _, note = _recover_latest(state, gh, night.tag, previous, save)try:(night.run_dir / "latest-rollback.log").write_text(note + "\n", encoding="utf-8")except OSError as e:@@ -627,7 +656,7 @@ def _restore_latest(night: Night, gh: GitHub, previous: str | None) -> str:def publish_night(night: Night, state: State, gh: GitHub, itch, zips: tuple[Path, Path], sizes: dict[str, int],- boot: float, *, previous: tuple[str, str | None], save: Callable[[], None],+ boot: float, *, previous: tuple[str, str | None], save: Callable[[], bool | None],runner: Runner) -> None:"""Draft first, so nothing public changes until the draft's bytes match: draft, verify, publish, then the site.`save` persists the state; it runs right after the draft exists and right after the release is public, so a@@ -643,10 +672,14 @@ def publish_night(night: Night, state: State, gh: GitHub, itch, zips: tuple[Pathnotes.write_text(release_notes(version=night.version, sha=night.sha, since=since, subjects=subjects,sha256_lines=sha256_lines(list(zips))), encoding="utf-8")gh.ensure_tag_available(night.tag) # again just before create: a release made since preflight is never ours- state.open_draft = night.tag # set before create: a draft a failed upload leaves behind is then cleaned- save()+ def created(release_id: int) -> None:+ state.open_draft = night.tag+ state.open_draft_id = release_id+ if save() is False:+ raise Refused("github-draft", f"could not persist ownership of {night.tag} (release ID {release_id}) before upload; check by hand")+try:- gh.create_draft(night.tag, night.sha, notes, list(zips))+ gh.create_draft(night.tag, night.sha, notes, list(zips), created=created)gh.verify_draft(night.tag, list(zips), night.run_dir / "draft-download")except Exception as e:_drop_draft(night, state, gh)@@ -694,6 +727,7 @@ def publish_night(night: Night, state: State, gh: GitHub, itch, zips: tuple[Pathgh.publish(night.tag, night.sha)verified = Truestate.open_draft = None+ state.open_draft_id = Nonestate.last_published = Published(night.tag, night.sha, night.version, sizes, boot)if len(state.boot_baseline) < BASELINE_NIGHTS:state.boot_baseline.append(boot)@@ -716,7 +750,7 @@ def publish_night(night: Night, state: State, gh: GitHub, itch, zips: tuple[Pathexcept BaseException as e:detail = _detail(e)if publish_started:- detail += _restore_latest(night, gh, previous_latest)+ detail += _restore_latest(night, state, gh, previous_latest, save)if not verified:if rollback_folder is not None: # itch must not keep a build the release does not havedetail += _itch_rollback(night, itch, rollback_folder, rollback_version)@@ -760,7 +794,7 @@ def _build_both(night: Night, runner: Runner, free_gb: Callable[[Path], float])def run_stages(night: Night, state: State, runner: Runner, gh: GitHub, itch, *, no_publish: bool,free_gb: Callable[[Path], float] = lambda p: shutil.disk_usage(p).free / 1e9,- save: Callable[[], None] = lambda: None) -> bool:+ save: Callable[[], bool | None] = lambda: None) -> bool:"""Every gate, then (unless no_publish) the publish. True when published, False when stopped before any store."""run_gates(night, runner)run_editmode(night, runner)@@ -784,12 +818,14 @@ def run_stages(night: Night, state: State, runner: Runner, gh: GitHub, itch, *,return True-def _try_save(state_path: Path, state: State) -> None:+def _try_save(state_path: Path, state: State) -> bool:try:save_state(state_path, state)+ return Trueexcept OSError as e: # never costs the night its record, and the final save tries againprint(f"could not save state: {e}", file=sys.stderr)notify("Nightly state not saved", f"{e}"[:200]) # a published release with unsaved state must not be silent+ return Falsedef run_night(cfg: Config, state_path: Path, job: Path, runner: Runner, gh: GitHub | None, itch, *, now: datetime,@@ -798,6 +834,7 @@ def run_night(cfg: Config, state_path: Path, job: Path, runner: Runner, gh: GitHoutcome, gate, detail = "REFUSED", "internal", ""state: State | None = Nonenight: Night | None = None+ recovery_note = ""day = night_of(now)try:try:@@ -809,6 +846,14 @@ def run_night(cfg: Config, state_path: Path, job: Path, runner: Runner, gh: GitHlog_line(stamp, "MISSED", tag=None, sha=None, gate="-", log=None))if client_error is not None or gh is None: # the record names the step, not "internal"raise client_error or Refused("github-client", "no GitHub client")+ pending = state.latest_recovery_pending+ if pending is not None:+ if no_publish:+ raise Refused("github-latest", "Latest recovery is pending; --no-publish leaves it alone")+ recovered, recovery_note = _recover_latest(state, gh, pending.failed, pending.previous,+ lambda: _try_save(state_path, state))+ if not recovered:+ raise Refused("github-latest", recovery_note)night = preflight(cfg, state, runner, gh, job=job, now=now, manual=manual, free_gb=free_gb,no_publish=no_publish)published = run_stages(night, state, runner, gh, itch, no_publish=no_publish, free_gb=free_gb,@@ -826,6 +871,8 @@ def run_night(cfg: Config, state_path: Path, job: Path, runner: Runner, gh: GitHoutcome, gate, detail = "REFUSED", "internal", f"{type(e).__name__}: {e}"finally:if not no_publish:+ if recovery_note and recovery_note not in detail:+ detail = " ".join(filter(None, [detail, recovery_note]))if night is not None and night.notes:detail = " ".join(filter(None, [detail, *night.notes]))line = log_line(now, outcome, tag=night.tag if night else None, sha=night.sha if night else None,diff --git a/tools/nightly_publish.py b/tools/nightly_publish.pyindex 3327f679e..529f8683b 100644--- a/tools/nightly_publish.py+++ b/tools/nightly_publish.py@@ -316,11 +316,23 @@ class GitHub:# --- the draft, its check, publishing --------------------------------------------------------------------------- def create_draft(self, tag: str, sha: str, notes: Path, assets: list[Path]) -> None:- """A normal draft marked Latest, whose tag will be created at exactly `sha` when it is published."""- self._run("github-draft", ["gh", "release", "create", tag, "--repo", self.slug, "--draft",- "--latest", "--target", sha, "--title", f"{tag} (nightly)",- "--notes-file", str(notes), *[str(a) for a in assets]], UPLOAD_TIMEOUT)+ def create_draft(self, tag: str, sha: str, notes: Path, assets: list[Path], *,+ created: Callable[[int], None]) -> int:+ """Create a normal draft marked Latest and checkpoint its returned ID before uploading assets. An unreadable+ create response never grants ownership by tag; a possibly stranded draft then needs a check by hand."""+ data = self._json("github-draft", ["gh", "api", f"repos/{self.slug}/releases", "--method", "POST",+ "--raw-field", f"tag_name={tag}", "--raw-field", f"target_commitish={sha}",+ "--raw-field", f"name={tag} (nightly)", "--field", f"body=@{notes}",+ "--field", "draft=true", "--field", "prerelease=false",+ "--raw-field", "make_latest=true"], dict, UPLOAD_TIMEOUT)+ release_id = data.get("id")+ if (type(release_id) is not int or release_id <= 0 or data.get("tag_name") != tag+ or data.get("draft") is not True):+ raise Refused("github-draft", f"create returned no usable draft ID for {tag}; check by hand")+ created(release_id)+ self._run("github-draft", ["gh", "release", "upload", tag, "--repo", self.slug,+ *[str(a) for a in assets]], UPLOAD_TIMEOUT)+ return release_iddef verify_draft(self, tag: str, local: list[Path], dest: Path) -> None:data = self._view("github-draft", tag, "isDraft,isPrerelease,assets")@@ -368,12 +380,16 @@ class GitHub:if at != sha:raise Refused("github-publish", f"the tag {tag} points at {at}, not at {sha}")- def delete_draft(self, tag: str) -> None:- """Delete a release only while gh shows it as a draft; never touches a tag."""- data = self._view("github-delete", tag, "isDraft")+ def delete_draft(self, tag: str, release_id: int | None) -> None:+ """Check the tag's ID and draft flag, then delete by that ID; never touches a tag or a replacement release."""+ if type(release_id) is not int or release_id <= 0:+ raise Refused("github-delete", f"{tag} has no saved draft ID, so it is not deleted; check by hand")+ data = self._view("github-delete", tag, "databaseId,isDraft")+ if type(data.get("databaseId")) is not int or data["databaseId"] != release_id:+ raise Refused("github-delete", f"{tag} has a different or unknown release ID, so it is not deleted; check by hand")if data.get("isDraft") is not True:- raise Refused("github-delete", f"{tag} is not a draft, so it is not deleted")- self._run("github-delete", ["gh", "release", "delete", tag, "--repo", self.slug, "--yes"])+ raise Refused("github-delete", f"{tag} is not a draft, so it is not deleted; check by hand")+ self._run("github-delete", ["gh", "api", f"repos/{self.slug}/releases/{release_id}", "--method", "DELETE"])# --- the size budget -------------------------------------------------------------------------------------------diff --git a/tools/nightly_state.py b/tools/nightly_state.pyindex a3649a4a5..ab36d4993 100644--- a/tools/nightly_state.py+++ b/tools/nightly_state.py@@ -166,6 +166,12 @@ class Published:boot_ms: float | None+@dataclass+class LatestRecovery:+ failed: str+ previous: str | None++@dataclassclass State:last_published: Published | None = None@@ -173,6 +179,8 @@ class State:last_run_day: str | None = Noneopen_draft: str | None = Nonesite_pending: str | None = None+ open_draft_id: int | None = None+ latest_recovery_pending: LatestRecovery | None = Nonedef _number(value: object) -> bool:@@ -217,8 +225,22 @@ def _state_from(raw: dict) -> State:baseline = raw.get("boot_baseline", [])if not isinstance(baseline, list) or not all(_number(x) for x in baseline):raise TypeError("boot_baseline must be a list of numbers")+ release_id = raw.get("open_draft_id")+ if release_id is not None and (type(release_id) is not int or release_id <= 0):+ raise TypeError("open_draft_id must be a positive integer or null")+ pending = raw.get("latest_recovery_pending")+ recovery = None+ if pending is not None:+ if (not isinstance(pending, dict) or set(pending) != {"failed", "previous"}+ or not isinstance(pending["failed"], str) or not pending["failed"]):+ raise TypeError("latest_recovery_pending has the wrong shape")+ previous = _opt_str(pending["previous"], "previous")+ if previous == "":+ raise TypeError("previous Latest must be a nonempty tag or null")+ recovery = LatestRecovery(pending["failed"], previous)return State(published, list(baseline), _day(raw.get("last_run_day")),- _opt_str(raw.get("open_draft"), "open_draft"), _opt_str(raw.get("site_pending"), "site_pending"))+ _opt_str(raw.get("open_draft"), "open_draft"), _opt_str(raw.get("site_pending"), "site_pending"),+ release_id, recovery)def load_state(path: Path) -> State:diff --git a/tools/tests/test_nightly.py b/tools/tests/test_nightly.pyindex 893becfb0..3cf2c7773 100644--- a/tools/tests/test_nightly.py+++ b/tools/tests/test_nightly.py@@ -9,6 +9,7 @@ import zipfilefrom contextlib import contextmanagerfrom datetime import date, datetimefrom pathlib import Path+from types import SimpleNamespaceimport pytest@@ -27,10 +28,12 @@ TAG = "v0.3.2"class FakeGH:- """The GitHub client as the night uses it. `release` is what release_state answers (None: no release); `fail`- maps a method name to an exception raised by it (a list raises one per call, then succeeds)."""+ """The GitHub client as the night uses it. `releases` holds (tag, ID, state) rows, including same-tag replacements;+ the last matching row is the tag lookup. `release` keeps older single-release tests readable. `fail` maps a+ method name to an exception raised by it (a list raises one per call, then succeeds)."""def __init__(self, release=None, *, fail=None, previous_tag="v0.3.1"):+ self.releases = []self.release = releaseself.fail = fail or {}self.previous_tag = previous_tag@@ -38,6 +41,23 @@ class FakeGH:self.calls = []self.baseline = None # a zip the download hands out+ @property+ def release(self):+ return self.releases[-1][2] if self.releases else None++ @release.setter+ def release(self, value):+ if value is None:+ self.releases.clear()+ elif self.releases:+ tag, release_id, _ = self.releases[-1]+ self.releases[-1] = (tag, release_id, value)+ else:+ self.releases.append((TAG, 101, value))++ def at_tag(self, tag):+ return next((r for r in reversed(self.releases) if r[0] == tag), None)+def _maybe_fail(self, name):err = self.fail.get(name)if isinstance(err, list):@@ -47,7 +67,8 @@ class FakeGH:def release_state(self, tag):self.calls.append(("release_state", tag))- return self.release+ row = self.at_tag(tag)+ return row[2] if row else Nonedef next_version(self):self.calls.append(("next_version",))@@ -55,12 +76,18 @@ class FakeGH:def ensure_tag_available(self, tag):self.calls.append(("ensure_tag_available", tag))- if self.release is not None:+ if self.at_tag(tag) is not None:raise ns.Refused("tag-exists", f"a {self.release} release already has the tag {tag}")- def delete_draft(self, tag):- self.calls.append(("delete_draft", tag))- self.release = None+ def delete_draft(self, tag, release_id=...):+ # Main calls by tag alone; model that deletion rather than failing on the signature.+ row = self.at_tag(tag)+ if release_id is ...:+ release_id = row[1] if row else None+ self.calls.append(("delete_draft", tag, release_id))+ if release_id is None or row != (tag, release_id, "draft"):+ raise ns.Refused("github-delete", f"{tag} has no matching owned draft ID; check by hand")+ self.releases.remove(row)def dispatch_site(self, deadline):self.calls.append(("dispatch_site", deadline))@@ -75,10 +102,14 @@ class FakeGH:self._maybe_fail("download")return self.baseline- def create_draft(self, tag, sha, notes, assets):+ def create_draft(self, tag, sha, notes, assets, *, created=None):self.calls.append(("create_draft", tag, sha, notes, list(assets)))self._maybe_fail("create_draft")- self.release = "draft"+ self.releases.append((tag, 101, "draft"))+ if created is not None:+ created(101)+ self._maybe_fail("upload")+ return 101def verify_draft(self, tag, local, dest):self.calls.append(("verify_draft", tag, list(local), dest))@@ -191,6 +222,22 @@ def gate_of(env, **kw):return e.value+def read_pending_with_old_state(monkeypatch):+ # Adapt only deserialization for baseline behavior tests. Main's State and run_night still do the work;+ # raw JSON assertions below must detect missing persistence, not unknown-key rejection.+ load = ns.load_state++ def read(path):+ if "latest_recovery_pending" in {f.name for f in dataclasses.fields(ns.State)}:+ return load(path)+ raw = json.loads(path.read_text())+ pending = raw.pop("latest_recovery_pending", None)+ state = ns._state_from(raw)+ state.latest_recovery_pending = SimpleNamespace(**pending) if pending is not None else None+ return state+ monkeypatch.setattr(nightly, "load_state", read)++def test_a_clean_preflight_builds_the_night(env):n = env.pre()assert (n.sha, n.version, n.tag, n.day) == (SHA, "0.3.2", TAG, date(2026, 10, 28))@@ -282,17 +329,20 @@ def test_the_clone_must_be_main_at_origin_main_and_clean(env, change):def test_same_day_rerun_cleans_its_draft_and_refuses_a_published_tag(env):gh = FakeGH("draft")st = ns.State(open_draft=TAG)+ st.open_draft_id = 101env.pre(st, gh)- assert ("delete_draft", TAG) in gh.calls+ assert ("delete_draft", TAG, 101) in gh.callsassert st.open_draft is Nonegh = FakeGH("published")with pytest.raises(ns.Refused) as e:- env.pre(ns.State(open_draft=TAG), gh)- assert e.value.gate == "tag-exists" and ("delete_draft", TAG) not in gh.calls+ st.open_draft = TAG+ st.open_draft_id = 101+ env.pre(st, gh)+ assert e.value.gate == "tag-exists" and "delete_draft" not in gh.names()gh = FakeGH("draft") # a draft this job did not leavewith pytest.raises(ns.Refused) as e:env.pre(ns.State(), gh)- assert e.value.gate == "tag-exists" and ("delete_draft", TAG) not in gh.calls+ assert e.value.gate == "tag-exists" and "delete_draft" not in gh.names()def test_a_stranded_own_draft_is_cleaned_and_the_night_proceeds(env):@@ -302,8 +352,9 @@ def test_a_stranded_own_draft_is_cleaned_and_the_night_proceeds(env):return ns.next_version([{"tag_name": "v0.3.1", "draft": False},{"tag_name": TAG, "draft": True}])gh, st = Releases("draft"), ns.State(open_draft=TAG)+ st.open_draft_id = 101assert env.pre(st, gh).tag == TAG- assert gh.calls == [("next_version",), ("release_state", TAG), ("delete_draft", TAG),+ assert gh.calls == [("next_version",), ("release_state", TAG), ("delete_draft", TAG, 101),("ensure_tag_available", TAG)]assert st.open_draft is None@@ -387,10 +438,11 @@ def test_no_publish_never_retries_the_site(env, monkeypatch):def test_no_publish_leaves_its_own_draft_alone(env):gh = FakeGH("draft")st = ns.State(open_draft=TAG)+ st.open_draft_id = 101with pytest.raises(ns.Refused) as e:env.pre(st, gh, no_publish=True)assert e.value.gate == "tag-exists"- assert ("delete_draft", TAG) not in gh.calls and st.open_draft == TAG+ assert "delete_draft" not in gh.names() and st.open_draft == TAGdef test_no_release_means_the_tag_is_free_and_any_release_refuses(env):@@ -1148,7 +1200,7 @@ def test_a_failed_draft_check_deletes_the_draft_and_refuses(night, env, pub, serwith pytest.raises(ns.Refused) as e:publish(night, st, gh, pub, env)assert e.value.gate == "github-draft" and "hash differs" in e.value.detail- assert ("delete_draft", TAG) in gh.calls and "publish" not in gh.names() and "dispatch_site" not in gh.names()+ assert ("delete_draft", TAG, 101) in gh.calls and "publish" not in gh.names() and "dispatch_site" not in gh.names()assert st.open_draft is None and st.last_published.sha == OLD and served == []@@ -1164,25 +1216,39 @@ def test_a_release_made_after_preflight_refuses_before_create_and_is_never_deletdef test_a_create_that_fails_after_leaving_a_draft_cleans_that_draft(night, env, pub, served):- class HalfMade(FakeGH):- def create_draft(self, tag, sha, notes, assets):- self.calls.append(("create_draft", tag, sha, notes, list(assets)))- self.release = "draft" # gh made the release, then an asset upload failed- raise ns.Refused("github-draft", "upload timed out")- gh = HalfMade()+ gh = FakeGH(fail={"upload": ns.Refused("github-draft", "upload timed out")})st = ns.State(last_published=last_published())with pytest.raises(ns.Refused, match="upload timed out"):publish(night, st, gh, pub, env)- assert [c for c in gh.calls if c[0] == "delete_draft"] == [("delete_draft", TAG)]+ assert [c for c in gh.calls if c[0] == "delete_draft"] == [("delete_draft", TAG, 101)]assert gh.release is None and st.open_draft is None and st.last_published.sha == OLD+def test_upload_failure_has_a_persisted_owned_id_before_cleanup(night, env, pub, served):+ # Mutation: save ownership only after upload, leaving a surviving draft unowned on disk.+ gh = FakeGH(fail={"upload": ns.Refused("github-draft", "upload timed out")})+ gh.delete_draft = lambda tag, release_id=None: (_ for _ in ()).throw(ns.Refused("github-delete", "offline"))+ st = ns.State(last_published=last_published())+ checkpoints = []++ def save():+ ns.save_state(env.state_path, st)+ checkpoints.append(json.loads(env.state_path.read_text()))+ with pytest.raises(ns.Refused, match="upload timed out"):+ publish(night, st, gh, pub, env, save=save)+ assert checkpoints[0].get("open_draft_id") == 101+ assert checkpoints[0]["open_draft"] == TAG+ assert gh.releases == [(TAG, 101, "draft")]+ assert json.loads(env.state_path.read_text())["open_draft_id"] == 101+ assert "verify_draft" not in gh.names() and "publish" not in gh.names()++def test_rollback_after_create_deletes_only_the_created_tag(night, env, pub, served):gh = FakeGH(fail={"verify_draft": ns.Refused("github-draft", "hash differs")})st = ns.State(open_draft="v0.3.0", last_published=last_published())with pytest.raises(ns.Refused):publish(night, st, gh, pub, env)- assert [c for c in gh.calls if c[0] == "delete_draft"] == [("delete_draft", TAG)]+ assert [c for c in gh.calls if c[0] == "delete_draft"] == [("delete_draft", TAG, 101)]assert st.open_draft is None@@ -1190,12 +1256,12 @@ def test_a_non_refusal_error_in_the_draft_check_still_deletes_the_draft(night, egh = FakeGH(fail={"verify_draft": OSError("disk")})with pytest.raises(ns.Refused) as e:publish(night, ns.State(last_published=last_published()), gh, pub, env)- assert e.value.gate == "github-draft" and "OSError" in e.value.detail and ("delete_draft", TAG) in gh.calls+ assert e.value.gate == "github-draft" and "OSError" in e.value.detail and ("delete_draft", TAG, 101) in gh.callsdef test_a_failed_cleanup_keeps_the_original_refusal_and_the_open_draft(night, env, pub, served, capsys):gh = FakeGH(fail={"verify_draft": ns.Refused("github-draft", "hash differs")})- gh.delete_draft = lambda tag: (_ for _ in ()).throw(ns.Refused("github-delete", "offline"))+ gh.delete_draft = lambda tag, release_id=None: (_ for _ in ()).throw(ns.Refused("github-delete", "offline"))st = ns.State(last_published=last_published())with pytest.raises(ns.Refused) as e:publish(night, st, gh, pub, env)@@ -1207,7 +1273,7 @@ def test_a_failed_publish_deletes_a_draft_that_is_still_one(night, env, pub, serst = ns.State(last_published=last_published())with pytest.raises(ns.Refused) as e:publish(night, st, gh, pub, env)- assert e.value.gate == "github-publish" and ("delete_draft", TAG) in gh.calls+ assert e.value.gate == "github-publish" and ("delete_draft", TAG, 101) in gh.callsassert st.last_published.sha == OLD and served == []@@ -1314,7 +1380,7 @@ def test_a_failed_latest_lookup_refuses_before_the_public_edit(night, env, pub,with pytest.raises(ns.Refused, match="offline"):publish(night, ns.State(), gh, pub, env)assert "publish" not in gh.names() and "restore_latest" not in gh.names()- assert ("delete_draft", TAG) in gh.calls+ assert ("delete_draft", TAG, 101) in gh.callsdef test_a_failed_save_after_publish_restores_latest(night, env, pub, served):@@ -1333,9 +1399,16 @@ def test_a_disk_error_saving_state_after_publish_keeps_the_good_release_latest(nmonkeypatch):monkeypatch.setattr(nightly, "notify", lambda *a: None)blocked = tmp_path / "state.json"- blocked.mkdir() # writing the state file fails with an OSError, which production's _try_save reports and absorbsgh, st = FakeGH(), ns.State(last_published=last_published())- publish(night, st, gh, pub, env, save=lambda: nightly._try_save(blocked, st))+ saved_ids = []+ def save():+ if gh.release == "published" and not blocked.is_dir():+ saved_ids.append(json.loads(blocked.read_text())["open_draft_id"])+ blocked.unlink()+ blocked.mkdir() # fail only after publication; the ownership checkpoint must have succeeded+ return nightly._try_save(blocked, st)+ publish(night, st, gh, pub, env, save=save)+ assert saved_ids == [101] and blocked.is_dir()assert gh.latest == TAG and "restore_latest" not in gh.names() and st.last_published.tag == TAG@@ -1382,6 +1455,7 @@ def test_state_is_saved_right_after_create_draft_and_right_after_publish(night,st = ns.State(last_published=last_published())with pytest.raises(Crash):publish(night, st, FakeGH(), pub, env, save=save(1)) # killed right after create_draft+ assert json.loads(path.read_text()).get("open_draft_id") == 101assert ns.load_state(path).open_draft == TAG and saves[0] == (TAG, last_published().tag)saves.clear()st = ns.State(last_published=last_published())@@ -1536,7 +1610,7 @@ def test_an_unusable_rollback_target_refuses_before_any_push(itch_night, env, hoerr, gh, st = refused_itch(itch_night, env)assert err.gate == "itch-rollback"assert not [c for c in gh.calls if c[0].startswith("itch.")] and "publish" not in gh.names()- assert ("delete_draft", TAG) in gh.calls and st.open_draft is None+ assert ("delete_draft", TAG, 101) in gh.calls and st.open_draft is None@pytest.mark.parametrize("step", ["push", "wait_live", "matches"])@@ -1560,7 +1634,7 @@ def test_a_failed_rollback_is_named_in_the_refusal_and_notified(itch_night, env)err, gh, st = refused_itch(itch_night, env)assert err.gate == "itch" and "never live" in err.detailassert "rollback" in err.detail and "butler push exited 1" in err.detail and "by hand" in err.detail- assert ("delete_draft", TAG) in gh.calls # the draft is still cleaned up+ assert ("delete_draft", TAG, 101) in gh.calls # the draft is still cleaned upassert any("itch" in a[0].lower() and "rollback" in a[1].lower() for a in env_notes)@@ -1570,7 +1644,7 @@ def test_a_github_publish_failure_after_itch_rolls_itch_back(itch_night, env):err, gh, st = refused_itch(itch_night, env)assert err.gate == "github-publish"assert ("itch.push", "itch-rollback", PREV_VERSION) in gh.calls and ("itch.wait_live", PREV_VERSION) in gh.calls- assert ("delete_draft", TAG) in gh.calls+ assert ("delete_draft", TAG, 101) in gh.callsdef test_a_failed_rollback_after_a_publish_failure_is_named_and_notified(itch_night, env):@@ -1590,7 +1664,7 @@ def test_an_interrupt_during_publish_rolls_itch_back_and_cleans_the_draft(itch_nwith pytest.raises(KeyboardInterrupt):run_itch(itch_night, env, st=st)assert ("itch.push", "itch-rollback", PREV_VERSION) in gh.calls and ("itch.wait_live", PREV_VERSION) in gh.calls- assert ("delete_draft", TAG) in gh.calls and st.open_draft is None+ assert ("delete_draft", TAG, 101) in gh.calls and st.open_draft is Nonedef test_the_itch_skip_reason_is_noted_on_the_night(night, env, pub, served):@@ -2492,3 +2566,253 @@ def test_a_partial_gzip_copy_cannot_reach_any_consumer_or_publication(night, envno_publish=False, free_gb=lambda p: 100.0)assert stages.names() == ["run_gates", "run_editmode", "build_web", "assert_clean_tree"]assert (stages.gz / "index.html").read_text() == "incomplete evidence"++[email protected]("rollback", [False, True])[email protected]("record_owned_row", [False, True])+def test_same_tag_foreign_id_survives_cleanup_and_rollback(env, night, rollback, record_owned_row, capsys):+ # Mutation: omit or pass the wrong saved ID to the fake's ownership check.+ # The real-client DELETE-address test covers deleting by tag after a successful check.+ gh = FakeGH()+ # Two logical same-tag records also cover the issue's defensive fixture contract; no live API capability is assumed.+ expected = ([(TAG, 101, "draft")] if record_owned_row else []) + [(TAG, 202, "draft"), ("v0.4.0", 303, "published")]+ gh.releases = list(expected)+ st = ns.State(open_draft=TAG)+ st.open_draft_id = 101+ refusal = ""+ if rollback:+ nightly._drop_draft(night, st, gh)+ else:+ try:+ env.pre(st, gh)+ except ns.Refused as e:+ refusal = e.detail+ assert gh.releases == expected+ if rollback:+ assert "check by hand" in capsys.readouterr().err+ else:+ assert "check by hand" in refusal+ assert st.open_draft == TAG and st.open_draft_id == 101+++def test_matching_persisted_id_cleans_our_stranded_draft_on_rerun(env):+ # Mutation: refuse every stranded draft, or lose the ID while loading saved state.+ gh = FakeGH()+ gh.releases = [("v0.4.0", 202, "draft"), (TAG, 101, "draft")]+ st = ns.State(open_draft=TAG, open_draft_id=101) # new-schema persistence contract+ ns.save_state(env.state_path, st)+ st = ns.load_state(env.state_path)+ assert env.pre(st, gh).tag == TAG+ assert gh.releases == [("v0.4.0", 202, "draft")]+ assert st.open_draft is None and st.open_draft_id is None+++def test_legacy_open_draft_without_id_refuses_and_survives(env):+ # Mutation: treat a missing ID as permission to delete a same-tag draft.+ env.state_path.write_text(json.dumps({"open_draft": TAG}))+ st = ns.load_state(env.state_path)+ gh = FakeGH("draft")+ refusal = ""+ try:+ env.pre(st, gh)+ except ns.Refused as e:+ refusal = e.detail+ assert gh.releases == [(TAG, 101, "draft")]+ assert "check by hand" in refusal+ assert st.open_draft == TAG and getattr(st, "open_draft_id", None) is None+++def test_failed_recovery_is_persisted_then_retried_before_next_preflight(night, env, pub, served):+ # Mutation: only report a recovery failure, or retry after preflight's no-change/site-pending path.+ gh = FakeGH(fail={"dispatch_site": ns.Refused("site", "site unavailable"),+ "restore_latest": ns.Refused("github-latest", "cannot verify")})+ st = ns.State(last_published=last_published())+ with pytest.raises(ns.Refused, match="check by hand"):+ publish(night, st, gh, pub, env, save=lambda: ns.save_state(env.state_path, st))+ pending = {"failed": TAG, "previous": "v0.3.1"}+ assert json.loads(env.state_path.read_text()).get("latest_recovery_pending") == pending+ gh.fail.clear()+ gh.calls.clear()+ assert env.night(gh=gh) == "SKIPPED"+ assert gh.names() == ["restore_latest", "dispatch_site"]+ assert gh.latest == "v0.3.1"+ assert ns.load_state(env.state_path).latest_recovery_pending is None+ assert "restored previous Latest v0.3.1" in env.log()+ assert any("restored previous Latest v0.3.1" in note[1] for note in env_notes)+ gh.calls.clear()+ assert env.night(gh=gh) == "SKIPPED"+ assert "restore_latest" not in gh.names()+++def test_unverified_restore_persists_even_if_latest_edit_reached_github(night, env, pub, served):+ # Mutation: clear recovery on an edit that has not been verified.+ gh = FakeGH(fail={"dispatch_site": ns.Refused("site", "site unavailable")})+ st = ns.State(last_published=last_published())++ def unverified(previous, failed):+ gh.calls.append(("restore_latest", previous, failed))+ gh.latest = previous # the edit reached GitHub, but verification failed+ raise ns.Refused("github-latest", "cannot verify")+ gh.restore_latest = unverified+ with pytest.raises(ns.Refused, match="cannot verify"):+ publish(night, st, gh, pub, env, save=lambda: ns.save_state(env.state_path, st))+ assert gh.latest == "v0.3.1"+ assert json.loads(env.state_path.read_text()).get("latest_recovery_pending") == {+ "failed": TAG, "previous": "v0.3.1"}++[email protected]("site_pending", [None, "0.3.2"])+def test_pending_recovery_precedes_unchanged_main_and_site_retry(env, monkeypatch, site_pending):+ # Mutation: run real preflight's skip or site deploy before retrying pending recovery.+ read_pending_with_old_state(monkeypatch)+ raw = dataclasses.asdict(ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None),+ site_pending=site_pending))+ raw["latest_recovery_pending"] = {"failed": TAG, "previous": "v0.3.1"}+ env.state_path.write_text(json.dumps(raw))+ gh = FakeGH()+ gh.latest = TAG++ observations = []+ def dispatch(deadline):+ gh.calls.append(("dispatch_site", deadline))+ observations.append((gh.latest, json.loads(env.state_path.read_text()).get("latest_recovery_pending")))+ gh.dispatch_site = dispatch+ monkeypatch.setattr(nightly, "demo_serves", lambda *a, **k: None)+ assert env.night(gh=gh) == "SKIPPED"+ assert gh.names() == ["restore_latest"] + (["dispatch_site"] if site_pending else [])+ assert observations == ([("v0.3.1", None)] if site_pending else [])+ assert json.loads(env.state_path.read_text()).get("latest_recovery_pending") is None+ gh.calls.clear()+ assert env.night(gh=gh) == "SKIPPED"+ assert gh.calls == []++[email protected]("current", ["v0.4.0", None, "v0.3.1"])+def test_pending_recovery_with_moved_latest_is_cleared_and_left_alone(env, monkeypatch, current):+ # Mutation: disregard restore_latest's acted=False result or keep retrying an obsolete recovery.+ gh = FakeGH()+ gh.latest = current+ read_pending_with_old_state(monkeypatch)+ raw = dataclasses.asdict(ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None)))+ raw["latest_recovery_pending"] = {"failed": TAG, "previous": "v0.3.1"}+ env.state_path.write_text(json.dumps(raw))+ assert env.night(gh=gh) == "SKIPPED"+ assert gh.calls == [("restore_latest", "v0.3.1", TAG)]+ assert gh.latest == current+ assert json.loads(env.state_path.read_text())["latest_recovery_pending"] is None+ assert "left alone" in env.log()+ assert any("left alone" in note[1] for note in env_notes)+ gh.calls.clear()+ assert env.night(gh=gh) == "SKIPPED"+ assert "restore_latest" not in gh.names()+++def test_pending_recovery_failure_stops_publication_and_keeps_record(env, monkeypatch, served):+ # Mutation: clear pending on an unverified recovery or continue into publishing after it fails.+ read_pending_with_old_state(monkeypatch)+ pending = {"failed": TAG, "previous": None}+ raw = dataclasses.asdict(ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None),+ site_pending="0.3.2"))+ raw["latest_recovery_pending"] = pending+ env.state_path.write_text(json.dumps(raw))+ gh = FakeGH(fail={"restore_latest": OSError("offline")})+ gh.latest = TAG+ outcome = env.night(gh=gh)+ assert "dispatch_site" not in gh.names() and "publish" not in gh.names()+ assert json.loads(env.state_path.read_text())["latest_recovery_pending"] == pending+ assert outcome == "REFUSED"+ assert gh.calls == [("restore_latest", None, TAG)] and served == []+ assert "check by hand" in env.log()+ assert any("offline" in note[1] for note in env_notes)+++def test_no_publish_leaves_pending_recovery_untouched(env, monkeypatch):+ # Mutation: let a dry run edit Latest or clear its persisted recovery.+ read_pending_with_old_state(monkeypatch)+ raw = dataclasses.asdict(ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None)))+ raw["latest_recovery_pending"] = {"failed": TAG, "previous": None}+ env.state_path.write_text(json.dumps(raw))+ before = env.state_path.read_bytes()+ gh = FakeGH()+ assert env.night(gh=gh, no_publish=True) == "REFUSED"+ assert gh.calls == []+ assert env.state_path.read_bytes() == before+++def test_publish_failure_cannot_clean_a_foreign_replacement_after_create(night, env, pub, served):+ gh = FakeGH()+ st = ns.State(last_published=last_published())+ def replaced(tag, local, dest):+ gh.releases[:] = [(TAG + "-replaced", 101, "draft"), (TAG, 202, "draft")]+ raise ns.Refused("github-draft", "verification failed after replacement")+ gh.verify_draft = replaced+ with pytest.raises(ns.Refused, match="verification failed after replacement"):+ publish(night, st, gh, pub, env, save=lambda: ns.save_state(env.state_path, st))+ assert gh.releases == [(TAG + "-replaced", 101, "draft"), (TAG, 202, "draft")]+ assert st.open_draft == TAG and getattr(st, "open_draft_id", None) == 101+ assert "publish" not in gh.names() and served == []+++def test_failed_ownership_checkpoint_prevents_upload(night, env, pub, served, monkeypatch):+ gh = FakeGH()+ st = ns.State(last_published=last_published())+ ns.save_state(env.state_path, st)+ before = env.state_path.read_bytes()+ stages_seen = []+ original = gh._maybe_fail+ def stage(name):+ stages_seen.append(name)+ return original(name)+ gh._maybe_fail = stage+ def cannot_save(*a, **k):+ raise OSError("checkpoint disk failure")+ monkeypatch.setattr(nightly, "save_state", cannot_save)+ err = None+ try:+ publish(night, st, gh, pub, env, save=lambda: nightly._try_save(env.state_path, st))+ except ns.Refused as e:+ err = e+ assert "upload" not in stages_seen+ assert err is not None and err.gate == "github-draft" and "persist" in err.detail+ assert "verify_draft" not in gh.names() and "publish" not in gh.names() and served == []+ assert env.state_path.read_bytes() == before+++def test_failed_recovery_checkpoint_stops_site_after_best_effort_repair(env, monkeypatch, served):+ st = ns.State(last_published=ns.Published(TAG, SHA, "0.3.2", {}, None), site_pending="0.3.2",+ latest_recovery_pending=ns.LatestRecovery(TAG, None))+ ns.save_state(env.state_path, st)+ before = env.state_path.read_bytes()+ def cannot_save(*a, **k):+ raise OSError("checkpoint disk failure")+ monkeypatch.setattr(nightly, "save_state", cannot_save)+ gh = FakeGH()+ gh.latest = TAG+ outcome = env.night(gh=gh)+ assert "dispatch_site" not in gh.names() and "publish" not in gh.names()+ assert outcome == "REFUSED" and gh.calls == [("restore_latest", None, TAG)]+ assert gh.latest is None and env.state_path.read_bytes() == before and served == []+ assert "could not be saved" in env.log() and "check by hand" in env.log()++[email protected]("failing_save", ["checkpoint", "result", "both"])+def test_raising_recovery_save_still_repairs_latest_and_returns_refusal(env, failing_save):+ gh = FakeGH()+ gh.latest = TAG+ st = ns.State()+ saves = []+ def save():+ stage = "checkpoint" if not saves else "result"+ saves.append(stage)+ if failing_save in (stage, "both"):+ raise ValueError("cannot serialize recovery state")+ err = None+ recovered, detail = True, ""+ try:+ recovered, detail = nightly._recover_latest(st, gh, TAG, "v0.3.1", save)+ except ValueError as e:+ err = e+ assert gh.calls == [("restore_latest", "v0.3.1", TAG)] and gh.latest == "v0.3.1"+ assert err is None+ assert saves == ["checkpoint", "result"] and not recovered+ assert "could not be saved" in detail and "check by hand" in detaildiff --git a/tools/tests/test_nightly_publish.py b/tools/tests/test_nightly_publish.pyindex 7eee94fb6..11d242a62 100644--- a/tools/tests/test_nightly_publish.py+++ b/tools/tests/test_nightly_publish.py@@ -1,5 +1,6 @@import hashlibimport io+import inspectimport jsonimport zipfilefrom pathlib import Path@@ -73,6 +74,18 @@ def not_found():return Refused("command", "gh release view exited 1: release not found")+def create_draft(gh, notes, zips, saved):+ # Exercise main's create path too; do not turn a missing callback into the regression signal.+ kwargs = {"created": saved.append} if "created" in inspect.signature(gh.create_draft).parameters else {}+ return gh.create_draft(TAG, SHA, notes, zips, **kwargs)+++def delete_draft(gh, release_id):+ # Only adapt the call shape. The real client still chooses the lookup and DELETE commands.+ args = (release_id,) if "release_id" in inspect.signature(gh.delete_draft).parameters else ()+ return gh.delete_draft(TAG, *args)++# --- release state ---------------------------------------------------------------------------------------------------def test_release_state_is_draft_published_or_none(gh, runner):@@ -152,11 +165,22 @@ def test_tag_lookup_error_refuses_instead_of_assuming_absence(gh, runner):def test_the_draft_is_normal_latest_targeting_the_commit(gh, runner, tmp_path, zips):+ # Mutation: recover an ID by tag instead of using the response to this run's create.+ runner.on(["gh", "api"], json.dumps({"id": 101, "tag_name": TAG, "draft": True}))runner.on(["gh", "release", "create"], "")- gh.create_draft(TAG, SHA, tmp_path / "notes.md", zips)- assert runner.calls[-1] == ["gh", "release", "create", TAG, "--repo", SLUG, "--draft",- "--latest", "--target", SHA, "--title", f"{TAG} (nightly)",- "--notes-file", str(tmp_path / "notes.md"), str(zips[0]), str(zips[1])]+ saved = []++ def upload(cmd):+ assert saved == [101] # a failed upload must already have an ownership checkpoint+ return ""+ runner.on(["gh", "release", "upload"], upload)+ assert gh.create_draft(TAG, SHA, tmp_path / "notes.md", zips, created=saved.append) == 101+ assert runner.calls[0] == ["gh", "api", f"repos/{SLUG}/releases", "--method", "POST",+ "--raw-field", f"tag_name={TAG}", "--raw-field", f"target_commitish={SHA}",+ "--raw-field", f"name={TAG} (nightly)", "--field", f"body=@{tmp_path / 'notes.md'}",+ "--field", "draft=true", "--field", "prerelease=false",+ "--raw-field", "make_latest=true"]+ assert runner.calls[1] == ["gh", "release", "upload", TAG, "--repo", SLUG, str(zips[0]), str(zips[1])]def draft_script(runner, zips, tmp_path, *, view=None, downloaded=None):@@ -324,26 +348,29 @@ def test_a_failing_gh_edit_is_a_publish_refusal(gh, runner):def test_delete_draft_removes_a_draft_and_never_cleans_tags(gh, runner):- runner.on(["gh", "release", "view"], '{"isDraft": true}')+ # Mutation: use a tag-addressed DELETE after an ownership check, risking a replacement release.+ runner.on(["gh", "release", "view"], '{"databaseId": 101, "isDraft": true}')+ runner.on(["gh", "api"], "")runner.on(["gh", "release", "delete"], "")- gh.delete_draft(TAG)- assert runner.calls[-1] == ["gh", "release", "delete", TAG, "--repo", SLUG, "--yes"]+ delete_draft(gh, 101)+ assert runner.calls == [["gh", "release", "view", TAG, "--repo", SLUG, "--json", "databaseId,isDraft"],+ ["gh", "api", f"repos/{SLUG}/releases/101", "--method", "DELETE"]]assert all("--cleanup-tag" not in c for c in runner.calls)def test_delete_draft_refuses_a_published_release_and_never_cleans_tags(gh, runner):- runner.on(["gh", "release", "view"], '{"isDraft": false}')+ runner.on(["gh", "release", "view"], '{"databaseId": 101, "isDraft": false}')with pytest.raises(Refused):- gh.delete_draft(TAG)- assert not any(c[:3] == ["gh", "release", "delete"] for c in runner.calls)+ delete_draft(gh, 101)+ assert len(runner.calls) == 1assert all("--cleanup-tag" not in c for c in runner.calls)def test_delete_draft_refuses_when_the_state_is_unknown(gh, runner):runner.on(["gh", "release", "view"], "garbage")with pytest.raises(Refused):- gh.delete_draft(TAG)- assert not any(c[:3] == ["gh", "release", "delete"] for c in runner.calls)+ delete_draft(gh, 101)+ assert len(runner.calls) == 1# --- previous build, download -----------------------------------------------------------------------------------------@@ -753,3 +780,63 @@ def test_the_frame_url_is_read_from_the_page():def test_a_frame_of_another_host_is_not_a_game_frame():assert gp.itch_frame_url('data-iframe="<iframe src="https://evil.example/html/1-2/index.html"') is None++[email protected]("release_id", [None, 202, True, "101"])+def test_delete_refuses_missing_or_foreign_id(gh, runner, release_id):+ # Mutation: skip ID validation or compare only the tag and draft flag.+ runner.on(["gh", "release", "view"], '{"databaseId": 101, "isDraft": true}')+ runner.on(["gh", "release", "delete"], "")+ with pytest.raises(Refused, match="check by hand"):+ delete_draft(gh, release_id)+ assert all("DELETE" not in c and c[:3] != ["gh", "release", "delete"] for c in runner.calls)+++def test_delete_by_id_preserves_same_tag_replacement_after_the_check(gh, runner):+ # Mutation: delete by tag after checking the ID, which would delete the new same-tag draft.+ releases = [(TAG, 101, True), ("v0.4.0", 303, False)]++ def view(cmd):+ # Another actor retargets the owned draft, then creates the replacement at our tag.+ releases[0] = (TAG + "-replaced", 101, True)+ releases.append((TAG, 202, True))+ return json.dumps({"databaseId": 101, "isDraft": True})++ def delete(cmd):+ if cmd[:3] == ["gh", "release", "delete"]:+ row = next(r for r in releases if r[0] == TAG)+ else:+ assert cmd == ["gh", "api", f"repos/{SLUG}/releases/101", "--method", "DELETE"]+ row = next(r for r in releases if r[1] == int(cmd[2].rsplit("/", 1)[1]))+ releases.remove(row)+ return ""+ runner.on(["gh", "release", "view"], view)+ runner.on(["gh", "api"], delete)+ runner.on(["gh", "release", "delete"], delete)+ delete_draft(gh, 101)+ assert releases == [("v0.4.0", 303, False), (TAG, 202, True)]+ assert runner.calls[-1] == ["gh", "api", f"repos/{SLUG}/releases/101", "--method", "DELETE"]++[email protected]("response", [{"id": True, "tag_name": TAG, "draft": True},+ {"id": 101, "tag_name": "v0.4.0", "draft": True},+ {"id": 101, "tag_name": TAG, "draft": False}, {}])+def test_create_with_unusable_response_never_claims_or_uploads(gh, runner, tmp_path, zips, response):+ # Mutation: guess an owned ID after create returned unknown data or a release for another tag.+ runner.on(["gh", "api"], json.dumps(response))+ runner.on(["gh", "release", "create"], "")+ saved = []+ with pytest.raises(Refused, match="check by hand"):+ create_draft(gh, tmp_path / "notes.md", zips, saved)+ assert saved == [] and len(runner.calls) == 1+++def test_failed_upload_has_already_checkpointed_create_id(gh, runner, tmp_path, zips):+ # Mutation: checkpoint only after uploads, losing ownership when an upload fails.+ runner.on(["gh", "api"], json.dumps({"id": 101, "tag_name": TAG, "draft": True}))+ runner.on(["gh", "release", "upload"], Refused("command", "upload failed"))+ runner.on(["gh", "release", "create"], Refused("command", "upload failed"))+ saved = []+ with pytest.raises(Refused, match="upload failed"):+ create_draft(gh, tmp_path / "notes.md", zips, saved)+ assert saved == [101]diff --git a/tools/tests/test_nightly_state.py b/tools/tests/test_nightly_state.pyindex fe075166d..d5768630b 100644--- a/tools/tests/test_nightly_state.py+++ b/tools/tests/test_nightly_state.py@@ -197,3 +197,38 @@ def test_notify_default_run_is_looked_up_when_called(monkeypatch):monkeypatch.setattr(subprocess, "run", lambda a, **k: calls.append(a))ns.notify("Statecraft nightly", "msg")assert calls and calls[0][:2] == ["osascript", "-e"]+++def test_old_state_without_ownership_or_recovery_fields_loads(tmp_path):+ # Mutation: require the new fields in state files written before this change.+ path = tmp_path / "state.json"+ path.write_text(json.dumps({"open_draft": "v0.3.2", "site_pending": "0.3.1", "boot_baseline": []}))+ state = ns.load_state(path)+ assert state.open_draft == "v0.3.2" and getattr(state, "open_draft_id", None) is None+ assert state.site_pending == "0.3.1" and getattr(state, "latest_recovery_pending", None) is None+++def test_ownership_and_pending_recovery_round_trip(tmp_path):+ # Mutation: omit the ID or pending record from serialization, including a null previous Latest.+ state = ns.State(open_draft="v0.3.2", open_draft_id=101,+ latest_recovery_pending=ns.LatestRecovery("v0.3.2", None))+ path = tmp_path / "state.json"+ ns.save_state(path, state)+ assert ns.load_state(path) == state++[email protected]("extra", [{"open_draft_id": True}, {"open_draft_id": "101"}, {"open_draft_id": 0},+ {"latest_recovery_pending": {}},+ {"latest_recovery_pending": {"failed": 1, "previous": None}},+ {"latest_recovery_pending": {"failed": "v0.3.2", "previous": False}},+ {"latest_recovery_pending": {"failed": "v0.3.2", "previous": ""}}])+def test_invalid_ownership_or_pending_record_refuses(tmp_path, extra):+ # Mutation: accept a malformed ownership ID or recovery target and guess a public action.+ # Value-validation guard: first prove the same keys are supported with valid values.+ path = tmp_path / "state.json"+ valid = {"open_draft_id": 101, "latest_recovery_pending": {"failed": "v0.3.2", "previous": None}}+ path.write_text(json.dumps(valid))+ assert ns.load_state(path).open_draft_id == 101+ path.write_text(json.dumps({**valid, **extra}))+ with pytest.raises(ns.Refused):+ ns.load_state(path)