A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
nightly: the save test finds the game frame from butler status, so the test page can stay Restricted (Refs #2056) (#2237)
Eyal Golan4723c2139cbe
diff --git a/docs/RELEASING.md b/docs/RELEASING.mdindex 3ded024e8..0f6fc16d5 100644--- a/docs/RELEASING.md+++ b/docs/RELEASING.md@@ -299,12 +299,14 @@ line ends with `steam=failed` (the `steam-build.log` and `steam-stage.log` are iis shown. The stage is skipped while `steam/steam.json` still has a `null` ID (until the owner has created the app,#2151), and with `uv run tools/nightly.py run --no-steam`.-**itch.io.** Pushes stay off until the owner runs `uv run tools/nightly.py savetest --tag <a published nightly>` once+**itch.io.** Pushes stay off until the owner or an agent (owner, 2 Nov 2026, "2 (a)") runs+`uv run tools/nightly.py savetest --tag <a published nightly>` onceand it prints `PASS` (the two-upload save test of `docs/m3-release.md`, "Upload to itch.io"); until then each nightlogs `itch: skipped (<reason>)`, naming the missing config key or the problem, and pushes nothing to itch. The save test pushes only to a separate test page, named in the job's `config.json` as-`savetest_itch_target` (`user/project:channel`) and `savetest_itch_page_url`, and refuses to run without them or if-they name the public page: each upload hides the game while itch unpacks it, which took up to an hour on 28 October-2026.+`savetest_itch_target` (`user/project:channel`), and refuses to run without it or if it names the public project:+each upload hides the game while itch unpacks it, which took up to an hour on 28 October 2026. It never reads the+test page: it loads each upload's game frame from the upload and build ids `butler status` shows, so the test page+can stay Restricted (#2056).## Refreshing the README screenshotsdiff --git a/docs/m3-release.md b/docs/m3-release.mdindex c491b3df0..6623f8864 100644--- a/docs/m3-release.md+++ b/docs/m3-release.md@@ -359,9 +359,12 @@ Published at: (owner fills in)- IndexedDB is per origin, so saves survive re-uploads to the same project and stay separate per browser profile.- The local checks above passed: reload, tab close, browser restart, and a second directory on the same origin.- **Automated test:** `uv run tools/nightly.py savetest --tag <published nightly>` runs this plan against a separate- itch test page (`savetest_itch_target` and `savetest_itch_page_url` in the job's `config.json`) and records its result- in the job's evidence file. It pushes to the test page twice, never to the public page, and refuses to run without- those two keys or if they name the public page. Only the owner starts it.+ itch test page (`savetest_itch_target` in the job's `config.json`) and records its result in the job's evidence+ file. It pushes to the test page twice, never to the public page, and refuses to run without that key or if it+ names the public project. It loads each upload's game frame from the upload and build ids of `butler status`+ (`https://html-classic.itch.zone/html/<upload>-<build>/index.html`), never from the test page, so that page can+ stay Restricted (#2056). The owner or an agent may start it, since it pushes only to the Restricted test page+ (owner, 2 Nov 2026, "2 (a)").- **Test plan (after the first two uploads):**1. Use one browser profile throughout, without clearing site data or using private mode. Record browser/version, OS,project page URL and the actual game-frame URL/origin (not only the outer itch.io page). Upload A as above. Play two@@ -390,9 +393,9 @@ may show "This save is from an earlier version of the game, so events may unfoldRecord that warning and both builds' git commits. Matching date/turn in this case is not evidence of exact state preservation, and it does notreplace the unchanged-content persistence control above. A changed state hash may be a replay effect rather than a storage failure.-Result: not run on itch.io (owner step).+Result: not run on itch.io yet.-| Evidence | Owner-run result |+| Evidence | Result || --- | --- || Browser/version | pending || OS | pending |diff --git a/tools/README.md b/tools/README.mdindex 9f6a3ea4a..5226d5e01 100644--- a/tools/README.md+++ b/tools/README.md@@ -220,12 +220,16 @@ and what is public are in `docs/RELEASING.md`, "Nightly builds". It runs on the`launchd.log` and `no-mcp-server`. A corrupt `config.json` or `state.json` refuses the night; it never counts as afirst night.- itch.io pushes stay off (`itch_enabled` is false) until the save test passes: set `itch_page_url` in `config.json`- to the itch page, and `savetest_itch_target` (`user/project:channel`) and `savetest_itch_page_url` to a separate- test page, then, from the clone and after the first PUBLISHED night,+ to the itch page, and `savetest_itch_target` (`user/project:channel`) to a separate test project, then, from the+ clone and after the first PUBLISHED night,`uv run tools/nightly.py savetest --tag <that nightly's tag>`. It pushes to the test page twice, never to the public- page, and refuses to run without those two keys or if they name the public page. On a pass, it turns `itch_enabled`- on in `config.json`. `INCONCLUSIVE` and `FAIL` leave itch off. A night pushes to itch only while the two test-page- keys name a separate page and `itch_evidence` records that PASS; otherwise its log line says+ page, and refuses to run without that key or if it names the public project. It never reads the test page (which+ can stay Restricted): it loads each upload's game frame from the upload and build ids `butler status` shows while+ that upload's version is live. The owner or an agent may start it (owner, 2 Nov 2026, "2 (a)"); `savetest.lock` in+ the job folder keeps two runs from overlapping. A `config.json` that still holds the old `savetest_itch_page_url` key+ refuses the night with a message to remove it (#2237 replaced it). On a+ pass, it turns `itch_enabled` on in `config.json`. `INCONCLUSIVE` and `FAIL` leave itch off. A night pushes to itch+ only while `savetest_itch_target` names a separate project and `itch_evidence` records that PASS; otherwise its log line says`itch: skipped (<reason>)`, naming the missing key or the problem (#2056).- The boot-time baseline is the median headless boot of the first 5 PUBLISHED nights; later nights must stay withinthe spread of those 5. To measure it again (a new machine, a new Chrome), delete `boot_baseline` from `state.json`;diff --git a/tools/nightly.py b/tools/nightly.pyindex fd9025c70..3470c7cd0 100644--- a/tools/nightly.py+++ b/tools/nightly.py@@ -30,11 +30,11 @@ from typing import Callableimport nightly_checksimport unity_postmerge-from nightly_publish import (GitHub, Itch, demo_serves, itch_frame_url, release_notes, sha256_lines, sha256_of,+from nightly_publish import (GitHub, Itch, demo_serves, itch_build_frame_url, release_notes, sha256_lines, sha256_of,unzip_to)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)+ notify, record, run_lock, save_state, savetest_lock, tag_for)from web_check import find_chromeHOLDER_ENV = unity_postmerge.machine_lock.HOLDER_ENV@@ -960,71 +960,76 @@ def run_night(cfg: Config, state_path: Path, job: Path, runner: Runner, gh: GitH# --- the itch.io save test --------------------------------------------------------------------------------------------PERSIST_SAVED = re.compile(r"^PERSISTENCE saved (\d{4}-\d{2}-\d{2}) turn (\d+) hash ([0-9a-f]+)$", re.M)-# The page names a new upload's frame only after itch has unpacked it; until then it carries just a JSON load_url-# ({"status":"extracting"}). Unpacking the web build took about 17 minutes on 28 October 2026, longer than the old-# 10-minute wait, so the save test now waits up to 40 minutes.-# While it waited for the second upload that day, itch answered 429 Too Many Requests; a 429 now slows the polling-# down (Retry-After, bounded) instead of ending the test, within the same 40 minutes.+# The frame URL comes from `butler status` (the upload and build ids), so the test page is never read and can stay+# Restricted (#2056, owner 2 Nov 2026: "Code change, page stays Restricted"). itch serves a new upload's frame only+# after it has unpacked it: unpacking the web build took about 17 minutes on 28 October 2026, so the save test polls+# the frame for up to 40 minutes. While it waited for the second upload that day, itch answered 429 Too Many+# Requests; a 429 slows the polling down (Retry-After, bounded) instead of ending the test, within the same 40 minutes.SAVETEST_FRAME_TRIES = 80SAVETEST_FRAME_SLEEP = 30SAVETEST_RATE_LIMIT_SLEEP = 120 # after an HTTP 429 without a usable Retry-AfterSAVETEST_RATE_LIMIT_MAX = 300 # a longer Retry-After is capped; the total wait stays within the frame budget+SAVETEST_FRAME_WAITING = (403, 404) # itch answers these until the frame is served; anything else ends the wait+SAVETEST_GAME_MARKER = b"createUnityInstance(" # in the index.html of unity/Assets/WebGLTemplates/StatecraftSAVETEST_RUN_MINUTES = 10TOOLS = Path(__file__).resolve().parent-def _page_text(fetch, url: str) -> str:+def _rate_limit_pause(e: urllib.error.HTTPError) -> int:+ """Seconds to wait after itch answered HTTP 429: its Retry-After, kept within bounds."""try:- with fetch(url, timeout=30) as response:- return response.read().decode("utf-8", "replace")- except (OSError, ValueError) as e: # URLError and HTTPException subclass OSError or ValueError- raise Refused("savetest", f"cannot read {url}: {type(e).__name__}: {e}") from e---def _rate_limit_pause(e: Refused) -> int | None:- """Seconds to wait after itch answered HTTP 429 (its Retry-After, kept within bounds), or None for any other error."""- cause = e.__cause__- if not isinstance(cause, urllib.error.HTTPError) or cause.code != 429:- return None- try:- asked = int((cause.headers or {}).get("Retry-After", ""))+ asked = int((e.headers or {}).get("Retry-After", ""))except ValueError:asked = SAVETEST_RATE_LIMIT_SLEEPreturn min(max(asked, SAVETEST_FRAME_SLEEP), SAVETEST_RATE_LIMIT_MAX)-def _frame_url(fetch, sleep, page_url: str, other: str | None = None) -> str | None:- """The game-frame URL the itch page embeds. With `other` it waits for a frame that is not that one; the last- frame seen (or None) comes back when the wait budget runs out. A 429 from itch only slows the polling down; if- itch still refuses when the budget runs out, that refusal is raised."""- found, limited = None, None+def _wait_for_frame(fetch, sleep, url: str) -> str | None:+ """None once the game frame at `url` is served: HTTP 200 from that very URL (no redirect) with the game's loader+ in it. Otherwise, when the wait budget runs out, what itch last answered ("HTTP 404", or a page that is not the+ game). A 403, a 404 or another page is "not served yet", a 429 only slows the polling down; any other failure is+ a Refused("savetest")."""waited, budget = 0, SAVETEST_FRAME_TRIES * SAVETEST_FRAME_SLEEPwhile True:try:- found, limited = itch_frame_url(_page_text(fetch, page_url)), None+ with fetch(url, timeout=30) as response:+ body = response.read()+ status, final = getattr(response, "status", None), response.geturl()+ if status == 200 and final == url and SAVETEST_GAME_MARKER in body:+ return None+ seen = f"HTTP {status} from {final}, not the game page"pause = SAVETEST_FRAME_SLEEP- except Refused as e:- pause = _rate_limit_pause(e)- if pause is None:- raise- limited = e- print(f"savetest: itch answered 429, waiting {pause} s", file=sys.stderr)- else:- if found is not None and found != other:- return found+ except urllib.error.HTTPError as e:+ if e.code == 429:+ pause = _rate_limit_pause(e)+ print(f"savetest: itch answered 429, waiting {pause} s", file=sys.stderr)+ elif e.code in SAVETEST_FRAME_WAITING:+ pause = SAVETEST_FRAME_SLEEP+ else:+ raise Refused("savetest", f"cannot read {url}: HTTP {e.code}") from e+ seen = f"HTTP {e.code}"+ except (OSError, ValueError) as e: # URLError and HTTPException subclass OSError or ValueError+ raise Refused("savetest", f"cannot read {url}: {type(e).__name__}: {e}") from eif waited + pause > budget:- if limited is not None:- raise limited- return found+ return seensleep(pause)waited += pause-def _frame_parts(url: str) -> tuple[str, str, str]:- """(scheme, host, upload segment): the segment of /html/<upload>-<build>/index.html names the upload."""- parts = urllib.parse.urlsplit(url)- segments = parts.path.split("/")- return parts.scheme, parts.netloc, segments[2] if len(segments) > 2 else ""+def _live_frame(itch: Itch, fetch, sleep, name: str, version: str, evidence: dict) -> tuple[str | None, str]:+ """(frame URL, "") of this run's upload `version` once itch serves its frame, or (None, why not). The URL is built+ from the upload and build ids `butler status` shows for the test channel while `version` is live there; the ids+ go into the evidence."""+ ids = itch.live_frame_ids(version)+ if ids is None:+ return None, f"butler status shows no upload and build ids of {version} live on the test channel after {name}"+ frame = itch_build_frame_url(*ids)+ evidence[name.replace(" ", "_")] = {"upload_id": ids[0], "build_id": ids[1], "frame_url": frame}+ seen = _wait_for_frame(fetch, sleep, frame)+ if seen is not None:+ minutes = SAVETEST_FRAME_TRIES * SAVETEST_FRAME_SLEEP // 60+ return None, f"the game frame of {name} ({frame}) still answered {seen} after {minutes} minutes"+ return frame, ""def _frame_check(runner: Runner, job_dir: Path, name: str, url: str, profile: Path, *extra: str) -> tuple[int, str]:@@ -1042,17 +1047,22 @@ def savetest(cfg: Config, config_path: Path, job: Path, runner: Runner, gh: GitH(the same content, a new upload URL on the same frame origin); B must load that date, turn and state hash twice."PASS" turns the itch push on (enable_itch); "INCONCLUSIVE" (the test could not be run or proves nothing) and"FAIL" leave it off. It pushes twice to the separate test page in savetest_itch_target, never to the public page:- each upload hides the game while itch unpacks it (up to an hour on 28 October 2026). Only the owner starts it."""+ each upload hides the game while itch unpacks it (up to an hour on 28 October 2026). The owner or an+ agent may start it (owner, 2 Nov 2026, "2 (a)"): it pushes only to the Restricted test page."""stamp = datetime.now(TZ).strftime("%Y%m%d-%H%M%S")work = Path(job) / "savetest" / stamp- evidence: dict = {"tag": tag, "page_url": cfg.savetest_itch_page_url, "target": cfg.savetest_itch_target}+ evidence: dict = {"tag": tag, "target": cfg.savetest_itch_target}result, detail = "INCONCLUSIVE", ""- try:- result, detail = _savetest(cfg, work, runner, gh, itch, tag, evidence, fetch, sleep)- except Stop as e:- detail = f"{e.gate}: {e.detail}"- except (OSError, SystemExit) as e: # find_chrome exits when there is no Chrome- detail = f"{type(e).__name__}: {e}"+ with savetest_lock(Path(job)) as held:+ if not held:+ detail = "another save test is running on this job (savetest.lock); nothing was pushed"+ else:+ try:+ result, detail = _savetest(cfg, work, runner, gh, itch, tag, evidence, fetch, sleep)+ except Stop as e:+ detail = f"{e.gate}: {e.detail}"+ except (OSError, SystemExit) as e: # find_chrome exits when there is no Chrome+ detail = f"{type(e).__name__}: {e}"evidence.update(result=result, detail=detail)if work.is_dir():(work / "evidence.json").write_text(json.dumps(evidence, indent=2, sort_keys=True) + "\n", encoding="utf-8")@@ -1067,28 +1077,32 @@ def _itch_project(target: str) -> str:return target.partition(":")[0].lower()-def _page_key(url: str) -> tuple[str, str]:- parts = urllib.parse.urlsplit(url.strip())- return parts.netloc.lower(), parts.path.rstrip("/").lower()+SAVETEST_TARGET = re.compile(r"[a-z0-9_-]+/[a-z0-9_-]+:[a-z0-9._-]+", re.I) # user/project:channel, nothing else+++def _page_project(url: str | None) -> str | None:+ """`user/project` of an itch page URL https://<user>.itch.io/<project>, or None for anything else."""+ parts = urllib.parse.urlsplit((url or "").strip())+ user, dot, host = parts.netloc.lower().partition(".")+ path = parts.path.strip("/").lower()+ return f"{user}/{path}" if dot and host == "itch.io" and path and "/" not in path else Nonedef _test_page_problem(cfg: Config) -> str | None:- """Why the save test may not push, or None: it needs its own test project, distinct from the public one."""- if not cfg.savetest_itch_target or not cfg.savetest_itch_page_url:- return "savetest_itch_target and savetest_itch_page_url must name a separate test page in the job's config"- if _itch_project(cfg.savetest_itch_target) == _itch_project(cfg.itch_target):+ """Why the save test may not push, or None: it needs its own test project, distinct from the public one (the+ project of itch_target, on any channel, and the project of the public itch_page_url)."""+ target = cfg.savetest_itch_target+ if not target:+ return "savetest_itch_target must name the separate test page's project (user/project:channel) in the job's config"+ if not SAVETEST_TARGET.fullmatch(target):+ return f"the save test's test page target {target!r} is not user/project:channel (letters, digits, - and _)"+ public = {_itch_project(cfg.itch_target), _page_project(cfg.itch_page_url)}+ if _itch_project(target) in public:return "the save test's test page must not be the public itch project (any channel of it uploads to its page)"- try:- test_page = _page_key(cfg.savetest_itch_page_url)- public_page = _page_key(cfg.itch_page_url) if cfg.itch_page_url else None- except ValueError as e:- return f"the save test's test page URL or the public page URL is not usable: {e}"- if test_page == public_page:- return "the save test's test page must not be the public itch page"return None-SAVETEST_KEYS = ("savetest_itch_target", "savetest_itch_page_url")+SAVETEST_KEYS = ("savetest_itch_target",)def itch_skip_reason(cfg: Config) -> str | None:@@ -1129,14 +1143,15 @@ def _savetest(cfg: Config, work: Path, runner: Runner, gh: GitHub, itch: Itch, tzip_path = gh.download(tag, "*-web.zip", work / "zip")evidence.update(zip=zip_path.name, zip_sha256=sha256_of(zip_path))folder = unzip_to(zip_path, work / "folder")+ if not (folder / "index.html").is_file():+ return "INCONCLUSIVE", f"{zip_path.name} has no index.html at its root, so the build's frame URL would not load"profile = work / "profile"itch.push(folder, f"{version}-savetest-a")itch.wait_live(f"{version}-savetest-a", time.monotonic() + ITCH_WAIT_SECONDS)- frame_a = _frame_url(fetch, sleep, cfg.savetest_itch_page_url)- evidence.update(upload_a={"build_id": itch.live_build_id(), "frame_url": frame_a})+ frame_a, why = _live_frame(itch, fetch, sleep, "upload a", f"{version}-savetest-a", evidence)if frame_a is None:- return "INCONCLUSIVE", "the itch page names no game frame after upload A"+ return "INCONCLUSIVE", whycode, text = _frame_check(runner, work, "a-first-save", frame_a, profile, "--first-save")saved = PERSIST_SAVED.search(text)if code != 0 or not re.search(r"^PASS:", text, re.M) or saved is None:@@ -1146,15 +1161,11 @@ def _savetest(cfg: Config, work: Path, runner: Runner, gh: GitHub, itch: Itch, titch.push(folder, f"{version}-savetest-b")itch.wait_live(f"{version}-savetest-b", time.monotonic() + ITCH_WAIT_SECONDS)- frame_b = _frame_url(fetch, sleep, cfg.savetest_itch_page_url, other=frame_a)- evidence.update(upload_b={"build_id": itch.live_build_id(), "frame_url": frame_b})+ frame_b, why = _live_frame(itch, fetch, sleep, "upload b", f"{version}-savetest-b", evidence)if frame_b is None:- return "INCONCLUSIVE", "the itch page names no game frame after upload B"- (scheme_a, host_a, seg_a), (scheme_b, host_b, seg_b) = _frame_parts(frame_a), _frame_parts(frame_b)- if (scheme_a, host_a) != (scheme_b, host_b):- return "INCONCLUSIVE", f"the frame origin changed ({scheme_a}://{host_a} to {scheme_b}://{host_b}): IndexedDB is per origin"- if seg_a == seg_b:- return "INCONCLUSIVE", f"upload B has the same frame URL as upload A ({seg_a}), so the test proves nothing"+ return "INCONCLUSIVE", why+ if frame_b == frame_a: # both frames are on itch's one frame host, so IndexedDB is shared between them+ return "INCONCLUSIVE", f"upload B has the same frame URL as upload A ({frame_a}), so the test proves nothing"expect = f"GAME OK {tuple_a['date']} turn {tuple_a['turn']} hash {tuple_a['hash']}"for n in (1, 2):diff --git a/tools/nightly_publish.py b/tools/nightly_publish.pyindex 529f8683b..0244014fa 100644--- a/tools/nightly_publish.py+++ b/tools/nightly_publish.py@@ -9,7 +9,6 @@ that this module cannot parse or does not expect is a Refused, never a pass. Stdfrom __future__ import annotationsimport hashlib-import htmlimport http.clientimport jsonimport re@@ -54,14 +53,14 @@ def release_notes(*, version: str, sha: str, since: str, subjects: list[str], shreturn "\n".join(lines)-FRAME_URL = re.compile(r"https://html-classic\.itch\.zone/html/[0-9-]+/[^\"'&<>\s]*index\.html")+ITCH_FRAME_HOST = "https://html-classic.itch.zone"-def itch_frame_url(page_html: str) -> str | None:- """The game-frame URL the public itch page embeds (None when it embeds none), without its ?v= cache query. The- page holds it HTML-escaped in a data attribute; its path segment is the upload and build ids joined by "-"."""- m = FRAME_URL.search(html.unescape(page_html))- return m.group(0) if m else None+def itch_build_frame_url(upload_id: int, build_id: int) -> str:+ """The game-frame URL of one itch HTML upload's build, as the itch page embeds it (without its ?v= cache query):+ /html/<upload id>-<build id>/index.html on itch's frame host. The captured page and `butler status` of the same+ live build (tests/data/itch_page.html, butler_status_live.txt) agree on it, so no page has to be read (#2056)."""+ return f"{ITCH_FRAME_HOST}/html/{int(upload_id)}-{int(build_id)}/index.html"def unzip_to(zip_path: Path, dest: Path) -> Path:@@ -122,9 +121,24 @@ class Itch:m = re.search(r"#(\d+)", row[2])return m.group(1) if m else None- def live_build_id(self) -> int | None:- """The id of the channel's live build now (None when there is none), from `butler status`."""- return self._live_id()+ @staticmethod+ def upload_id(status_text: str, channel: str = "html5") -> str | None:+ """The id of the channel's upload (butler prints "#<id>" in the UPLOAD cell), only while its build is live+ under the same rule as live_version; anything but exactly one "#<digits>" is None."""+ row = Itch._row(status_text, channel)+ if row is None or not row[2].startswith(LIVE_MARK):+ return None+ m = re.fullmatch(r"#(\d+)", row[1])+ return m.group(1) if m else None++ def live_frame_ids(self, version: str) -> tuple[int, int] | None:+ """(upload id, build id) of the channel's live build from one `butler status`, only while that build is+ `version` (the VERSION cell, butler's UserVersion of a completed build); None otherwise."""+ text = self._run(["status", self.project], Path.cwd())+ if self.live_version(text, self.channel) != version:+ return None+ upload, build = self.upload_id(text, self.channel), self.build_id(text, self.channel)+ return (int(upload), int(build)) if upload and build else Nonedef _run(self, args: list[str], cwd: Path, timeout: float = 300) -> str:try:diff --git a/tools/nightly_state.py b/tools/nightly_state.pyindex ab36d4993..35c5e31a6 100644--- a/tools/nightly_state.py+++ b/tools/nightly_state.py@@ -86,7 +86,6 @@ class Config:itch_target: str = "eyalgolan/statecraft-israel:html5"itch_page_url: str | None = Nonesavetest_itch_target: str | None = None # a separate test page: the save test never pushes to the public one- savetest_itch_page_url: str | None = Noneitch_enabled: bool = Falseitch_evidence: str | None = Nonebutler: Path = HOME / ".local/bin/butler"@@ -113,6 +112,13 @@ def _read_json_object(path: Path, gate: str) -> dict:return data+# A key the job no longer reads still refuses the night, like any unknown key, but its refusal says how to fix it.+REMOVED_KEYS = {+ "savetest_itch_page_url": "remove savetest_itch_page_url from config.json; #2237 replaced it (the save test "+ "finds the game frame from butler status and never reads the test page)",+}++def load_config(path: Path) -> Config:if not path.exists():return Config()@@ -120,6 +126,8 @@ def load_config(path: Path) -> Config:known = {f.name: f for f in fields(Config)}values: dict[str, object] = {}for key, value in raw.items():+ if key in REMOVED_KEYS:+ raise Refused("config", f"{key!r} in {path} is no longer used: {REMOVED_KEYS[key]}")if key not in known:raise Refused("config", f"unknown key {key!r} in {path}")default = known[key].default@@ -335,10 +343,10 @@ def notify(title: str, message: str, run=None) -> None:@contextlib.contextmanager-def _run_lock(job: Path) -> Iterator[bool]:+def _run_lock(job: Path, name: str = "run.lock") -> Iterator[bool]:import fcntl # POSIX only; imported here so the shared types load anywherejob.mkdir(parents=True, exist_ok=True)- with (job / "run.lock").open("a") as fh:+ with (job / name).open("a") as fh:try:fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)except OSError:@@ -353,3 +361,9 @@ def _run_lock(job: Path) -> Iterator[bool]:def run_lock(job: Path) -> ContextManager[bool]:"""Yields True when this process holds <job>/run.lock, False when another run already does."""return _run_lock(job)+++def savetest_lock(job: Path) -> ContextManager[bool]:+ """Yields True when this process holds <job>/savetest.lock, False when another save test already does: agents+ may start the save test too (owner, 2 Nov 2026, "2 (a)"), and two runs must not push to the test page at once."""+ return _run_lock(job, "savetest.lock")diff --git a/tools/tests/test_nightly.py b/tools/tests/test_nightly.pyindex c81bf5447..90806bb6d 100644--- a/tools/tests/test_nightly.py+++ b/tools/tests/test_nightly.py@@ -5,6 +5,7 @@ import shutilimport subprocessimport sysimport time+import urllib.parseimport zipfilefrom contextlib import contextmanagerfrom datetime import date, datetime@@ -1522,7 +1523,6 @@ def test_itch_is_skipped_with_a_logged_reason_when_there_is_no_client(night, envPREV_TAG = "v0.3.0-nightly.20261027"PREV_VERSION = "0.3.0-nightly.20261027"-PAGE_URL = "https://example.invalid/statecraft-israel-savetest"TEST_TARGET = "eyalgolan/statecraft-israel-savetest:html5"@@ -1568,7 +1568,7 @@ def itch_night(night, env, tmp_path, served):"""An itch-enabled night with real zips for tonight and the previous build: a separate test page is configuredand the save test's PASS evidence is on record, so the push may go ahead (#2056)."""night.cfg = dataclasses.replace(night.cfg, itch_enabled=True, savetest_itch_target=TEST_TARGET,- savetest_itch_page_url=PAGE_URL, itch_evidence=evidence_file(tmp_path, "PASS"))+ itch_evidence=evidence_file(tmp_path, "PASS"))clone = str(night.cfg.clone)env.runner.add(["git", "-C", clone, "log", "--format=%s"], out="Fix a thing\n")zips = (zip_of(tmp_path / "web.zip", "tonight"), zip_of(tmp_path / "pages.zip", "pages"))@@ -1709,16 +1709,14 @@ def test_a_site_failure_after_publish_does_not_roll_itch_back(itch_night, env):# --- #2056: itch only with a separate test page and a recorded save test PASS --------------------------------------------NO_TEST_PAGE = ("itch: skipped (the job config has no savetest_itch_target or savetest_itch_page_url, so no save test "- "can run on a separate test page)")+NO_TEST_PAGE = "itch: skipped (the job config has no savetest_itch_target, so no save test can run on a separate test page)"@pytest.mark.parametrize("change, reason", [- ({"savetest_itch_target": None, "savetest_itch_page_url": None}, NO_TEST_PAGE),- ({"savetest_itch_target": None}, "itch: skipped (the job config has no savetest_itch_target, so"),- ({"savetest_itch_page_url": ""}, "itch: skipped (the job config has no savetest_itch_page_url, so"),+ ({"savetest_itch_target": None}, NO_TEST_PAGE),+ ({"savetest_itch_target": ""}, NO_TEST_PAGE),({"savetest_itch_target": "eyalgolan/statecraft-israel:savetest"}, "must not be the public itch project"),- ({"itch_page_url": PAGE_URL}, "must not be the public itch page"),+ ({"savetest_itch_target": "EyalGolan/Statecraft-Israel:html5"}, "must not be the public itch project"),({"itch_enabled": False}, "itch: skipped (save test not passed)"),({"itch_evidence": None}, "itch_enabled is set but no save test evidence is recorded"),({"itch_evidence": "/nonexistent/evidence.json"}, "is unreadable"),@@ -1946,8 +1944,10 @@ SAVED = "PERSISTENCE saved 1948-05-16 turn 1 hash ab12\n"class SaveItch:"""The itch client of the save test: each push moves the live build id on by one."""- def __init__(self, calls, *, fail=None):+ def __init__(self, calls, *, fail=None, same=False, ids=True, live_as=None):self.calls, self.fail, self.pushes, self.build = calls, fail or {}, 0, 100+ self.same, self.ids = same, ids # `same`: butler keeps showing upload A's build; `ids`: False shows none+ self.live_as, self.live = live_as, None # `live_as`: the version butler shows live after wait_livedef push(self, folder, version):self.calls.append(("itch.push", Path(folder).name, version))@@ -1960,9 +1960,13 @@ class SaveItch:self.calls.append(("itch.wait_live", version))if "wait_live" in self.fail:raise self.fail["wait_live"]+ self.live = self.live_as or version- def live_build_id(self):- return self.build+ def live_frame_ids(self, version):+ self.calls.append(("itch.live_frame_ids", version))+ if not self.ids or version != self.live: # as Itch.live_frame_ids: only the expected version's ids+ return None+ return UPLOAD_ID, 101 if self.same else self.buildclass SaveRunner(FakeRunner):@@ -1980,9 +1984,15 @@ class SaveRunner(FakeRunner):return code+GAME_HTML = '<script>createUnityInstance(canvas, {productVersion: "0.3.2"})</script>' # the Statecraft template++class Page:- def __init__(self, text):- self.text = text+ def __init__(self, text, *, url=None, status=200):+ self.text, self.url, self.status = text, url, status++ def geturl(self):+ return self.urldef __enter__(self):return self@@ -1994,37 +2004,55 @@ class Page:return self.text.encode()-def page_for(itch, *, same=False, frame=True):- """A fetch answering the itch page: its frame follows the itch client's build, or never changes with `same`."""+UPLOAD_ID = 19840947+++def frame_of(build):+ return f"{ITCH_HOST}/html/{UPLOAD_ID}-{build}/index.html"+++def http_error(url, code, retry_after=None):+ import email.message+ import urllib.error+ headers = email.message.Message()+ if retry_after is not None:+ headers["Retry-After"] = retry_after+ return urllib.error.HTTPError(url, code, "error", headers, None)+++def frame_for(itch, fetched, *, missing=0, code=404, answer=None):+ """A fetch answering only the game frame of the itch client's live build (never an itch page): its first+ `missing` answers are HTTP `code`, as while itch still unpacks an upload; `answer(url)` replaces the game page."""def fetch(url, timeout=30):- assert url == PAGE_URL- build = 101 if same else itch.build- inner = f"{ITCH_HOST}/html/19840947-{build}/index.html?v=1" if frame else "none"- return Page(f'<div data-iframe="<iframe src="{inner}">">')+ fetched.append(url)+ assert url == frame_of(101 if itch.same else itch.build)+ if len(fetched) <= missing:+ raise http_error(url, code)+ return answer(url) if answer else Page(GAME_HTML, url=url)return fetchclass Saved:"""A save test: a config file, a published release and the fakes."""- def __init__(self, tmp_path, monkeypatch, *, release="published", page_url=PAGE_URL, target=TEST_TARGET,- public_page=None, **runner_kw):+ def __init__(self, tmp_path, monkeypatch, *, release="published", target=TEST_TARGET, itch_kw=None, **runner_kw):self.job = tmp_path / "job"self.job.mkdir()self.config = self.job / "config.json"- config = {"savetest_itch_page_url": page_url, "savetest_itch_target": target, "itch_page_url": public_page}+ config = {"savetest_itch_target": target, "itch_page_url": "https://eyalgolan.itch.io/statecraft-israel"}self.config.write_text(json.dumps({k: v for k, v in config.items() if v is not None}) + "\n")self.cfg = ns.load_config(self.config)self.cfg = dataclasses.replace(self.cfg, handoff=tmp_path / "HANDOFF.md")self.gh = FakeGH(release=release)self.gh.baseline = zip_of(tmp_path / "tonight-web.zip", "tonight")- self.itch = SaveItch(self.gh.calls)+ self.itch = SaveItch(self.gh.calls, **(itch_kw or {}))+ self.fetched = []self.runner = SaveRunner(**runner_kw)monkeypatch.setattr(nightly, "find_chrome", lambda: Path("/fake/chrome"))def run(self, fetch=None, tag=TAG, sleep=lambda s: None):return nightly.savetest(self.cfg, self.config, self.job, self.runner, self.gh, self.itch, tag=tag,- fetch=fetch or page_for(self.itch), sleep=sleep)+ fetch=fetch or frame_for(self.itch, self.fetched), sleep=sleep)def evidence(self):return json.loads(next((self.job / "savetest").glob("*/evidence.json")).read_text())@@ -2047,7 +2075,10 @@ def test_savetest_passes_only_with_matching_tuple_new_url_same_origin(saved):version = TAG[1:]assert [c for c in t.gh.calls if c[0].startswith("itch.")] == [("itch.push", "folder", f"{version}-savetest-a"), ("itch.wait_live", f"{version}-savetest-a"),- ("itch.push", "folder", f"{version}-savetest-b"), ("itch.wait_live", f"{version}-savetest-b")]+ ("itch.live_frame_ids", f"{version}-savetest-a"),+ ("itch.push", "folder", f"{version}-savetest-b"), ("itch.wait_live", f"{version}-savetest-b"),+ ("itch.live_frame_ids", f"{version}-savetest-b")]+ assert t.fetched == [frame_of(101), frame_of(102)] # #2056: only the build's own frame, never the itch pagefirst, b1, b2 = t.runner.runsprofile = first[first.index("--profile") + 1]assert first[first.index("--url") + 1] == f"{ITCH_HOST}/html/19840947-101/index.html" and "--first-save" in first@@ -2057,26 +2088,95 @@ def test_savetest_passes_only_with_matching_tuple_new_url_same_origin(saved):assert run[run.index("--expect") + 1] == "GAME OK 1948-05-16 turn 1 hash ab12"assert run[:5] == ["uv", "run", str(nightly.TOOLS / "machine_lock.py"), "--shared", "--"]ev = t.evidence()- assert ev["upload_a"] == {"build_id": 101, "frame_url": f"{ITCH_HOST}/html/19840947-101/index.html"}- assert ev["upload_b"]["build_id"] == 102 and ev["tuple"] == {"date": "1948-05-16", "turn": 1, "hash": "ab12"}+ assert ev["upload_a"] == {"upload_id": UPLOAD_ID, "build_id": 101, "frame_url": frame_of(101)}+ assert ev["upload_b"] == {"upload_id": UPLOAD_ID, "build_id": 102, "frame_url": frame_of(102)} and ev["tuple"] == {"date": "1948-05-16", "turn": 1, "hash": "ab12"}assert ev["chrome"] == "/fake/chrome" and len(ev["zip_sha256"]) == 64 and ev["result"] == "PASS"assert t.enabled() and json.loads(t.config.read_text())["itch_evidence"].endswith("evidence.json")assert "SAVETEST PASS" in t.log() and TAG in t.log()def test_savetest_same_frame_url_is_inconclusive_and_keeps_itch_off(saved):- t = saved()- assert t.run(page_for(t.itch, same=True)) == "INCONCLUSIVE"+ t = saved(itch_kw={"same": True})+ assert t.run() == "INCONCLUSIVE"assert not t.enabled() and len(t.runner.runs) == 1 # B is never loadedassert "same frame URL" in t.evidence()["detail"] and "SAVETEST INCONCLUSIVE" in t.log()-def test_savetest_another_frame_origin_is_inconclusive(saved, monkeypatch):- t = saved() # itch_frame_url only matches the one host today; the origin check guards a change of that- hosts = iter(["html-classic.itch.zone", "html-classic.example.zone"])- monkeypatch.setattr(nightly, "itch_frame_url",- lambda page: f"https://{next(hosts)}/html/1-{t.itch.build}/index.html")- assert t.run() == "INCONCLUSIVE" and not t.enabled() and "origin changed" in t.evidence()["detail"]+def test_both_frames_are_on_the_one_frame_origin():+ # IndexedDB is per origin: the frame URL is built from butler's ids on one fixed host, so A and B share it+ a = urllib.parse.urlsplit(nightly.itch_build_frame_url(UPLOAD_ID, 101))+ b = urllib.parse.urlsplit(nightly.itch_build_frame_url(UPLOAD_ID, 102))+ assert (a.scheme, a.netloc) == (b.scheme, b.netloc) == ("https", "html-classic.itch.zone") and a.path != b.path+++# --- review round on #2237 ------------------------------------------------------------------------------------------++def test_the_frame_ids_must_belong_to_the_version_this_run_pushed(saved):+ t = saved(itch_kw={"live_as": "9.9.9-savetest-a"}) # another run's upload went live in between+ assert t.run() == "INCONCLUSIVE" and t.runner.runs == [] and t.fetched == [] and not t.enabled()+ assert f"{TAG[1:]}-savetest-a" in t.evidence()["detail"]++[email protected]("answer", [+ lambda url: Page("<html>Sign in to itch.io</html>", url=url), # 200, not the game+ lambda url: Page(GAME_HTML, url="https://itch.io/login"), # redirected elsewhere+ lambda url: Page(GAME_HTML, url=url, status=203), # not a plain 200+])+def test_only_the_game_page_itself_counts_as_a_served_frame(saved, answer):+ t = saved()+ sleeps = []+ assert t.run(frame_for(t.itch, t.fetched, answer=answer), sleep=sleeps.append) == "INCONCLUSIVE"+ assert t.runner.runs == [] and not t.enabled() and "not the game" in t.evidence()["detail"]+ assert sum(sleeps) <= nightly.SAVETEST_FRAME_TRIES * nightly.SAVETEST_FRAME_SLEEP++[email protected]("code", [401, 410, 500])+def test_any_other_http_answer_from_the_frame_ends_inconclusive_at_once(saved, code):+ t = saved()+ assert t.run(frame_for(t.itch, t.fetched, missing=10_000, code=code)) == "INCONCLUSIVE"+ assert t.runner.runs == [] and len(t.fetched) == 1 and f"HTTP {code}" in t.evidence()["detail"]+++def test_a_b_frame_that_is_never_served_is_inconclusive_not_fail(saved):+ t = saved()+ def fetch(url, timeout=30):+ if t.itch.pushes == 2:+ raise http_error(url, 404)+ return Page(GAME_HTML, url=url)+ assert t.run(fetch) == "INCONCLUSIVE" and len(t.runner.runs) == 1 and not t.enabled()+++def test_a_second_save_test_pushes_nothing_while_one_runs(saved):+ import fcntl+ t = saved()+ with (t.job / "savetest.lock").open("a") as held:+ fcntl.flock(held, fcntl.LOCK_EX | fcntl.LOCK_NB)+ assert t.run() == "INCONCLUSIVE"+ assert not any(c[0].startswith("itch.") or c[0] == "download" for c in t.gh.calls) and t.runner.runs == []+ assert "another save test" in t.log() and not t.enabled()+ assert t.run() == "PASS" # the lock is free again once the other run ends++[email protected]("target", [" eyalgolan/statecraft-israel-savetest:html5", "eyalgolan/statecraft-israel/:html5",+ "eyalgolan/statecraft-israel:", "eyalgolan/statecraft-israel-savetest:html5\n",+ "eyalgolan/statecraft israel:html5"])+def test_a_malformed_save_test_target_is_refused_before_any_push(saved, target):+ t = saved(target=target)+ assert t.run() == "INCONCLUSIVE" and not t.enabled() and "test page" in t.log()+ assert not any(c[0].startswith("itch.") or c[0] == "download" for c in t.gh.calls)+++def test_the_project_of_the_public_page_url_is_refused_as_a_test_target(saved):+ t = saved(target="eyalgolan/other-game:html5")+ t.cfg = dataclasses.replace(t.cfg, itch_page_url="https://EyalGolan.itch.io/other-game/")+ assert t.run() == "INCONCLUSIVE" and "must not be the public itch project" in t.log()+ assert not any(c[0].startswith("itch.") for c in t.gh.calls)+++def test_a_save_test_pass_enables_the_nightly_push(saved):+ t = saved()+ assert t.run() == "PASS"+ assert nightly.itch_skip_reason(ns.load_config(t.config)) is Nonedef test_savetest_mismatch_fails_and_keeps_itch_off(saved):@@ -2102,8 +2202,8 @@ def test_savetest_without_a_durable_first_save_is_inconclusive(saved, saved_run)assert [c[0] for c in t.gh.calls].count("itch.push") == 1 # B is never pushed[email protected]("kw", [{"release": "draft"}, {"release": None}, {"page_url": ""}])-def test_savetest_needs_a_published_nightly_and_a_page_url(saved, kw):[email protected]("kw", [{"release": "draft"}, {"release": None}])+def test_savetest_needs_a_published_nightly(saved, kw):t = saved(**kw)assert t.run() == "INCONCLUSIVE" and not t.enabled()assert not any(c[0].startswith("itch.") or c[0] == "download" for c in t.gh.calls) and t.runner.runs == []@@ -2111,34 +2211,68 @@ def test_savetest_needs_a_published_nightly_and_a_page_url(saved, kw):def test_savetest_waits_while_itch_is_still_unpacking_the_upload(saved):- t = saved() # 28 Oct 2026: the page showed only a load_url for about 17 minutes before it named the frame- framed, calls = page_for(t.itch), {"n": 0}+ t = saved() # 28 Oct 2026: itch took about 17 minutes to unpack the web build after butler showed it live+ sleeps = []+ assert t.run(frame_for(t.itch, t.fetched, missing=30), sleep=sleeps.append) == "PASS" and t.enabled()+ assert t.fetched[:31] == [frame_of(101)] * 31 and sleeps[:30] == [nightly.SAVETEST_FRAME_SLEEP] * 30- def fetch(url, timeout=30):- calls["n"] += 1- if calls["n"] <= 30: # 30 polls x 30 s = 15 minutes of {"status":"extracting"}- return Page('<div class="html_embed_widget">Embed({"load_url":"https:\\/\\/x.itch.io\\/g\\/html_url\\/1"})')- return framed(url, timeout)- assert t.run(fetch) == "PASS" and t.enabled()+[email protected]("code", [403, 404])+def test_a_frame_that_never_loads_ends_inconclusive_within_the_wait_budget(saved, code):+ t = saved() # e.g. a frame itch would not serve signed out: nothing is played, itch stays off+ sleeps = []+ assert t.run(frame_for(t.itch, t.fetched, missing=10_000, code=code), sleep=sleeps.append) == "INCONCLUSIVE"+ assert not t.enabled() and t.runner.runs == [] and [c[0] for c in t.gh.calls].count("itch.push") == 1+ assert sum(sleeps) <= nightly.SAVETEST_FRAME_TRIES * nightly.SAVETEST_FRAME_SLEEP+ assert f"HTTP {code}" in t.evidence()["detail"] and frame_of(101) in t.evidence()["detail"]+++def test_savetest_without_live_frame_ids_is_inconclusive(saved):+ t = saved(itch_kw={"ids": False})+ assert t.run() == "INCONCLUSIVE" and t.runner.runs == [] and t.fetched == [] and not t.enabled()+ assert "upload and build ids" in t.evidence()["detail"]+++def test_savetest_needs_index_html_at_the_root_of_the_zip(saved, tmp_path):+ t = saved() # the frame URL names <upload>-<build>/index.html, so the page must sit at the zip's root+ with zipfile.ZipFile(t.gh.baseline, "w") as z:+ z.writestr("web/index.html", "nested")+ assert t.run() == "INCONCLUSIVE" and not t.enabled()+ assert not any(c[0].startswith("itch.") for c in t.gh.calls) and "index.html" in t.evidence()["detail"]@pytest.mark.parametrize("kw", [{"target": None}, {"target": "eyalgolan/statecraft-israel:html5"},{"target": "eyalgolan/statecraft-israel:savetest"}, # another channel, same page{"target": "EyalGolan/Statecraft-Israel:html5"},{"target": "eyalgolan/statecraft-israel"}, # no channel: still the public project- {"page_url": None}, {"public_page": PAGE_URL},- {"public_page": PAGE_URL.upper() + "/#game"},- {"page_url": "http://["}]) # a malformed URL refuses instead of raising+ {"target": ""}])def test_savetest_runs_only_against_a_separate_test_page(saved, kw):t = saved(**kw) # 28 Oct 2026: each upload hid the public game while itch unpacked it, for up to an hourassert t.run() == "INCONCLUSIVE" and not t.enabled() and "test page" in t.log()assert not any(c[0].startswith("itch.") or c[0] == "download" for c in t.gh.calls) and t.runner.runs == []-def test_savetest_reads_the_test_page_and_records_it_in_the_evidence(saved):+def test_savetest_records_its_target_and_no_page_in_the_evidence(saved):t = saved()assert t.run() == "PASS"- assert t.evidence()["page_url"] == PAGE_URL and t.evidence()["target"] == TEST_TARGET+ assert t.evidence()["target"] == TEST_TARGET and "page_url" not in t.evidence()+++def test_the_savetest_page_url_key_is_gone_from_the_config():+ # #2056 (owner, 2 Nov 2026: "Code change, page stays Restricted"): the save test never reads the test page,+ # so the job config has no key for its URL; the old key is refused like any unknown one+ assert "savetest_itch_page_url" not in {f.name for f in dataclasses.fields(ns.Config)}+ assert nightly.SAVETEST_KEYS == ("savetest_itch_target",)+++def test_a_config_still_holding_the_removed_page_url_key_is_refused_with_the_fix(tmp_path):+ config = tmp_path / "config.json"+ config.write_text(json.dumps({"savetest_itch_target": TEST_TARGET,+ "savetest_itch_page_url": "https://eyalgolan.itch.io/statecraft-israel-savetest"}))+ with pytest.raises(ns.Refused) as e:+ ns.load_config(config)+ assert e.value.gate == "config"+ assert "remove savetest_itch_page_url from config.json; #2237 replaced it" in e.value.detaildef test_the_savetest_command_refuses_before_any_client_without_a_test_target(tmp_path, monkeypatch, capsys):@@ -2161,24 +2295,19 @@ def test_the_savetest_command_builds_its_itch_client_on_the_test_target(tmp_pathmonkeypatch.setattr(nightly, "savetest", lambda cfg, config, job, runner, gh, itch, *, tag: "PASS")cfg = dataclasses.replace(ns.Config(), butler=butler, handoff=tmp_path / "HANDOFF.md",itch_page_url="https://eyalgolan.itch.io/statecraft-israel",- savetest_itch_target=TEST_TARGET, savetest_itch_page_url=PAGE_URL)+ savetest_itch_target=TEST_TARGET)assert nightly.run_savetest(cfg, tmp_path, TAG) == 0 and built == [TEST_TARGET]def too_many_requests(retry_after=None):- import email.message- import urllib.error- headers = email.message.Message()- if retry_after is not None:- headers["Retry-After"] = retry_after- return urllib.error.HTTPError(PAGE_URL, 429, "Too Many Requests", headers, None)+ return http_error(frame_of(101), 429, retry_after)@pytest.mark.parametrize("retry_after,pause", [("90", 90), (None, nightly.SAVETEST_RATE_LIMIT_SLEEP), ("soon",nightly.SAVETEST_RATE_LIMIT_SLEEP), ("5", nightly.SAVETEST_FRAME_SLEEP)])-def test_savetest_backs_off_and_keeps_waiting_when_itch_rate_limits_the_page(saved, retry_after, pause):+def test_savetest_backs_off_and_keeps_waiting_when_itch_rate_limits_the_frame(saved, retry_after, pause):t = saved() # 28 Oct 2026: itch answered 429 Too Many Requests while the test waited for upload B's frame- framed, calls, sleeps = page_for(t.itch), {"n": 0}, []+ framed, calls, sleeps = frame_for(t.itch, t.fetched), {"n": 0}, []def fetch(url, timeout=30):calls["n"] += 1@@ -2200,22 +2329,6 @@ def test_savetest_a_rate_limit_that_never_lifts_ends_inconclusive_within_the_waiassert sleeps and max(sleeps) == nightly.SAVETEST_RATE_LIMIT_MAX and "429" in t.log()-def test_savetest_a_page_without_a_frame_is_inconclusive(saved):- t = saved()- assert t.run(page_for(t.itch, frame=False)) == "INCONCLUSIVE" and t.runner.runs == [] and not t.enabled()---def test_savetest_waits_for_the_page_to_name_the_new_frame(saved):- t = saved()- seen = []- base = page_for(t.itch)- def fetch(url, timeout=30): # the page lags: after upload B its first two answers still name A's frame- seen.append(t.itch.pushes)- stale = t.itch.pushes == 2 and seen.count(2) <= 2- return base(url) if not stale else Page('"%s/html/19840947-101/index.html"' % ITCH_HOST)- assert t.run(fetch) == "PASS" and seen.count(2) == 3--@pytest.mark.parametrize("step", ["push", "wait_live"])def test_savetest_an_itch_failure_is_inconclusive_and_recorded(saved, step):t = saved()@@ -2223,7 +2336,7 @@ def test_savetest_an_itch_failure_is_inconclusive_and_recorded(saved, step):assert t.run() == "INCONCLUSIVE" and not t.enabled() and f"itch: {step} failed" in t.log()-def test_savetest_an_unreadable_page_is_inconclusive(saved):+def test_savetest_an_unreachable_frame_is_inconclusive(saved):t = saved()def fetch(url, timeout=30):raise OSError("offline")diff --git a/tools/tests/test_nightly_publish.py b/tools/tests/test_nightly_publish.pyindex 11d242a62..3a646582c 100644--- a/tools/tests/test_nightly_publish.py+++ b/tools/tests/test_nightly_publish.py@@ -1,4 +1,5 @@import hashlib+import htmlimport ioimport inspectimport json@@ -769,17 +770,46 @@ def test_no_butler_command_names_the_credentials_file():assert not any(w in src for w in ('"login"', '"logout"'))-# --- Task 8: the itch page's game frame -----------------------------------------------------------------------------+# --- Task 8 / #2056: the game frame of the live build, from `butler status` ----------------------------------------------def test_the_frame_url_is_read_from_the_page():- page = (DATA / "itch_page.html").read_text()- assert "html-classic.itch.zone/html/19840947-2217587/index.html?v=" in page.replace(""", "") # as captured- assert gp.itch_frame_url(page) == "https://html-classic.itch.zone/html/19840947-2217587/index.html" # no ?v= query- assert gp.itch_frame_url("<html>no game</html>") is None+def test_the_live_upload_id_is_read_from_the_channel_row():+ # butler's status.go: the UPLOAD cell is fmt.Sprintf("#%d", ch.Upload.ID), the BUILD cell "<sign> #<build id>"+ assert gp.Itch.upload_id(live_text()) == "19840947"+ assert gp.Itch.upload_id(live_text().replace("\u2713 ", "")) is None # not live: no frame to load+ assert gp.Itch.upload_id(status_with(build="\u2713 #5", channel="webgl")) is None-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]("upload", ["", "19840947", "#x", "#19840947 #2"])+def test_an_upload_cell_that_is_not_one_id_gives_no_upload_id(upload):+ text = status_with().replace("#19840947", upload, 1)+ assert gp.Itch.upload_id(text) is None+++def test_the_frame_url_from_butler_status_is_the_one_the_captured_page_embeds():+ # The two fixtures were captured from the live public page and `butler status` (#1879): upload #19840947 build+ # #2217587 in the status table, /html/19840947-2217587/index.html in the page's iframe+ frame = gp.itch_build_frame_url(int(gp.Itch.upload_id(live_text())), int(gp.Itch.build_id(live_text())))+ assert frame == "https://html-classic.itch.zone/html/19840947-2217587/index.html"+ assert f"{frame}?v=" in html.unescape((DATA / "itch_page.html").read_text())+++def test_live_frame_ids_reads_one_status_of_the_project(runner):+ runner.on([str(BUTLER), "status", ITCH_PROJECT], live_text())+ assert gp.Itch(runner, BUTLER, ITCH_TARGET).live_frame_ids("0.3.1") == (19840947, 2217587)+ assert runner.calls == [[str(BUTLER), "status", ITCH_PROJECT]]+++def test_live_frame_ids_needs_the_expected_version_live(runner):+ # butler's status.go: the VERSION cell is the build's UserVersion once the build is completed (live)+ runner.on([str(BUTLER), "status", ITCH_PROJECT], live_text())+ assert gp.Itch(runner, BUTLER, ITCH_TARGET).live_frame_ids("0.3.2-savetest-a") is None++[email protected]("text", [status_with(build="#101 (processing)"), status_with(channel="webgl"),+ status_with().replace("#19840947", "", 1)])+def test_live_frame_ids_is_none_without_a_live_build_and_its_upload(runner, text):+ runner.on([str(BUTLER), "status", ITCH_PROJECT], text)+ assert gp.Itch(runner, BUTLER, ITCH_TARGET).live_frame_ids("0.3.1") is None@pytest.mark.parametrize("release_id", [None, 202, True, "101"])