Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Tools: a nightly release job that publishes main at 03:00 only when every gate passes (#1879)

Eyal Golan5c56d7e57a10
diff --git a/changelog.d/nightly-release.md b/changelog.d/nightly-release.md
new file mode 100644
index 000000000..a5de9a9f8
--- /dev/null
+++ b/changelog.d/nightly-release.md
@@ -0,0 +1,3 @@
+- Nightly builds: every night at 03:00 (Israel time) the newest `main` is built, checked against the build that is live
+ and, only if every check passes, published as a GitHub pre-release that the website's demo serves (`docs/RELEASING.md`,
+ "Nightly builds"). itch.io uploads follow once the automated save test passes.
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index db1bccafe..383d86971 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -171,6 +171,64 @@ macOS IL2CPP parity check is not an MVP release gate.
`tar -tzf <archive> | grep -E '^(\./)?(LICENSE|NOTICE|THIRD-PARTY-NOTICES.md|OFL-EBGaramond.txt|OFL-FrankRuhlLibre.txt)$'`.
It must print five lines for each archive.
+## Nightly builds
+
+Every night at 03:00 (Israel time) the newest `main` is built and, only if every gate passes, becomes the public web
+game: a GitHub **pre-release** tagged `vX.Y.Z-nightly.YYYYMMDD` (X.Y.Z from `sim/Statecraft.Sim/SimInfo.cs`, the date
+that of the night), which the website's `/demo/` serves, and, once itch pushes are enabled, the itch.io page. The job is
+`tools/nightly.py` under launchd; the install steps are in `tools/README.md`, "Nightly release". Nothing here changes
+the versioned releases above (steps 1-7): those stay owner-run, and a nightly is never marked Latest and never deleted.
+
+The gates, in order. The first one that fails ends the night as REFUSED, and nothing public changes:
+1. Preflight: `origin/main` differs from the last published nightly (otherwise the night is SKIPPED), at least 40 GB
+ free, no `EXCLUSIVE-WINDOW` file, the Unity licence, editor and slot script present, and no release already holding
+ tonight's tag.
+2. `build-sim`, then `scripts/check.sh origin/main` (`check`) and `scripts/oss/release_gate.sh` (`release-gate`), the
+ same bar as a release.
+3. The sim tests under `he_IL` and `en_US` (`sim-he_IL`, `sim-en_US`).
+4. The Unity warm-up and the full EditMode run (`editmode`), with at least one test and no failure.
+5. The two WebGL builds, the gzip one and the Pages one (`build-web`), with the nightly version stamped in after the
+ gates; the tree must be clean afterwards, and the stamp is never committed. Then both zips (`package`).
+6. `web_check.py` on both builds (`web-check`).
+7. Download size (`sizes`): the data, wasm and framework files may grow at most 2% over the build that is live.
+8. Headless boot time (`boot`): the median of three boots. The first 5 published nights set the baseline; after
+ that a boot slower than the slowest baseline night plus the spread of the baseline is refused.
+
+A nightly never moves a golden: golden moves arrive through reviewed pull requests, and the nightly only needs the
+golden tests of the full run to pass.
+
+**Size budget.** A pull request that adds download size on purpose puts this line in its body, with the megabytes
+(1 MB = 1,000,000 bytes) it adds:
+
+```
+Nightly size budget: +N MB
+```
+
+The next nightly allows the growth of the 2% plus the lines of every pull request merged since the last published
+nightly; without the line, an increase beyond 2% refuses the night. The new size is the baseline from then on.
+
+**Publishing** (only after every gate): a draft pre-release with both zips and notes listing the commits since the
+last nightly (the tag points at the commit the night started from, even if `main` moves during the build), the assets
+checked against the local zips, the itch push when enabled (checked by build id and a fetch of the live files, and
+rolled back to the previous build if anything later fails), the release made public, then `site.yml` started and the
+demo checked for the new version. A failed night leaves no public change. A draft it stranded is deleted only by a rerun on the
+same date; a draft left from an earlier date stays until someone removes it (it never reaches `/demo/`, because
+`site.yml` skips drafts). An unknown draft or an already published release with tonight's tag refuses the night.
+
+**The record.** One line per night in `~/israel-game/.superpowers/nightly/LOG.md` (and a `NIGHTLY:` line in `~/israel-game/.superpowers/HANDOFF.md`),
+`<date time> <OUTCOME> tag=... sha=... gate=... log=<run folder>`:
+- `PUBLISHED`: every gate passed and the stores serve the new build.
+- `SKIPPED`: `main` has not moved since the last published nightly (an unfinished site deploy is retried).
+- `REFUSED`: `gate=` names the step that stopped it, and `log=` the folder holding every step's log. A desktop
+ notification is shown too.
+- `MISSED`: no run started on that date (the Mac was asleep or logged out); the next run adds the line.
+
+A night that starts after 03:30 is MISSED unless it was started by hand with `--manual`.
+
+**itch.io.** Pushes stay off until the owner runs `uv run tools/nightly.py savetest --tag <a published nightly>` once
+and it prints `PASS` (the two-upload save test of `docs/m3-release.md`, "Upload to itch.io"); the nightly then logs
+that itch was skipped.
+
## Refreshing the README screenshots
The README's screenshots are claims about the current build. Re-take them whenever the build looks different, and
diff --git a/docs/m3-release.md b/docs/m3-release.md
index 701eb02f4..502a48730 100644
--- a/docs/m3-release.md
+++ b/docs/m3-release.md
@@ -327,9 +327,10 @@ the owner's review also stands as their fact check); `egypt_adl_gaza`, `egypt_mv
| `jordan_adl_iraqi_*` (four stages), `jordan_adl_a_latrun`, `jordan_adl_bc_south`, `jordan_adl_d_arava` | Jordan, 3 Apr 1949 (line A by its deadlines: 8 May, 22 May, 17 Jul 1949) | low accuracy, traced from a low-resolution scan, and labelled so; the Art. VI.3 stage areas as read; Latrun traced along the outer loop; Jerusalem, the no-man's-lands and Mount Scopus left out (gaps) |
| On-screen strings | from 1949 | the map label ("Mandate sub-districts, 1947 · 1949 armistice lines: Egypt (and the 1950 modus vivendi), Lebanon, Jordan (low accuracy), Syria"), the info panel lines ("On the ... · low accuracy, from a low-resolution scan"), the agreement titles in the "Egypt-Israel" style (the agreements' own: "Egyptian-Israeli", "Lebanese-Israeli", "Hashemite Jordan Kingdom-Israel", "Israeli-Syrian"), and the seven Hebrew strings in `strings.he.yaml` (Hebrew is off until reviewed) |
-## Deferred to M4: upload to itch.io (OWNER STEP)
-Deferred to the start of M4, as a private Draft (owner ruling, 2026-10-10). The steps stay correct for then. This needs the
-owner's itch.io account and is never automated, and the build must pass the sensitivity gate above (`-shareable`).
+## Upload to itch.io
+The steps below are the project's first setup (OWNER STEP: they need the owner's itch.io account). Nightly builds are now
+pushed with `butler` by `tools/nightly.py`, enabled only after `nightly.py savetest` passes (owner, 27 October 2026,
+"Public: website + itch"). The build must pass the sensitivity gate above (`-shareable`).
1. Sign in at https://itch.io. Go to Dashboard, then **Create new project**.
2. Set the title to "Statecraft: Israel (M3 preview)", Kind of project to **HTML**, and Classification to Games.
3. Under Uploads, upload the zip made by `bash scripts/oss/package_web.sh unity/Builds/Web-gzip unity/Builds/statecraft-m3-web.zip` (it puts the licence and attribution files inside, then runs `tools/package_release.py`; see `docs/RELEASING.md`) and tick **This file will be played in the browser**.
@@ -351,13 +352,15 @@ uncompressed (checked with curl on two public Unity games, 17 October 2026). Tha
Published at: (owner fills in)
-## Saves on itch.io: the fix, and its test (the test is deferred to M4)
+## Saves on itch.io: the fix, and its test
- **Problem:** on WebGL, `Application.persistentDataPath` is `/idbfs/<MD5 of the page's directory URL>`. itch.io serves every upload from a new URL, so a new upload would hide the saves made with the previous one.
- **Fix (Task 21):** the autosave lives at the fixed path `/idbfs/statecraft-saves/autosave.txt`.
- The template sets `autoSyncPersistentDataPath: true`, so closing the file persists it to IndexedDB.
- 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.
-- **Test plan (OWNER STEP, deferred to M4 with the upload; after the first two uploads):**
+- **Automated test:** `uv run tools/nightly.py savetest --tag <published nightly>` runs this plan against the public
+ itch page and records its result in the job's evidence file. It pushes to the public page twice, so only the owner starts it.
+- **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
turns and copy the last `TURN` line, including date, turn and full state hash. Record the upload/build ID, the git
@@ -415,6 +418,6 @@ changed page-directory paths and changed-content warnings. Those code/tests supp
- The headless smoke plays five turns; a full-slice smoke is M4.
- The wheel-zoom step (one notch = 10%) was measured in Chrome on macOS only. Firefox reports wheel deltas in lines and
Windows at 125% scaling reports 125 px per notch, so re-check the step in the owner's M4 itch.io check.
-- Not uploaded to itch.io: the upload and the cross-upload save test are deferred to the start of M4 (owner ruling,
- 2026-10-10). The seven sensitive events are `sensitivity-reviewed`, with the owner's sign-off recorded in commit
+- Nightlies upload to itch.io once the cross-upload save test passes (owner, 27 October 2026; until then this build is
+ not uploaded there). The seven sensitive events are `sensitivity-reviewed`, with the owner's sign-off recorded in commit
[25d2ef6](https://github.com/eyalgolan/statecraft-israel/commit/25d2ef6004436668b42e289aff3dce06af128e09) (see above).
diff --git a/docs/superpowers/plans/2026-10-27-nightly-release-plan.md b/docs/superpowers/plans/2026-10-27-nightly-release-plan.md
new file mode 100644
index 000000000..c79b07cde
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-27-nightly-release-plan.md
@@ -0,0 +1,1007 @@
+# Nightly Release Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Every night at 03:00 Asia/Jerusalem, build the newest `origin/main` on the owner's Mac and, only if every gate passes, publish it as a GitHub pre-release that the website's `/demo/` serves (and, once the save test passes, on itch.io), refusing anything that could be worse than what is live.
+
+**Architecture:** A launchd agent starts `tools/nightly_launch.py` (a copy in the job folder), which takes the run lock, moves a dedicated clone's own `main` to `origin/main` and runs `tools/nightly.py run` from that clone. `nightly.py` is a straight pipeline (preflight, gates, Unity EditMode, two stamped WebGL builds, no-regression checks, draft-first publish, record), where every stage raises `Refused`/`Skipped`/`Missed` and one `finally` writes the night's line. Pure decisions live in `nightly_checks.py`, store side effects (gh, butler, Pages) in `nightly_publish.py`, and state/config/log in `nightly_state.py`. Every process goes through one injectable `Runner`, so the tests run the whole pipeline on fakes.
+
+**Tech Stack:** Python 3.12 stdlib (the tools' `uv run` scripts), pytest 9.1.1, `gh` 2.97 and `butler` 15.32 through their stored logins, Unity 6000.3.25f1 batch mode, launchd.
+
+**Spec:** `docs/superpowers/specs/2026-10-27-nightly-release-design.md` (approved by the owner on 27 October 2026, "Approve as written"; committed in Task 9). Read it with this plan.
+
+## Global Constraints
+
+- Runs on the owner's Mac under launchd at 03:00 Asia/Jerusalem. The Mac stays awake (owner: "Mac stays awake"), so there is no wake schedule.
+- Never spend money. This means no paid service, no purchase and no top-up. GitHub Actions on this public repository and itch.io uploads are free.
+- Never print or store a token or key. `gh` and `butler` use their existing stored credentials (`butler` reads `~/Library/Application Support/itch/butler_creds` by itself). No code reads that file, sets `GH_TOKEN` or runs `gh auth token`.
+- No force-push, no history rewrite, no `git push` at all, no merge, and no deletion of a published release or tag. The only deletion is `gh release delete <tag> --yes` of a release that `gh release view` shows `isDraft: true` at that moment, never with `--cleanup-tag`.
+- Unity runs only through `UNITY_SLOTS=3 python3 -I ~/israel-game/.superpowers/coordinator-tools/unity_slots.py [--webgl] <clone>/unity -- uv run <clone>/tools/machine_lock.py --shared -- <Unity ...>`. Only the two `Build.Web` runs pass `--webgl`, and there is no `--wait-unity`. The headless boot measurement alone takes `machine_lock.py --exclusive --wait-unity`.
+- Every Unity batch job runs with `UNITY_MCP_SERVER_PATH` set to an existing empty file (`<job>/no-mcp-server`). `-quit` goes on `-executeMethod` jobs (builds) only, never with `-runTests`. The warm-up has no `-quit`, because it exits by itself.
+- Disk: at least 40 GB free (`shutil.disk_usage`) at preflight and again before each WebGL build, otherwise REFUSED. It never builds anyway.
+- Unknown counts as fail: a missing file, an unparsable output, a timeout, a missing baseline or a `gh`/`butler` error is REFUSED, never a pass.
+- Tests are pytest with fakes for git, gh, butler, Unity and HTTP. No test starts `git`, `gh`, `butler`, Unity or Chrome, or opens a network connection. The only real child process allowed in tests is `sys.executable` (the deadline test).
+- Tools tests run in CI on ubuntu-24.04 with `uv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 --with pyproj==3.8.0 pytest tools/tests -q`. New modules use the stdlib only. Test modules that import a module using `fcntl` start with `pytest.importorskip("fcntl")`, as `test_unity_postmerge.py` does.
+- Repo rules apply:
+ - The PR adds `changelog.d/nightly-release.md`.
+ - No em dashes anywhere (code, docs, commit messages).
+ - No internal task ids or session names in committed text.
+ - Agents never tick the PR template's licence attestation box; the owner does.
+- Docs in the same PR:
+ - `docs/RELEASING.md` gets a "Nightly builds" section.
+ - `docs/m3-release.md:330-332` says the itch upload is automated for nightlies (the owner's 27 Oct choice).
+ - The spec is committed as `docs/superpowers/specs/2026-10-27-nightly-release-design.md`.
+ - This plan is committed as `docs/superpowers/plans/2026-10-27-nightly-release-plan.md`.
+- itch pushes stay disabled (`itch_enabled: false` in the job's `config.json`) until `nightly.py savetest` passes. A pass flips that flag through `nightly_state.enable_itch`, which changes config and no code.
+- Paths:
+ - Job folder: `~/israel-game/.superpowers/nightly/` (ignored by git), holding `config.json`, `state.json`, `LOG.md`, `runs/`, `run.lock`, `launchd.log`, `nightly_launch.py` and `no-mcp-server`.
+ - Clone: `~/.cache/statecraft/nightly/repo`.
+- Version: `X.Y.Z-nightly.YYYYMMDD`, with X.Y.Z from `sim/Statecraft.Sim/SimInfo.cs` and the date the Asia/Jerusalem date at the start of the run. The tag is `v` + version. The zips are `statecraft-israel-v<version>-web.zip` and `statecraft-israel-v<version>-web-pages.zip`.
+
+## Review Focus
+
+- **launchd's environment:** PATH may lack a tool, or gh's keychain login may be unavailable. The expectation is a REFUSED line in LOG.md naming the step, never a crash with no record. Test `test_a_missing_tool_is_refused_and_recorded` (Task 2).
+- **A second run on the same date:** this is a manual rerun after a REFUSED night, or after a PUBLISHED one with a newer `main`. The expectation:
+ - A draft left by this job is deleted first.
+ - An unknown draft or a published release with tonight's tag is REFUSED.
+ - Nothing is ever overwritten.
+
+ Test `test_same_day_rerun_cleans_its_draft_and_refuses_a_published_tag` (Task 2).
+- **`main` moving during the run:** a merge at 04:00 must not change what ships. The tag targets the preflight commit, and the notes stop there. Test `test_release_targets_the_preflight_commit` (Task 6).
+- **The deadline or a Unity timeout hitting mid-build:** the expectation is REFUSED, settings restored, no stamp left, and nothing published. Test `test_a_build_timeout_restores_settings_and_refuses` (Task 4).
+- **A corrupt `state.json` or `config.json`:** this must fail closed (REFUSED), never act as a first night with no baseline and no last published commit. Test `test_a_corrupt_state_or_config_refuses` (Task 1).
+
+---
+
+## File Structure
+
+| File | Responsibility |
+|---|---|
+| `tools/nightly_state.py` (create) | Config, state, version and tag naming, night/late-start/missed-day logic, LOG.md and HANDOFF lines, desktop notification, run lock, the `Refused`/`Skipped`/`Missed` outcomes |
+| `tools/nightly_checks.py` (create) | Pure checks: check.sh, release gate and dotnet summaries; golden and smoke expects; web_check pass list; sizes and the PR size budget; boot parse and bound; zip notices; `productVersion` |
+| `tools/nightly_publish.py` (create) | `GitHub` (draft, verify, publish, delete draft, previous build, merged PR bodies, site dispatch), `demo_serves`, `Itch` (push, status, fetch-compare), `release_notes`, `unzip_to` |
+| `tools/nightly.py` (create) | `ProcRunner`, preflight, gates, EditMode, stamp + builds + packaging, checks wiring, publish order with rollback, `run` and `savetest` subcommands |
+| `tools/nightly_launch.py` (create) | launchd entry point: run lock, clone fetch/reset/clean, first Library clone, then runs the clone's `tools/nightly.py run` |
+| `tools/nightly.plist.in` (create) | launchd job, `StartCalendarInterval` 03:00 |
+| `tools/web_check.py` (modify) | `--url`, `--profile`, `--first-save` for the itch save test |
+| `tools/tests/conftest.py` (modify) | `FakeRunner` and the `no_processes` fixture |
+| `tools/tests/test_nightly_state.py`, `test_nightly_checks.py`, `test_nightly_publish.py`, `test_nightly.py`, `test_nightly_launch.py` (create); `test_web_check.py` (modify) | Tests |
+| `docs/RELEASING.md`, `docs/m3-release.md`, `tools/README.md`, `changelog.d/nightly-release.md`, `docs/superpowers/specs/…`, `docs/superpowers/plans/…` | Docs |
+
+Shared types (defined in Task 1, used everywhere):
+
+```python
+class Stop(Exception): # outcome in {"REFUSED", "SKIPPED", "MISSED"}
+ outcome: str; gate: str; detail: str
+class Refused(Stop): ... # Refused(gate: str, detail: str)
+class Skipped(Stop): ... # Skipped(detail: str), gate "-"
+class Missed(Stop): ... # Missed(detail: str), gate "-"
+
+class Runner(Protocol):
+ def run(self, cmd: list[str], *, cwd: Path, log: Path, deadline: float,
+ env: dict[str, str] | None = None, holder: Path | None = None) -> int: ...
+ def capture(self, cmd: list[str], *, cwd: Path, timeout: float = 300) -> str: ... # raises Refused("command", ...) on non-zero
+```
+
+`deadline` is a `time.monotonic()` value. `run` returns 124 when it stopped the command at the deadline.
+
+---
+
+### Task 1: State, config, naming and the night's record
+
+**Files:**
+- Create: `tools/nightly_state.py`
+- Modify: `tools/tests/conftest.py` (append `FakeRunner`, `no_processes`)
+- Test: `tools/tests/test_nightly_state.py`
+
+**Interfaces:**
+- Consumes: nothing.
+- Produces:
+ - `Stop`, `Refused`, `Skipped`, `Missed`, `Runner` (above).
+ - `TZ = ZoneInfo("Asia/Jerusalem")`; `JOB = Path.home() / "israel-game/.superpowers/nightly"`.
+ - `@dataclass(frozen=True) class Config`. The fields and defaults are:
+ - `main_repo=HOME/israel-game`
+ - `clone=HOME/.cache/statecraft/nightly/repo`
+ - `unity_slots=HOME/israel-game/.superpowers/coordinator-tools/unity_slots.py`
+ - `exclusive_marker=HOME/israel-game/.superpowers/coordination/EXCLUSIVE-WINDOW`
+ - `handoff=HOME/israel-game/.superpowers/HANDOFF.md`
+ - `licence=HOME/Library/Unity/licenses/UnityEntitlementLicense.xml`
+ - `repo_slug="eyalgolan/statecraft-israel"`
+ - `site_demo_url="https://eyalgolan.github.io/statecraft-israel/demo/"`
+ - `itch_target="eyalgolan/statecraft-israel:html5"`
+ - `itch_page_url: str | None = None`
+ - `itch_enabled=False`
+ - `itch_evidence: str | None = None`
+ - `butler=HOME/.local/bin/butler`
+ - `min_free_gb=40`
+ - `window_end="03:30"`
+ - `deadline_hours=6.0`
+ - `unity_slots_count=3`
+ - `load_config(path: Path) -> Config`.
+ - `enable_itch(path: Path, evidence: Path) -> None`.
+ - `@dataclass class Published: tag: str; sha: str; version: str; sizes: dict[str, int]; boot_ms: float | None`.
+ - `@dataclass class State: last_published: Published | None = None; boot_baseline: list[float] = []; last_run_day: str | None = None; open_draft: str | None = None; site_pending: str | None = None`.
+ - `load_state(path: Path) -> State`; `save_state(path: Path, state: State) -> None`.
+ - `base_version(siminfo_text: str) -> str`; `nightly_version(base: str, day: date) -> str`; `tag_for(version: str) -> str`.
+ - `night_of(now: datetime) -> date`; `late_start(now: datetime, window_end: str) -> bool`; `missed_days(last_run_day: str | None, today: date) -> list[date]`.
+ - `log_line(now: datetime, outcome: str, *, tag: str | None, sha: str | None, gate: str, log: Path | None) -> str`.
+ - `record(log_md: Path, handoff: Path, line: str) -> None`.
+ - `notify(title: str, message: str, run=subprocess.run) -> None`.
+ - `run_lock(job: Path) -> ContextManager[bool]`.
+
+- [ ] **Step 1: Write the failing tests**
+
+```python
+def test_version_and_tag_follow_the_spec():
+ assert ns.base_version('public const string Version = "0.3.1";') == "0.3.1"
+ assert ns.nightly_version("0.3.1", date(2026, 10, 28)) == "0.3.1-nightly.20261028"
+ assert ns.tag_for("0.3.1-nightly.20261028") == "v0.3.1-nightly.20261028"
+ with pytest.raises(ValueError): ns.base_version('Version = "0.3"')
+
+def test_the_night_is_the_jerusalem_date():
+ assert ns.night_of(datetime(2026, 10, 28, 0, 30, tzinfo=timezone.utc)) == date(2026, 10, 28) # 02:30 IST
+ assert ns.night_of(datetime(2026, 10, 27, 21, 59, tzinfo=timezone.utc)) == date(2026, 10, 27)
+
+def test_a_start_after_0330_is_late():
+ il = ns.TZ
+ assert not ns.late_start(datetime(2026, 10, 28, 3, 0, tzinfo=il), "03:30")
+ assert ns.late_start(datetime(2026, 10, 28, 3, 31, tzinfo=il), "03:30")
+
+def test_missed_days_are_the_dates_between_runs():
+ assert ns.missed_days("2026-10-25", date(2026, 10, 28)) == [date(2026, 10, 26), date(2026, 10, 27)]
+ assert ns.missed_days(None, date(2026, 10, 28)) == []
+
+def test_log_line_names_outcome_tag_sha_gate_and_log(tmp_path):
+ line = ns.log_line(datetime(2026, 10, 28, 3, 0, tzinfo=ns.TZ), "REFUSED", tag="v0.3.1-nightly.20261028",
+ sha="0123456789abcdef0123", gate="editmode", log=tmp_path / "runs/x")
+ assert line == f"2026-10-28 03:00 REFUSED tag=v0.3.1-nightly.20261028 sha=0123456789ab gate=editmode log={tmp_path}/runs/x"
+ with pytest.raises(ValueError): ns.log_line(datetime.now(ns.TZ), "OK", tag=None, sha=None, gate="-", log=None)
+
+def test_record_appends_to_log_and_handoff(tmp_path):
+ ns.record(tmp_path / "LOG.md", tmp_path / "HANDOFF.md", "L1"); ns.record(tmp_path / "LOG.md", tmp_path / "HANDOFF.md", "L2")
+ assert (tmp_path / "LOG.md").read_text().splitlines()[-2:] == ["- L1", "- L2"]
+ assert (tmp_path / "HANDOFF.md").read_text().splitlines()[-1] == "- NIGHTLY: L2"
+
+def test_state_round_trips_and_a_missing_file_is_empty(tmp_path): ... # Published survives save/load; missing -> State()
+
+def test_a_corrupt_state_or_config_refuses(tmp_path): # Review Focus
+ (tmp_path / "state.json").write_text("{bad"); (tmp_path / "config.json").write_text('{"itch_enabled": "yes"}')
+ with pytest.raises(ns.Refused) as e: ns.load_state(tmp_path / "state.json")
+ assert e.value.gate == "state"
+ with pytest.raises(ns.Refused): ns.load_config(tmp_path / "config.json")
+ (tmp_path / "config.json").write_text('{"surprise": 1}')
+ with pytest.raises(ns.Refused): ns.load_config(tmp_path / "config.json")
+
+def test_only_enable_itch_flips_the_flag_and_keeps_other_keys(tmp_path):
+ p = tmp_path / "config.json"; p.write_text('{"itch_page_url": "https://x.itch.io/y"}')
+ assert ns.load_config(p).itch_enabled is False
+ ns.enable_itch(p, tmp_path / "evidence.json")
+ c = ns.load_config(p); assert c.itch_enabled and c.itch_page_url == "https://x.itch.io/y" and c.itch_evidence.endswith("evidence.json")
+
+def test_notify_quotes_the_message_for_applescript():
+ calls = []; ns.notify("Statecraft nightly", 'gate "x" \\ y', run=lambda a, **k: calls.append(a))
+ assert calls[0][:2] == ["osascript", "-e"] and '\\"x\\"' in calls[0][2] and "\\\\ y" in calls[0][2]
+
+def test_the_run_lock_is_exclusive(tmp_path):
+ with ns.run_lock(tmp_path) as first:
+ with ns.run_lock(tmp_path) as second:
+ assert first is True and second is False
+```
+
+- [ ] **Step 2: Run them to verify they fail**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_state.py -q`
+Expected: FAIL, `ModuleNotFoundError: No module named 'nightly_state'`
+
+- [ ] **Step 3: Implement `tools/nightly_state.py`, then add `FakeRunner` and `no_processes` to `conftest.py`**
+
+`load_config` behaviour:
+- A missing file gives the defaults.
+- Unreadable JSON, an unknown key or a value whose type differs from the default's raises `Refused("config", ...)`.
+- `Path` fields are read from strings with `~` expanded.
+
+`load_state` behaviour:
+- A missing file gives `State()`.
+- Any parse or shape error raises `Refused("state", ...)`.
+- `save_state` and `enable_itch` write atomically (a temp file, then `os.replace`, as `unity_postmerge.save_state` does).
+
+`late_start` compares the local wall time with `window_end` on the same date. `record` opens each file in append mode and writes one line per call.
+
+`notify` runs `osascript -e 'display notification "<msg>" with title "<title>"'`, with backslashes and double quotes escaped.
+
+`run_lock` uses `fcntl.flock(LOCK_EX | LOCK_NB)` on `<job>/run.lock`.
+
+Add to conftest:
+- `FakeRunner(Runner)` keeps `rules: list[(prefix tuple, code, out, effect)]` added by `add(prefix, code=0, out="", effect=None)`. It records `calls`. `run` writes `out` to `log` and calls `effect(cmd)`. A call no rule matches raises `AssertionError(f"unexpected command {cmd}")`.
+- `no_processes` (fixture) monkeypatches `subprocess.Popen`, `subprocess.run` and `urllib.request.urlopen` to raise.
+
+- [ ] **Step 4: Run them to verify they pass**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_state.py -q`
+Expected: `11 passed`
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add tools/nightly_state.py tools/tests/test_nightly_state.py tools/tests/conftest.py
+git commit -m "nightly: state, config, naming and the nightly record"
+```
+
+---
+
+### Task 2: Runner, preflight and the dedicated clone
+
+`scripts/oss/release_gate.sh` refuses unless `git rev-parse --abbrev-ref HEAD` is `main`. `~/israel-game` itself has `main` checked out, so a worktree cannot hold `main`. The nightly therefore works in its own clone, whose `main` it alone moves.
+
+**Files:**
+- Create: `tools/nightly.py` (runner, preflight, `main` skeleton)
+- Test: `tools/tests/test_nightly.py`
+
+**Interfaces:**
+- Consumes:
+ - Task 1 (all).
+ - `GitHub.release_state`, `GitHub.delete_draft`, `GitHub.dispatch_site` and `demo_serves` from Task 6. They are faked here, so this task does not wait for Task 6.
+- Produces:
+ - `class ProcRunner(Runner)`, constructed as `ProcRunner(grace: float = 60)`: `run` starts the command in its own process group with `env | {"STATECRAFT_LOCK_HOLDER": holder}` when `holder` is given. At the deadline it does the following:
+ 1. Signals the PID in the holder record (`unity_postmerge._holder`, `_parent` check) with SIGTERM, then SIGKILL after 60 s.
+ 2. Sends the top process SIGTERM, then SIGKILL after 60 s.
+ 3. Returns 124.
+ - `@dataclass class Night: now: datetime; day: date; sha: str; version: str; tag: str; run_dir: Path; deadline: float; job: Path; cfg: Config; manifest: str`.
+ - `preflight(cfg: Config, state: State, runner: Runner, gh: "GitHub", *, job: Path, now: datetime, manual: bool, free_gb: Callable[[Path], float]) -> Night`.
+ - `main(argv: list[str] | None = None) -> int` with subcommands:
+ - `run [--manual] [--no-publish]`
+ - `savetest --tag TAG` (Task 8)
+
+ Exit codes: 0 PUBLISHED/SKIPPED/MISSED/no-publish pass, 1 REFUSED, 2 usage.
+ - `run_night(cfg, state_path: Path, job: Path, runner: Runner, gh, itch, *, now, manual, no_publish) -> str` (the outcome). In a `finally` it saves state and writes `record(...)` for every outcome except `--no-publish`. It calls `notify` on REFUSED. `KeyboardInterrupt` propagates after recording.
+
+- [ ] **Step 1: Write the failing tests** (all with `no_processes`, `FakeRunner`, a fake `gh`)
+
+```python
+def test_an_unchanged_main_is_skipped(tmp_path): ...
+ # state.last_published.sha == clone HEAD -> outcome "SKIPPED", LOG line "SKIPPED", no Unity/gh write call in runner.calls
+def test_a_late_start_is_missed_and_earlier_gaps_are_reported(tmp_path): ...
+ # now 09:10 IST, not manual -> "MISSED"; last_run_day 2026-10-25, today 10-28 -> LOG has MISSED lines for 10-26, 10-27, 10-28
+def test_a_manual_run_ignores_the_window(tmp_path): ...
+def test_low_disk_refuses_before_anything_runs(tmp_path): # free_gb=39.9 -> Refused gate "disk"; runner.calls == clone checks only
+def test_the_exclusive_window_marker_refuses(tmp_path): ... # gate "exclusive-window"
+def test_a_missing_licence_unity_editor_or_unity_slots_refuses(tmp_path): ... # gates "unity-licence", "unity-editor", "unity-slots"
+def test_the_clone_must_be_main_at_origin_main_and_clean(tmp_path): ... # branch != main / HEAD != origin/main / dirty -> gate "clone"
+def test_same_day_rerun_cleans_its_draft_and_refuses_a_published_tag(tmp_path): # Review Focus
+ # state.open_draft == tonight's tag and gh says isDraft -> gh.delete_draft(tag) called, run continues
+ # gh says the tag is a published release -> Refused gate "tag-exists"; an unknown draft with the tag -> Refused gate "tag-exists"
+def test_a_missing_tool_is_refused_and_recorded(tmp_path): # Review Focus
+ # runner.capture raises FileNotFoundError("gh") -> outcome REFUSED, LOG line has gate=preflight, notify called once
+def test_run_bounded_terminates_at_the_deadline(tmp_path): # the one real child: sys.executable -c "time.sleep(60)"
+ t = time.monotonic(); code = nightly.ProcRunner(grace=1).run([sys.executable, "-c", "import time; time.sleep(60)"],
+ cwd=tmp_path, log=tmp_path / "l", deadline=time.monotonic() + 1)
+ assert code == 124 and time.monotonic() - t < 10
+```
+
+- [ ] **Step 2: Run them to verify they fail**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly.py -q`
+Expected: FAIL, `ModuleNotFoundError: No module named 'nightly'`
+
+- [ ] **Step 3: Implement `ProcRunner`, `preflight`, `run_night` (stages after preflight stubbed to `raise NotImplementedError`) and `main`**
+
+`preflight` runs these checks in this order, each failure raising the named gate:
+1. Late start: `late_start` and not `manual` raises `Missed`. Before any outcome is written, `missed_days` lines are recorded with outcome MISSED.
+2. The clone: `git -C <clone> rev-parse --abbrev-ref HEAD` == `main`, `rev-parse HEAD` == `rev-parse refs/remotes/origin/main`, and `status --porcelain --untracked-files=no` is empty (gate `clone`).
+3. Unchanged: `sha == state.last_published.sha` raises `Skipped("main unchanged since <tag>")`. Before skipping, retry the site when `state.site_pending` is set (Task 6 `GitHub.dispatch_site` + `demo_serves`).
+4. `free_gb(clone) >= cfg.min_free_gb` (gate `disk`).
+5. `cfg.exclusive_marker` is absent (gate `exclusive-window`).
+6. `cfg.licence.is_file()`, checked with stat only and never read (gate `unity-licence`).
+7. `unity_postmerge.unity_path(<m_EditorVersion>)` exists (gate `unity-editor`).
+8. `cfg.unity_slots.is_file()` (gate `unity-slots`).
+9. The tag check from the Review Focus test (gate `tag-exists`).
+
+Then it builds `run_dir = job/"runs"/f"{now:%Y%m%d-%H%M%S}"`, sets `deadline = monotonic() + cfg.deadline_hours*3600`, and reads `manifest` from `sim/Statecraft.Sim.Tests/golden/manifest.txt` in the clone.
+
+`run_night` converts `FileNotFoundError`, `OSError` and `subprocess.SubprocessError` raised in a stage into `Refused(<stage name>, str(e))`.
+
+- [ ] **Step 4: Run them to verify they pass**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly.py -q`
+Expected: `10 passed`
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add tools/nightly.py tools/tests/test_nightly.py
+git commit -m "nightly: runner with a deadline, preflight in a dedicated clone"
+```
+
+---
+
+### Task 3: Gates before building, and the full EditMode run
+
+**Files:**
+- Create: `tools/nightly_checks.py` (summary parsers)
+- Modify: `tools/nightly.py` (`run_gates`, `unity_argv`, `unity_env`, `run_editmode`)
+- Test: `tools/tests/test_nightly_checks.py`, `tools/tests/test_nightly.py`
+
+**Interfaces:**
+- Consumes: `Night`, `Runner`, `Refused`; from `unity_postmerge`: `parse_results(path) -> Results`, `passed(r, exit) -> bool`, `unity_path(version) -> str`, `WARM_UP`.
+- Produces:
+ - `check_sh_verdict(text: str, code: int) -> str | None`; `release_gate_verdict(text: str, code: int) -> str | None`; `dotnet_totals(text: str) -> tuple[int, int]` (failed, total) (in `nightly_checks.py`).
+ - `unity_argv(night: Night, unity_args: list[str], *, webgl: bool) -> list[str]`; `unity_env(night: Night) -> dict[str, str]`.
+ - `run_gates(night: Night, runner: Runner) -> None`; `run_editmode(night: Night, runner: Runner) -> None`; `restore_settings(night: Night, runner: Runner) -> None`.
+
+- [ ] **Step 1: Write the failing tests**
+
+```python
+PASSED = "Passed! - Failed: 0, Passed: 3216, Skipped: 0, Total: 3216, Duration: 1 m" # format seen in real logs
+def test_dotnet_totals_sum_every_project():
+ assert nc.dotnet_totals(PASSED + "\n" + PASSED.replace("3216", "12")) == (0, 3228)
+ assert nc.dotnet_totals("Failed! - Failed: 5, Passed: 3211, Skipped: 0, Total: 3216") == (5, 3216)
+ assert nc.dotnet_totals("Build succeeded.") == (0, 0)
+
+def test_check_sh_must_pass_and_must_have_compiled_unity():
+ ok = "== unity compile (dotnet, outside Unity)\n...\nALL CHECKS PASSED\n"
+ assert nc.check_sh_verdict(ok, 0) is None
+ assert "SKIPPED" in nc.check_sh_verdict("== unity compile: SKIPPED, no unity/Library ...\nALL CHECKS PASSED", 0)
+ assert nc.check_sh_verdict(ok, 1) is not None
+
+def test_release_gate_needs_its_ok_line_and_exit_0():
+ assert nc.release_gate_verdict("...\n\nRELEASE GATE OK\n", 0) is None
+ assert nc.release_gate_verdict("...\nRELEASE GATE FAILED\n", 1) is not None
+ assert nc.release_gate_verdict("RELEASE GATE OK\n", 1) is not None
+
+# tools/tests/test_nightly.py
+def test_unity_goes_through_slots_and_the_shared_lock(night):
+ argv = nightly.unity_argv(night, ["-runTests"], webgl=False)
+ assert argv[:3] == ["python3", "-I", str(night.cfg.unity_slots)] and "--webgl" not in argv
+ i = argv.index("--"); assert argv[i + 1:i + 6] == ["uv", "run", str(night.cfg.clone / "tools/machine_lock.py"), "--shared", "--"]
+ assert "--wait-unity" not in argv and "-nographics" not in argv
+ assert nightly.unity_argv(night, ["-quit"], webgl=True)[3] == "--webgl"
+ env = nightly.unity_env(night); assert env["UNITY_SLOTS"] == "3" and Path(env["UNITY_MCP_SERVER_PATH"]).is_file()
+
+def test_gates_run_in_order_with_both_locales(night, fake_runner): ...
+ # order: build_sim_for_unity.py, bash scripts/check.sh origin/main, bash scripts/oss/release_gate.sh,
+ # dotnet test sim/Statecraft.sln -c Release --nologo with LANG=LC_ALL=he_IL.UTF-8, then en_US.UTF-8
+def test_a_locale_run_with_zero_tests_or_a_failure_refuses(night, fake_runner): ... # gate "sim-he_IL" / "sim-en_US"
+def test_editmode_needs_tests_and_no_failures_and_never_quits(night, fake_runner, tmp_path):
+ # warm-up argv has "-executeMethod", WARM_UP and no "-quit"; test argv has "-runTests" and no "-quit";
+ # results xml with total 0 -> Refused gate "editmode"; restore_settings called even when the runner raises
+def test_the_exclusive_marker_appearing_before_a_unity_step_refuses(night, fake_runner): ...
+```
+
+- [ ] **Step 2: Run them to verify they fail**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_checks.py tools/tests/test_nightly.py -q`
+Expected: FAIL, `ModuleNotFoundError: No module named 'nightly_checks'`
+
+- [ ] **Step 3: Implement**
+
+`dotnet_totals` matches `(Passed|Failed)!\s+-\s+Failed:\s+(\d+),\s+Passed:\s+\d+,\s+Skipped:\s+\d+,\s+Total:\s+(\d+)`.
+
+`run_gates` runs each step with `runner.run(..., cwd=clone, log=run_dir/"<step>.log", deadline=min(night.deadline, now+limit))`, using these step limits in minutes:
+
+| Step | Limit (min) |
+|---|---|
+| build_sim | 15 |
+| check | 45 |
+| release_gate | 60 |
+| each locale | 30 |
+
+It then reads the log and applies the matching verdict. Gate names are `build-sim`, `check`, `release-gate`, `sim-he_IL` and `sim-en_US`.
+
+`unity_argv` is `python3 -I <unity_slots> [--webgl] <clone>/unity -- uv run <clone>/tools/machine_lock.py --shared -- <unity_path> -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -projectPath <clone>/unity <unity_args...>`.
+
+`unity_env` sets `UNITY_SLOTS=str(cfg.unity_slots_count)` and touches `<job>/no-mcp-server`.
+
+`run_editmode` does the following:
+1. Re-checks the marker.
+2. Runs the warm-up: `-buildTarget OSXUniversal -executeMethod <WARM_UP> -logFile <run_dir>/warmup.log`, limit 60 min.
+3. Runs the tests: `-buildTarget OSXUniversal -runTests -testPlatform EditMode -testResults <run_dir>/editmode.xml -logFile <run_dir>/editmode.log`, limit 150 min, with `holder=run_dir/"lock-holder"`.
+4. Calls `restore_settings` (`git checkout -- unity/ProjectSettings unity/Assets/Settings`) in a `finally`.
+5. Raises `Refused("editmode", ...)` unless `up.passed(up.parse_results(xml), code)`.
+
+- [ ] **Step 4: Run them to verify they pass**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_checks.py tools/tests/test_nightly.py -q`
+Expected: all pass, 0 failed.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add tools/nightly_checks.py tools/nightly.py tools/tests/test_nightly_checks.py tools/tests/test_nightly.py
+git commit -m "nightly: check.sh, release gate, both locales and the full EditMode run"
+```
+
+---
+
+### Task 4: Version stamp, the two WebGL builds and packaging
+
+RELEASING.md step 5 runs `git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset` after each build, which also removes the stamp. So the stamp is applied before each build and removed after it. The built `index.html` carries `productVersion: "<bundleVersion>"` (template `unity/Assets/WebGLTemplates/Statecraft/index.html:43`), which proves the stamp took effect. In-game, `Application.version` feeds `ReportLinks.Version` (the feedback presenter).
+
+**Files:**
+- Modify: `tools/nightly.py` (`stamp_bundle_version`, `build_web`, `package_zip`), `tools/nightly_checks.py` (`product_version`)
+- Test: `tools/tests/test_nightly.py`, `tools/tests/test_nightly_checks.py`
+
+**Interfaces:**
+- Consumes: `unity_argv`, `unity_env`, `restore_settings` (Task 3).
+- Produces:
+ - `stamp_bundle_version(settings: Path, version: str) -> None`.
+ - `product_version(index_html: str) -> str | None`.
+ - `build_web(night: Night, runner: Runner, *, pages: bool, free_gb) -> Path`, which returns `<clone>/unity/Builds/Web-gzip` or `Web-pages`.
+ - `package_zip(night: Night, runner: Runner, build: Path, pages: bool) -> Path`, which returns `<run_dir>/statecraft-israel-v<version>-web[-pages].zip`.
+ - `assert_clean_tree(night: Night, runner: Runner) -> None`.
+
+- [ ] **Step 1: Write the failing tests**
+
+```python
+def test_the_stamp_replaces_exactly_the_one_bundle_version(tmp_path):
+ s = tmp_path / "ProjectSettings.asset"; s.write_text(" productName: X\n bundleVersion: 0.3.1\n other: 1\n")
+ nightly.stamp_bundle_version(s, "0.3.1-nightly.20261028")
+ assert s.read_text() == " productName: X\n bundleVersion: 0.3.1-nightly.20261028\n other: 1\n"
+ s.write_text("no version here\n")
+ with pytest.raises(ValueError): nightly.stamp_bundle_version(s, "0.3.1-nightly.20261028")
+
+def test_product_version_reads_the_built_page():
+ assert nc.product_version('productName: "S",\n productVersion: "0.3.1-nightly.20261028",') == "0.3.1-nightly.20261028"
+ assert nc.product_version("<html></html>") is None
+
+def test_builds_follow_releasing_step_5(night, fake_runner):
+ # gzip argv tail: -quit -buildTarget WebGL -executeMethod Statecraft.Game.EditorTools.Build.Web -compression gzip -shareable -logFile <abs>
+ # pages adds: -decompressionFallback -out Builds/Web-pages ; both have "--webgl" in the slots part
+def test_the_stamp_is_applied_before_and_removed_after_each_build(night, fake_runner): ...
+ # effect on the build call asserts ProjectSettings.asset holds the stamp; afterwards restore_settings ran
+def test_a_build_page_without_tonights_version_refuses(night, fake_runner): ... # gate "version-stamp"
+def test_low_disk_before_the_second_build_refuses(night, fake_runner): ... # free_gb 39 on the 2nd call -> gate "disk"
+def test_a_build_timeout_restores_settings_and_refuses(night, fake_runner): # Review Focus
+ # runner returns 124 for the Build.Web call -> Refused gate "build-web"; restore_settings called; settings file unstamped
+def test_packaging_needs_the_notices_line(night, fake_runner): ...
+ # package_web.sh exit 0 without "OK: notices inside" -> Refused gate "package"
+def test_the_tree_must_be_clean_after_the_builds(night, fake_runner): ... # status --porcelain non-empty -> gate "dirty-tree"
+```
+
+- [ ] **Step 2: Run them to verify they fail**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly.py tools/tests/test_nightly_checks.py -q`
+Expected: FAIL on the new tests (`AttributeError: module 'nightly' has no attribute 'stamp_bundle_version'`).
+
+- [ ] **Step 3: Implement**
+
+`stamp_bundle_version` uses `re.subn(r"^( bundleVersion: )\S+$", ..., flags=re.M)` and requires exactly one replacement.
+
+`build_web` does the following:
+1. Re-checks disk and the marker.
+2. Stamps the version.
+3. Runs Unity with `webgl=True`, limit 120 min, log `<run_dir>/unity-build-web-<gz|pages>.log` (absolute).
+4. Calls `restore_settings` in a `finally`.
+5. Requires exit 0 and `product_version(index.html) == night.version`.
+
+`package_zip` runs `bash scripts/oss/package_web.sh <build> <zip>` in the clone (limit 20 min). It requires exit 0, and the log must contain `PACKAGED ` and `OK: notices inside`.
+
+`assert_clean_tree` runs `git status --porcelain --untracked-files=no` and requires empty output.
+
+- [ ] **Step 4: Run them to verify they pass**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly.py tools/tests/test_nightly_checks.py -q`
+Expected: all pass, 0 failed.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add tools/nightly.py tools/nightly_checks.py tools/tests/test_nightly.py tools/tests/test_nightly_checks.py
+git commit -m "nightly: stamped gzip and Pages WebGL builds, packaged as in RELEASING step 5"
+```
+
+---
+
+### Task 5: No-regression checks (web_check passes, sizes with the PR budget, headless boot)
+
+**Files:**
+- Modify: `tools/nightly_checks.py`, `tools/nightly.py` (`run_web_checks`, `check_sizes`, `measure_boot`)
+- Test: `tools/tests/test_nightly_checks.py`, `tools/tests/test_nightly.py`
+
+**Interfaces:**
+- Consumes: `package_release.build_files(build) -> list[str]`, `package_release.BUILD_FILE`; `GitHub.previous_build_tag`, `GitHub.download`, `GitHub.merged_pr_bodies` (Task 6, faked here).
+- Produces (in `nightly_checks.py`):
+ - `golden_expects(manifest: str) -> list[str]`; `smoke_expect(manifest: str) -> str`; `smoke_orders_expect(manifest: str) -> str`.
+ - `web_check_passes(build: Path, manifest: str) -> list[list[str]]`.
+ - `web_sizes(build: Path) -> dict[str, int]`; `web_sizes_from_zip(zip_path: Path) -> dict[str, int]`, both with keys `data`, `wasm`, `framework`.
+ - `size_budget_bytes(pr_bodies: list[str]) -> int`; `size_verdict(old: dict[str, int], new: dict[str, int], budget: int, tolerance: float = 0.02) -> str | None`.
+ - `boot_ms(web_check_output: str) -> int`; `boot_verdict(median_ms: float, baseline: list[float], nights: int = 5) -> tuple[str, str | None]`.
+ - `zip_missing_notices(zip_path: Path) -> list[str]`.
+- Produces (in `nightly.py`):
+ - `run_web_checks(night: Night, runner: Runner, build: Path) -> None`.
+ - `check_sizes(night: Night, gh, build: Path, previous_zip: Path, prev_sha: str | None) -> dict[str, int]`.
+ - `measure_boot(night: Night, runner: Runner, build: Path) -> float`.
+
+- [ ] **Step 1: Write the failing tests**
+
+```python
+MANIFEST = "# c\nhash1950 aa\nhash1952 bb\nsmoke5 cc\nsmoke-orders dd\n"
+def test_expects_come_from_the_manifest():
+ assert nc.golden_expects(MANIFEST) == ["GOLDEN OK hash1950 aa", "GOLDEN OK hash1952 bb", "GOLDEN OK smoke5 cc", "GOLDEN OK smoke-orders dd"]
+ assert nc.smoke_expect(MANIFEST) == "SMOKE OK 5 turns 1948-10-15 cc"
+ assert nc.smoke_orders_expect(MANIFEST) == "SMOKE ORDERS OK 1948-06-15 dd"
+ with pytest.raises(ValueError): nc.smoke_expect("hash1950 aa\n")
+
+def test_the_passes_are_releasing_step_5_plus_smoke_orders(tmp_path):
+ p = nc.web_check_passes(tmp_path, MANIFEST)
+ assert len(p) == 7 and p[0][1:3] == ["--query", "golden&smoke=5"] and p[1][1:3] == ["--query", "smoke-orders"]
+ assert [x[x.index("--startscreen") + 1] for x in p if "--startscreen" in x] == ["new", "recording", "new", "recording"]
+ assert sum("lang=he" in x for x in p) == 2 and "--persistence" in p[6]
+ assert all(x[x.index("--stall") + 1] == "90" for x in p[2:])
+
+def test_sizes_sum_data_wasm_framework_named_by_index_html(tmp_path): ... # a stale Build/ file not in index.html is ignored
+def test_zip_and_folder_sizes_agree(tmp_path): ...
+def test_size_growth_within_2_percent_passes_and_beyond_refuses():
+ old = {"data": 900, "wasm": 90, "framework": 10}
+ assert nc.size_verdict(old, {"data": 920, "wasm": 90, "framework": 10}, 0) is None # +20 = 2.0%
+ assert "1021" in nc.size_verdict(old, {"data": 921, "wasm": 90, "framework": 10}, 0) # +21 > 2%
+ assert nc.size_verdict(old, {"data": 921, "wasm": 90, "framework": 10}, 1) is None # budgeted
+
+def test_the_budget_line_is_exact_and_summed():
+ bodies = ["x\nNightly size budget: +1.5 MB\n", "Nightly size budget: +2 MB", "nightly size budget +9 MB", "Nightly size budget: -3 MB"]
+ assert nc.size_budget_bytes(bodies) == 3_500_000
+
+def test_boot_reads_screens_ready_and_needs_a_pass():
+ out = "console: BOOT phase=screens ready at=8123 ms dt=40 ms\nconsole: GAME OK 1948-05-15 turn 0 hash ab\nPASS: saw GAME OK\n"
+ assert nc.boot_ms(out) == 8123
+ with pytest.raises(ValueError): nc.boot_ms(out.replace("PASS: saw GAME OK", "TIMEOUT: never saw GAME OK"))
+
+def test_the_boot_bound_is_the_baseline_spread():
+ assert nc.boot_verdict(9000, [8000, 8100]) == ("collecting", None)
+ base = [8000, 8100, 8050, 8200, 8150] # max 8200, spread 200 -> limit 8400
+ assert nc.boot_verdict(8400, base) == ("checked", None)
+ assert "8401" in nc.boot_verdict(8401, base)[1]
+
+def test_web_checks_run_under_the_shared_lock_and_all_must_pass(night, fake_runner): ... # any exit != 0 or no "PASS:" -> gate "web-check"
+def test_boot_takes_the_exclusive_lock_from_the_main_checkout_three_times(night, fake_runner):
+ # each argv: uv run <clone>/tools/machine_lock.py --exclusive --wait-unity --timeout 2700 -- uv run <clone>/tools/web_check.py
+ # <abs build> --query bootlog --expect "GAME OK" --timeout 300 --stall 90 ; cwd == cfg.main_repo ; median of 3 returned
+def test_sizes_refuse_without_a_baseline_zip(night, fake_gh): ... # gate "sizes"
+def test_a_budget_is_looked_up_only_when_growth_exceeds_2_percent(night, fake_gh): ...
+def test_a_truncated_pr_list_refuses(night, fake_gh): ... # merged_pr_bodies raises Refused("sizes", ...)
+```
+
+- [ ] **Step 2: Run them to verify they fail**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_checks.py tools/tests/test_nightly.py -q`
+Expected: FAIL, `AttributeError: module 'nightly_checks' has no attribute 'golden_expects'`
+
+- [ ] **Step 3: Implement**
+
+`golden_expects` mirrors the RELEASING step 5 loop: every non-comment manifest line gives `GOLDEN OK <name> <hash>`.
+
+`web_check_passes` returns the argument lists after `web_check.py`:
+1. `[build, --query, golden&smoke=5, *(--expect g for g in golden_expects), --expect smoke_expect]`
+2. `[build, --query, smoke-orders, --expect smoke_orders_expect]`
+3. The four `--startscreen` passes and `--persistence`, each with `--timeout 300 --stall 90`, exactly as in RELEASING step 5.
+
+`run_web_checks` runs each pass for both builds as `uv run <clone>/tools/machine_lock.py --shared -- uv run <clone>/tools/web_check.py <pass>` (limit 10 min each), cwd = clone.
+
+`web_sizes` picks the single `index.html`-named file ending `.data.gz`, `.wasm.gz` and `.framework.js.gz` (ValueError on zero or several of one kind). The `_from_zip` form reads the zip's `index.html` entry and its member sizes.
+
+`size_budget_bytes` matches `^Nightly size budget: \+(\d+(?:\.\d+)?) MB\s*$` with `re.M`. MB is 1,000,000 bytes.
+
+`size_verdict` refuses when `sum(new) - sum(old) > tolerance * sum(old) + budget`. The reason names the old and new totals and the budget.
+
+`check_sizes` behaves as follows:
+- The baseline is `web_sizes_from_zip(previous_zip)`, the `-web.zip` of the previous published build (Task 6's `previous_build_tag`). A missing zip raises `Refused("sizes", "no baseline")`.
+- PR bodies are fetched only when growth exceeds 2%. The shas in `git rev-list <prev_sha>..<night.sha>` are passed to `gh.merged_pr_bodies`, and `prev_sha` comes from `state.last_published.sha` or `git rev-list -n 1 <previous tag>`.
+
+`measure_boot` runs the exclusive argv from the test 3 times. `--timeout 2700` makes machine_lock give up after 45 minutes waiting for Unity, which is then REFUSED with gate `boot`. The step limit is 60 min, the cwd is the main checkout (so `machine_lock.worktrees()` sees every lane's editor), and the result is the median of `boot_ms`.
+
+`boot_verdict` uses the spread from the spec: limit = max(baseline) + (max - min). It is "collecting" until 5 published nights have recorded a median.
+
+- [ ] **Step 4: Run them to verify they pass**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_checks.py tools/tests/test_nightly.py -q`
+Expected: all pass, 0 failed.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add tools/nightly_checks.py tools/nightly.py tools/tests/test_nightly_checks.py tools/tests/test_nightly.py
+git commit -m "nightly: web checks on both builds, size budget against the last published build, headless boot"
+```
+
+---
+
+### Task 6: GitHub draft-first publish, the site deploy and the /demo/ check
+
+**Files:**
+- Create: `tools/nightly_publish.py` (`GitHub`, `demo_serves`, `release_notes`, `unzip_to`)
+- Modify: `tools/nightly.py` (`publish_night` without itch; wire stages into `run_night`)
+- Test: `tools/tests/test_nightly_publish.py`, `tools/tests/test_nightly.py`
+
+**Interfaces:**
+- Consumes: `Runner`, `Refused`, `State`, `Published`, `zip_missing_notices`.
+- Produces:
+ - `release_notes(*, version: str, sha: str, since: str, subjects: list[str], sha256_lines: list[str]) -> str`.
+ - `class GitHub(runner: Runner, slug: str, cwd: Path)`:
+ - `release_state(tag) -> str | None`, returning `"draft"`, `"published"` or `None`
+ - `previous_build_tag(state_tag: str | None) -> str`
+ - `download(tag, pattern, dest: Path) -> Path`
+ - `create_draft(tag, sha, notes: Path, assets: list[Path]) -> None`
+ - `verify_draft(tag, local: list[Path], dest: Path) -> None`
+ - `publish(tag, sha) -> None`
+ - `delete_draft(tag) -> None`
+ - `merged_pr_bodies(shas: set[str]) -> list[str]`
+ - `dispatch_site(deadline: float) -> None`
+ - `demo_serves(url: str, version: str, *, deadline: float, fetch=urllib.request.urlopen, sleep=time.sleep, now=time.monotonic) -> None`.
+ - `unzip_to(zip_path: Path, dest: Path) -> Path`.
+ - `publish_night(night, state, gh, itch, zips: tuple[Path, Path], sizes, boot) -> None` (in `nightly.py`; Task 7 adds the itch branch).
+
+- [ ] **Step 1: Write the failing tests** (`FakeRunner` scripts gh's JSON)
+
+```python
+def test_the_draft_is_a_prerelease_never_latest_targeting_the_commit(fake_runner, tmp_path):
+ gh.create_draft("v0.3.1-nightly.20261028", SHA, tmp_path / "notes.md", [WEB, PAGES])
+ assert fake_runner.calls[-1] == ["gh", "release", "create", "v0.3.1-nightly.20261028", "--repo", SLUG, "--draft",
+ "--prerelease", "--latest=false", "--target", SHA, "--title", "v0.3.1-nightly.20261028 (nightly)",
+ "--notes-file", str(tmp_path / "notes.md"), str(WEB), str(PAGES)]
+
+def test_verify_draft_compares_hashes_and_notices(fake_runner, tmp_path): ...
+ # downloaded bytes differ -> Refused gate "github-draft"; a zip without LICENSE -> Refused; isDraft false -> Refused
+def test_publish_checks_draft_off_prerelease_on_latest_unchanged_and_tag_at_sha(fake_runner): ...
+ # gh release edit <tag> --draft=false ; view json; gh api repos/<slug>/releases/latest --jq .tag_name != tag;
+ # git ls-remote origin refs/tags/<tag> == SHA ; any mismatch -> Refused gate "github-publish"
+def test_delete_draft_refuses_a_published_release_and_never_cleans_tags(fake_runner):
+ # view says isDraft false -> raises, and no "gh release delete" call is made; argv never contains "--cleanup-tag"
+def test_previous_build_is_state_tag_else_newest_release_with_a_web_zip(fake_runner): ...
+def test_merged_pr_bodies_filter_by_merge_commit_and_refuse_truncation(fake_runner): ... # 500 rows -> Refused "sizes"
+def test_site_dispatch_finds_the_new_run_and_watches_it(fake_runner): ...
+ # gh workflow run site.yml --repo SLUG --ref main ; gh run list --repo SLUG --workflow site.yml --event workflow_dispatch
+ # --limit 5 --json databaseId,createdAt ; gh run watch <id> --repo SLUG --exit-status ; non-zero -> Refused gate "site"
+def test_demo_serves_polls_until_the_version_appears():
+ pages = iter([b'productVersion: "0.3.1"', b'productVersion: "0.3.1-nightly.20261028"'])
+ gp.demo_serves(DEMO, "0.3.1-nightly.20261028", deadline=100, fetch=lambda u, timeout: io.BytesIO(next(pages)),
+ sleep=lambda s: None, now=iter(range(0, 1000, 30)).__next__)
+def test_release_notes_list_commits_and_hashes_and_say_nightly(): ...
+def test_release_targets_the_preflight_commit(night, fake_gh): # Review Focus
+ # origin/main moves after preflight (fake ls-remote of main returns another sha): create_draft gets night.sha,
+ # notes come from git log <prev>..<night.sha>
+def test_a_failed_draft_check_deletes_the_draft_and_refuses(night, fake_gh): ...
+def test_a_site_failure_after_publish_retries_once_then_refuses_and_marks_site_pending(night, fake_gh):
+ # dispatch_site fails twice -> outcome REFUSED gate "site"; release stays published (no delete_draft call);
+ # state.last_published is tonight (the release is public); state.site_pending == tonight's version
+def test_a_published_night_updates_state_and_boot_baseline(night, fake_gh): ...
+ # last_published = Published(tag, sha, version, sizes, boot_ms); boot_baseline appended while len < 5
+def test_no_publish_stops_before_any_store_call(night, fake_gh, capsys): ...
+ # no gh release/workflow or butler call; stdout has "NO-PUBLISH: all gates passed for v0.3.1-nightly.20261028";
+ # LOG.md and HANDOFF untouched; state unchanged
+```
+
+- [ ] **Step 2: Run them to verify they fail**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_publish.py tools/tests/test_nightly.py -q`
+Expected: FAIL, `ModuleNotFoundError: No module named 'nightly_publish'`
+
+- [ ] **Step 3: Implement `nightly_publish.py` and `publish_night`**
+
+`release_notes` contains:
+1. The line "Automated nightly build of `main` at <sha12>. A pre-release, not a versioned release."
+2. `- <subject>` lines from `git log --format=%s <since>..<sha>`.
+3. The `shasum -a 256` lines, as in RELEASING step 6.
+
+`since` is the previous nightly's sha, or on the first night the previous build tag.
+
+`verify_draft` works as follows:
+1. `gh release view <tag> --repo <slug> --json isDraft,isPrerelease,assets` must show `isDraft` true, `isPrerelease` true, and asset names equal to the local names.
+2. `gh release download <tag> --repo <slug> --dir <dest> --pattern "*.zip"` is run.
+3. The SHA-256 of each downloaded file must equal its local file, and `zip_missing_notices` must be empty (RELEASING step 7's five notices).
+
+`publish_night` order (itch added in Task 7):
+1. Write the notes.
+2. `create_draft`.
+3. `verify_draft`. On failure: `delete_draft`, then REFUSED `github-draft`.
+4. `publish`. On failure: `delete_draft` if `release_state` is still `"draft"`, then REFUSED `github-publish`.
+5. Set `state.last_published`, and append to `boot_baseline` while it is shorter than 5.
+6. `dispatch_site`, then `demo_serves(cfg.site_demo_url, version, deadline=now+15 min)`. On failure, run them once more; a second failure sets `state.site_pending` and is REFUSED `site`, with the notification saying the release is public and the demo is unchanged.
+
+The outcome is PUBLISHED.
+
+Wire the stages in `run_night`:
+
+preflight → gates → editmode → build gz → build pages → assert_clean_tree → package both → web checks → sizes → boot → (no-publish? stop) → publish.
+
+- [ ] **Step 4: Run them to verify they pass**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_publish.py tools/tests/test_nightly.py -q`
+Expected: all pass, 0 failed.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add tools/nightly_publish.py tools/nightly.py tools/tests/test_nightly_publish.py tools/tests/test_nightly.py
+git commit -m "nightly: draft-first GitHub pre-release, site deploy and /demo/ version check"
+```
+
+---
+
+### Task 7: itch.io push with rollback (behind `itch_enabled`)
+
+**Files:**
+- Modify: `tools/nightly_publish.py` (`Itch`), `tools/nightly.py` (`publish_night` itch branch)
+- Create: `tools/tests/data/butler_status_live.txt`, `tools/tests/data/butler_status_pending.txt`
+- Test: `tools/tests/test_nightly_publish.py`, `tools/tests/test_nightly.py`
+
+**Interfaces:**
+- Consumes: `GitHub.download`, `unzip_to`, `Config.itch_*`, `Config.butler`.
+- Produces:
+ - `class Itch(runner: Runner, butler: Path, target: str)`, where target is `user/project:channel`:
+ - `live_version(status_text: str) -> str | None` (static, parses this target's channel row)
+ - `push(folder: Path, version: str) -> None`
+ - `wait_live(version: str, deadline: float, sleep=time.sleep) -> None`
+ - `matches(folder: Path, dest: Path) -> None`
+ - `build_id(status_text: str) -> str | None`
+
+- [ ] **Step 1: Capture the real `butler status` output as fixtures (read-only, done by hand once)**
+
+Run: `~/.local/bin/butler status eyalgolan/statecraft-israel > tools/tests/data/butler_status_live.txt`
+Expected: a table naming channel `html5` with its upload, build and version columns, and no token in the text (check with `grep -ciE 'key|token' tools/tests/data/butler_status_live.txt` printing `0`). If the project or channel does not exist yet, stop here. Itch stays disabled, and the owner creates the project (docs/m3-release.md steps 1-4) first. For the pending fixture, copy the live one and edit the build cell to the state butler prints while a build processes, as seen at the first real push. Until then, mark that test `xfail(strict=True, reason="pending fixture not captured")`.
+
+- [ ] **Step 2: Write the failing tests**
+
+```python
+def test_live_version_reads_the_channel_row():
+ text = (DATA / "butler_status_live.txt").read_text()
+ assert gp.Itch.live_version(text) == "<the version in the captured row>"
+def test_a_processing_build_is_not_live(): ... # pending fixture -> None
+def test_push_uses_the_folder_target_and_userversion(fake_runner, tmp_path):
+ gp.Itch(fake_runner, BUTLER, "eyalgolan/statecraft-israel:html5").push(tmp_path, "0.3.1-nightly.20261028")
+ assert fake_runner.calls[-1] == [str(BUTLER), "push", str(tmp_path), "eyalgolan/statecraft-israel:html5",
+ "--userversion", "0.3.1-nightly.20261028"]
+def test_fetch_compare_refuses_any_difference(fake_runner, tmp_path): ... # butler fetch <target> <dest>; path->sha256 maps differ -> Refused "itch"
+def test_itch_disabled_is_logged_and_never_calls_butler(night, fake_gh): ... # run log says "itch: skipped (save test not passed)"
+def test_itch_rollback_target_is_ready_before_the_push(night, fake_gh):
+ # previous -web.zip cannot be downloaded/unzipped -> Refused gate "itch-rollback" and butler push never called
+def test_an_itch_failure_rolls_back_and_deletes_the_draft(night, fake_gh):
+ # wait_live times out -> push(previous folder, previous version); delete_draft(tag); REFUSED gate "itch"
+def test_a_github_publish_failure_after_itch_rolls_itch_back(night, fake_gh): ...
+def test_no_butler_command_names_the_credentials_file():
+ src = (TOOLS / "nightly_publish.py").read_text() + (TOOLS / "nightly.py").read_text()
+ assert "butler_creds" not in src and "--identity" not in src and "auth token" not in src and "GH_TOKEN" not in src
+```
+
+- [ ] **Step 3: Run them to verify they fail**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_publish.py tools/tests/test_nightly.py -q`
+Expected: FAIL, `AttributeError: module 'nightly_publish' has no attribute 'Itch'`
+
+- [ ] **Step 4: Implement**
+
+`live_version` splits the status table rows and finds the row whose channel cell is the target's channel. It returns its version cell, or `None` when that row's build cell shows the processing state or the row is missing. The parsing is written against the captured fixture, not guessed.
+
+`wait_live` polls `butler status <user/project>` every 30 s until `live_version == version` or the deadline (15 min).
+
+`matches` runs `butler fetch <target> <dest>` and compares the relative-path to SHA-256 maps of `dest` and the pushed folder.
+
+The itch branch in `publish_night` sits between `verify_draft` and `publish`. When `cfg.itch_enabled` is true:
+1. Download and unzip the previous build's `-web.zip`, with version `previous_tag[1:]`, as the rollback folder. On failure: REFUSED `itch-rollback`, nothing pushed.
+2. Unzip tonight's `-web.zip`.
+3. `push`, `wait_live`, `matches`. On failure: push the rollback folder, run its `wait_live`, `delete_draft`, then REFUSED `itch`.
+4. A later failure in `publish` also pushes the rollback folder back.
+
+After a successful `publish`, a site failure does not roll itch back. The build passed every gate, and only the Pages deploy failed.
+
+- [ ] **Step 5: Run them to verify they pass**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_publish.py tools/tests/test_nightly.py -q`
+Expected: all pass, 0 failed (one `xfail` until the pending fixture exists).
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add tools/nightly_publish.py tools/nightly.py tools/tests/test_nightly_publish.py tools/tests/test_nightly.py tools/tests/data/butler_status_live.txt tools/tests/data/butler_status_pending.txt
+git commit -m "nightly: itch.io push behind a config flag, verified by status and fetch, with rollback"
+```
+
+---
+
+### Task 8: The two-upload itch save test, and docs/m3-release.md
+
+The test follows docs/m3-release.md:354-388 (unchanged content, same game-frame origin, different upload URL, full `date, turn, hash` tuple, two loads of B). IndexedDB is per origin, so it opens the itch game-frame URL directly in one kept Chrome profile.
+
+**Files:**
+- Modify: `tools/web_check.py` (`--url`, `--profile`, `--first-save`; `PersistenceCheck(first_save_only=...)`), `tools/nightly.py` (`savetest`), `tools/nightly_publish.py` (`itch_frame_url`), `docs/m3-release.md:330-332`, `docs/m3-release.md:354` (heading), `docs/m3-release.md:418`
+- Create: `tools/tests/data/itch_page.html` (captured once, read-only)
+- Test: `tools/tests/test_web_check.py`, `tools/tests/test_nightly.py`, `tools/tests/test_nightly_publish.py`
+
+**Interfaces:**
+- Consumes: `Itch.push`, `Itch.wait_live`, `Itch.build_id`, `GitHub.download`, `unzip_to`, `enable_itch`.
+- Produces:
+ - `web_check` CLI: `web_check.py [build] [--url URL] [--profile DIR] [--first-save] ...`. Exactly one of `build` and `--url` is required. With `--first-save`, it prints `PERSISTENCE saved <date> turn <n> hash <h>` and passes after the first durable commit.
+ - `itch_frame_url(page_html: str) -> str | None`.
+ - `savetest(cfg: Config, config_path: Path, job: Path, runner: Runner, gh: GitHub, itch: Itch, *, tag: str, fetch=urllib.request.urlopen) -> str`, returning `"PASS"`, `"FAIL"` or `"INCONCLUSIVE"`.
+
+- [ ] **Step 1: Capture the itch page once (read-only)**
+
+Run: `curl -s "<itch_page_url>" > tools/tests/data/itch_page.html && grep -c "html-classic.itch.zone" tools/tests/data/itch_page.html`
+Expected: a count of 1 or more. A 0 (a draft or password page) means the page cannot be tested yet, so the save test stays INCONCLUSIVE and itch stays disabled. Report that to the owner and continue with the other steps using a hand-made fixture holding one escaped `data-iframe` placeholder.
+
+- [ ] **Step 2: Write the failing tests**
+
+```python
+# test_web_check.py
+def test_first_save_stops_after_the_first_durable_commit(capsys):
+ # drive PersistenceCheck(first_save_only=True) with: GAME OK ... turn 0, TURN 1 1948-05-16 hash ab,
+ # AUTOSAVE PENDING 1 1948-05-16 turn 1 hash ab, AUTOSAVE OK 1 1948-05-16 turn 1 hash ab
+ # -> done True, no "reload" action sent, stdout has "PERSISTENCE saved 1948-05-16 turn 1 hash ab"
+def test_url_and_build_are_exclusive_and_one_is_required(): ... # parser errors on both / neither
+def test_a_given_profile_is_kept(tmp_path): ... # the profile dir chosen by main() is --profile and is not removed (unit-level helper)
+
+# test_nightly_publish.py
+def test_the_frame_url_is_read_from_the_page():
+ assert gp.itch_frame_url((DATA / "itch_page.html").read_text()).startswith("https://html-classic.itch.zone/html/")
+ assert gp.itch_frame_url("<html>no game</html>") is None
+
+# test_nightly.py
+def test_savetest_passes_only_with_matching_tuple_new_url_same_origin(fake_runner, fake_gh, fake_itch, tmp_path):
+ # push A -> frame A; web_check --url A --profile P --first-save -> tuple; push B (same folder) -> new build id, frame B
+ # frame B != frame A and same scheme+host; web_check --url B --profile P --expect "GAME OK <d> turn <n> hash <h>" twice
+ # -> "PASS", enable_itch called with the evidence file (both frame URLs, build ids, zip sha256, tuple, Chrome path)
+def test_savetest_same_frame_url_is_inconclusive_and_keeps_itch_off(...): ...
+def test_savetest_mismatch_fails_and_keeps_itch_off(...): ...
+def test_savetest_needs_a_published_nightly_and_a_page_url(...): ... # draft tag / no itch_page_url -> INCONCLUSIVE, no push
+```
+
+- [ ] **Step 3: Run them to verify they fail**
+
+Run: `uv run --with pytest==9.1.1 --with websockets==15.0.1 pytest tools/tests/test_web_check.py tools/tests/test_nightly.py tools/tests/test_nightly_publish.py -q`
+Expected: FAIL, `TypeError: PersistenceCheck.__init__() got an unexpected keyword argument 'first_save_only'`
+
+- [ ] **Step 4: Implement**
+
+`web_check.py`:
+- `build` becomes `nargs="?"`.
+- With `--url`, no server starts and the page opens that URL, with `page_query` appended using `&` when it already has a query.
+- With `--profile`, that folder is used and not deleted in `finally`.
+- `--first-save` implies the persistence driver with `first_save_only=True`. In `_reload_when_durable`, when that is set, it prints the saved line and sets `_done` instead of reloading.
+- `res_error` and the viewport stay as they are.
+
+`itch_frame_url` HTML-unescapes the page and returns the first `https://html-classic\.itch\.zone/html/\d+/[^"'&<>\s]*index\.html`.
+
+`savetest` does the following:
+1. Requires `cfg.itch_page_url` and `gh.release_state(tag) == "published"`, else INCONCLUSIVE.
+2. Downloads and unzips the tag's `-web.zip`.
+3. Pushes it as upload A and runs `wait_live`. It reads `build_id` and the frame URL, then runs the A first-save in a new profile under `<job>/savetest/<stamp>/profile`.
+4. Pushes the same folder again as upload B and runs `wait_live`. It requires a new `build_id`, a different frame URL and the same origin, else INCONCLUSIVE.
+5. Loads B twice expecting the `GAME OK` tuple, else FAIL.
+6. Writes `evidence.json` and calls `enable_itch` on PASS.
+7. Records `SAVETEST <result>` in LOG.md.
+
+`docs/m3-release.md` edits:
+- 330-332: the heading becomes "Upload to itch.io". The paragraph keeps steps 1-6 for the project's first setup (owner) and says nightly builds are now pushed with `butler` by `tools/nightly.py`, enabled only after `nightly.py savetest` passes (owner, 27 October 2026, "Public: website + itch"). It keeps "the build must pass the sensitivity gate above (`-shareable`)".
+- 354: the heading drops "(the test is deferred to M4)". A line under the test plan says the automated test is `uv run tools/nightly.py savetest --tag <published nightly>` and that its result is recorded in the job's evidence file.
+- Keep every phrase `tools/tests/test_cross_upload_save_plan.py` asserts, including "Result: not run on itch.io", until a real run's result is recorded in a later PR.
+- 418: "Not uploaded to itch.io" says nightlies upload once the save test passes.
+
+- [ ] **Step 5: Run them to verify they pass**
+
+Run: `uv run --with pytest==9.1.1 --with websockets==15.0.1 pytest tools/tests/test_web_check.py tools/tests/test_nightly.py tools/tests/test_nightly_publish.py tools/tests/test_cross_upload_save_plan.py -q`
+Expected: all pass, 0 failed.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add tools/web_check.py tools/nightly.py tools/nightly_publish.py tools/tests/test_web_check.py tools/tests/test_nightly.py tools/tests/test_nightly_publish.py tools/tests/data/itch_page.html docs/m3-release.md
+git commit -m "nightly: automated two-upload itch save test that enables itch pushes on a pass"
+```
+
+---
+
+### Task 9: launchd job, launcher, install docs, RELEASING section, spec and changelog
+
+**Files:**
+- Create: `tools/nightly_launch.py`, `tools/nightly.plist.in`, `changelog.d/nightly-release.md`, `docs/superpowers/specs/2026-10-27-nightly-release-design.md`, `docs/superpowers/plans/2026-10-27-nightly-release-plan.md`
+- Modify: `tools/README.md` (new "Nightly release" section after "Post-merge Unity run"; the expected test count line at :117), `docs/RELEASING.md` (new "## Nightly builds" section before "## Refreshing the README screenshots", :174)
+- Test: `tools/tests/test_nightly_launch.py`
+
+**Interfaces:**
+- Consumes: `unity_postmerge.fill_plist(text, *, uv, repo, home, path) -> str`, `unity_postmerge.KEEP`; `nightly_state.run_lock`, `load_config`.
+- Produces:
+ - `nightly_launch.main(argv) -> int` with `--uv PATH --home JOB`.
+ - `prepare_clone(cfg: Config, git=...) -> None`.
+ - The `com.statecraft.nightly` launchd label.
+
+- [ ] **Step 1: Write the failing tests**
+
+```python
+def test_the_plist_runs_at_0300_and_never_on_an_interval():
+ filled = up.fill_plist((TOOLS / "nightly.plist.in").read_text(), uv="/opt/uv", repo="/r", home="/h", path="/usr/bin:/bin")
+ p = plistlib.loads(filled.encode())
+ assert p["Label"] == "com.statecraft.nightly" and p["StartCalendarInterval"] == {"Hour": 3, "Minute": 0}
+ assert "StartInterval" not in p and not p.get("RunAtLoad") and "@" not in filled
+ assert p["ProgramArguments"][:3] == ["/opt/uv", "run", "/h/nightly_launch.py"]
+
+def test_prepare_clone_resets_only_the_clones_own_main_and_keeps_the_library(tmp_path):
+ # fake git records: fetch --quiet --tags origin +refs/heads/main:refs/remotes/origin/main ; checkout --quiet main ;
+ # reset --hard refs/remotes/origin/main ; clean -ffdx -e /unity/Library/ ... ; every call has cwd == cfg.clone,
+ # none has cwd == cfg.main_repo except the one-time "cp -c -R <main_repo>/unity/Library <clone>/unity/Library"
+def test_a_missing_clone_is_refused_and_recorded_not_cloned(tmp_path): ... # LOG line "REFUSED ... gate=clone"
+def test_a_run_in_progress_exits_0_and_touches_nothing(tmp_path): ...
+def test_no_nightly_module_pushes_merges_or_deletes_tags():
+ src = "".join((TOOLS / n).read_text() for n in ("nightly.py", "nightly_publish.py", "nightly_state.py", "nightly_checks.py", "nightly_launch.py"))
+ for banned in ("git push", "\"push\", \"--force\"", "--cleanup-tag", "\"tag\", \"-d\"", "pr merge", "push --force"):
+ assert banned not in src
+```
+
+- [ ] **Step 2: Run them to verify they fail**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_launch.py -q`
+Expected: FAIL, `ModuleNotFoundError: No module named 'nightly_launch'`
+
+- [ ] **Step 3: Implement the launcher and the plist**
+
+The launcher does the following:
+1. Holds `run_lock(home)`. When the lock is held, it prints "a run is in progress" and returns 0.
+2. Runs `prepare_clone`:
+ - If the clone is missing, it records a REFUSED line with gate `clone` (the install section creates the clone; the launcher never clones).
+ - The first time, it APFS-clones the main checkout's Library.
+3. Returns `subprocess.call([uv, "run", str(clone / "tools/nightly.py"), "run"])`. The clone's own script therefore runs, so a merged change takes effect on the next night.
+
+The plist mirrors `tools/unity_postmerge.plist.in`, with `StartCalendarInterval` `{Hour 3, Minute 0}` in place of `StartInterval`, no `RunAtLoad`, and stdout/stderr to `@HOME@/launchd.log`.
+
+- [ ] **Step 4: Run them to verify they pass**
+
+Run: `uv run --with pytest==9.1.1 pytest tools/tests/test_nightly_launch.py -q`
+Expected: `5 passed`
+
+- [ ] **Step 5: Write the docs**
+
+`tools/README.md` "Nightly release" section covers the following (each fact once, in the voice of the "Post-merge Unity run" section):
+- What runs and when.
+- The job folder and the clone.
+- The install commands: `git clone https://github.com/eyalgolan/statecraft-israel.git ~/.cache/statecraft/nightly/repo`, `mkdir -p` the job folder, `cp tools/nightly_launch.py`, the `sed` fill with `@PATH@` including the folders of `uv`, `gh`, `dotnet`, `git` and `~/.local/bin`, then `plutil -lint` and `launchctl bootstrap gui/$(id -u) ...`.
+- A first by-hand `uv run tools/nightly.py run --manual --no-publish` from the clone, which must print `NO-PUBLISH: all gates passed for v<version>`.
+- Uninstall (`launchctl bootout gui/$(id -u)/com.statecraft.nightly`).
+- How to reset the boot baseline (delete `boot_baseline` from `state.json`; the next 5 published nights re-measure it).
+- The savetest command.
+
+`docs/RELEASING.md` "## Nightly builds" covers the following:
+- The schedule and what is public.
+- The gates, by name and in order.
+- The PR body line `Nightly size budget: +N MB` (MB = 1,000,000 bytes) that a PR adding download size must carry, or the next nightly is refused.
+- The outcomes in `LOG.md`.
+- That versioned releases (steps 1-7) are unchanged.
+- That nightlies are never marked Latest and never deleted.
+
+Update the `tools/README.md` expected test count to the number the full run in Step 6 prints.
+
+Copy the spec to `docs/superpowers/specs/2026-10-27-nightly-release-design.md` with only these edits:
+- The status line becomes "Approved by the owner on 27 October 2026 ("Approve as written"). Built from docs/superpowers/plans/2026-10-27-nightly-release-plan.md."
+- The parenthetical after "need >= 40 GB free at launch", which names an internal file, becomes "(the coordinator's disk rule)".
+- The session name after each "builder's call," is removed, leaving "(builder's call)".
+
+Copy this plan to `docs/superpowers/plans/2026-10-27-nightly-release-plan.md`.
+
+`changelog.d/nightly-release.md`:
+
+```markdown
+- Nightly builds: every night at 03:00 (Israel time) the newest `main` is built, checked against the build that is live
+ and, only if every check passes, published as a GitHub pre-release that the website's demo serves (`docs/RELEASING.md`,
+ "Nightly builds"). itch.io uploads follow once the automated save test passes.
+```
+
+Run: `grep -rnP "\x{2014}" tools/nightly*.py tools/nightly.plist.in docs/RELEASING.md docs/m3-release.md tools/README.md changelog.d/nightly-release.md docs/superpowers/specs/2026-10-27-nightly-release-design.md docs/superpowers/plans/2026-10-27-nightly-release-plan.md; grep -c "builder's call," docs/superpowers/specs/2026-10-27-nightly-release-design.md; grep -c "the coordinator's disk rule" docs/superpowers/specs/2026-10-27-nightly-release-design.md; diff "$APPROVED_SPEC" docs/superpowers/specs/2026-10-27-nightly-release-design.md`
+Expected:
+- The em dash grep prints nothing.
+- Then `0`, then `1`.
+- `diff` (with `APPROVED_SPEC` set to the approved copy of the spec, and echoed first) shows only the status line, the disk-rule line and the "builder's call" lines.
+
+- [ ] **Step 6: Run the full checks on the branch and on its base, and compare**
+
+Run (the branch, then `origin/main` in a scratch worktree): `bash scripts/check.sh origin/main`
+Expected: `ALL CHECKS PASSED` on the branch. The tools tests line has the base's passed count plus the new tests, with the same skipped count. A failure that also appears on the base is PRE-EXISTING and is reported. A NEW failure blocks the PR.
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add tools/nightly_launch.py tools/nightly.plist.in tools/tests/test_nightly_launch.py tools/README.md docs/RELEASING.md changelog.d/nightly-release.md docs/superpowers/specs/2026-10-27-nightly-release-design.md docs/superpowers/plans/2026-10-27-nightly-release-plan.md
+git commit -m "nightly: launchd job at 03:00, install and release docs, spec and changelog"
+```
+
+---
+
+## After the PR merges (owner, not part of the PR)
+
+1. Install with the `tools/README.md` steps, then run the `--manual --no-publish` trial in the clone. Each REFUSED gate it prints is fixed before bootstrapping launchd.
+2. After the first PUBLISHED nightly, with `itch_page_url` set in `config.json`, run `uv run tools/nightly.py savetest --tag <that tag>` once.
diff --git a/docs/superpowers/specs/2026-10-27-nightly-release-design.md b/docs/superpowers/specs/2026-10-27-nightly-release-design.md
new file mode 100644
index 000000000..1aa5f2c90
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-27-nightly-release-design.md
@@ -0,0 +1,78 @@
+# Nightly release: design
+
+Status: Approved by the owner on 27 October 2026 ("Approve as written"). Built from docs/superpowers/plans/2026-10-27-nightly-release-plan.md.
+
+## Intent
+
+The owner, 27 October 2026: "we need a nightly build process that releases a version at a specific time every day. build that process and make sure it doesnt introduce any bugs, degregations or gaps." Asked who it is for and when, the owner chose "Public: website + itch" and "03:00 (Recommended)" (Israel time).
+
+So every night at 03:00 the newest `main` becomes the public game: the website's `/demo/` and the itch.io page. Because players get it with nobody watching, the process must refuse to publish anything worse than what is already live. A skipped night is acceptable; a broken public build is not.
+
+## Goals
+
+1. At 03:00 Asia/Jerusalem, build the current `origin/main` and, only if every gate passes, publish it to GitHub Releases (which updates the website demo through `site.yml`) and to itch.io.
+2. Gate each nightly at least as strictly as a normal release (docs/RELEASING.md steps 4-5 and 7), plus a no-regression comparison against the build that is live now.
+3. Leave a clear record each night: published, skipped (no change), or refused (which gate, with the log), in a place the coordinator reads.
+4. Never disturb the coordinator lanes or the Codex root: take the Unity and WebGL slots like any other job.
+
+## Non-goals
+
+- No desktop players in the nightly (the MVP release is web only, owner ruling 20 Oct 2026, #814). The Mac player can be added later.
+- No change to how versioned releases (v0.3.x) are made; they stay the owner-run process in docs/RELEASING.md.
+- No new gameplay or UI.
+
+## Anti-goals (a failure even if it "works")
+
+- Publishing a nightly that fails to boot, regresses load time, moves the goldens without a recorded reason, or contains an unreviewed sensitive item.
+- Publishing over a working public build when any gate could not run (missing disk, Unity busy for hours, screen-dependent check that could not execute). Unknown counts as fail.
+- A nightly that silently replaces the last real release as "Latest" on GitHub, or that leaves the website demo pointing at a broken zip.
+- Storing or printing the itch.io key or a GitHub token anywhere.
+
+## Constraints (verified 27 Oct 2026)
+
+- Unity is not in CI (AGENTS.md); WebGL builds run only on the owner's Mac with `tools/release_build.py`. The nightly therefore runs on this Mac, from a dedicated worktree, under `launchd`.
+- `scripts/oss/release_gate.sh` refuses to run except on the merged `main` and refuses while an owner decision is open, an asset is `owner-verify`/`licence: unknown`, the sensitivity gate refuses content, or the history scan has an open secret-shape row. The nightly runs it unchanged; if it refuses, the night is REFUSED (this is intended: it is the same bar as a release).
+- `site.yml` builds `/demo/` from the newest release in `gh release list` that has a `*-web-pages.zip`, but it has NO release trigger: it runs on a push to `main` touching its paths, or on `workflow_dispatch`. The nightly therefore starts the deploy itself (`gh workflow run site.yml`) and waits for it. v0.3.1 is a regular (Latest) release today; a newer nightly pre-release is still the newest list entry, so the site serves the nightly, which is what "Public: website + itch" asks for.
+- itch.io: `butler` is installed (`~/.local/bin/butler`) with saved credentials. docs/m3-release.md:330-332 says the itch upload is an owner step "never automated"; the owner's 27 Oct choice replaces that, and the doc is updated in the same PR.
+- `tools/web_check.py` runs Chrome in `--headless=new`, so it can run while the screen is locked; `tools/headed.py` checks cannot (a locked console stalls headed boots). The nightly uses only headless checks plus the boot/size measurements that do not need a visible window.
+- Disk: WebGL builds need >= 40 GB free at launch (the coordinator's disk rule). Below that the night is REFUSED, never "build anyway".
+- Hard rules apply: never spend money, no force-push, no history rewrite, merges only via merge.sh (the nightly never merges anything).
+
+## How it works (proposal)
+
+Nightly job, `tools/nightly.py`, started by a `launchd` agent at 03:00:
+
+1. **Preflight.** `git fetch`; if `origin/main` equals the commit of the last published nightly, record SKIPPED (no change) and stop. Check disk >= 40 GB, no `EXCLUSIVE-WINDOW` file, Unity licence available. Fail closed.
+2. **Prepare** a clean dedicated worktree at `origin/main` (reused nightly, `git reset --hard origin/main` inside that worktree only, never in shared checkouts).
+3. **Gates before building:** `bash scripts/check.sh` (with the Unity compile actually running), `bash scripts/oss/release_gate.sh` must print `RELEASE GATE OK`, sim tests under he_IL and en_US.
+4. **Unity:** warm-up, FULL EditMode (total > 0, 0 failures), through `unity_slots.py --webgl` and `machine_lock`, with the settings churn restored afterwards.
+5. **Build and package** exactly as docs/RELEASING.md step 5 (gzip, `--startscreen` passes, `tools/package_release.py`), both the `-web.zip` (itch, GitHub) and the `-web-pages.zip` (site demo). The build carries the version `X.Y.Z-nightly.YYYYMMDD` (base version from `SimInfo.cs`) in `bundleVersion` and the in-game label, stamped in the nightly worktree only AFTER `release_gate.sh` passed on the clean tree (builder's call): a per-night `bundleVersion` keeps returning players' browser cache from growing every night and makes bug reports name the nightly. The stamp is never committed.
+6. **No-regression checks:**
+ - `web_check.py` smoke (`golden&smoke=5`, `smoke-orders`) must pass on the built player.
+ - **Sizes** (owner, 27 Oct: "Budget in the PR (Recommended)"): refuse if data.gz + wasm.gz + framework grow more than 2% over the previous published nightly, unless a PR merged since then records the size increase in its body (the asset load-gate measurements); then the new size becomes the baseline.
+ - **Boot time** (owner: "Sizes + headless boot (Recommended)"): a new headless boot-time measurement (Chrome `--headless=new`, same flags every night, 3 runs, median) with its own baseline from the first nightly; refuse a slowdown beyond a bound measured from 5 baseline nights' spread (recorded in the nightly log, not invented). The visible-window `tools/headed.py boot` stays a PR gate.
+ - **Goldens:** a nightly never moves goldens; golden moves arrive only through reviewed PRs (their docs/determinism.md rows are checked at PR time), so the nightly only requires the golden tests in the FULL run to pass (builder's call).
+7. **Publish** only if every step passed, in this order so nothing public changes until both stores are verified:
+ a. `gh release create vX.Y.Z-nightly.YYYYMMDD --prerelease --draft` with the web zips and generated notes (commits since the previous nightly), never marked Latest; download the draft's assets and diff them against the local zips.
+ b. `butler push` the plain gzip `-web.zip` contents (the itch file per docs/RELEASING.md step 5 and docs/m3-release.md:347-350) to `eyalgolan/statecraft-israel:html5 --userversion X.Y.Z-nightly.YYYYMMDD`, then `butler status` must show the new build live.
+ c. Publish the draft (`gh release edit --draft=false`), then `gh workflow run site.yml` and wait for it to succeed; fetch `https://eyalgolan.github.io/statecraft-israel/demo/` and check it serves the new version.
+ d. On any failure after (b): push the previous nightly's (or release's) web build back to itch, delete the unpublished draft (a draft has no tag yet), and record REFUSED. If (c)'s site deploy fails after the release is public, re-run `site.yml` once; if it still fails, the demo keeps the previous deployment (Pages only switches on success) and the night is recorded REFUSED with an alert.
+8. **Record** one line per night (PUBLISHED / SKIPPED / REFUSED + gate + log path) in `~/israel-game/.superpowers/nightly/LOG.md` and the HANDOFF; on REFUSED send a desktop notification.
+9. **Retention:** no deletion of published nightly releases or tags (deleting public tags is avoided under the no-history-rewrite rule; builder's call). Revisit if the list becomes unwieldy.
+10. **itch save safety first** (owner, 27 Oct: "Automated save check (Recommended)"): before nightly itch pushes are enabled, build an automated two-upload save test against itch (save in build A, push build B, reload the itch page, confirm the save survives; docs/m3-release.md:354-388). Until it passes, the nightly publishes to GitHub and the site only, and skips itch with a logged reason.
+11. **Machine:** the Mac stays plugged in and awake (owner, 27 Oct: "Mac stays awake"); no wake schedule. If the job does not start by 03:30 (asleep, logged out), the next run reports the missed night.
+
+## Left to the builder
+
+- Exact structure of `tools/nightly.py`, its tests (pytest, with fakes for git/gh/butler/Unity), and the `launchd` plist.
+- Where the noise bound for sizes comes from (reuse the asset load gate's definition; do not invent a number).
+
+## Decisions recorded
+
+Owner, 27 Oct 2026: "Public: website + itch"; "03:00 (Recommended)"; "Automated save check (Recommended)"; "Sizes + headless boot (Recommended)"; "Budget in the PR (Recommended)"; "Mac stays awake".
+
+Coordinator's calls (owner to check): the nightly triggers `site.yml` itself; itch gets the plain `-web.zip`; draft-first publish order with rollback; per-night `bundleVersion` stamp after the gate; no deletion of nightlies; goldens gated only by the FULL run.
+
+## Docs to update in the same PR
+
+docs/RELEASING.md (a Nightly section) and docs/m3-release.md:330-332 (the itch upload is now automated for nightlies, per the owner's 27 Oct choice).
diff --git a/tools/README.md b/tools/README.md
index 0aa5aa8fb..4080f943a 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -114,7 +114,7 @@ Run from the repo root; this installs every pinned dependency (rasterio included
uv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 --with pyproj==3.8.0 pytest tools/tests -q
```
-Expected: `917 passed, 4 skipped` (two need skimage and scipy, and two are the headed browser checks; add `--headed` and `--with websockets==15.0.1` to run them). Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
+Expected: `1892 passed, 5 skipped, 1 xfailed` (one needs pypdf, two need skimage and scipy, and two are the headed browser checks; add `--headed` and `--with websockets==15.0.1` to run them; the xfail is the nightly's pending itch fixture). Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
## Required attribution (Copernicus DEM licence, modified data)
@@ -202,3 +202,64 @@ itself needs the `cp` again; a change to `unity_postmerge.py` does not.
Uninstall: `launchctl bootout gui/$(id -u)/com.statecraft.unity-postmerge`, then delete the plist. To remove the
worktree too: `git worktree remove --force ~/.cache/statecraft/unity-postmerge/worktree`. A trial without opening an
issue or moving the state: `uv run tools/unity_postmerge.py --dry-run --home <scratch folder>`.
+
+## Nightly release
+
+`tools/nightly.py` builds the newest `main` every night and publishes it when every gate passes; the gates, the outputs
+and what is public are in `docs/RELEASING.md`, "Nightly builds". It runs on the owner's Mac from a launchd job
+(`tools/nightly.plist.in`) at 03:00, and the Mac has to be awake.
+- launchd starts `nightly_launch.py` (a copy in the job folder, `~/israel-game/.superpowers/nightly`, next to a copy of
+ `nightly_state.py`). It fetches `origin/main` into the job's own clone (`~/.cache/statecraft/nightly/repo`), resets
+ that clone to it (`checkout main`, `reset --hard`, `clean -ffdx` keeping the Unity Library and the NuGet plugin
+ download) and runs `tools/nightly.py run` from there. So a merged change to the script takes effect on the next
+ night, no checkout's working tree is used, and what Unity changed in the clone (`ProjectSettings.asset`,
+ `Assets/Settings`, the prickly pear material) is gone before the next night. A missing clone is a REFUSED line in
+ `LOG.md` (`gate=clone`); the launcher never clones. While a run is in progress it exits 0 and touches nothing.
+- The job folder holds `config.json` (optional; its keys are the fields of `Config` in `nightly_state.py`, and a wrong
+ one refuses the night), `state.json`, `LOG.md`, `runs/` (one folder per night with every step's log), `run.lock`,
+ `launchd.log` and `no-mcp-server`. A corrupt `config.json` or `state.json` refuses the night; it never counts as a
+ first 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, 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 public itch page twice and, on a
+ pass, turns `itch_enabled` on in `config.json`. `INCONCLUSIVE` and `FAIL` leave itch off.
+- The boot-time baseline is the median headless boot of the first 5 PUBLISHED nights; later nights must stay within
+ the spread of those 5. To measure it again (a new machine, a new Chrome), delete `boot_baseline` from `state.json`;
+ the next 5 published nights record it.
+
+Install (owner's Mac only, from a checkout of `main` that has these files):
+
+```bash
+job=~/israel-game/.superpowers/nightly
+clone=~/.cache/statecraft/nightly/repo
+mkdir -p "$job" "$(dirname "$clone")"
+git clone https://github.com/eyalgolan/statecraft-israel.git "$clone"
+cp -c -R ~/israel-game/unity/Library "$clone/unity/Library"
+cp tools/nightly_launch.py tools/nightly_state.py "$job/"
+sed -e "s#@UV@#$(command -v uv)#g" -e "s#@REPO@#$HOME/israel-game#g" -e "s#@HOME@#$job#g" \
+ -e "s#@PATH@#$(dirname "$(command -v uv)"):$(dirname "$(command -v gh)"):$(dirname "$(command -v dotnet)"):$(dirname "$(command -v git)"):$HOME/.local/bin:/usr/bin:/bin:/usr/sbin:/sbin#g" \
+ tools/nightly.plist.in > ~/Library/LaunchAgents/com.statecraft.nightly.plist
+plutil -lint ~/Library/LaunchAgents/com.statecraft.nightly.plist
+```
+
+Before loading it, run one night by hand without publishing, from the clone:
+
+```bash
+cd "$clone" && uv run tools/nightly.py run --manual --no-publish
+```
+
+It runs every gate and build, writes nothing to `LOG.md` or `state.json` and touches no store, and must end with
+`NO-PUBLISH: all gates passed for v<version>`. A run that ends `REFUSED` prints no reason (a by-hand run writes no
+`LOG.md` line); the step that stopped it has its log in the newest folder under `$job/runs/` (a refusal before the first step, such as disk,
+licence or the clone, leaves none). Fix that step first
+(`gh` and `butler` must be logged in, and the Unity licence and `unity_slots.py` must be where `Config` says), then
+run it again. Then:
+
+```bash
+launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.statecraft.nightly.plist
+```
+
+A change to `nightly_launch.py` or `nightly_state.py` needs the `cp` again; a change to `nightly.py` does not.
+
+Uninstall: `launchctl bootout gui/$(id -u)/com.statecraft.nightly`, then delete the plist. To remove the clone too,
+delete `~/.cache/statecraft/nightly/repo`.
diff --git a/tools/nightly.plist.in b/tools/nightly.plist.in
new file mode 100644
index 000000000..a64f2ae24
--- /dev/null
+++ b/tools/nightly.plist.in
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<!-- launchd job for tools/nightly.py. Filled in and installed by hand, outside the repository: see the "Nightly
+ release" section of tools/README.md. @UV@, @REPO@, @HOME@ and @PATH@ are replaced on install (@REPO@ is unused:
+ the job's config names the main checkout). It runs the launcher copied into the job folder (@HOME@), which
+ prepares the job's clone and runs tools/nightly.py from it. launchd runs the job at 03:00 local time (the Mac's
+ clock is Israel time) and never starts a second copy while one is running. -->
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>com.statecraft.nightly</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>@UV@</string>
+ <string>run</string>
+ <string>@HOME@/nightly_launch.py</string>
+ <string>--uv</string>
+ <string>@UV@</string>
+ <string>--home</string>
+ <string>@HOME@</string>
+ </array>
+ <key>WorkingDirectory</key>
+ <string>@HOME@</string>
+ <key>EnvironmentVariables</key>
+ <dict>
+ <key>PATH</key>
+ <string>@PATH@</string>
+ </dict>
+ <key>StartCalendarInterval</key>
+ <dict>
+ <key>Hour</key>
+ <integer>3</integer>
+ <key>Minute</key>
+ <integer>0</integer>
+ </dict>
+ <key>StandardOutPath</key>
+ <string>@HOME@/launchd.log</string>
+ <key>StandardErrorPath</key>
+ <string>@HOME@/launchd.log</string>
+</dict>
+</plist>
diff --git a/tools/nightly.py b/tools/nightly.py
new file mode 100644
index 000000000..9ecaa6724
--- /dev/null
+++ b/tools/nightly.py
@@ -0,0 +1,949 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+# ///
+"""The nightly release job: a bounded command runner, the preflight and the run skeleton (stdlib only).
+
+The job works in its own clone of the repository, because release_gate.sh refuses unless `main` is checked out and
+the owner's checkout already holds it. Every way a night can end early is a Stop from nightly_state; run_night turns
+each one, and any unexpected failure, into one line of record, so no night leaves without a trace."""
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import shutil
+import statistics
+import signal
+import subprocess
+import sys
+import time
+import urllib.parse
+import urllib.request
+import zipfile
+from dataclasses import dataclass, field
+from datetime import date, datetime
+from pathlib import Path
+from typing import Callable
+
+import nightly_checks
+import unity_postmerge
+from 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, base_version,
+ enable_itch, late_start, load_config, load_state, log_line, missed_days, night_of,
+ nightly_version, notify, record, run_lock, save_state, tag_for)
+from web_check import find_chrome
+
+HOLDER_ENV = unity_postmerge.machine_lock.HOLDER_ENV
+STAGE_ERRORS = (FileNotFoundError, OSError, subprocess.SubprocessError)
+
+
+# --- the runner -------------------------------------------------------------------------------------------------
+
+class ProcRunner(Runner):
+ """Runs the job's real commands. `grace` is the pause between SIGTERM and SIGKILL at the deadline."""
+
+ def __init__(self, grace: float = 60):
+ self.grace = grace
+
+ def run(self, cmd: list[str], *, cwd: Path, log: Path, deadline: float,
+ env: dict[str, str] | None = None, holder: Path | None = None) -> int:
+ full = dict(os.environ if env is None else env)
+ if holder is not None:
+ holder.unlink(missing_ok=True)
+ full[HOLDER_ENV] = str(holder)
+ Path(log).parent.mkdir(parents=True, exist_ok=True)
+ with open(log, "ab") as out:
+ proc = subprocess.Popen(cmd, cwd=cwd, stdout=out, stderr=subprocess.STDOUT, env=full,
+ start_new_session=True)
+ try:
+ return proc.wait(timeout=max(0.0, deadline - time.monotonic()))
+ except subprocess.TimeoutExpired:
+ pass
+ if holder is not None:
+ self._stop_holder(holder)
+ self._stop_group(proc)
+ return 124
+
+ def _stop_holder(self, record_file: Path) -> None:
+ """Stop the command machine_lock recorded (the Unity process), while it is still machine_lock's child."""
+ held = unity_postmerge._holder(record_file)
+ if held is None:
+ return
+ lock_pid, child = held
+ for sig in (signal.SIGTERM, signal.SIGKILL):
+ if unity_postmerge._parent(child) != lock_pid:
+ return
+ try:
+ os.kill(child, sig)
+ except ProcessLookupError:
+ return
+ end = time.monotonic() + self.grace
+ while unity_postmerge._parent(child) == lock_pid and time.monotonic() < end:
+ time.sleep(min(0.5, self.grace))
+
+ def _stop_group(self, proc: subprocess.Popen) -> None:
+ try:
+ os.killpg(proc.pid, signal.SIGTERM)
+ proc.wait(timeout=self.grace)
+ except (ProcessLookupError, subprocess.TimeoutExpired):
+ pass
+ try: # always: a member that ignores SIGTERM (a build's grandchild) must not outlive the deadline
+ os.killpg(proc.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ try:
+ proc.wait(timeout=self.grace + 5)
+ except subprocess.TimeoutExpired:
+ pass
+
+ def capture(self, cmd: list[str], *, cwd: Path, timeout: float = 300) -> str:
+ try:
+ p = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout)
+ except subprocess.TimeoutExpired as e:
+ raise Refused("command", f"{cmd[0]} timed out after {timeout:g}s") from e
+ if p.returncode:
+ raise Refused("command", f"{' '.join(cmd[:3])} exited {p.returncode}: {p.stderr.strip()[-300:]}")
+ return p.stdout
+
+
+# --- preflight --------------------------------------------------------------------------------------------------
+
+@dataclass
+class Night:
+ now: datetime
+ day: date
+ sha: str
+ version: str
+ tag: str
+ run_dir: Path
+ deadline: float
+ job: Path
+ cfg: Config
+ manifest: str
+ notes: list[str] = field(default_factory=list) # lines for the night's LOG.md entry
+
+
+def _git(runner: Runner, clone: Path, *args: str) -> str:
+ return runner.capture(["git", "-C", str(clone), *args], cwd=clone).strip()
+
+
+def _check_clone(runner: Runner, clone: Path) -> str:
+ branch = _git(runner, clone, "rev-parse", "--abbrev-ref", "HEAD")
+ sha = _git(runner, clone, "rev-parse", "HEAD")
+ origin = _git(runner, clone, "rev-parse", "refs/remotes/origin/main")
+ dirty = _git(runner, clone, "status", "--porcelain", "--untracked-files=no")
+ if branch != "main":
+ raise Refused("clone", f"the clone is on {branch!r}, not main")
+ if sha != origin:
+ raise Refused("clone", f"the clone is at {sha[:12]}, not origin/main {origin[:12]}")
+ if dirty:
+ raise Refused("clone", "the clone has uncommitted changes to tracked files")
+ return sha
+
+
+def _editor_version(clone: Path) -> str:
+ text = (clone / "unity/ProjectSettings/ProjectVersion.txt").read_text(encoding="utf-8")
+ m = re.search(r"^m_EditorVersion:\s*(\S+)\s*$", text, re.M)
+ if not m:
+ raise Refused("unity-editor", "no m_EditorVersion in ProjectVersion.txt")
+ return m.group(1)
+
+
+SITE_WAIT_SECONDS = 15 * 60
+BASELINE_NIGHTS = 5
+
+
+def preflight(cfg: Config, state: State, runner: Runner, gh: GitHub, *, job: Path, now: datetime, manual: bool,
+ free_gb: Callable[[Path], float], no_publish: bool = False) -> Night:
+ day = night_of(now)
+ if late_start(now, cfg.window_end) and not manual:
+ raise Missed(f"started after {cfg.window_end}")
+ clone = cfg.clone
+ sha = _check_clone(runner, clone)
+ last = state.last_published
+ if last is not None and sha == last.sha:
+ detail = f"main unchanged since {last.tag}"
+ if state.site_pending and not no_publish: # a deploy is a public change, so --no-publish never starts one
+ try:
+ gh.dispatch_site(time.monotonic() + SITE_WAIT_SECONDS)
+ demo_serves(cfg.site_demo_url, state.site_pending,
+ deadline=time.monotonic() + SITE_WAIT_SECONDS)
+ state.site_pending = None
+ detail += "; the pending site deploy now serves"
+ except Exception as e: # any error leaves the deploy pending for the next night, and the night skipped
+ detail += (f"; the pending site deploy still failed: "
+ f"{e.detail if isinstance(e, Stop) else f'{type(e).__name__}: {e}'}")
+ raise Skipped(detail)
+ free = free_gb(clone)
+ if free < cfg.min_free_gb:
+ raise Refused("disk", f"{free:.1f} GB free, {cfg.min_free_gb} GB needed")
+ if cfg.exclusive_marker.exists():
+ raise Refused("exclusive-window", f"{cfg.exclusive_marker} exists")
+ if not cfg.licence.is_file(): # stat only, never read
+ raise Refused("unity-licence", f"{cfg.licence} is missing")
+ editor = Path(unity_postmerge.unity_path(_editor_version(clone)))
+ if not editor.exists():
+ raise Refused("unity-editor", f"{editor} is missing")
+ if not cfg.unity_slots.is_file():
+ raise Refused("unity-slots", f"{cfg.unity_slots} is missing")
+ base = base_version((clone / "sim/Statecraft.Sim/SimInfo.cs").read_text(encoding="utf-8"))
+ version = nightly_version(base, day)
+ tag = tag_for(version)
+ release = gh.release_state(tag)
+ if release == "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 tonight
+ state.open_draft = None
+ elif release is not None:
+ raise Refused("tag-exists", f"a {release} release already has the tag {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")
+ return Night(now, day, sha, version, tag, run_dir, time.monotonic() + cfg.deadline_hours * 3600, job, cfg,
+ manifest)
+
+
+# --- gates, Unity and the full EditMode run ---------------------------------------------------------------------
+
+WARM_UP_OK = "UnityMcpGuard warm-up: gate defines in place"
+
+
+def _limit(night: Night, minutes: float) -> float:
+ return min(night.deadline, time.monotonic() + minutes * 60)
+
+
+def _step(night: Night, runner: Runner, name: str, cmd: list[str], minutes: float,
+ env: dict[str, str] | None = None) -> tuple[int, str]:
+ log = night.run_dir / f"{name}.log"
+ code = runner.run(cmd, cwd=night.cfg.clone, log=log, deadline=_limit(night, minutes), env=env)
+ return code, log.read_text(encoding="utf-8", errors="replace") if log.is_file() else ""
+
+
+def run_gates(night: Night, runner: Runner) -> None:
+ clone = night.cfg.clone
+ code, _ = _step(night, runner, "build-sim", ["uv", "run", str(clone / "tools/build_sim_for_unity.py")], 15)
+ if code != 0:
+ raise Refused("build-sim", "timed out" if code == 124 else f"build_sim_for_unity exited {code}")
+ code, text = _step(night, runner, "check", ["bash", "scripts/check.sh", "origin/main"], 45)
+ why = nightly_checks.check_sh_verdict(text, code)
+ if why:
+ raise Refused("check", "timed out" if code == 124 else why)
+ code, text = _step(night, runner, "release-gate", ["bash", "scripts/oss/release_gate.sh"], 60)
+ why = nightly_checks.release_gate_verdict(text, code)
+ if why:
+ raise Refused("release-gate", "timed out" if code == 124 else why)
+ for locale in ("he_IL", "en_US"):
+ lang = f"{locale}.UTF-8"
+ env = {**os.environ, "LANG": lang, "LC_ALL": lang}
+ code, text = _step(night, runner, f"sim-{locale}",
+ ["dotnet", "test", "sim/Statecraft.sln", "-c", "Release", "--nologo"], 30, env)
+ failed, total = nightly_checks.dotnet_totals(text)
+ if code == 124:
+ raise Refused(f"sim-{locale}", "timed out")
+ if code != 0 or failed or total == 0:
+ raise Refused(f"sim-{locale}", f"dotnet test exited {code}: {failed} failed of {total} tests")
+
+
+def unity_argv(night: Night, unity_args: list[str], *, webgl: bool) -> list[str]:
+ clone = night.cfg.clone
+ editor = unity_postmerge.unity_path(_editor_version(clone))
+ return ["python3", "-I", str(night.cfg.unity_slots), *(["--webgl"] if webgl else []), str(clone / "unity"), "--",
+ "uv", "run", str(clone / "tools/machine_lock.py"), "--shared", "--",
+ editor, "-batchmode", "-CI", "false", "-GITHUB_ACTIONS", "false", "-TF_BUILD", "false",
+ "-projectPath", str(clone / "unity"), *unity_args]
+
+
+def unity_env(night: Night) -> dict[str, str]:
+ empty = night.job / "no-mcp-server"
+ empty.parent.mkdir(parents=True, exist_ok=True)
+ empty.touch()
+ return {**os.environ, "UNITY_SLOTS": str(night.cfg.unity_slots_count), "UNITY_MCP_SERVER_PATH": str(empty)}
+
+
+def check_window(night: Night) -> None:
+ if night.cfg.exclusive_marker.exists():
+ raise Refused("exclusive-window", f"{night.cfg.exclusive_marker} appeared before a Unity step")
+
+
+# Unity 6000.3.25f1 flips m_DoubleSidedGI in this material during EditMode; left alone, assert_clean_tree refuses every night.
+CHURNED_MATERIAL = "unity/Assets/Art/HexTiles/Props/arab_village_prickly_pear/prickly_pear-rock.mat"
+RESTORE_ARGV = ["git", "checkout", "--", "unity/ProjectSettings", "unity/Assets/Settings", CHURNED_MATERIAL]
+
+
+def restore_settings(night: Night, runner: Runner) -> None:
+ """Unity rewrites project settings while it runs; put them back so the tree stays clean."""
+ code = runner.run(list(RESTORE_ARGV),
+ cwd=night.cfg.clone, log=night.run_dir / "restore-settings.log",
+ deadline=time.monotonic() + 120)
+ if code != 0:
+ raise Refused("restore-settings", f"git checkout of the Unity settings exited {code}")
+
+
+def _note_restore(night: Night, err: Refused) -> None:
+ note = f"restore-settings failed while another refusal was pending: {err.detail}"
+ print(note, file=sys.stderr)
+ (night.run_dir / "restore-settings.note").write_text(note + "\n", encoding="utf-8")
+
+
+def run_editmode(night: Night, runner: Runner) -> None:
+ env = unity_env(night)
+ xml = night.run_dir / "editmode.xml"
+ restore_error: Refused | None = None
+ pending = False
+ check_window(night) # before Unity has touched anything, so there is nothing to restore
+ try:
+ warm = unity_argv(night, ["-buildTarget", "OSXUniversal", "-executeMethod", unity_postmerge.WARM_UP,
+ "-logFile", str(night.run_dir / "warmup.log")], webgl=False)
+ warm_code = runner.run(warm, cwd=night.cfg.clone, log=night.run_dir / "warmup.out",
+ deadline=_limit(night, 60), env=env, holder=night.run_dir / "lock-holder")
+ if warm_code == 124:
+ raise Refused("editmode", "the Unity warm-up timed out")
+ warm_log = night.run_dir / "warmup.log"
+ warm_text = warm_log.read_text(encoding="utf-8", errors="replace") if warm_log.is_file() else ""
+ if warm_code != 0 or WARM_UP_OK not in warm_text:
+ raise Refused("editmode", f"the Unity warm-up failed or did not confirm (exit {warm_code})")
+ check_window(night)
+ argv = unity_argv(night, ["-buildTarget", "OSXUniversal", "-runTests", "-testPlatform", "EditMode",
+ "-testResults", str(xml), "-logFile", str(night.run_dir / "editmode.log")],
+ webgl=False)
+ code = runner.run(argv, cwd=night.cfg.clone, log=night.run_dir / "editmode.out",
+ deadline=_limit(night, 150), env=env, holder=night.run_dir / "lock-holder")
+ except BaseException:
+ pending = True
+ raise
+ finally:
+ try:
+ restore_settings(night, runner)
+ except Refused as e:
+ restore_error = e
+ if restore_error is not None and pending:
+ _note_restore(night, restore_error) # never replace the error already on its way
+ restore_error = None
+ results = unity_postmerge.parse_results(xml)
+ if not unity_postmerge.passed(results, code):
+ why = ("timed out" if code == 124 else results.broken
+ or f"exit {code}, {results.failed} failed of {results.total} tests")
+ if restore_error is not None:
+ _note_restore(night, restore_error)
+ raise Refused("editmode", why)
+ if restore_error is not None:
+ raise restore_error
+
+
+# --- the version stamp, the two web builds and packaging ---------------------------------------------------------
+
+SETTINGS_ASSET = "unity/ProjectSettings/ProjectSettings.asset"
+BUNDLE_VERSION_RE = re.compile(r"^( bundleVersion: )\S+$", re.M)
+BUILD_WEB = ["-quit", "-buildTarget", "WebGL", "-executeMethod", "Statecraft.Game.EditorTools.Build.Web"]
+
+
+def stamp_bundle_version(settings: Path, version: str) -> None:
+ """Put tonight's version in the settings file; the stamp is never committed, restore_settings removes it."""
+ text = settings.read_text(encoding="utf-8")
+ new, n = BUNDLE_VERSION_RE.subn(lambda m: m.group(1) + version, text)
+ if n != 1:
+ raise ValueError(f"expected exactly one bundleVersion line in {settings}, found {n}")
+ settings.write_text(new, encoding="utf-8")
+
+
+BUILD_FAILURE_RE = re.compile(r"error CS\d+|Build completed with a result of 'Failed'|BuildFailedException|"
+ r"\bException\b|Fatal Error|Aborting batchmode", re.I)
+
+
+def _build_failure_detail(log: Path) -> str:
+ """The last few error lines of Unity's own log, so the record says why a build failed."""
+ try:
+ text = log.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ return " (no Unity log was written)"
+ lines = [ln.strip()[:160] for ln in text.splitlines() if BUILD_FAILURE_RE.search(ln)]
+ return f": {' | '.join(lines[-3:])}" if lines else " (no error line in the Unity log)"
+
+
+def build_web(night: Night, runner: Runner, *, pages: bool, free_gb: Callable[[Path], float]) -> Path:
+ """One WebGL build as in RELEASING step 5: gzip for GitHub Releases and itch, or the Pages variant."""
+ clone = night.cfg.clone
+ free = free_gb(clone)
+ if free < night.cfg.min_free_gb:
+ raise Refused("disk", f"{free:.1f} GB free, {night.cfg.min_free_gb} GB needed before a WebGL build")
+ check_window(night)
+ name = "Web-pages" if pages else "Web-gzip"
+ build = clone / "unity/Builds" / name
+ shutil.rmtree(build, ignore_errors=True) # a page left by an earlier run must not pass the stamp check
+ log = night.run_dir / f"unity-build-web-{'pages' if pages else 'gz'}.log"
+ args = [*BUILD_WEB, "-compression", "gzip"]
+ if pages:
+ args += ["-decompressionFallback", "-shareable", "-out", f"Builds/{name}"]
+ else:
+ args += ["-shareable"]
+ args += ["-logFile", str(log.resolve())]
+ env = unity_env(night)
+ restore_error: Refused | None = None
+ pending = False
+ code = 0
+ try:
+ try:
+ stamp_bundle_version(clone / SETTINGS_ASSET, night.version)
+ except ValueError as e:
+ raise Refused("version-stamp", str(e)) from e
+ code = runner.run(unity_argv(night, args, webgl=True), cwd=clone,
+ log=night.run_dir / f"unity-build-web-{'pages' if pages else 'gz'}.out",
+ deadline=_limit(night, 120), env=env, holder=night.run_dir / "lock-holder")
+ except BaseException:
+ pending = True
+ raise
+ finally:
+ try:
+ restore_settings(night, runner)
+ except Refused as e:
+ restore_error = e
+ if restore_error is not None and pending:
+ _note_restore(night, restore_error) # never replace the error already on its way
+ restore_error = None
+ if code != 0:
+ if restore_error is not None:
+ _note_restore(night, restore_error)
+ if code == 124:
+ raise Refused("build-web", "the Unity build timed out")
+ raise Refused("build-web", f"the Unity build exited {code}{_build_failure_detail(log)}")
+ if restore_error is not None:
+ raise restore_error
+ index = build / "index.html"
+ page = index.read_text(encoding="utf-8", errors="replace") if index.is_file() else ""
+ built = nightly_checks.product_version(page)
+ if built != night.version:
+ raise Refused("version-stamp", f"{name}/index.html says {built!r}, tonight's version is {night.version!r}")
+ return build
+
+
+def package_zip(night: Night, runner: Runner, build: Path, pages: bool) -> Path:
+ zip_path = night.run_dir / f"statecraft-israel-v{night.version}-web{'-pages' if pages else ''}.zip"
+ code, text = _step(night, runner, f"package-{'pages' if pages else 'gz'}",
+ ["bash", "scripts/oss/package_web.sh", str(build), str(zip_path)], 20)
+ if code != 0:
+ raise Refused("package", "timed out" if code == 124 else f"package_web.sh exited {code}")
+ if "PACKAGED " not in text or "OK: notices inside" not in text:
+ raise Refused("package", "package_web.sh did not confirm the zip and its notices")
+ return zip_path
+
+
+def assert_clean_tree(night: Night, runner: Runner) -> None:
+ dirty = _git(runner, night.cfg.clone, "status", "--porcelain", "--untracked-files=no")
+ if dirty:
+ raise Refused("dirty-tree", f"the clone has tracked changes after the builds: {dirty[:200]}")
+
+
+# --- the no-regression checks: web_check passes, download size, headless boot -------------------------------------
+
+def run_web_checks(night: Night, runner: Runner, build: Path) -> None:
+ """Every RELEASING step 5 pass on one build, under the shared machine lock; each must exit 0 and print PASS:."""
+ clone = night.cfg.clone
+ try:
+ passes = nightly_checks.web_check_passes(build, night.manifest)
+ except ValueError as e:
+ raise Refused("web-check", str(e)) from e
+ for i, args in enumerate(passes, 1):
+ argv = ["uv", "run", str(clone / "tools/machine_lock.py"), "--shared", "--",
+ "uv", "run", str(clone / "tools/web_check.py"), *args]
+ code, text = _step(night, runner, f"web-check-{build.name}-{i}", argv, 10)
+ if code == 124:
+ raise Refused("web-check", f"{build.name} pass {i} timed out")
+ if code != 0 or not re.search(r"^PASS:", text, re.M):
+ raise Refused("web-check", f"{build.name} pass {i} exited {code} without a PASS line")
+
+
+def check_sizes(night: Night, gh: GitHub, build: Path, previous_zip: Path, prev_sha: str | None, *,
+ runner: Runner) -> dict[str, int]:
+ """Refuse when the download grew more than 2% over the previous published build, unless the PRs merged since
+ then record a size budget. Returns the new sizes, which become the next night's baseline."""
+ try:
+ if not Path(previous_zip).is_file():
+ raise Refused("sizes", "no baseline: the previous published web zip is missing")
+ old = nightly_checks.web_sizes_from_zip(previous_zip)
+ new = nightly_checks.web_sizes(build)
+ except (ValueError, OSError, zipfile.BadZipFile) as e:
+ raise Refused("sizes", f"cannot measure the download size: {e}") from e
+ if nightly_checks.size_verdict(old, new, 0) is None:
+ return new
+ if prev_sha is None:
+ raise Refused("sizes", "the download grew and the previous published commit is unknown, so no budget can be read")
+ shas = set(_git(runner, night.cfg.clone, "rev-list", f"{prev_sha}..{night.sha}").split())
+ budget = nightly_checks.size_budget_bytes(gh.merged_pr_bodies(shas))
+ why = nightly_checks.size_verdict(old, new, budget)
+ if why:
+ raise Refused("sizes", why)
+ return new
+
+
+def measure_boot(night: Night, runner: Runner, build: Path) -> float:
+ """The median of three headless boots, each alone on the machine (no other Unity, no other check)."""
+ clone = night.cfg.clone
+ runs: list[int] = []
+ for i in (1, 2, 3):
+ argv = ["uv", "run", str(clone / "tools/machine_lock.py"), "--exclusive", "--wait-unity", "--timeout", "2700",
+ "--", "uv", "run", str(clone / "tools/web_check.py"), str(build), "--query", "bootlog",
+ "--expect", "GAME OK", "--timeout", "300", "--stall", "90"]
+ log = night.run_dir / f"boot-{i}.log"
+ code = runner.run(argv, cwd=night.cfg.main_repo, log=log, deadline=_limit(night, 60))
+ text = log.read_text(encoding="utf-8", errors="replace") if log.is_file() else ""
+ if code == 124:
+ raise Refused("boot", f"boot run {i} timed out")
+ if code == 3:
+ raise Refused("boot", f"boot run {i}: another Unity was still running after 45 minutes")
+ if code != 0:
+ raise Refused("boot", f"boot run {i} exited {code}")
+ try:
+ runs.append(nightly_checks.boot_ms(text))
+ except ValueError as e:
+ raise Refused("boot", f"boot run {i}: {e}") from e
+ return float(statistics.median(runs))
+
+
+# --- publishing -------------------------------------------------------------------------------------------------
+
+def previous_build(night: Night, state: State, gh: GitHub, runner: Runner) -> tuple[str, str | None]:
+ """The tag of the build tonight is compared with, and its commit when known (None blocks a size budget lookup)."""
+ last = state.last_published
+ tag = gh.previous_build_tag(last.tag if last else None)
+ if last is not None:
+ return tag, last.sha
+ # the first night: the release's commit, so the clone needs its tag; a failed fetch refuses, it is not guessed
+ _git(runner, night.cfg.clone, "fetch", "--no-tags", "origin", f"refs/tags/{tag}:refs/tags/{tag}")
+ return tag, _git(runner, night.cfg.clone, "rev-list", "-n", "1", f"refs/tags/{tag}") or None
+
+
+def _drop_draft(night: Night, state: State, gh: GitHub) -> None:
+ """Delete tonight's draft if it is still one. A failure here never replaces the refusal that caused it."""
+ try:
+ present = gh.release_state(night.tag)
+ if present == "draft":
+ gh.delete_draft(night.tag)
+ if present != "published":
+ state.open_draft = None
+ except Exception as e:
+ print(f"could not delete the draft {night.tag}: {e}", file=sys.stderr) # open_draft stays, so a rerun cleans it
+
+
+ITCH_WAIT_SECONDS = 15 * 60
+
+
+def _detail(e: BaseException) -> str:
+ return e.detail if isinstance(e, Stop) else f"{type(e).__name__}: {e}"
+
+
+def _itch_rollback(night: Night, itch, folder: Path, version: str) -> str:
+ """Put the previous build back on itch and wait until it is live. Returns "" on success, otherwise a sentence
+ for the refusal detail: a failed rollback leaves the public itch page possibly broken, so it is also notified."""
+ try:
+ itch.push(folder, version)
+ itch.wait_live(version, time.monotonic() + ITCH_WAIT_SECONDS)
+ return ""
+ except Exception as e:
+ note = (f"; the itch rollback to {version} failed ({_detail(e)}), so the public itch page may be broken: "
+ "check it by hand")
+ print(f"itch rollback failed: {_detail(e)}", file=sys.stderr)
+ notify("Nightly itch rollback failed", f"{night.tag}: the itch rollback failed, the public itch page may be broken"[:200])
+ return note
+
+
+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],
+ 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
+ kill leaves a record of both."""
+ prev_tag, prev_sha = previous
+ use_itch = night.cfg.itch_enabled
+ if use_itch and itch is None: # before any store change: enabled means the push is part of this night
+ raise Refused("itch", "itch is enabled but there is no itch client")
+ since = prev_sha or prev_tag
+ subjects = [ln for ln in _git(runner, night.cfg.clone, "log", "--format=%s", f"{since}..{night.sha}").splitlines()
+ if ln]
+ notes = night.run_dir / "release-notes.md"
+ notes.write_text(release_notes(version=night.version, sha=night.sha, since=since, subjects=subjects,
+ sha256_lines=sha256_lines(list(zips))), encoding="utf-8")
+ state.open_draft = night.tag # set first: a half-made draft is then recognised and cleaned by a rerun
+ try:
+ gh.create_draft(night.tag, night.sha, notes, list(zips))
+ save()
+ gh.verify_draft(night.tag, list(zips), night.run_dir / "draft-download")
+ except Exception as e:
+ _drop_draft(night, state, gh)
+ raise Refused("github-draft", e.detail if isinstance(e, Stop) else f"{type(e).__name__}: {e}") from e
+ except BaseException:
+ _drop_draft(night, state, gh)
+ raise
+ rollback_folder: Path | None = None
+ rollback_version = prev_tag[1:] if prev_tag.startswith("v") else prev_tag
+ if use_itch:
+ try: # the way back is ready before anything is pushed
+ previous_zip = gh.download(prev_tag, "*-web.zip", night.run_dir / "itch-rollback-zip")
+ rollback_folder = unzip_to(previous_zip, night.run_dir / "itch-rollback")
+ except Exception as e:
+ _drop_draft(night, state, gh)
+ raise Refused("itch-rollback", f"the previous build {prev_tag} cannot be prepared: {_detail(e)}") from e
+ except BaseException:
+ _drop_draft(night, state, gh)
+ raise
+ pushed = False
+ try:
+ folder = unzip_to(zips[0], night.run_dir / "itch-push")
+ pushed = True # from here a push may have reached itch, even if it then raises
+ itch.push(folder, night.version)
+ itch.wait_live(night.version, time.monotonic() + ITCH_WAIT_SECONDS)
+ itch.matches(folder, night.run_dir / "itch-fetch")
+ except Exception as e:
+ detail = _detail(e)
+ if pushed:
+ detail += _itch_rollback(night, itch, rollback_folder, rollback_version)
+ _drop_draft(night, state, gh)
+ raise Refused("itch", detail) from e
+ except BaseException:
+ if pushed:
+ _itch_rollback(night, itch, rollback_folder, rollback_version)
+ _drop_draft(night, state, gh)
+ raise
+ try:
+ gh.publish(night.tag, night.sha)
+ except Exception as e:
+ detail = _detail(e)
+ if rollback_folder is not None: # itch must not keep a build the release does not have
+ detail += _itch_rollback(night, itch, rollback_folder, rollback_version)
+ try:
+ now_state = gh.release_state(night.tag)
+ except Exception:
+ now_state = "unknown"
+ if now_state == "draft":
+ _drop_draft(night, state, gh)
+ elif now_state in ("published", "unknown"):
+ detail += f" (the release may be public: check {night.tag} by hand)"
+ raise Refused("github-publish", detail) from e
+ except BaseException: # an interrupt: the same cleanup, then on with the interrupt
+ if rollback_folder is not None:
+ _itch_rollback(night, itch, rollback_folder, rollback_version)
+ _drop_draft(night, state, gh)
+ raise
+ state.open_draft = None
+ state.last_published = Published(night.tag, night.sha, night.version, sizes, boot)
+ if len(state.boot_baseline) < BASELINE_NIGHTS:
+ state.boot_baseline.append(boot)
+ state.site_pending = night.version # until the demo serves this version, a later night retries the deploy
+ save()
+ if not use_itch:
+ skip = "itch: skipped (save test not passed)"
+ print(skip)
+ night.notes.append(skip)
+ failure = "no attempt"
+ for _ in range(2): # the release is public already, so one more try before the demo is left on the old build
+ try:
+ gh.dispatch_site(time.monotonic() + SITE_WAIT_SECONDS)
+ demo_serves(night.cfg.site_demo_url, night.version, deadline=time.monotonic() + SITE_WAIT_SECONDS)
+ state.site_pending = None
+ return
+ except Exception as e: # any error here leaves the release public, so it must end as a site refusal
+ failure = e.detail if isinstance(e, Stop) else f"{type(e).__name__}: {e}"
+ raise Refused("site", f"{night.tag} is public and the demo is unchanged: {failure}")
+
+
+# --- the night --------------------------------------------------------------------------------------------------
+
+def _build_both(night: Night, runner: Runner, free_gb: Callable[[Path], float]) -> tuple[Path, Path]:
+ """The gzip and Pages builds. The tree is checked after them, and also after a failed one, so the record says
+ whether the settings came back."""
+ try:
+ gz = build_web(night, runner, pages=False, free_gb=free_gb)
+ pages = build_web(night, runner, pages=True, free_gb=free_gb)
+ except BaseException:
+ try:
+ assert_clean_tree(night, runner)
+ except Exception as e: # never replace the build failure on its way
+ note = f"the tree was not clean after a failed build: {e}"
+ print(note, file=sys.stderr)
+ (night.run_dir / "dirty-tree.note").write_text(note + "\n", encoding="utf-8")
+ raise
+ assert_clean_tree(night, runner)
+ return gz, pages
+
+
+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:
+ """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)
+ gz, pages = _build_both(night, runner, free_gb)
+ zips = (package_zip(night, runner, gz, False), package_zip(night, runner, pages, True))
+ run_web_checks(night, runner, gz)
+ run_web_checks(night, runner, pages)
+ previous = previous_build(night, state, gh, runner) # once a night, shared with the notes
+ prev_tag, prev_sha = previous
+ previous_zip = gh.download(prev_tag, "*-web.zip", night.run_dir / "previous")
+ sizes = check_sizes(night, gh, gz, previous_zip, prev_sha, runner=runner)
+ boot = measure_boot(night, runner, gz)
+ phase, why = nightly_checks.boot_verdict(boot, state.boot_baseline, BASELINE_NIGHTS)
+ if why:
+ raise Refused("boot", why)
+ print(f"boot: {boot:.0f} ms ({phase}, {len(state.boot_baseline)} baseline nights)")
+ if no_publish:
+ print(f"NO-PUBLISH: all gates passed for {night.tag}")
+ return False
+ publish_night(night, state, gh, itch, zips, sizes, boot, previous=previous, save=save, runner=runner)
+ return True
+
+
+def _try_save(state_path: Path, state: State) -> None:
+ try:
+ save_state(state_path, state)
+ except OSError as e: # never costs the night its record, and the final save tries again
+ print(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
+
+
+def run_night(cfg: Config, state_path: Path, job: Path, runner: Runner, gh: GitHub | None, itch, *, now: datetime,
+ manual: bool, no_publish: bool, client_error: Refused | None = None,
+ free_gb: Callable[[Path], float] = lambda p: shutil.disk_usage(p).free / 1e9) -> str:
+ outcome, gate, detail = "REFUSED", "internal", ""
+ state: State | None = None
+ night: Night | None = None
+ day = night_of(now)
+ try:
+ try:
+ state = load_state(state_path)
+ if not no_publish:
+ for gap in missed_days(state.last_run_day, day):
+ stamp = datetime(gap.year, gap.month, gap.day, tzinfo=TZ)
+ record(job / "LOG.md", cfg.handoff,
+ log_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")
+ 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,
+ save=lambda: _try_save(state_path, state))
+ outcome, gate = ("PUBLISHED" if published else "NO-PUBLISH"), "-"
+ except Stop as e:
+ outcome, gate, detail = e.outcome, e.gate, e.detail
+ except STAGE_ERRORS as e:
+ stage = "preflight" if night is None else "run"
+ outcome, gate, detail = "REFUSED", stage, str(e)
+ except KeyboardInterrupt:
+ outcome, gate, detail = "REFUSED", "interrupted", "interrupted"
+ raise
+ except Exception as e: # fail closed with a record, never a silent crash
+ outcome, gate, detail = "REFUSED", "internal", f"{type(e).__name__}: {e}"
+ finally:
+ if not no_publish:
+ 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,
+ gate=gate, log=night.run_dir if night else None)
+ record(job / "LOG.md", cfg.handoff, f"{line} {detail}".rstrip() if detail else line)
+ if state is not None: # after the record, so a failed save never costs the night its line
+ state.last_run_day = day.isoformat()
+ _try_save(state_path, state)
+ if outcome == "REFUSED":
+ notify("Nightly refused", f"{gate}: {detail}"[:200])
+ return outcome
+
+
+# --- 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)
+SAVETEST_FRAME_TRIES = 20 # the page names a new upload's frame a little after butler shows the build live
+SAVETEST_FRAME_SLEEP = 30
+SAVETEST_RUN_MINUTES = 10
+TOOLS = Path(__file__).resolve().parent
+
+
+def _page_text(fetch, url: str) -> str:
+ 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 _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 tries run out."""
+ found = None
+ for attempt in range(SAVETEST_FRAME_TRIES):
+ found = itch_frame_url(_page_text(fetch, page_url))
+ if found is not None and found != other:
+ return found
+ if attempt + 1 < SAVETEST_FRAME_TRIES:
+ sleep(SAVETEST_FRAME_SLEEP)
+ return found
+
+
+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 _frame_check(runner: Runner, job_dir: Path, name: str, url: str, profile: Path, *extra: str) -> tuple[int, str]:
+ """web_check on one itch game-frame URL, in the savetest's one kept Chrome profile, under the shared machine lock."""
+ argv = ["uv", "run", str(TOOLS / "machine_lock.py"), "--shared", "--", "uv", "run", str(TOOLS / "web_check.py"),
+ "--url", url, "--profile", str(profile), "--timeout", "420", *extra]
+ log = job_dir / f"{name}.log"
+ code = runner.run(argv, cwd=TOOLS, log=log, deadline=time.monotonic() + SAVETEST_RUN_MINUTES * 60)
+ return code, log.read_text(encoding="utf-8", errors="replace") if log.is_file() else ""
+
+
+def savetest(cfg: Config, config_path: Path, job: Path, runner: Runner, gh: GitHub, itch: Itch, *, tag: str,
+ fetch=urllib.request.urlopen, sleep: Callable[[float], None] = time.sleep) -> str:
+ """The two-upload save test of docs/m3-release.md: upload A, play a turn and let the autosave commit; upload B
+ (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 to the PUBLIC itch page twice, so only the owner starts it."""
+ stamp = datetime.now(TZ).strftime("%Y%m%d-%H%M%S")
+ work = Path(job) / "savetest" / stamp
+ evidence: dict = {"tag": tag, "page_url": cfg.itch_page_url, "target": cfg.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}"
+ 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")
+ if result == "PASS":
+ enable_itch(config_path, work / "evidence.json")
+ record(Path(job) / "LOG.md", cfg.handoff, f"SAVETEST {result} tag={tag} {detail}".rstrip())
+ return result
+
+
+def _savetest(cfg: Config, work: Path, runner: Runner, gh: GitHub, itch: Itch, tag: str, evidence: dict, fetch,
+ sleep) -> tuple[str, str]:
+ """(result, detail) of the test; a Refused or OSError out of it is the caller's INCONCLUSIVE."""
+ if not cfg.itch_page_url:
+ return "INCONCLUSIVE", "itch_page_url is not set in the job's config"
+ state = gh.release_state(tag)
+ if state != "published":
+ return "INCONCLUSIVE", f"{tag} is {state or 'not a release'}, the save test needs a published nightly"
+ evidence["chrome"] = str(find_chrome())
+ work.mkdir(parents=True, exist_ok=True)
+ version = tag[1:] if tag.startswith("v") else tag
+ zip_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")
+ 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.itch_page_url)
+ evidence.update(upload_a={"build_id": itch.live_build_id(), "frame_url": frame_a})
+ if frame_a is None:
+ return "INCONCLUSIVE", "the itch page names no game frame after upload A"
+ code, 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:
+ return "INCONCLUSIVE", f"upload A did not reach a durable first save (web_check exited {code})"
+ tuple_a = {"date": saved.group(1), "turn": int(saved.group(2)), "hash": saved.group(3)}
+ evidence["tuple"] = tuple_a
+
+ itch.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.itch_page_url, other=frame_a)
+ evidence.update(upload_b={"build_id": itch.live_build_id(), "frame_url": frame_b})
+ 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"
+
+ expect = f"GAME OK {tuple_a['date']} turn {tuple_a['turn']} hash {tuple_a['hash']}"
+ for n in (1, 2):
+ code, text = _frame_check(runner, work, f"b-load-{n}", frame_b, profile, "--expect", expect)
+ if code == 124:
+ return "INCONCLUSIVE", f"load {n} of upload B timed out"
+ if code != 0 or not re.search(r"^PASS:", text, re.M):
+ return "FAIL", f"load {n} of upload B did not show '{expect}' (web_check exited {code})"
+ return "PASS", f"upload B shows '{expect}' on two loads"
+
+
+# --- command line -----------------------------------------------------------------------------------------------
+
+def _clients(cfg: Config):
+ """(GitHub, itch). itch is an Itch client only when the config enables it, else None and the night skips itch."""
+ try:
+ if shutil.which("gh") is None:
+ raise Refused("github-client", "gh is not on PATH")
+ runner = ProcRunner()
+ itch = None
+ if cfg.itch_enabled:
+ if not Path(cfg.butler).is_file():
+ raise Refused("itch-client", f"itch is enabled but {cfg.butler} is missing")
+ itch = Itch(runner, cfg.butler, cfg.itch_target)
+ return GitHub(runner, cfg.repo_slug, cfg.clone), itch
+ except Refused:
+ raise
+ except Exception as e:
+ raise Refused("github-client", f"{type(e).__name__}: {e}") from e
+
+
+def run_savetest(cfg: Config, job: Path, tag: str) -> int:
+ """The savetest command: real clients (butler is needed whether or not itch is enabled yet); 0 only on PASS."""
+ try:
+ if shutil.which("gh") is None:
+ raise Refused("github-client", "gh is not on PATH")
+ if not Path(cfg.butler).is_file():
+ raise Refused("itch-client", f"{cfg.butler} is missing")
+ runner = ProcRunner()
+ gh, itch = GitHub(runner, cfg.repo_slug, cfg.clone), Itch(runner, cfg.butler, cfg.itch_target)
+ except Refused as e:
+ print(e, file=sys.stderr)
+ return 1
+ result = savetest(cfg, job / "config.json", job, runner, gh, itch, tag=tag)
+ print(result)
+ return 0 if result == "PASS" else 1
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(prog="nightly.py")
+ sub = parser.add_subparsers(dest="command", required=True)
+ run = sub.add_parser("run")
+ run.add_argument("--manual", action="store_true")
+ run.add_argument("--no-publish", action="store_true")
+ test = sub.add_parser("savetest", help="the two-upload itch.io save test: pushes to the PUBLIC itch page twice")
+ test.add_argument("--tag", required=True, help="a published nightly release tag")
+ args = parser.parse_args(argv)
+ job = JOB
+ now = datetime.now(TZ)
+ try:
+ cfg = load_config(job / "config.json")
+ except Refused as e: # a corrupt config is a recorded REFUSED night, not a first night on defaults
+ if not getattr(args, "no_publish", False): # the savetest command has no such flag
+ line = log_line(now, "REFUSED", tag=None, sha=None, gate=e.gate, log=None)
+ record(job / "LOG.md", Config().handoff, f"{line} {e.detail}")
+ notify("Nightly refused", str(e)[:200])
+ print(e, file=sys.stderr)
+ return 1
+ with run_lock(job) as held:
+ if not held:
+ print("another nightly run holds run.lock", file=sys.stderr)
+ return 1
+ if args.command == "savetest":
+ return run_savetest(cfg, job, args.tag)
+ client_error = None
+ try:
+ gh, itch = _clients(cfg)
+ except Refused as e: # run_night records the unusable client as a REFUSED night
+ gh = itch = None
+ client_error = e
+ outcome = run_night(cfg, job / "state.json", job, ProcRunner(), gh, itch, now=now, manual=args.manual,
+ no_publish=args.no_publish, client_error=client_error)
+ print(outcome)
+ return 1 if outcome == "REFUSED" else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/nightly_checks.py b/tools/nightly_checks.py
new file mode 100644
index 000000000..704e87d83
--- /dev/null
+++ b/tools/nightly_checks.py
@@ -0,0 +1,205 @@
+"""Parsers for the summaries the gates print (stdlib only). Each verdict is None for a pass, otherwise the reason.
+Anything missing or unrecognised counts as a failure, never a pass."""
+from __future__ import annotations
+
+import re
+import zipfile
+from fractions import Fraction
+from pathlib import Path
+
+import package_release
+
+DOTNET_RE = re.compile(r"(?:Passed|Failed)!\s+-\s+Failed:\s+(\d+),\s+Passed:\s+\d+,\s+Skipped:\s+\d+,\s+Total:\s+(\d+)")
+COMPILE_RAN = "== unity compile (dotnet, outside Unity)"
+
+
+def dotnet_totals(text: str) -> tuple[int, int]:
+ """(failed, total) summed over every test project's summary line."""
+ failed = total = 0
+ for m in DOTNET_RE.finditer(text):
+ failed += int(m.group(1))
+ total += int(m.group(2))
+ return failed, total
+
+
+def check_sh_verdict(text: str, code: int) -> str | None:
+ if code != 0:
+ return f"check.sh exited {code}"
+ if "unity compile: SKIPPED" in text:
+ return "check.sh SKIPPED the Unity compile, so the gate did not run"
+ if COMPILE_RAN not in text:
+ return "check.sh never ran the Unity compile"
+ if "ALL CHECKS PASSED" not in text:
+ return "check.sh did not print ALL CHECKS PASSED"
+ return None
+
+
+def release_gate_verdict(text: str, code: int) -> str | None:
+ if code != 0:
+ return f"release_gate.sh exited {code}"
+ if "RELEASE GATE OK" not in text:
+ return "release_gate.sh did not print RELEASE GATE OK"
+ return None
+
+
+PRODUCT_VERSION_RE = re.compile(r'productVersion:\s*"([^"]*)"')
+
+
+def product_version(index_html: str) -> str | None:
+ """The version the WebGL template printed into a built index.html, or None when the page has none."""
+ m = PRODUCT_VERSION_RE.search(index_html)
+ return m.group(1) if m else None
+
+
+# --- the web checks of RELEASING step 5 ---------------------------------------------------------------------------
+
+def _manifest_goldens(manifest: str) -> list[tuple[str, str]]:
+ """(name, hash) of every non-comment manifest line, as the RELEASING step 5 loop reads them."""
+ rows = []
+ for line in manifest.splitlines():
+ parts = line.split()
+ if parts and not parts[0].startswith("#"):
+ rows.append((parts[0], parts[1] if len(parts) > 1 else ""))
+ return rows
+
+
+def _golden_hash(manifest: str, name: str) -> str:
+ for n, h in _manifest_goldens(manifest):
+ if n == name and h:
+ return h
+ raise ValueError(f"the golden manifest has no {name} line")
+
+
+def golden_expects(manifest: str) -> list[str]:
+ return [f"GOLDEN OK {n} {h}" for n, h in _manifest_goldens(manifest)]
+
+
+def smoke_expect(manifest: str) -> str:
+ return f"SMOKE OK 5 turns 1948-10-15 {_golden_hash(manifest, 'smoke5')}"
+
+
+def smoke_orders_expect(manifest: str) -> str:
+ return f"SMOKE ORDERS OK 1948-06-15 {_golden_hash(manifest, 'smoke-orders')}"
+
+
+def web_check_passes(build: Path, manifest: str) -> list[list[str]]:
+ """The arguments after web_check.py for every pass of RELEASING step 5, plus the smoke-orders golden."""
+ b = str(build)
+ steady = ["--timeout", "300", "--stall", "90"]
+ golden = [b, "--query", "golden&smoke=5"]
+ for g in golden_expects(manifest):
+ golden += ["--expect", g]
+ golden += ["--expect", smoke_expect(manifest)]
+ return [golden,
+ [b, "--query", "smoke-orders", "--expect", smoke_orders_expect(manifest)],
+ [b, "--startscreen", "new", *steady],
+ [b, "--startscreen", "recording", *steady],
+ [b, "--startscreen", "new", "--query", "lang=he", *steady],
+ [b, "--startscreen", "recording", "--query", "lang=he", *steady],
+ [b, "--persistence", *steady]]
+
+
+# --- download size ---------------------------------------------------------------------------------------------------
+
+SIZE_KINDS = {"data": ".data.gz", "wasm": ".wasm.gz", "framework": ".framework.js.gz"}
+BUDGET_RE = re.compile(r"^Nightly size budget: \+(\d+(?:\.\d+)?) MB\s*$", re.M)
+
+
+def _pick_sizes(names: list[str], size_of) -> dict[str, int]:
+ out = {}
+ for kind, suffix in SIZE_KINDS.items():
+ found = [n for n in names if n.endswith(suffix)]
+ if len(found) != 1:
+ raise ValueError(f"index.html names {len(found)} {suffix} files, expected exactly one")
+ out[kind] = size_of(found[0])
+ return out
+
+
+def web_sizes(build: Path) -> dict[str, int]:
+ """Bytes of the data, wasm and framework files the build's index.html names (a stale Build/ file is ignored)."""
+ def size_of(name: str) -> int:
+ f = build / "Build" / name
+ if not f.is_file():
+ raise ValueError(f"index.html names Build/{name}, which is missing")
+ return f.stat().st_size
+ return _pick_sizes(package_release.build_files(build), size_of)
+
+
+def web_sizes_from_zip(zip_path: Path) -> dict[str, int]:
+ with zipfile.ZipFile(zip_path) as z:
+ try:
+ page = z.read("index.html").decode("utf-8", errors="replace")
+ except KeyError as e:
+ raise ValueError(f"{zip_path} has no index.html") from e
+ names = sorted(set(package_release.BUILD_FILE.findall(page)))
+
+ def size_of(name: str) -> int:
+ try:
+ return z.getinfo(f"Build/{name}").file_size
+ except KeyError as e:
+ raise ValueError(f"index.html names Build/{name}, which {zip_path} lacks") from e
+ return _pick_sizes(names, size_of)
+
+
+def size_budget_bytes(pr_bodies: list[str]) -> int:
+ """The sum of every `Nightly size budget: +N MB` line (MB = 1,000,000 bytes), in integers."""
+ total = Fraction(0)
+ for body in pr_bodies:
+ for m in BUDGET_RE.finditer(body):
+ total += Fraction(m.group(1)) * 1_000_000
+ return int(total)
+
+
+def size_verdict(old: dict[str, int], new: dict[str, int], budget: int, tolerance: float = 0.02) -> str | None:
+ """None when the growth is within tolerance plus the budget. Integer and Fraction math only: byte totals are
+ never converted to float, and the tolerance is read from its decimal text, so +2.0% is exact."""
+ old_total, new_total = sum(old.values()), sum(new.values())
+ allowed = Fraction(str(tolerance)) * old_total + budget
+ if new_total - old_total > allowed:
+ return (f"download size grew from {old_total} to {new_total} bytes, more than {tolerance:.0%} "
+ f"plus the {budget} byte budget the merged PRs record")
+ return None
+
+
+# --- headless boot ---------------------------------------------------------------------------------------------------
+
+BOOT_RE = re.compile(r"^(?:console: )?BOOT phase=screens ready at=(\d+) ms\b", re.M)
+
+
+def boot_ms(web_check_output: str) -> int:
+ """The `screens ready` boot phase (DiagLog.BootPhase, via ?bootlog), which web_check.py echoes as `console: ...`.
+ A run without web_check's PASS line, or with a TIMEOUT or FAIL line, is not a measurement."""
+ if not re.search(r"^PASS:", web_check_output, re.M) or re.search(r"^(TIMEOUT|FAIL|STALLED|BROWSER EXITED)",
+ web_check_output, re.M):
+ raise ValueError("web_check did not pass, so the boot time is not a measurement")
+ m = BOOT_RE.search(web_check_output)
+ if not m:
+ raise ValueError("web_check printed no BOOT phase=screens ready line")
+ return int(m.group(1))
+
+
+def boot_verdict(median_ms: float, baseline: list[float], nights: int = 5) -> tuple[str, str | None]:
+ """("collecting", None) until `nights` baseline medians exist; then the bound is max + (max - min) of them."""
+ if len(baseline) < nights:
+ return "collecting", None
+ recent = baseline[-nights:]
+ top, spread = max(recent), max(recent) - min(recent)
+ limit = top + spread
+ if median_ms > limit:
+ return "checked", f"headless boot took {median_ms:.0f} ms, over the {limit:.0f} ms bound (max {top:.0f} + spread {spread:.0f})"
+ return "checked", None
+
+
+# --- the published zip -----------------------------------------------------------------------------------------------
+
+NOTICES = ("LICENSE", "NOTICE", "THIRD-PARTY-NOTICES.md", "OFL-EBGaramond.txt", "OFL-FrankRuhlLibre.txt")
+
+
+def zip_missing_notices(zip_path: Path) -> list[str]:
+ """The notices of RELEASING step 7 that a downloaded zip lacks (all five when it cannot be read)."""
+ try:
+ with zipfile.ZipFile(zip_path) as z:
+ names = set(z.namelist())
+ except (OSError, zipfile.BadZipFile):
+ return list(NOTICES)
+ return [n for n in NOTICES if n not in names]
diff --git a/tools/nightly_launch.py b/tools/nightly_launch.py
new file mode 100644
index 000000000..9dc9b517c
--- /dev/null
+++ b/tools/nightly_launch.py
@@ -0,0 +1,95 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+# ///
+"""launchd's entry point for the nightly release (tools/nightly.py). Installed as a copy in the job folder, next to a
+copy of nightly_state.py, so it depends on no checkout's working tree. It takes the job's run lock, moves the
+dedicated clone's own `main` to `origin/main` (resetting and cleaning only that clone, keeping its Unity Library) and
+runs tools/nightly.py from the clone, so a merged change to the script takes effect on the next night. The clone is
+created by hand at install time (tools/README.md, "Nightly release"): a missing clone is a recorded REFUSED night,
+never a clone made here. When a run is in progress the launcher exits 0 and touches nothing.
+
+The lock is held only while the clone is prepared: nightly.py takes the same lock itself and would find it taken.
+
+Usage: uv run nightly_launch.py --uv PATH --home JOB_FOLDER"""
+from __future__ import annotations
+
+import argparse
+import subprocess
+import sys
+from datetime import datetime
+from pathlib import Path
+from typing import Callable
+
+from nightly_state import TZ, Config, Refused, load_config, log_line, notify, record, run_lock
+
+# What `git clean -x` keeps in the clone: Unity's import cache and the Unity-MCP plugin's NuGet download. The same
+# list as unity_postmerge.KEEP (a test keeps them equal; this file runs without the checkout, so it cannot import it).
+KEEP = ("/unity/Library/", "/unity/Assets/Plugins/NuGet/", "/unity/Assets/Plugins/NuGet.meta")
+FETCH = ("fetch", "--quiet", "--tags", "origin", "+refs/heads/main:refs/remotes/origin/main")
+
+
+def _git(cwd: Path, *args: str) -> str:
+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
+
+
+def _copy_library(cwd: Path, src: Path, dest: Path) -> None:
+ subprocess.run(["cp", "-c", "-R", str(src), str(dest)], cwd=cwd, check=True, capture_output=True, text=True)
+
+
+def prepare_clone(cfg: Config, git: Callable[..., str] = _git,
+ copy: Callable[[Path, Path, Path], None] = _copy_library) -> None:
+ """Leaves the clone on `main`, at origin/main, with no change the last night left behind. `reset --hard` restores
+ every tracked file Unity touched (ProjectSettings.asset, Assets/Settings, the prickly_pear material) and `clean`
+ removes what it added; only the KEEP paths survive. Raises Refused("clone", ...) when it cannot."""
+ clone = cfg.clone
+ if not (clone / ".git").exists():
+ raise Refused("clone", f"{clone} is not a git clone (create it as the install steps say)")
+ try:
+ git(clone, *FETCH)
+ git(clone, "checkout", "--quiet", "main")
+ git(clone, "reset", "--hard", "refs/remotes/origin/main")
+ git(clone, "clean", "-ffdx", *[x for k in KEEP for x in ("-e", k)])
+ lib, src = clone / "unity" / "Library", cfg.main_repo / "unity" / "Library"
+ if not lib.exists() and src.is_dir(): # the first night only: the main checkout's warm import cache
+ copy(cfg.main_repo, src, lib)
+ except subprocess.CalledProcessError as e:
+ tail = (e.stderr or "").strip()[-300:]
+ raise Refused("clone", f"{' '.join(str(a) for a in e.cmd[:3])} failed: {tail}") from e
+
+
+def _refuse(cfg: Config, home: Path, e: Refused, now: datetime) -> None:
+ line = log_line(now, "REFUSED", tag=None, sha=None, gate=e.gate, log=None)
+ record(home / "LOG.md", cfg.handoff, f"{line} {e.detail}")
+ notify("Nightly refused", str(e)[:200])
+ print(e, file=sys.stderr)
+
+
+def main(argv: list[str] | None = None, *, git: Callable[..., str] = _git,
+ copy: Callable[[Path, Path, Path], None] = _copy_library,
+ call: Callable[[list[str]], int] = subprocess.call, now: datetime | None = None) -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--uv", required=True)
+ ap.add_argument("--home", type=Path, required=True)
+ a = ap.parse_args(argv)
+ now = now or datetime.now(TZ)
+ a.home.mkdir(parents=True, exist_ok=True)
+ try:
+ cfg = load_config(a.home / "config.json")
+ except Refused as e: # a corrupt config is a recorded REFUSED night, not a night on defaults
+ _refuse(Config(), a.home, e, now)
+ return 1
+ with run_lock(a.home) as held:
+ if not held:
+ print("nightly_launch: a run is in progress")
+ return 0
+ try:
+ prepare_clone(cfg, git, copy)
+ except Refused as e:
+ _refuse(cfg, a.home, e, now)
+ return 1
+ return call([a.uv, "run", str(cfg.clone / "tools" / "nightly.py"), "run"])
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/nightly_publish.py b/tools/nightly_publish.py
new file mode 100644
index 000000000..5707c86c8
--- /dev/null
+++ b/tools/nightly_publish.py
@@ -0,0 +1,399 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+# ///
+"""GitHub and the site for the nightly release job: the draft-first pre-release, the site deploy and the /demo/ check.
+
+Every call goes through the job's Runner, so tests script gh's JSON and no test touches the network. Anything gh says
+that this module cannot parse or does not expect is a Refused, never a pass. Stdlib only."""
+from __future__ import annotations
+
+import hashlib
+import html
+import http.client
+import json
+import re
+import time
+import urllib.error
+import urllib.request
+import zipfile
+from datetime import date, timedelta
+from pathlib import Path
+from typing import Callable
+
+import nightly_checks
+from nightly_state import Refused, Runner
+
+SHA_SHOWN = 12
+PR_LIMIT = 500 # `gh pr list` returns at most this many rows; a full page may be a truncated one
+RELEASE_LIST_LIMIT = 30
+UPLOAD_TIMEOUT = 1800
+ITCH_POLL_SECONDS = 30
+LIVE_MARK = "\u2713" # butler prints this in the BUILD cell only once the build is live
+
+
+def sha256_of(path: Path) -> str:
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def sha256_lines(files: list[Path]) -> list[str]:
+ """`shasum -a 256` lines (hash, two spaces, file name), as RELEASING step 6 pastes them."""
+ return [f"{sha256_of(f)} {Path(f).name}" for f in files]
+
+
+def release_notes(*, version: str, sha: str, since: str, subjects: list[str], sha256_lines: list[str]) -> str:
+ shown = since[:SHA_SHOWN] if len(since) == 40 and all(c in "0123456789abcdef" for c in since) else since
+ lines = [f"Automated nightly build of `main` at {sha[:SHA_SHOWN]}. A pre-release, not a versioned release.", "",
+ f"Version {version}.", "", f"Changes since {shown}:", ""]
+ lines += [f"- {s}" for s in subjects] or ["- (no commits)"]
+ lines += ["", "SHA-256:", "", "```", *sha256_lines, "```", ""]
+ return "\n".join(lines)
+
+
+FRAME_URL = re.compile(r"https://html-classic\.itch\.zone/html/[0-9-]+/[^\"'&<>\s]*index\.html")
+
+
+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 unzip_to(zip_path: Path, dest: Path) -> Path:
+ """Extract a zip into `dest` (created), refusing any entry that would land outside it."""
+ dest = Path(dest)
+ dest.mkdir(parents=True, exist_ok=True)
+ root = dest.resolve()
+ try:
+ with zipfile.ZipFile(zip_path) as z:
+ for info in z.infolist():
+ target = (root / info.filename).resolve()
+ if target != root and root not in target.parents:
+ raise Refused("unzip", f"{info.filename!r} in {Path(zip_path).name} leaves the target folder")
+ z.extractall(root)
+ except (zipfile.BadZipFile, OSError) as e:
+ raise Refused("unzip", f"cannot extract {Path(zip_path).name}: {e}") from e
+ return dest
+
+
+class Itch:
+ """The itch.io channel of the nightly, through butler (which finds its saved login by itself). `target` is
+ `user/project:channel`. Every butler failure is a Refused("itch"); nothing here reads or sets a credential."""
+
+ def __init__(self, runner: Runner, butler: Path, target: str):
+ project, sep, channel = target.rpartition(":")
+ user, slash, name = project.partition("/")
+ if not (sep and slash and user and name and channel and "/" not in name and ":" not in project):
+ raise Refused("itch", f"the itch target {target!r} is not user/project:channel")
+ self.runner, self.butler, self.target = runner, Path(butler), target
+ self.project, self.channel = project, channel
+ self._floor: int | None = None # the highest live build id seen; a push is live only with a newer one
+
+ @staticmethod
+ def _row(status_text: str, channel: str) -> list[str] | None:
+ """The cells of the one table row for `channel`; None when it is missing or appears twice."""
+ rows = []
+ for line in status_text.splitlines():
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
+ if line.strip().startswith("|") and len(cells) >= 4 and cells[0] == channel:
+ rows.append(cells)
+ return rows[0] if len(rows) == 1 else None
+
+ @staticmethod
+ def live_version(status_text: str, channel: str = "html5") -> str | None:
+ """The version of the channel's live build. Anything but a build cell that starts with the live mark (a
+ build still processing, an unknown text, a missing row) is None, so it can never count as live."""
+ row = Itch._row(status_text, channel)
+ if row is None or not row[2].startswith(LIVE_MARK) or not row[3]:
+ return None
+ return row[3]
+
+ @staticmethod
+ def build_id(status_text: str, channel: str = "html5") -> str | None:
+ """The id of the channel's live build, under the same rule as live_version."""
+ row = Itch._row(status_text, channel)
+ if row is None or not row[2].startswith(LIVE_MARK):
+ return None
+ 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()
+
+ def _run(self, args: list[str], cwd: Path, timeout: float = 300) -> str:
+ try:
+ return self.runner.capture([str(self.butler), *args], cwd=cwd, timeout=timeout)
+ except Refused as e:
+ raise Refused("itch", e.detail) from e
+
+ def _live_id(self) -> int | None:
+ text = self._run(["status", self.project], Path.cwd())
+ found = self.build_id(text, self.channel)
+ return int(found) if found else None
+
+ def push(self, folder: Path, version: str) -> None:
+ """Push `folder`. The live build id is read first, so wait_live can tell the new build from the old row.
+ With no readable id nothing is pushed (fail closed); a rollback after a stalled push keeps the earlier floor."""
+ current = self._live_id()
+ known = [i for i in (current, self._floor) if i is not None]
+ if not known:
+ raise Refused("itch", f"{self.target} shows no live build id before the push, so the push cannot be confirmed")
+ self._floor = max(known)
+ self._run(["push", str(folder), self.target, "--userversion", version], Path(folder), UPLOAD_TIMEOUT)
+
+ def wait_live(self, version: str, deadline: float, sleep: Callable[[float], None] = time.sleep,
+ now: Callable[[], float] = time.monotonic) -> None:
+ """Poll `butler status` until `version` is live under a build id newer than the one before the push;
+ Refused("itch") at the deadline."""
+ if self._floor is None:
+ raise Refused("itch", "wait_live needs a push first: no build id was read before it")
+ seen = "nothing"
+ while True:
+ try:
+ text = self._run(["status", self.project], Path.cwd())
+ live = self.live_version(text, self.channel)
+ found = self.build_id(text, self.channel)
+ if live is not None and found is not None:
+ new_id = int(found)
+ if live == version and new_id > self._floor:
+ self._floor = new_id
+ return
+ seen = f"{live!r} on build {new_id}"
+ else:
+ seen = "no live build"
+ except Refused as e: # a failed status call is "not live yet", the deadline decides
+ seen = f"a status error ({e.detail})"
+ if now() >= deadline:
+ raise Refused("itch", f"{self.target} still shows {seen}, not {version} on a build newer than "
+ f"{self._floor}")
+ sleep(ITCH_POLL_SECONDS)
+
+ @staticmethod
+ def _hashes(root: Path) -> dict[str, str]:
+ return {p.relative_to(root).as_posix(): sha256_of(p) for p in sorted(Path(root).rglob("*")) if p.is_file()}
+
+ def matches(self, folder: Path, dest: Path) -> None:
+ """Fetch the live build into `dest` and refuse unless it holds exactly the files that were pushed."""
+ dest = Path(dest)
+ dest.mkdir(parents=True, exist_ok=True)
+ self._run(["fetch", self.target, str(dest)], dest.parent, UPLOAD_TIMEOUT)
+ want, got = self._hashes(Path(folder)), self._hashes(dest)
+ if want != got:
+ diff = sorted(k for k in want.keys() | got.keys() if want.get(k) != got.get(k))
+ raise Refused("itch", f"the fetched build differs from the pushed folder in {len(diff)} files, "
+ f"first: {diff[0]}")
+
+
+class GitHub:
+ """The release and site calls of the nightly. `cwd` is the job's clone (used for `git ls-remote` and `git log`)."""
+
+ def __init__(self, runner: Runner, slug: str, cwd: Path, *, sleep: Callable[[float], None] = time.sleep,
+ now: Callable[[], float] = time.monotonic):
+ self.runner, self.slug, self.cwd = runner, slug, Path(cwd)
+ self.sleep, self.now = sleep, now
+
+ # --- plumbing --------------------------------------------------------------------------------------------------
+
+ def _run(self, gate: str, cmd: list[str], timeout: float = 300) -> str:
+ try:
+ return self.runner.capture(cmd, cwd=self.cwd, timeout=timeout)
+ except Refused as e:
+ raise Refused(gate, e.detail) from e
+
+ def _json(self, gate: str, cmd: list[str], kind: type, timeout: float = 300):
+ text = self._run(gate, cmd, timeout)
+ try:
+ data = json.loads(text)
+ except ValueError as e:
+ raise Refused(gate, f"{' '.join(cmd[:3])} printed something that is not JSON") from e
+ if not isinstance(data, kind):
+ raise Refused(gate, f"{' '.join(cmd[:3])} printed JSON of the wrong shape")
+ return data
+
+ def _view(self, gate: str, tag: str, fields: str) -> dict:
+ return self._json(gate, ["gh", "release", "view", tag, "--repo", self.slug, "--json", fields], dict)
+
+ # --- release state ---------------------------------------------------------------------------------------------
+
+ def release_state(self, tag: str) -> str | None:
+ """'draft', 'published', or None when no release has this tag."""
+ try:
+ data = self._view("github-state", tag, "isDraft")
+ except Refused as e:
+ if "release not found" in e.detail:
+ return None
+ raise
+ flag = data.get("isDraft")
+ if not isinstance(flag, bool):
+ raise Refused("github-state", f"gh did not say whether {tag} is a draft")
+ return "draft" if flag else "published"
+
+ def previous_build_tag(self, state_tag: str | None) -> str:
+ """The last published nightly, or on the first night the newest release that carries a web zip."""
+ if state_tag:
+ return state_tag
+ rows = self._json("sizes", ["gh", "release", "list", "--repo", self.slug, "--exclude-drafts", "--limit",
+ str(RELEASE_LIST_LIMIT), "--json", "tagName"], list)
+ for row in rows:
+ tag = row.get("tagName") if isinstance(row, dict) else None
+ if not isinstance(tag, str):
+ raise Refused("sizes", "gh release list returned a row without a tag")
+ names = self._asset_names("sizes", self._view("sizes", tag, "assets"))
+ if any(n.endswith("-web.zip") for n in names):
+ return tag
+ raise Refused("sizes", f"none of the newest {RELEASE_LIST_LIMIT} releases has a web zip to compare with")
+
+ @staticmethod
+ def _asset_names(gate: str, data: dict) -> list[str]:
+ assets = data.get("assets")
+ if not isinstance(assets, list) or not all(isinstance(a, dict) and isinstance(a.get("name"), str)
+ for a in assets):
+ raise Refused(gate, "gh returned no usable asset list")
+ return [a["name"] for a in assets]
+
+ def download(self, tag: str, pattern: str, dest: Path) -> Path:
+ """Download the assets of a release matching `pattern`; exactly one file must arrive."""
+ dest = Path(dest)
+ dest.mkdir(parents=True, exist_ok=True)
+ self._run("github-download", ["gh", "release", "download", tag, "--repo", self.slug, "--dir", str(dest),
+ "--pattern", pattern], UPLOAD_TIMEOUT)
+ found = sorted(dest.glob(pattern))
+ if len(found) != 1:
+ raise Refused("github-download", f"{len(found)} files matching {pattern} came from {tag}, expected one")
+ return found[0]
+
+ # --- the draft, its check, publishing --------------------------------------------------------------------------
+
+ def create_draft(self, tag: str, sha: str, notes: Path, assets: list[Path]) -> None:
+ """A draft pre-release, never 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", "--prerelease",
+ "--latest=false", "--target", sha, "--title", f"{tag} (nightly)",
+ "--notes-file", str(notes), *[str(a) for a in assets]], UPLOAD_TIMEOUT)
+
+ def verify_draft(self, tag: str, local: list[Path], dest: Path) -> None:
+ data = self._view("github-draft", tag, "isDraft,isPrerelease,assets")
+ if data.get("isDraft") is not True or data.get("isPrerelease") is not True:
+ raise Refused("github-draft", f"{tag} is not a draft pre-release")
+ names = sorted(self._asset_names("github-draft", data))
+ want = sorted(Path(p).name for p in local)
+ if names != want:
+ raise Refused("github-draft", f"the draft's assets are {names}, expected {want}")
+ dest = Path(dest)
+ self._run("github-draft", ["gh", "release", "download", tag, "--repo", self.slug, "--dir", str(dest),
+ "--pattern", "*.zip"], UPLOAD_TIMEOUT)
+ for path in local:
+ got = dest / Path(path).name
+ if not got.is_file() or sha256_of(got) != sha256_of(Path(path)):
+ raise Refused("github-draft", f"{Path(path).name} on the draft differs from the local file")
+ missing = nightly_checks.zip_missing_notices(got)
+ if missing:
+ raise Refused("github-draft", f"{got.name} on the draft lacks {', '.join(missing)}")
+
+ def publish(self, tag: str, sha: str) -> None:
+ """Make the draft public, then check it is a pre-release, not Latest, and that its tag points at `sha`."""
+ try:
+ self._publish(tag, sha)
+ except Refused as e:
+ raise Refused("github-publish", e.detail) from e
+
+ def _publish(self, tag: str, sha: str) -> None:
+ self._run("github-publish", ["gh", "release", "edit", tag, "--repo", self.slug, "--draft=false",
+ "--latest=false"])
+ data = self._view("github-publish", tag, "isDraft,isPrerelease")
+ if data.get("isDraft") is not False or data.get("isPrerelease") is not True:
+ raise Refused("github-publish", f"{tag} is not a public pre-release after publishing")
+ latest = self._run("github-publish", ["gh", "api", f"repos/{self.slug}/releases/latest", "--jq",
+ ".tag_name"]).strip()
+ if latest == tag:
+ raise Refused("github-publish", f"{tag} is now the Latest release and needs a manual fix: set the "
+ "real release as Latest again")
+ refs: dict[str, str] = {}
+ for line in self._run("github-publish", ["git", "-C", str(self.cwd), "ls-remote", "origin",
+ f"refs/tags/{tag}"]).splitlines():
+ parts = line.split()
+ if len(parts) == 2:
+ refs[parts[1]] = parts[0]
+ at = refs.get(f"refs/tags/{tag}^{{}}") or refs.get(f"refs/tags/{tag}")
+ 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")
+ 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"])
+
+ # --- the size budget -------------------------------------------------------------------------------------------
+
+ def merged_pr_bodies(self, shas: set[str]) -> list[str]:
+ """The bodies of the PRs whose merge commit is one of `shas` (squash and merge commits alike)."""
+ if not shas:
+ return []
+ dates = self._run("sizes", ["git", "-C", str(self.cwd), "log", "--no-walk", "--format=%cs", *sorted(shas)])
+ days = [d for d in dates.split() if len(d) == 10]
+ if not days:
+ raise Refused("sizes", "cannot date the commits since the previous build")
+ try:
+ since = (date.fromisoformat(min(days)) - timedelta(days=1)).isoformat() # a day of slack
+ except ValueError as e:
+ raise Refused("sizes", f"git printed an unreadable commit date: {e}") from e
+ rows = self._json("sizes", ["gh", "pr", "list", "--repo", self.slug, "--state", "merged", "--limit",
+ str(PR_LIMIT), "--search", f"merged:>={since}", "--json", "body,mergeCommit"],
+ list)
+ if len(rows) >= PR_LIMIT:
+ raise Refused("sizes", f"{len(rows)} merged PRs came back, so the list may be truncated and no size "
+ "budget can be trusted")
+ bodies = []
+ for row in rows:
+ commit = row.get("mergeCommit") if isinstance(row, dict) else None
+ if isinstance(commit, dict) and commit.get("oid") in shas:
+ bodies.append(row.get("body") or "")
+ return bodies
+
+ # --- the site --------------------------------------------------------------------------------------------------
+
+ def dispatch_site(self, deadline: float) -> None:
+ """Run site.yml on main and wait for that run (not an older one) to succeed."""
+ listing = ["gh", "run", "list", "--repo", self.slug, "--workflow", "site.yml", "--event",
+ "workflow_dispatch", "--limit", "5", "--json", "databaseId,createdAt"]
+ before = {r.get("databaseId") for r in self._json("site", listing, list) if isinstance(r, dict)}
+ self._run("site", ["gh", "workflow", "run", "site.yml", "--repo", self.slug, "--ref", "main"])
+ run_id = None
+ while run_id is None:
+ fresh = [r for r in self._json("site", listing, list)
+ if isinstance(r, dict) and r.get("databaseId") not in before]
+ if fresh:
+ run_id = max(fresh, key=lambda r: str(r.get("createdAt")))["databaseId"]
+ elif self.now() >= deadline:
+ raise Refused("site", "the dispatched site run did not appear before the deadline")
+ else:
+ self.sleep(5)
+ self._run("site", ["gh", "run", "watch", str(run_id), "--repo", self.slug, "--exit-status"],
+ max(1.0, deadline - self.now()))
+
+
+def demo_serves(url: str, version: str, *, deadline: float, fetch=urllib.request.urlopen, sleep=time.sleep,
+ now=time.monotonic) -> None:
+ """Poll the demo page until it prints `version`; Refused("site") at the deadline."""
+ sep = "&" if "?" in url else "?"
+ probe = f"{url}{sep}nightly={version}" # a fresh URL, so a cache cannot keep serving the old page
+ seen = "nothing"
+ while True:
+ try:
+ with fetch(probe, timeout=30) as resp:
+ page = resp.read().decode("utf-8", errors="replace")
+ seen = repr(nightly_checks.product_version(page))
+ if nightly_checks.product_version(page) == version:
+ return
+ except (OSError, urllib.error.URLError, http.client.HTTPException, ValueError) as e:
+ seen = f"an error ({e})"
+ if now() >= deadline:
+ raise Refused("site", f"{url} still serves {seen}, not {version}")
+ sleep(30)
diff --git a/tools/nightly_state.py b/tools/nightly_state.py
new file mode 100644
index 000000000..ff658b38e
--- /dev/null
+++ b/tools/nightly_state.py
@@ -0,0 +1,325 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+# ///
+"""State, configuration, naming and the nightly record for the nightly release job (tools/nightly*.py).
+
+Everything the other nightly modules share lives here: the ways a night ends early (Stop and its subclasses), the
+command runner they are given, the job's config and state files, how a night is named and dated, and the one-line
+record of each night. Stdlib only. A bad state or config file refuses the night instead of falling back to defaults,
+so a typo can never publish on a guess."""
+from __future__ import annotations
+
+import contextlib
+import json
+import math
+import os
+import re
+import subprocess
+from dataclasses import asdict, dataclass, field, fields
+from datetime import date, datetime, time, timedelta
+from pathlib import Path
+from typing import ContextManager, Iterator, Protocol
+from zoneinfo import ZoneInfo
+
+TZ = ZoneInfo("Asia/Jerusalem")
+HOME = Path.home()
+JOB = HOME / "israel-game/.superpowers/nightly"
+OUTCOMES = ("PUBLISHED", "SKIPPED", "REFUSED", "MISSED")
+SHA_SHOWN = 12
+
+
+class Stop(Exception):
+ """A night that ends without publishing. `outcome` is REFUSED, SKIPPED or MISSED."""
+ outcome = "REFUSED"
+
+ def __init__(self, gate: str, detail: str):
+ super().__init__(f"{gate}: {detail}")
+ self.gate = gate
+ self.detail = detail
+
+
+class Refused(Stop):
+ outcome = "REFUSED"
+
+ def __init__(self, gate: str, detail: str):
+ super().__init__(gate, detail)
+
+
+class Skipped(Stop):
+ outcome = "SKIPPED"
+
+ def __init__(self, detail: str):
+ super().__init__("-", detail)
+
+
+class Missed(Stop):
+ outcome = "MISSED"
+
+ def __init__(self, detail: str):
+ super().__init__("-", detail)
+
+
+class Runner(Protocol):
+ """Runs commands for the job. `deadline` is a time.monotonic() value; `run` returns 124 when it stopped the command
+ at the deadline. `capture` raises Refused("command", ...) on a non-zero exit."""
+
+ def run(self, cmd: list[str], *, cwd: Path, log: Path, deadline: float,
+ env: dict[str, str] | None = None, holder: Path | None = None) -> int: ...
+
+ def capture(self, cmd: list[str], *, cwd: Path, timeout: float = 300) -> str: ...
+
+
+# --- config -----------------------------------------------------------------------------------------------------
+
+@dataclass(frozen=True)
+class Config:
+ main_repo: Path = HOME / "israel-game"
+ clone: Path = HOME / ".cache/statecraft/nightly/repo"
+ unity_slots: Path = HOME / "israel-game/.superpowers/coordinator-tools/unity_slots.py"
+ exclusive_marker: Path = HOME / "israel-game/.superpowers/coordination/EXCLUSIVE-WINDOW"
+ handoff: Path = HOME / "israel-game/.superpowers/HANDOFF.md"
+ licence: Path = HOME / "Library/Unity/licenses/UnityEntitlementLicense.xml"
+ repo_slug: str = "eyalgolan/statecraft-israel"
+ site_demo_url: str = "https://eyalgolan.github.io/statecraft-israel/demo/"
+ itch_target: str = "eyalgolan/statecraft-israel:html5"
+ itch_page_url: str | None = None
+ itch_enabled: bool = False
+ itch_evidence: str | None = None
+ butler: Path = HOME / ".local/bin/butler"
+ min_free_gb: int = 40
+ window_end: str = "03:30"
+ deadline_hours: float = 6.0
+ unity_slots_count: int = 3
+
+
+def _atomic_write(path: Path, text: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(f"{path.name}.tmp{os.getpid()}")
+ tmp.write_text(text, encoding="utf-8")
+ os.replace(tmp, path)
+
+
+def _read_json_object(path: Path, gate: str) -> dict:
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as e:
+ raise Refused(gate, f"{path} is unreadable: {e}") from e
+ if not isinstance(data, dict):
+ raise Refused(gate, f"{path} must hold a JSON object")
+ return data
+
+
+def load_config(path: Path) -> Config:
+ if not path.exists():
+ return Config()
+ raw = _read_json_object(path, "config")
+ known = {f.name: f for f in fields(Config)}
+ values: dict[str, object] = {}
+ for key, value in raw.items():
+ if key not in known:
+ raise Refused("config", f"unknown key {key!r} in {path}")
+ default = known[key].default
+ if isinstance(default, Path):
+ ok = isinstance(value, str) and bool(value)
+ values[key] = Path(value).expanduser() if ok else value
+ elif default is None: # an optional string
+ ok = value is None or isinstance(value, str)
+ values[key] = value
+ elif isinstance(default, bool):
+ ok = isinstance(value, bool)
+ values[key] = value
+ elif isinstance(default, float):
+ ok = isinstance(value, (int, float)) and not isinstance(value, bool)
+ values[key] = value
+ elif isinstance(default, int):
+ ok = isinstance(value, int) and not isinstance(value, bool)
+ values[key] = value
+ else:
+ ok = isinstance(value, str)
+ values[key] = value
+ if not ok:
+ raise Refused("config", f"{key!r} in {path} has the wrong type: {value!r}")
+ return Config(**values)
+
+
+def enable_itch(path: Path, evidence: Path) -> None:
+ """Turn the itch push on and record the evidence file for it, keeping every other key."""
+ load_config(path) # refuses on a broken file instead of overwriting it
+ raw = _read_json_object(path, "config") if path.exists() else {}
+ raw["itch_enabled"] = True
+ raw["itch_evidence"] = str(evidence)
+ _atomic_write(path, json.dumps(raw, indent=2, sort_keys=True) + "\n")
+
+
+# --- state ------------------------------------------------------------------------------------------------------
+
+@dataclass
+class Published:
+ tag: str
+ sha: str
+ version: str
+ sizes: dict[str, int]
+ boot_ms: float | None
+
+
+@dataclass
+class State:
+ last_published: Published | None = None
+ boot_baseline: list[float] = field(default_factory=list)
+ last_run_day: str | None = None
+ open_draft: str | None = None
+ site_pending: str | None = None
+
+
+def _number(value: object) -> bool:
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
+ return False
+ try:
+ return math.isfinite(value)
+ except OverflowError: # an integer too large for a float
+ return False
+
+
+def _opt_str(value: object, name: str) -> str | None:
+ if value is not None and not isinstance(value, str):
+ raise TypeError(f"{name} must be a string or null")
+ return value
+
+
+def _day(value: object) -> str | None:
+ if value is not None:
+ if not isinstance(value, str):
+ raise TypeError("last_run_day must be a string or null")
+ date.fromisoformat(value) # ValueError (a bad date) is caught by load_state
+ return value
+
+
+def _state_from(raw: dict) -> State:
+ extra = set(raw) - {f.name for f in fields(State)}
+ if extra:
+ raise TypeError(f"unknown keys {sorted(extra)}")
+ published = None
+ lp = raw.get("last_published")
+ if lp is not None:
+ if not isinstance(lp, dict) or set(lp) != {f.name for f in fields(Published)}:
+ raise TypeError("last_published has the wrong shape")
+ sizes = lp["sizes"]
+ boot = lp["boot_ms"]
+ if (not all(isinstance(lp[k], str) for k in ("tag", "sha", "version")) or not isinstance(sizes, dict)
+ or not all(isinstance(k, str) and type(v) is int for k, v in sizes.items())
+ or not (boot is None or _number(boot))):
+ raise TypeError("last_published has the wrong types")
+ published = Published(lp["tag"], lp["sha"], lp["version"], dict(sizes), boot)
+ 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")
+ 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"))
+
+
+def load_state(path: Path) -> State:
+ if not path.exists():
+ return State()
+ raw = _read_json_object(path, "state")
+ try:
+ return _state_from(raw)
+ except (TypeError, KeyError, ValueError) as e:
+ raise Refused("state", f"{path} has a bad shape: {e}") from e
+
+
+def save_state(path: Path, state: State) -> None:
+ _atomic_write(path, json.dumps(asdict(state), indent=2, sort_keys=True) + "\n")
+
+
+# --- naming and dates -------------------------------------------------------------------------------------------
+
+def base_version(siminfo_text: str) -> str:
+ m = re.search(r'Version\s*=\s*"(\d+\.\d+\.\d+)"', siminfo_text)
+ if not m:
+ raise ValueError("no Version = \"X.Y.Z\" found")
+ return m.group(1)
+
+
+def nightly_version(base: str, day: date) -> str:
+ return f"{base}-nightly.{day:%Y%m%d}"
+
+
+def tag_for(version: str) -> str:
+ return f"v{version}"
+
+
+def night_of(now: datetime) -> date:
+ """The night is the Jerusalem calendar date of the start."""
+ return now.astimezone(TZ).date()
+
+
+def late_start(now: datetime, window_end: str) -> bool:
+ local = now.astimezone(TZ)
+ return local.time().replace(tzinfo=None) > time.fromisoformat(window_end)
+
+
+def missed_days(last_run_day: str | None, today: date) -> list[date]:
+ """The dates strictly between the last run and today."""
+ if last_run_day is None:
+ return []
+ last = date.fromisoformat(last_run_day)
+ return [last + timedelta(days=i) for i in range(1, (today - last).days)]
+
+
+# --- the night's record -----------------------------------------------------------------------------------------
+
+def log_line(now: datetime, outcome: str, *, tag: str | None, sha: str | None, gate: str, log: Path | None) -> str:
+ if outcome not in OUTCOMES:
+ raise ValueError(f"outcome must be one of {OUTCOMES}, not {outcome!r}")
+ stamp = now.astimezone(TZ).strftime("%Y-%m-%d %H:%M")
+ short = sha[:SHA_SHOWN] if sha else "-"
+ return f"{stamp} {outcome} tag={tag or '-'} sha={short} gate={gate} log={log if log else '-'}"
+
+
+def _append_line(path: Path, line: str) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ lead = ""
+ if path.exists() and path.stat().st_size:
+ with path.open("rb") as f:
+ f.seek(-1, os.SEEK_END)
+ lead = "" if f.read(1) == b"\n" else "\n"
+ with path.open("a", encoding="utf-8") as f:
+ f.write(f"{lead}{line}\n")
+
+
+def record(log_md: Path, handoff: Path, line: str) -> None:
+ _append_line(log_md, f"- {line}")
+ _append_line(handoff, f"- NIGHTLY: {line}")
+
+
+def notify(title: str, message: str, run=None) -> None:
+ run = run or subprocess.run # looked up now, so a test that patches subprocess.run also covers the default
+ def esc(s: str) -> str:
+ return s.replace("\\", "\\\\").replace('"', '\\"')
+ script = f'display notification "{esc(message)}" with title "{esc(title)}"'
+ try:
+ run(["osascript", "-e", script], check=False, capture_output=True, timeout=30)
+ except (OSError, subprocess.SubprocessError):
+ pass # a missing notification never changes the night's outcome
+
+
+def _run_lock(job: Path) -> Iterator[bool]:
+ import fcntl # POSIX only; imported here so the shared types load anywhere
+ job.mkdir(parents=True, exist_ok=True)
+ with (job / "run.lock").open("a") as fh:
+ try:
+ fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ yield False
+ return
+ try:
+ yield True
+ finally:
+ fcntl.flock(fh, fcntl.LOCK_UN)
+
+
+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)
diff --git a/tools/tests/conftest.py b/tools/tests/conftest.py
index ef709d103..55f01b9a5 100644
--- a/tools/tests/conftest.py
+++ b/tools/tests/conftest.py
@@ -1,10 +1,14 @@
+import subprocess
import sys
+import urllib.request
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import pytest
+from nightly_state import Refused, Runner
+
def pytest_addoption(parser):
parser.addoption("--headed", action="store_true", help="also run the headed-browser checks (opens Chrome for Testing)")
@@ -21,3 +25,48 @@ def pytest_collection_modifyitems(config, items):
for item in items:
if "headed" in item.keywords:
item.add_marker(skip)
+
+
+class FakeRunner(Runner):
+ """A nightly Runner that never starts a process. `add(prefix, code, out, effect)` answers any command that starts
+ with `prefix` (first rule added wins): `run` writes `out` to the log, calls `effect(cmd)` and returns `code`."""
+
+ def __init__(self):
+ self.rules: list[tuple[tuple, int, str, object]] = []
+ self.calls: list[list[str]] = []
+
+ def add(self, prefix, code=0, out="", effect=None):
+ self.rules.append((tuple(prefix), code, out, effect))
+
+ def _match(self, cmd):
+ self.calls.append(list(cmd))
+ for prefix, code, out, effect in self.rules:
+ if tuple(cmd[:len(prefix)]) == prefix:
+ return code, out, effect
+ raise AssertionError(f"unexpected command {cmd}")
+
+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):
+ code, out, effect = self._match(cmd)
+ Path(log).parent.mkdir(parents=True, exist_ok=True)
+ Path(log).write_text(out, encoding="utf-8")
+ if effect:
+ effect(cmd)
+ return code
+
+ def capture(self, cmd, *, cwd, timeout=300):
+ code, out, effect = self._match(cmd)
+ if effect:
+ effect(cmd)
+ if code != 0:
+ raise Refused("command", f"{' '.join(cmd)} exited {code}")
+ return out
+
+
+def no_processes(monkeypatch):
+ """Any real process or network call in the test fails it."""
+ def boom(*a, **k):
+ raise AssertionError("a test started a real process or network call")
+ monkeypatch.setattr(subprocess, "Popen", boom)
+ monkeypatch.setattr(subprocess, "run", boom)
+ monkeypatch.setattr(urllib.request, "urlopen", boom)
diff --git a/tools/tests/data/butler_status_live.txt b/tools/tests/data/butler_status_live.txt
new file mode 100644
index 000000000..4464ffff0
--- /dev/null
+++ b/tools/tests/data/butler_status_live.txt
@@ -0,0 +1,5 @@
++---------+-----------+----------------------------+---------+
+| CHANNEL | UPLOAD | BUILD | VERSION |
++---------+-----------+----------------------------+---------+
+| html5 | #19840947 | ✓ #2217587 (from #2211125) | 0.3.1 |
++---------+-----------+----------------------------+---------+
diff --git a/tools/tests/data/itch_page.html b/tools/tests/data/itch_page.html
new file mode 100644
index 000000000..b8690fb09
--- /dev/null
+++ b/tools/tests/data/itch_page.html
@@ -0,0 +1,35 @@
+<!DOCTYPE HTML><html lang="en"><head><meta charset="UTF-8"/><meta content="#090e1a" name="theme-color"/><meta content="https://img.itch.zone/aW1nLzMxMDUyMzYzLnBuZw==/original/QNymRJ.png" property="og:image"/><link type="image/png" href="https://img.itch.zone/aW1nLzMxMDUyMzYzLnBuZw==/32x32%23/F4APSe.png" rel="icon"/><meta content="itch.io" property="og:site_name"/><meta content="4503599627724030" property="twitter:account_id"/><meta content="A historical strategy game: govern Israel from May 1948, with real decisions at their real dates." property="og:description"/><meta content="A historical strategy game: govern Israel from May 1948, with real decisions at their real dates." name="description"/><meta content="width=device-width, initial-scale=1" name="viewport"/><meta content="games/5179460" name="itch:path"/><link type="application/rss+xml" title="Statecraft: Israel Devlog" href="https://eyalgolan.itch.io/statecraft-israel/devlog.rss" rel="alternate"/><meta content="@itchio" name="twitter:site"/><meta content="Statecraft: Israel by eyalgolan" name="twitter:title"/><meta content="A historical strategy game: govern Israel from May 1948, with real decisions at their real dates. Play in your browser" name="twitter:description"/><meta content="summary_large_image" name="twitter:card"/><meta content="https://img.itch.zone/aW1nLzMxMDUyMzYzLnBuZw==/508x254%23mb/SQfSPX.png" property="twitter:image"/><meta content="https://eyalgolan.itch.io/statecraft-israel" name="twitter:url"/><script type="application/ld+json">{"@type":"BreadcrumbList","itemListElement":[{"position":1,"item":{"name":"Games","@id":"https:\/\/itch.io\/games"},"@type":"ListItem"},{"position":2,"item":{"name":"Strategy","@id":"https:\/\/itch.io\/games\/genre-strategy"},"@type":"ListItem"},{"position":3,"item":{"name":"Free","@id":"https:\/\/itch.io\/games\/free"},"@type":"ListItem"}],"@context":"http:\/\/schema.org"}</script><script type="application/ld+json">{"description":"A historical strategy game: govern Israel from May 1948, with real decisions at their real dates.","@context":"http:\/\/schema.org\/","name":"Statecraft: Israel","@type":"Product"}</script><title>Statecraft: Israel by eyalgolan</title><meta name="csrf_token" value="REDACTED" /><link href="https://static.itch.io/game.css?1793126460" rel="stylesheet"/><script type="text/javascript">window.itchio_translations_url = 'https://static.itch.io/translations';</script><script type="text/javascript" src="https://static.itch.io/lib.min.js?1793126460"></script><script type="text/javascript" src="https://static.itch.io/bundle.min.js?1793126460"></script><script id="lib_react_src" data-src="https://static.itch.io/react.min.js?1793126460"></script><script type="text/javascript" src="https://static.itch.io/game.min.js?1793126460"></script><script type="text/javascript">I.current_user = null;I.subdomain = true;</script><script type="text/javascript">if (!window.location.hostname.match(/localhost/)) { window.dataLayer = window.dataLayer || [];
+ function gtag(){dataLayer.push(arguments);}
+ gtag('js', new Date());
+ gtag('config', "G-36R7NPBMLS", {});
+ (function(d, t, s, m) {
+ s = d.createElement(t);
+ s.src = "https:\/\/www.googletagmanager.com\/gtag\/js?id=G-36R7NPBMLS";
+ s.async = 1;
+ m = d.getElementsByTagName(t)[0];
+ m.parentNode.insertBefore(s, m);
+ })(document, "script");
+ }</script><style type="text/css" id="game_theme">:root{--itchio_ui_bg: #2a2b2e;--itchio_ui_bg_dark: #242527}.wrapper{--itchio_font_family: serif;--itchio_bg_color: #090e1a;--itchio_bg2_color: rgba(14, 22, 38, 1);--itchio_bg2_sub: #252d3d;--itchio_text_color: #ece4d2;--itchio_link_color: #e8cc8e;--itchio_border_color: #283857;--itchio_button_color: #c4a05c;--itchio_button_fg_color: #ffffff;--itchio_button_shadow_color: #ab8743;--itchio_editor_bg: rgba(37, 45, 61, 1);--itchio_editor_border: rgba(236, 228, 210, 0.5);--itchio_editor_toolbar_fg: #e8cc8e;--itchio_editor_toolbar_border: rgba(236, 228, 210, 0.5);--itchio_editor_toolbar_active_bg: #c4a05c;--itchio_editor_toolbar_active_fg: #ffffff;--itchio_editor_accent_bg: #c4a05c;--itchio_editor_accent_fg: #ffffff;--itchio_editor_menu_bg: #252d3d;--itchio_editor_menu_fg: #ece4d2;--itchio_editor_menu_fg_muted: rgba(236, 228, 210, 0.6);--itchio_editor_menu_border: rgba(236, 228, 210, 0.5);background-color:#090e1a;/*! */ /* */}.inner_column{color:#ece4d2;font-family:serif,Lato,LatoExtended,sans-serif;background-color:rgba(14, 22, 38, 1)}.inner_column ::selection{color:#ffffff;background:#c4a05c}.inner_column ::-moz-selection{color:#ffffff;background:#c4a05c}.inner_column h1,.inner_column h2,.inner_column h3,.inner_column h4,.inner_column h5,.inner_column h6{font-family:inherit;font-weight:bold;color:#e8cc8e}.inner_column a,.inner_column .footer a{color:#e8cc8e}.inner_column .button,.inner_column .button:hover,.inner_column .button:active{background-color:#c4a05c;color:#ffffff;text-shadow:0 1px 0px #ab8743}.inner_column hr{background-color:#283857}.inner_column table{border-color:#283857}.game_frame{background:#252d3d;/*! */ /* */}.game_frame .embed_info{background-color:rgba(14, 22, 38, 0.85)}.game_loading .loader_bar .loader_bar_slider{background-color:#c4a05c}.view_game_page .reward_row,.view_game_page .bundle_row{border-color:#252d3d !important}.view_game_page .game_info_panel_widget{background:rgba(37, 45, 61, 1)}.view_game_page .star_value .star_fill{color:#c4a05c}.view_game_page .rewards .quantity_input{background:rgba(37, 45, 61, 1);border-color:rgba(236, 228, 210, 0.5);color:#ece4d2}.view_game_page .right_col{display:block}.game_devlog_page li .meta_row .post_likes{border-color:#252d3d}.game_devlog_post_page .post_like_button{box-shadow:inset 0 0 0 1px #283857}.game_comments_widget .community_post .post_footer a,.game_comments_widget .community_post .post_footer .vote_btn,.game_comments_widget .community_post .post_header .post_date a,.game_comments_widget .community_post .post_header .edit_message{color:rgba(236, 228, 210, 0.5)}.game_comments_widget .community_post .reveal_full_post_btn{background:linear-gradient(to bottom,transparent,#0e1626 50%,#0e1626);color:#e8cc8e}.game_comments_widget .community_post .post_votes{border-color:rgba(236, 228, 210, 0.2)}.game_comments_widget .community_post .post_votes .vote_btn:hover{background:rgba(236, 228, 210, 0.05)}.game_comments_widget .community_post .post_footer .vote_btn{border-color:rgba(236, 228, 210, 0.5)}.game_comments_widget .community_post .post_footer .vote_btn span{color:inherit}.game_comments_widget .community_post .post_footer .vote_btn:hover,.game_comments_widget .community_post .post_footer .vote_btn.voted{background-color:#c4a05c;color:#ffffff;text-shadow:0 1px 0px #ab8743;border-color:#c4a05c}.game_comments_widget .form .click_input,.game_comments_widget .form .forms_markdown_input_widget{border-color:rgba(236, 228, 210, 0.5);background:transparent}.game_comments_widget .form .click_input,.game_comments_widget .form .forms_markdown_input_widget{background:rgba(37, 45, 61, 1)}.game_comments_widget .form .forms_markdown_input_widget .markdown_toolbar button{color:inherit;opacity:0.6}.game_comments_widget .form .forms_markdown_input_widget .markdown_toolbar button:hover,.game_comments_widget .form .forms_markdown_input_widget .markdown_toolbar button:active{opacity:1;background-color:#c4a05c !important;color:#ffffff !important;text-shadow:0 1px 0px #ab8743 !important}.game_comments_widget .form .forms_markdown_input_widget .markdown_toolbar,.game_comments_widget .form .forms_markdown_input_widget li{border-color:rgba(236, 228, 210, 0.5)}.game_comments_widget .form textarea{border-color:rgba(236, 228, 210, 0.5);background:rgba(37, 45, 61, 1);color:inherit}.game_comments_widget .hint{color:rgba(236, 228, 210, 0.5)}.game_community_preview_widget .community_topic_row .topic_tag{background-color:#252d3d}.footer .svgicon,.view_game_page .more_information_toggle .svgicon{fill:#ece4d2 !important}</style></head><body data-page_name="view_game" class="embedded_game locale_en game_layout_widget layout_widget responsive no_theme_toggle" data-host="itch.io"><ul id="user_tools" class="user_tools hidden"><li><a data-user_id="19576964" class="follow_user_btn action_btn" data-unfollow_url="https://eyalgolan.itch.io/-/unfollow?game_id=5179460&amp;source=game" data-follow_url="https://eyalgolan.itch.io/-/follow?game_id=5179460&amp;source=game" href="https://itch.io/login?return_to=https%3A%2F%2Feyalgolan.itch.io%2Fstatecraft-israel&amp;intent=follow_user" data-register_action="follow_user"><svg stroke="currentColor" class="svgicon icon_user_plus on_follow" role="img" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" version="1.1" width="18" aria-hidden><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="8.5" cy="7" r="4"></circle><line x1="20" y1="8" x2="20" y2="14"></line><line x1="23" y1="11" x2="17" y2="11"></line></svg><svg stroke="currentColor" class="svgicon icon_user_check on_unfollow" role="img" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" version="1.1" width="18" aria-hidden><path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="8.5" cy="7" r="4"></circle><polyline points="17 11 19 13 23 9"></polyline></svg><span class="on_follow"><span class="full_label">Follow eyalgolan</span><span class="mobile_label">Follow</span></span><span class="on_unfollow"><span class="full_label">Following eyalgolan</span><span class="mobile_label">Following</span></span></a></li><li><a data-game_id="5179460" href="https://itch.io/login?return_to=https%3A%2F%2Feyalgolan.itch.io%2Fstatecraft-israel&amp;intent=add_to_collection" class="action_btn add_to_collection_btn"><svg stroke="currentColor" class="svgicon icon_collection_add2" role="img" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" version="1.1" width="18" aria-hidden><path d="M 1,6 H 14" /><path d="M 1,11 H 14" /><path d="m 1,16 h 9" /><path d="M 18,11 V 21" /><path d="M 13,16 H 23" /></svg><span class="full_label">Add To Collection</span><span class="mobile_label">Collection</span></a></li><li class="community_link"><a href="https://eyalgolan.itch.io/statecraft-israel#comments" class="action_btn"><svg stroke="currentColor" class="svgicon icon_comment" role="img" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" version="1.1" width="18" aria-hidden><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" /></svg>Comments</a></li><li class="devlog_link"><a href="https://eyalgolan.itch.io/statecraft-israel/devlog" class="action_btn"><svg stroke="currentColor" class="svgicon icon_news" role="img" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" version="1.1" width="18" aria-hidden><rect x="1" y="3" width="22" height="18" rx="2" ry="2"></rect><line x1="6" y1="8" x2="18" y2="8"></line><line x1="6" y1="12" x2="18" y2="12"></line><line x1="6" y1="16" x2="18" y2="16"></line></svg>Devlog</a></li><li><a target="_blank" data-label="related_btn" href="https://itch.io/games-like/5179460/statecraft-israel" class="action_btn related_games_btn"><svg stroke="currentColor" class="svgicon icon_map" role="img" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" version="1.1" width="18" aria-hidden><polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"></polygon><line x1="8" y1="2" x2="8" y2="18"></line><line x1="16" y1="6" x2="16" y2="22"></line></svg> <span class="full_label">Related games</span><span class="mobile_label">Related</span></a></li></ul><script type="text/javascript">new I.GameUserTools('#user_tools')</script><div id="wrapper" class="main wrapper game_page_wrapper"><div id="inner_column" class="inner_column size_large family_serif"><div id="header" class="header align_center has_image"><img alt="Statecraft: Israel" src="https://img.itch.zone/aW1nLzMxMDY1NDgxLnBuZw==/original/1vQDVU.png"/><h1 itemprop="name" class="game_title">Statecraft: Israel</h1></div><div id="view_html_game_4510943" class="view_html_game_page view_game_page page_widget base_widget ready"><div id="html_embed_7636450" class="html_embed_widget base_widget embed_wrapper"><div data-height="720" data-width="1280" style="width: 1280px; height: 720px" class="game_frame game_pending"><button title="Enter fullscreen" class="fullscreen_btn"><img src="https://itch.io/static/images/enlarge.svg?1793126460"/></button><div data-iframe="&lt;iframe mozallowfullscreen=&quot;true&quot; scrolling=&quot;no&quot; id=&quot;game_drop&quot; src=&quot;https://html-classic.itch.zone/html/19840947-2217587/index.html?v=1793022659&quot; allowfullscreen=&quot;true&quot; msallowfullscreen=&quot;true&quot; allow=&quot;autoplay; fullscreen *; geolocation; microphone; camera; midi; monetization; xr-spatial-tracking; gamepad; gyroscope; accelerometer; xr; cross-origin-isolated; web-share&quot; frameborder=&quot;0&quot; allowtransparency=&quot;true&quot; webkitallowfullscreen=&quot;true&quot;&gt;&lt;/iframe&gt;" class="iframe_placeholder"><button class="button load_iframe_btn"><svg stroke="currentColor" class="svgicon icon_play" role="img" height="24" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" version="1.1" width="24" aria-hidden><circle cx="12" cy="12" r="10"></circle><polygon points="10 8 16 12 10 16 10 8"></polygon></svg> Run game</button></div></div></div><div class="columns"><div class="left_col column"><div class="formatted_description user_formatted"><p><strong>A turn-based strategy game about governing Israel. You are the prime minister on 15 May 1948. The ministers are the real ones, the map is real, and every historical fact comes with a source.</strong></p>
+<p>Each turn you:</p>
+<ul>
+<li>appoint and replace real ministers such as David Ben-Gurion, Eliezer Kaplan and Moshe Sharett, inside a real coalition;</li>
+<li>divide a tiny budget between security, immigrant absorption, the ma&#x27;abarot transit camps and austerity;</li>
+<li>manage security on a five-level escalation ladder, from routine threats to full war;</li>
+<li>face real decisions at their real dates, such as the First Truce, the Altalena affair and the Bernadotte assassination, and see why each outcome happened in the &quot;Why?&quot; panel.</li>
+</ul>
+<p><strong>How to play.</strong></p>
+<ul>
+<li>Each turn is one month. Look over the country, give your orders, then press End turn.</li>
+<li>Most orders cost Attention, shown in the top bar. It refills every turn, and Attention you don&#x27;t spend doesn&#x27;t carry over.</li>
+<li>Click a city on the map to see its housing and jobs, and set how many of its people are in work.</li>
+<li>An event card asks for a decision. A card you leave unanswered goes to the responsible minister when you end the turn.</li>
+<li>After a turn, open Why? to see each change and its cause.</li>
+</ul>
+<p><strong>This is an early prototype (v0.1.1).</strong> It runs 44 monthly turns, from 15 May 1948 to 15 January 1952. Some art is still placeholder, and the larger design (units you command, cities and construction) is still being built. Your game saves in your browser.</p>
+<p dir="rtl"><strong>בעברית.</strong> משחק אסטרטגיה בתורות על ניהול מדינת ישראל. אתם ראש הממשלה ב-15 במאי 1948. השרים אמיתיים, המפה אמיתית, ולכל עובדה היסטורית יש מקור. גרסה מלאה בעברית בדרך.</p>
+<p><strong>Content note.</strong> The game deals with war, terror and the Holocaust as historical events. Its framing is Israeli, every fact cites a source, and no quotes are invented.</p>
+<p><strong>Free and open source.</strong> Code: MIT. Assets: CC BY 4.0; content: CC BY-SA 4.0. Source code, sources, the roadmap and bug reports: <a href="https://github.com/eyalgolan/statecraft-israel" rel="nofollow noopener" referrerpolicy="origin">github.com/eyalgolan/statecraft-israel</a>. Want to help? Start with <a href="https://github.com/eyalgolan/statecraft-israel/blob/main/CONTRIBUTING.md" rel="nofollow noopener" referrerpolicy="origin">CONTRIBUTING.md</a>.</p>
+<p><strong>AI use.</strong> The code is written with AI coding agents and reviewed through tests and review gates. Some images are AI-generated, such as the start screen&#x27;s painting; the event photographs are archival.</p>
+<p><strong>Credits.</strong> 3D models: Tal Heuberger.</p>
+<p><em>An independent project. It is not affiliated with or endorsed by Firaxis, 2K, the State of Israel or any person depicted.</em></p></div><div class="more_information_toggle"><div class="toggle_row"><a href="javascript:void(0)" class="toggle_info_btn">More information<svg height="6" width="12" class="svgicon icon_down_tick" role="img" version="1.1" viewBox="0 0 37 20" aria-hidden><path d="m2.0858 0c-1.1535 0-2.0858 0.86469-2.0858 1.9331 0 0.5139 0.21354 1.0183 0.38704 1.1881l18.113 16.879 18.112-16.879c0.174-0.1696 0.388-0.674 0.388-1.1879 0-1.0684-0.932-1.9331-2.086-1.9331-0.577 0-1.111 0.23008-1.49 0.57992l-14.924 13.894-14.925-13.893c-0.3777-0.34998-0.9134-0.581-1.4902-0.581z"/></svg></a></div><div class="info_panel_wrapper"><div id="game_info_panel_3538496" class="game_info_panel_widget base_widget"><table><tbody><tr><td>Updated</td><td><abbr title="26 October 2026 @ 13:42 UTC"><span aria-hidden="true" class="icon icon-stopwatch"></span> 1 day ago</abbr></td></tr><tr><td>Published</td><td><abbr title="18 October 2026 @ 08:57 UTC"><span aria-hidden="true" class="icon icon-stopwatch"></span> 9 days ago</abbr></td></tr><tr><td>Status</td><td><a href="https://itch.io/games/in-development">In development</a></td></tr><tr><td>Platforms</td><td><a href="https://itch.io/games/html5">HTML5</a></td></tr><tr><td>Author</td><td><a href="https://eyalgolan.itch.io">eyalgolan</a></td></tr><tr><td>Genre</td><td><a href="https://itch.io/games/genre-strategy">Strategy</a>, <a href="https://itch.io/games/genre-simulation">Simulation</a></td></tr><tr><td>Made with</td><td><a href="https://itch.io/games/made-with-unity">Unity</a></td></tr><tr><td>Tags</td><td><a href="https://itch.io/games/tag-hex-based">Hex Based</a>, <a href="https://itch.io/games/tag-historical">Historical</a>, <a href="https://itch.io/games/tag-israel">israel</a>, <a href="https://itch.io/games/tag-management">Management</a>, <a href="https://itch.io/games/tag-open-source">Open Source</a>, <a href="https://itch.io/games/tag-politics">politics</a>, <a href="https://itch.io/games/tag-singleplayer">Singleplayer</a>, <a href="https://itch.io/games/tag-turn-based">Turn-based</a></td></tr><tr><td>AI Disclosure</td><td><a href="https://itch.io/games/ai-assisted">AI Assisted</a>, <a href="https://itch.io/games/ai-code">Code</a>, <a href="https://itch.io/games/ai-graphics">Graphics</a>, <a href="https://itch.io/games/ai-text">Text</a></td></tr></tbody></table></div></div></div><section id="devlog" class="game_devlog"><h2>Development log</h2><ul><li><a href="https://eyalgolan.itch.io/statecraft-israel/devlog/1730944/v031-share-sends-the-picture-again-hebrew-skip-works-after-end-turn-and-syrian-and-iraqi-figures-on-the-map">v0.3.1: Share sends the picture again, Hebrew Skip works after End turn, and Syr...</a><div class="post_date"><abbr title="26 October 2026 @ 13:42 UTC"><span aria-hidden="true" class="icon icon-stopwatch"></span> 1 day ago</abbr></div></li><li><a href="https://eyalgolan.itch.io/statecraft-israel/devlog/1729243/v030-three-advisors-ben-gurion-golda-meyerson-and-moshe-dayan-now-talk-you-through-the-first-turn">v0.3.0: Three advisors, Ben-Gurion, Golda Meyerson and Moshe Dayan, now talk you...</a><div class="post_date"><abbr title="25 October 2026 @ 17:45 UTC"><span aria-hidden="true" class="icon icon-stopwatch"></span> 2 days ago</abbr></div></li><li><a href="https://eyalgolan.itch.io/statecraft-israel/devlog/1721500/v014-your-brigades-move-easier-sharing-and-no-lost-turns">v0.1.4: your brigades move, easier sharing, and no lost turns</a><div class="post_date"><abbr title="21 October 2026 @ 23:21 UTC"><span aria-hidden="true" class="icon icon-stopwatch"></span> 5 days ago</abbr></div></li><li><a href="https://eyalgolan.itch.io/statecraft-israel/devlog/1720550/v013-a-first-turn-guide-objectives-sound-and-hebrew-event-cards">v0.1.3: a first-turn guide, objectives, sound, and Hebrew event cards</a><div class="post_date"><abbr title="21 October 2026 @ 13:34 UTC"><span aria-hidden="true" class="icon icon-stopwatch"></span> 6 days ago</abbr></div></li></ul></section><div id="game_comments_9817388" class="game_comments_widget base_widget"><h2 id="comments">Leave a comment</h2><p class="form_placeholder"><a href="https://itch.io/login?return_to=https%3A%2F%2Feyalgolan.itch.io%2Fstatecraft-israel" data-register_action="comment">Log in with itch.io</a> to leave a comment.</p><div id="community_topic_posts_4249332" class="community_topic_posts_widget base_widget"><div id="community_post_list_4452712" class="community_post_list_widget base_widget"><script id="vote_counts_tpl" type="text/template"><% if (up_score > 0) { %><span class="upvotes">(+{{up_score}})</span><% } %><% if (down_score > 0) { %><span class="downvotes">(-{{down_score}})</span><% } %></script></div></div></div></div><div class="right_col column"><div class="video_embed"></div><div class="screenshot_list"><a target="_blank" href="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1My5wbmc=/original/yCGbNK.png" data-image_lightbox="true"><img srcset="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1My5wbmc=/347x500/p2DU45.png 1x, https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1My5wbmc=/794x1000/hRhGWM.png 2x" class="screenshot" data-screenshot_id="31052353" src="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1My5wbmc=/347x500/p2DU45.png"/></a><a target="_blank" href="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1MS5wbmc=/original/2ohJQv.png" data-image_lightbox="true"><img srcset="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1MS5wbmc=/347x500/piil82.png 1x, https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1MS5wbmc=/794x1000/0yh0p5.png 2x" class="screenshot" data-screenshot_id="31052351" src="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1MS5wbmc=/347x500/piil82.png"/></a><a target="_blank" href="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM0OS5wbmc=/original/KVU7%2Bz.png" data-image_lightbox="true"><img srcset="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM0OS5wbmc=/347x500/i3QyfM.png 1x, https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM0OS5wbmc=/794x1000/knfzUw.png 2x" class="screenshot" data-screenshot_id="31052349" src="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM0OS5wbmc=/347x500/i3QyfM.png"/></a><a target="_blank" href="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1NC5wbmc=/original/of%2FNrB.png" data-image_lightbox="true"><img srcset="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1NC5wbmc=/347x500/fahG6Y.png 1x, https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1NC5wbmc=/794x1000/jdG%2F0O.png 2x" class="screenshot" data-screenshot_id="31052354" src="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1NC5wbmc=/347x500/fahG6Y.png"/></a><a target="_blank" href="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1MC5wbmc=/original/B9274O.png" data-image_lightbox="true"><img srcset="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1MC5wbmc=/347x500/IkLVua.png 1x, https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1MC5wbmc=/794x1000/cm0V71.png 2x" class="screenshot" data-screenshot_id="31052350" src="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1MC5wbmc=/347x500/IkLVua.png"/></a><a target="_blank" href="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1Mi5wbmc=/original/AjI9YV.png" data-image_lightbox="true"><img srcset="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1Mi5wbmc=/347x500/KtY4XO.png 1x, https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1Mi5wbmc=/794x1000/CUWgSl.png 2x" class="screenshot" data-screenshot_id="31052352" src="https://img.itch.zone/aW1hZ2UvNTE3OTQ2MC8zMTA1MjM1Mi5wbmc=/347x500/KtY4XO.png"/></a></div></div></div></div><div id="view_game_footer" class="footer"><a href="https://itch.io/" class="icon_logo"><svg height="17" width="20" class="svgicon icon_itchio_new" role="img" version="1.1" viewBox="0 0 262.728 235.452" aria-hidden><path d="M31.99 1.365C21.287 7.72.2 31.945 0 38.298v10.516C0 62.144 12.46 73.86 23.773 73.86c13.584 0 24.902-11.258 24.903-24.62 0 13.362 10.93 24.62 24.515 24.62 13.586 0 24.165-11.258 24.165-24.62 0 13.362 11.622 24.62 25.207 24.62h.246c13.586 0 25.208-11.258 25.208-24.62 0 13.362 10.58 24.62 24.164 24.62 13.585 0 24.515-11.258 24.515-24.62 0 13.362 11.32 24.62 24.903 24.62 11.313 0 23.773-11.714 23.773-25.046V38.298c-.2-6.354-21.287-30.58-31.988-36.933C180.118.197 157.056-.005 122.685 0c-34.37.003-81.228.54-90.697 1.365zm65.194 66.217a28.025 28.025 0 0 1-4.78 6.155c-5.128 5.014-12.157 8.122-19.906 8.122a28.482 28.482 0 0 1-19.948-8.126c-1.858-1.82-3.27-3.766-4.563-6.032l-.006.004c-1.292 2.27-3.092 4.215-4.954 6.037a28.5 28.5 0 0 1-19.948 8.12c-.934 0-1.906-.258-2.692-.528-1.092 11.372-1.553 22.24-1.716 30.164l-.002.045c-.02 4.024-.04 7.333-.06 11.93.21 23.86-2.363 77.334 10.52 90.473 19.964 4.655 56.7 6.775 93.555 6.788h.006c36.854-.013 73.59-2.133 93.554-6.788 12.883-13.14 10.31-66.614 10.52-90.474-.022-4.596-.04-7.905-.06-11.93l-.003-.045c-.162-7.926-.623-18.793-1.715-30.165-.786.27-1.757.528-2.692.528a28.5 28.5 0 0 1-19.948-8.12c-1.862-1.822-3.662-3.766-4.955-6.037l-.006-.004c-1.294 2.266-2.705 4.213-4.563 6.032a28.48 28.48 0 0 1-19.947 8.125c-7.748 0-14.778-3.11-19.906-8.123a28.025 28.025 0 0 1-4.78-6.155 27.99 27.99 0 0 1-4.736 6.155 28.49 28.49 0 0 1-19.95 8.124c-.27 0-.54-.012-.81-.02h-.007c-.27.008-.54.02-.813.02a28.49 28.49 0 0 1-19.95-8.123 27.992 27.992 0 0 1-4.736-6.155zm-20.486 26.49l-.002.01h.015c8.113.017 15.32 0 24.25 9.746 7.028-.737 14.372-1.105 21.722-1.094h.006c7.35-.01 14.694.357 21.723 1.094 8.93-9.747 16.137-9.73 24.25-9.746h.014l-.002-.01c3.833 0 19.166 0 29.85 30.007L210 165.244c8.504 30.624-2.723 31.373-16.727 31.4-20.768-.773-32.267-15.855-32.267-30.935-11.496 1.884-24.907 2.826-38.318 2.827h-.006c-13.412 0-26.823-.943-38.318-2.827 0 15.08-11.5 30.162-32.267 30.935-14.004-.027-25.23-.775-16.726-31.4L46.85 124.08c10.684-30.007 26.017-30.007 29.85-30.007zm45.985 23.582v.006c-.02.02-21.863 20.08-25.79 27.215l14.304-.573v12.474c0 .584 5.74.346 11.486.08h.006c5.744.266 11.485.504 11.485-.08v-12.474l14.304.573c-3.928-7.135-25.79-27.215-25.79-27.215v-.006l-.003.002z"/></svg></a><a href="https://itch.io/">itch.io</a><span class="dot">·</span><a href="https://eyalgolan.itch.io">View all by eyalgolan</a><span class="dot">·</span><a data-lightbox_url="https://eyalgolan.itch.io/statecraft-israel/report" href="javascript:void(0);" class="report_game_btn">Report</a><span class="dot">·</span><a data-lightbox_url="https://eyalgolan.itch.io/statecraft-israel/embed" href="javascript:void(0);" class="embed_game_btn">Embed</a><span class="dot last_dot">·</span><div class="update_timestamp">Updated <abbr title="26 October 2026 @ 13:42 UTC"> 1 day ago</abbr></div><div class="breadcrumbs"><a href="https://itch.io/games">Games</a> › <a href="https://itch.io/games/genre-strategy">Strategy</a> › <a href="https://itch.io/games/free">Free</a></div></div></div></div><script type="text/javascript">I.setup_layout()</script><script id="loading_lightbox_tpl" type="text/template"><div aria-live="polite" class="lightbox loading_lightbox"><div class="loader_outer"><div class="loader_label">Loading</div><div class="loader_bar"><div class="loader_bar_slider"></div></div></div></div></script><script type="text/javascript">init_HtmlEmbed('#html_embed_7636450', {"height":720,"width":1280,"start_maximized":false});init_GameInfoPanel('#game_info_panel_3538496', null);new I.CommunityViewTopic('#community_topic_posts_4249332', {"report_url":"https:\/\/itch.io\/post\/:post_id\/report"});init_ViewHtmlGame('#view_html_game_4510943', {"game":{"type":5,"id":5179460,"actual_price":0,"slug":"statecraft-israel","hit_url":"https:\/\/eyalgolan.itch.io\/statecraft-israel\/rh\/REDACTED","play_url":"https:\/\/eyalgolan.itch.io\/statecraft-israel\/rp\/REDACTED","play_after":30,"min_price":0,"type_name":"html"}});
+I.setup_page();</script></body></html>
\ No newline at end of file
diff --git a/tools/tests/test_nightly.py b/tools/tests/test_nightly.py
new file mode 100644
index 000000000..b6e54220e
--- /dev/null
+++ b/tools/tests/test_nightly.py
@@ -0,0 +1,1801 @@
+import dataclasses
+import json
+import subprocess
+import sys
+import time
+import zipfile
+from datetime import date, datetime
+from pathlib import Path
+
+import pytest
+
+pytest.importorskip("fcntl") # nightly imports unity_postmerge, which locks with flock
+
+import nightly
+import nightly_state as ns
+from conftest import FakeRunner
+
+SHA = "a" * 40
+OLD = "b" * 40
+NOW = datetime(2026, 10, 28, 3, 0, tzinfo=ns.TZ)
+TAG = "v0.3.1-nightly.20261028"
+
+
+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)."""
+
+ def __init__(self, release=None, *, fail=None, previous_tag="v0.3.1"):
+ self.release = release
+ self.fail = fail or {}
+ self.previous_tag = previous_tag
+ self.calls = []
+ self.baseline = None # a zip the download hands out
+
+ def _maybe_fail(self, name):
+ err = self.fail.get(name)
+ if isinstance(err, list):
+ err = err.pop(0) if err else None
+ if err is not None:
+ raise err
+
+ def release_state(self, tag):
+ self.calls.append(("release_state", tag))
+ return self.release
+
+ def delete_draft(self, tag):
+ self.calls.append(("delete_draft", tag))
+ self.release = None
+
+ def dispatch_site(self, deadline):
+ self.calls.append(("dispatch_site", deadline))
+ self._maybe_fail("dispatch_site")
+
+ def previous_build_tag(self, state_tag):
+ self.calls.append(("previous_build_tag", state_tag))
+ return state_tag or self.previous_tag
+
+ def download(self, tag, pattern, dest):
+ self.calls.append(("download", tag, pattern, dest))
+ self._maybe_fail("download")
+ return self.baseline
+
+ def create_draft(self, tag, sha, notes, assets):
+ self.calls.append(("create_draft", tag, sha, notes, list(assets)))
+ self.release = "draft"
+ self._maybe_fail("create_draft")
+
+ def verify_draft(self, tag, local, dest):
+ self.calls.append(("verify_draft", tag, list(local), dest))
+ self._maybe_fail("verify_draft")
+
+ def publish(self, tag, sha):
+ self.calls.append(("publish", tag, sha))
+ self._maybe_fail("publish")
+ self.release = "published"
+
+ def merged_pr_bodies(self, shas):
+ self.calls.append(("merged_pr_bodies", set(shas)))
+ return []
+
+ def names(self):
+ return [c[0] for c in self.calls]
+
+
+class Env:
+ """A tmp job folder, a tmp clone with the files preflight reads, and a FakeRunner answering the clone checks."""
+
+ def __init__(self, tmp_path, monkeypatch):
+ self.job = tmp_path / "job"
+ self.job.mkdir()
+ clone = tmp_path / "clone"
+ (clone / "sim/Statecraft.Sim").mkdir(parents=True)
+ (clone / "sim/Statecraft.Sim/SimInfo.cs").write_text('public const string Version = "0.3.1";\n')
+ (clone / "sim/Statecraft.Sim.Tests/golden").mkdir(parents=True)
+ (clone / "sim/Statecraft.Sim.Tests/golden/manifest.txt").write_text("golden-manifest\n")
+ (clone / "unity/ProjectSettings").mkdir(parents=True)
+ (clone / "unity/ProjectSettings/ProjectVersion.txt").write_text("m_EditorVersion: 6000.3.25f1\n")
+ self.licence = tmp_path / "lic.xml"
+ self.licence.write_text("x")
+ self.editor = tmp_path / "Unity"
+ self.editor.write_text("x")
+ self.slots = tmp_path / "unity_slots.py"
+ self.slots.write_text("x")
+ self.marker = tmp_path / "EXCLUSIVE-WINDOW"
+ monkeypatch.setattr(nightly.unity_postmerge, "unity_path", lambda version: str(self.editor))
+ self.cfg = ns.Config(clone=clone, licence=self.licence, unity_slots=self.slots, exclusive_marker=self.marker,
+ handoff=tmp_path / "HANDOFF.md")
+ self.runner = FakeRunner()
+ self.branch, self.head, self.origin, self.dirty = "main", SHA, SHA, ""
+ self._rules()
+ self.state_path = self.job / "state.json"
+
+ def _rules(self):
+ clone = str(self.cfg.clone)
+ # FakeRunner answers fixed text, so rules are rebuilt by set() when a field changes
+ self.runner.rules.clear()
+ self.runner.add(["git", "-C", clone, "rev-parse", "--abbrev-ref", "HEAD"], out=self.branch + "\n")
+ self.runner.add(["git", "-C", clone, "rev-parse", "HEAD"], out=self.head + "\n")
+ self.runner.add(["git", "-C", clone, "rev-parse", "refs/remotes/origin/main"], out=self.origin + "\n")
+ self.runner.add(["git", "-C", clone, "status", "--porcelain", "--untracked-files=no"], out=self.dirty)
+
+ def set(self, **kw):
+ for k, v in kw.items():
+ setattr(self, k, v)
+ self._rules()
+
+ def pre(self, state=None, gh=None, *, now=NOW, manual=False, free=100.0, no_publish=False):
+ return nightly.preflight(self.cfg, state or ns.State(), self.runner, gh or FakeGH(), job=self.job, now=now,
+ manual=manual, free_gb=lambda p: free, no_publish=no_publish)
+
+ def night(self, state=None, gh=None, *, now=NOW, manual=False, free=100.0, no_publish=False):
+ if state is not None:
+ ns.save_state(self.state_path, state)
+ return nightly.run_night(self.cfg, self.state_path, self.job, self.runner, gh or FakeGH(), None, now=now,
+ manual=manual, no_publish=no_publish, free_gb=lambda p: free)
+
+ def log(self):
+ p = self.job / "LOG.md"
+ return p.read_text() if p.exists() else ""
+
+
+def env(tmp_path, monkeypatch, no_processes):
+ monkeypatch.setattr(nightly, "notify", lambda *a, **k: env_notes.append(a))
+ env_notes.clear()
+ return Env(tmp_path, monkeypatch)
+
+
+env_notes: list = []
+
+
+def gate_of(env, **kw):
+ with pytest.raises(ns.Stop) as e:
+ env.pre(**kw)
+ return e.value
+
+
+def test_a_clean_preflight_builds_the_night(env):
+ n = env.pre()
+ assert (n.sha, n.version, n.tag, n.day) == (SHA, "0.3.1-nightly.20261028", TAG, date(2026, 10, 28))
+ assert n.manifest.strip() == "golden-manifest"
+ assert n.run_dir == env.job / "runs" / "20261028-030000" and n.job == env.job
+ assert n.deadline > time.monotonic()
+
+
+def test_an_unchanged_main_is_skipped(env):
+ st = ns.State(last_published=ns.Published("v0.3.0-nightly.20261027", SHA, "0.3.0", {}, None))
+ assert env.night(st) == "SKIPPED"
+ assert "SKIPPED" in env.log()
+ assert all(c[0] == "git" for c in env.runner.calls) # no Unity, no gh write
+ assert env.state_path.exists() and ns.load_state(env.state_path).last_run_day == "2026-10-28"
+
+
+def test_a_late_start_is_missed_and_earlier_gaps_are_reported(env):
+ late = datetime(2026, 10, 28, 9, 10, tzinfo=ns.TZ)
+ assert env.night(ns.State(last_run_day="2026-10-25"), now=late) == "MISSED"
+ missed = [ln for ln in env.log().splitlines() if "MISSED" in ln]
+ assert [ln[2:12] for ln in missed] == ["2026-10-26", "2026-10-27", "2026-10-28"]
+ assert env.runner.calls == [] # missed before any clone check
+
+
+def test_a_manual_run_ignores_the_window(env):
+ late = datetime(2026, 10, 28, 9, 10, tzinfo=ns.TZ)
+ assert env.pre(now=late, manual=True).tag == TAG
+
+
+def test_low_disk_refuses_before_anything_runs(env):
+ e = gate_of(env, free=39.9)
+ assert isinstance(e, ns.Refused) and e.gate == "disk"
+ assert all(c[0] == "git" for c in env.runner.calls)
+
+
+def test_the_exclusive_window_marker_refuses(env):
+ env.marker.write_text("x")
+ assert gate_of(env).gate == "exclusive-window"
+
+
[email protected]("what,gate", [("licence", "unity-licence"), ("editor", "unity-editor"),
+ ("slots", "unity-slots")])
+def test_a_missing_licence_unity_editor_or_unity_slots_refuses(env, what, gate):
+ getattr(env, what).unlink()
+ assert gate_of(env).gate == gate
+
+
[email protected]("change", [{"branch": "feat/x"}, {"head": OLD}, {"dirty": " M a.cs\n"}])
+def test_the_clone_must_be_main_at_origin_main_and_clean(env, change):
+ env.set(**change)
+ e = gate_of(env)
+ assert isinstance(e, ns.Refused) and e.gate == "clone"
+
+
+def test_same_day_rerun_cleans_its_draft_and_refuses_a_published_tag(env):
+ gh = FakeGH("draft")
+ st = ns.State(open_draft=TAG)
+ env.pre(st, gh)
+ assert ("delete_draft", TAG) in gh.calls
+ assert st.open_draft is None
+ gh = 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
+ gh = FakeGH("draft") # a draft this job did not leave
+ with 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
+
+
+def test_a_missing_tool_is_refused_and_recorded(env):
+ def gone(cmd):
+ raise FileNotFoundError("gh")
+ env.runner.rules.clear()
+ env.runner.add(["git"], effect=gone)
+ assert env.night() == "REFUSED"
+ assert "REFUSED" in env.log() and "gate=preflight" in env.log()
+ assert len(env_notes) == 1
+
+
+def test_no_publish_writes_no_record(env):
+ st = ns.State(last_published=ns.Published("v0.3.0", SHA, "0.3.0", {}, None))
+ assert env.night(st, no_publish=True) == "SKIPPED"
+ assert env.log() == "" and ns.load_state(env.state_path).last_run_day is None
+
+
+def test_a_corrupt_state_refuses_without_overwriting_it(env):
+ env.state_path.write_text("{nope")
+ assert env.night() == "REFUSED"
+ assert env.state_path.read_text() == "{nope" and "gate=state" in env.log()
+
+
+def pending_state():
+ return ns.State(last_published=ns.Published("v0.3.0", SHA, "0.3.0", {}, None), site_pending="0.3.0-nightly.20261027")
+
+
+def test_site_pending_is_retried_before_skipping(env, monkeypatch):
+ served = []
+ monkeypatch.setattr(nightly, "demo_serves", lambda url, version, *, deadline: served.append((url, version, deadline)))
+ gh = FakeGH()
+ assert env.night(pending_state(), gh) == "SKIPPED"
+ assert gh.names() == ["dispatch_site"] and gh.calls[0][1] > time.monotonic()
+ assert [s[:2] for s in served] == [(env.cfg.site_demo_url, "0.3.0-nightly.20261027")]
+ assert ns.load_state(env.state_path).site_pending is None # the retry worked, so nothing is pending
+ assert "SKIPPED" in env.log() and "now serves" in env.log()
+
+
[email protected]("where", ["dispatch", "demo"])
+def test_a_failing_site_retry_stays_pending_and_the_night_stays_skipped(env, monkeypatch, where):
+ def demo(url, version, *, deadline):
+ if where == "demo":
+ raise ns.Refused("site", "still serves 0.3.0")
+ monkeypatch.setattr(nightly, "demo_serves", demo)
+ gh = FakeGH(fail={"dispatch_site": ns.Refused("site", "run failed")} if where == "dispatch" else None)
+ assert env.night(pending_state(), gh) == "SKIPPED"
+ assert ns.load_state(env.state_path).site_pending == "0.3.0-nightly.20261027"
+ assert "SKIPPED" in env.log() and "still failed" in env.log() and env_notes == []
+
+
[email protected]("where", ["dispatch", "demo"])
+def test_a_non_refusal_error_in_the_site_retry_keeps_the_night_skipped_and_pending(env, monkeypatch, where):
+ def demo(url, version, *, deadline):
+ if where == "demo":
+ raise KeyError("databaseId")
+ monkeypatch.setattr(nightly, "demo_serves", demo)
+ gh = FakeGH(fail={"dispatch_site": KeyError("databaseId")} if where == "dispatch" else None)
+ assert env.night(pending_state(), gh) == "SKIPPED"
+ assert ns.load_state(env.state_path).site_pending == "0.3.0-nightly.20261027"
+ assert "KeyError" in env.log() and "still failed" in env.log()
+
+
+def test_no_publish_never_retries_the_site(env, monkeypatch):
+ monkeypatch.setattr(nightly, "demo_serves", lambda *a, **k: pytest.fail("a store call under --no-publish"))
+ gh = FakeGH()
+ assert env.night(pending_state(), gh, no_publish=True) == "SKIPPED"
+ assert gh.calls == []
+
+
+def test_no_publish_leaves_its_own_draft_alone(env):
+ gh = FakeGH("draft")
+ st = ns.State(open_draft=TAG)
+ env.pre(st, gh, no_publish=True)
+ assert ("delete_draft", TAG) not in gh.calls and st.open_draft == TAG
+
+
+def test_no_release_means_the_tag_is_free_and_any_release_refuses(env):
+ gh = FakeGH(None)
+ assert env.pre(gh=gh).tag == TAG
+ for state in ("draft", "published"):
+ with pytest.raises(ns.Refused) as e:
+ env.pre(gh=FakeGH(state))
+ assert e.value.gate == "tag-exists"
+
+
+def test_run_bounded_terminates_at_the_deadline(tmp_path):
+ t = time.monotonic()
+ code = nightly.ProcRunner(grace=1).run([sys.executable, "-c", "import time; time.sleep(60)"],
+ cwd=tmp_path, log=tmp_path / "l", deadline=time.monotonic() + 1)
+ assert code == 124 and time.monotonic() - t < 10
+
+
+def test_capture_refuses_on_a_non_zero_exit(tmp_path):
+ r = nightly.ProcRunner()
+ assert r.capture([sys.executable, "-c", "print('hi')"], cwd=tmp_path).strip() == "hi"
+ with pytest.raises(ns.Refused) as e:
+ r.capture([sys.executable, "-c", "raise SystemExit(3)"], cwd=tmp_path)
+ assert e.value.gate == "command"
+
+
+def test_the_deadline_kills_a_grandchild_that_ignores_sigterm(tmp_path):
+ import threading
+ pidfile = tmp_path / "pid"
+ grand = ("import signal,time,pathlib;signal.signal(signal.SIGTERM,signal.SIG_IGN);"
+ f"pathlib.Path({str(pidfile)!r}).write_text(str(__import__('os').getpid()));time.sleep(60)")
+ top = ("import subprocess,sys,time;subprocess.Popen([sys.executable,'-c',sys.argv[1]]);time.sleep(60)")
+ code = nightly.ProcRunner(grace=1).run([sys.executable, "-c", top, grand], cwd=tmp_path, log=tmp_path / "l",
+ deadline=time.monotonic() + 8) # long enough for a busy machine to start both
+ assert code == 124
+ end = time.monotonic() + 30
+ while not pidfile.exists() and time.monotonic() < end: # the grandchild may only just have written it
+ time.sleep(0.1)
+ assert pidfile.exists(), "the grandchild never started, so the test proves nothing"
+ pid = int(pidfile.read_text())
+ time.sleep(0.5)
+ with pytest.raises(ProcessLookupError):
+ import os
+ os.kill(pid, 0)
+
+
+def test_a_failed_state_save_still_writes_the_record(env, monkeypatch):
+ def boom(*a, **k):
+ raise OSError("disk full")
+ monkeypatch.setattr(nightly, "save_state", boom)
+ st = ns.State(last_published=ns.Published("v0.3.0", SHA, "0.3.0", {}, None))
+ assert env.night(st) == "SKIPPED"
+ assert "SKIPPED" in env.log()
+
+
+# --- gates and the full EditMode run (Task 3) -------------------------------------------------------------------
+
+import os
+from nightly_state import Refused
+
+OK_CHECK = "== unity compile (dotnet, outside Unity)\nALL CHECKS PASSED\n"
+DOTNET_OK = "Passed! - Failed: 0, Passed: 10, Skipped: 0, Total: 10, Duration: 1 s"
+
+
+class EnvRunner(FakeRunner):
+ """Also records the env each command ran with."""
+
+ def __init__(self):
+ super().__init__()
+ self.envs = []
+
+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):
+ self.envs.append((list(cmd), env, holder))
+ return super().run(cmd, cwd=cwd, log=log, deadline=deadline, env=env, holder=holder)
+
+
+def night(env):
+ env.runner = EnvRunner()
+ env._rules()
+ n = env.pre()
+ n.run_dir.mkdir(parents=True)
+ return n
+
+
+def test_unity_goes_through_slots_and_the_shared_lock(night):
+ argv = nightly.unity_argv(night, ["-runTests"], webgl=False)
+ assert argv[:3] == ["python3", "-I", str(night.cfg.unity_slots)] and "--webgl" not in argv
+ i = argv.index("--")
+ assert argv[i + 1:i + 6] == ["uv", "run", str(night.cfg.clone / "tools/machine_lock.py"), "--shared", "--"]
+ assert "--wait-unity" not in argv and "-nographics" not in argv
+ assert argv[-1] == "-runTests" and str(night.cfg.clone / "unity") in argv
+ assert nightly.unity_argv(night, ["-quit"], webgl=True)[3] == "--webgl"
+ env = nightly.unity_env(night)
+ assert env["UNITY_SLOTS"] == "3" and Path(env["UNITY_MCP_SERVER_PATH"]).is_file()
+ assert Path(env["UNITY_MCP_SERVER_PATH"]).read_text() == ""
+
+
+class LocaleRunner(EnvRunner):
+ """Answers `dotnet test` by the LANG it runs with."""
+
+ def __init__(self, he, en):
+ super().__init__()
+ self.by_lang = {"he_IL.UTF-8": he, "en_US.UTF-8": en}
+
+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):
+ if cmd[:2] == ["dotnet", "test"]:
+ self.calls.append(list(cmd))
+ self.envs.append((list(cmd), env, holder))
+ code, out = self.by_lang[env["LANG"]]
+ Path(log).parent.mkdir(parents=True, exist_ok=True)
+ Path(log).write_text(out)
+ return code
+ return super().run(cmd, cwd=cwd, log=log, deadline=deadline, env=env, holder=holder)
+
+
+def gates_runner(night, env, *, check=(0, OK_CHECK), rg=(0, "RELEASE GATE OK\n"), he=(0, DOTNET_OK),
+ en=(0, DOTNET_OK)):
+ r = LocaleRunner(he, en)
+ clone = night.cfg.clone
+ r.add(["uv", "run", f"{clone}/tools/build_sim_for_unity.py"], 0, "")
+ r.add(["bash", "scripts/check.sh", "origin/main"], *check)
+ r.add(["bash", "scripts/oss/release_gate.sh"], *rg)
+ return r
+
+
+def test_gates_run_in_order_with_both_locales(night, env):
+ r = gates_runner(night, env)
+ nightly.run_gates(night, r)
+ assert r.calls == [
+ ["uv", "run", f"{night.cfg.clone}/tools/build_sim_for_unity.py"],
+ ["bash", "scripts/check.sh", "origin/main"],
+ ["bash", "scripts/oss/release_gate.sh"],
+ ["dotnet", "test", "sim/Statecraft.sln", "-c", "Release", "--nologo"],
+ ["dotnet", "test", "sim/Statecraft.sln", "-c", "Release", "--nologo"],
+ ]
+ langs = [(e["LANG"], e["LC_ALL"]) for c, e, _ in r.envs if c[0] == "dotnet"]
+ assert langs == [("he_IL.UTF-8", "he_IL.UTF-8"), ("en_US.UTF-8", "en_US.UTF-8")]
+
+
[email protected]("which,gate,kw", [
+ ("build", "build-sim", None),
+ ("check", "check", dict(check=(1, OK_CHECK))),
+ ("check-skip", "check", dict(check=(0, "== unity compile: SKIPPED, no unity/Library\nALL CHECKS PASSED\n"))),
+ ("rg", "release-gate", dict(rg=(0, "RELEASE GATE FAILED\n"))),
+ ("he", "sim-he_IL", dict(he=(0, "Build succeeded."))),
+ ("he-fail", "sim-he_IL", dict(he=(1, "Failed! - Failed: 2, Passed: 8, Skipped: 0, Total: 10"))),
+ ("en", "sim-en_US", dict(en=(0, "Build succeeded."))),
+ ("en-fail", "sim-en_US", dict(en=(1, "Failed! - Failed: 1, Passed: 9, Skipped: 0, Total: 10"))),
+ ("timeout", "check", dict(check=(124, OK_CHECK))),
+])
+def test_a_failing_gate_refuses_by_name(night, env, which, gate, kw):
+ r = gates_runner(night, env, **(kw or {}))
+ if which == "build":
+ r.rules.insert(0, (("uv", "run", f"{night.cfg.clone}/tools/build_sim_for_unity.py"), 2, "", None))
+ with pytest.raises(Refused) as e:
+ nightly.run_gates(night, r)
+ assert e.value.gate == gate
+
+
+def test_a_later_gate_does_not_run_after_a_refusal(night, env):
+ r = gates_runner(night, env, check=(1, OK_CHECK))
+ with pytest.raises(Refused):
+ nightly.run_gates(night, r)
+ assert not any(c[0] == "dotnet" or c[:2] == ["bash", "scripts/oss/release_gate.sh"] for c in r.calls)
+
+
+WARM_OK = "UnityMcpGuard warm-up: gate defines in place\n"
+
+
+class EditRunner(EnvRunner):
+ """Unity steps (python3 -I ...) answer by kind: the warm-up has -executeMethod, the test run -runTests."""
+
+ def __init__(self, night, xml, code, warm_code, warm_log, restore_code):
+ super().__init__()
+ self.night, self.xml, self.code, self.warm_code = night, xml, code, warm_code
+ self.warm_log, self.restore_code = warm_log, restore_code
+
+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):
+ self.envs.append((list(cmd), env, holder))
+ self.calls.append(list(cmd))
+ d = self.night.run_dir
+ if cmd[0] == "git":
+ return self.restore_code
+ if "-executeMethod" in cmd:
+ (d / "warmup.log").write_text(self.warm_log)
+ return self.warm_code
+ if self.xml is not None:
+ (d / "editmode.xml").write_text(self.xml)
+ return self.code
+
+
+def editmode_runner(night, *, xml='<test-run total="5" passed="5" failed="0"/>', code=0, warm_code=0,
+ warm_log=WARM_OK, restore_code=0):
+ return EditRunner(night, xml, code, warm_code, warm_log, restore_code)
+
+
+def test_editmode_needs_tests_and_no_failures_and_never_quits(night, env):
+ r = editmode_runner(night)
+ nightly.run_editmode(night, r)
+ warm, tests, restore = r.envs
+ assert "-executeMethod" in warm[0] and nightly.unity_postmerge.WARM_UP in warm[0] and "-quit" not in warm[0]
+ assert "-runTests" in tests[0] and "-quit" not in tests[0] and "-testPlatform" in tests[0]
+ assert "--webgl" not in tests[0] and warm[1]["UNITY_MCP_SERVER_PATH"] == tests[1]["UNITY_MCP_SERVER_PATH"]
+ assert tests[2] == night.run_dir / "lock-holder"
+ assert restore[0] == nightly.RESTORE_ARGV
+
+
+def test_editmode_with_zero_tests_refuses_and_still_restores_settings(night, env):
+ r = editmode_runner(night, xml='<test-run total="0" passed="0" failed="0"/>')
+ with pytest.raises(Refused) as e:
+ nightly.run_editmode(night, r)
+ assert e.value.gate == "editmode"
+ assert r.envs[-1][0][0] == "git"
+
+
+def test_editmode_failure_or_missing_results_or_timeout_refuses(night, env):
+ for kw in (dict(xml='<test-run total="5" passed="4" failed="1"/>'), dict(xml=None), dict(code=124)):
+ r = editmode_runner(night, **kw)
+ with pytest.raises(Refused) as e:
+ nightly.run_editmode(night, r)
+ assert e.value.gate == "editmode"
+
+
+def test_settings_are_restored_when_the_runner_raises(night, env):
+ r = editmode_runner(night)
+ real = r.run
+
+ def boom(cmd, **k):
+ if "-runTests" in cmd:
+ raise OSError("disk gone")
+ return real(cmd, **k)
+ r.run = boom
+ with pytest.raises(OSError):
+ nightly.run_editmode(night, r)
+ assert r.envs[-1][0][0] == "git"
+
+
+def test_the_exclusive_marker_appearing_before_a_unity_step_refuses(night, env):
+ env.marker.write_text("x")
+ r = editmode_runner(night)
+ with pytest.raises(Refused) as e:
+ nightly.run_editmode(night, r)
+ assert e.value.gate == "exclusive-window" and not r.envs
+
+
+def test_a_warm_up_timeout_refuses_and_restores(night, env):
+ r = editmode_runner(night, warm_code=124)
+ with pytest.raises(Refused) as e:
+ nightly.run_editmode(night, r)
+ assert e.value.gate == "editmode" and "timed out" in e.value.detail
+ assert [c[0][0] for c in r.envs] == ["python3", "git"]
+
+
[email protected]("kw", [dict(warm_code=1), dict(warm_log=""), dict(warm_code=1, warm_log=WARM_OK)])
+def test_a_failed_or_unconfirmed_warm_up_refuses_before_any_test_run(night, env, kw):
+ r = editmode_runner(night, **kw)
+ with pytest.raises(Refused) as e:
+ nightly.run_editmode(night, r)
+ assert e.value.gate == "editmode" and "warm-up" in e.value.detail
+ assert not any("-runTests" in c for c in r.calls)
+ assert r.envs[-1][0][0] == "git"
+
+
+def test_the_warm_up_and_the_test_run_share_the_lock_holder(night, env):
+ r = editmode_runner(night)
+ nightly.run_editmode(night, r)
+ assert r.envs[0][2] == night.run_dir / "lock-holder" == r.envs[1][2]
+
+
+def test_a_failed_restore_does_not_replace_the_original_refusal(night, env, capsys):
+ r = editmode_runner(night, xml='<test-run total="5" passed="4" failed="1"/>', restore_code=1)
+ with pytest.raises(Refused) as e:
+ nightly.run_editmode(night, r)
+ assert e.value.gate == "editmode"
+ assert "restore-settings" in (night.run_dir / "restore-settings.note").read_text() + capsys.readouterr().err
+
+
+def test_a_failed_restore_alone_refuses(night, env):
+ r = editmode_runner(night, restore_code=1)
+ with pytest.raises(Refused) as e:
+ nightly.run_editmode(night, r)
+ assert e.value.gate == "restore-settings"
+
+
[email protected]("how", ["warm-up refusal", "runner raises"])
+def test_a_pending_error_and_a_failed_restore_keep_the_original(night, env, how):
+ if how == "warm-up refusal":
+ r = editmode_runner(night, warm_code=1, restore_code=1)
+ expect, exc = "editmode", Refused
+ else:
+ r = editmode_runner(night, restore_code=1)
+ real = r.run
+
+ def boom(cmd, **k):
+ if "-runTests" in cmd:
+ raise OSError("disk gone")
+ return real(cmd, **k)
+ r.run = boom
+ expect, exc = None, OSError
+ with pytest.raises(exc) as e:
+ nightly.run_editmode(night, r)
+ if expect:
+ assert e.value.gate == expect
+ assert "restore-settings" in (night.run_dir / "restore-settings.note").read_text()
+
+
+def test_a_restore_only_failure_is_not_swallowed_inside_a_caller_except_block(night, env):
+ r = editmode_runner(night, restore_code=1)
+ try:
+ raise ValueError("caller is handling something")
+ except ValueError:
+ with pytest.raises(Refused) as e:
+ nightly.run_editmode(night, r)
+ assert e.value.gate == "restore-settings"
+
+
+# --- the stamp, the two web builds and packaging ----------------------------------------------------------------
+
+STAMPED = "0.3.1-nightly.20261028"
+RESTORE_CMD = nightly.RESTORE_ARGV
+
+
+def test_the_stamp_replaces_exactly_the_one_bundle_version(tmp_path):
+ s = tmp_path / "ProjectSettings.asset"
+ s.write_text(" productName: X\n bundleVersion: 0.3.1\n other: 1\n")
+ nightly.stamp_bundle_version(s, STAMPED)
+ assert s.read_text() == f" productName: X\n bundleVersion: {STAMPED}\n other: 1\n"
+ s.write_text("no version here\n")
+ with pytest.raises(ValueError):
+ nightly.stamp_bundle_version(s, STAMPED)
+ s.write_text(" bundleVersion: 1\n bundleVersion: 2\n")
+ with pytest.raises(ValueError):
+ nightly.stamp_bundle_version(s, STAMPED)
+
+
+class WebRunner(EnvRunner):
+ """Answers the Build.Web runs (index.html carries `page_version`), the settings restore and the packaging."""
+
+ def __init__(self, night, *, page_version=STAMPED, build_code=0, package_out="PACKAGED x\nOK: notices inside x\n",
+ package_code=0):
+ super().__init__()
+ self.night, self.page_version, self.build_code = night, page_version, build_code
+ self.package_out, self.package_code = package_out, package_code
+ self.settings = night.cfg.clone / "unity/ProjectSettings/ProjectSettings.asset"
+ self.settings.parent.mkdir(parents=True, exist_ok=True)
+ self.settings.write_text(" bundleVersion: 0.3.1\n")
+ self.stamped_at_build = []
+ self.restores = 0
+
+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):
+ self.envs.append((list(cmd), env, holder))
+ self.calls.append(list(cmd))
+ if cmd[0] == "git" and cmd[1:3] == ["checkout", "--"]:
+ self.restores += 1
+ self.settings.write_text(" bundleVersion: 0.3.1\n")
+ return 0
+ if "-executeMethod" in cmd:
+ self.stamped_at_build.append(self.settings.read_text())
+ pages = "-decompressionFallback" in cmd
+ out = self.night.cfg.clone / "unity/Builds" / ("Web-pages" if pages else "Web-gzip")
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "index.html").write_text(f'productVersion: "{self.page_version}",\n')
+ return self.build_code
+ if cmd[0] == "bash":
+ Path(log).parent.mkdir(parents=True, exist_ok=True)
+ Path(log).write_text(self.package_out)
+ return self.package_code
+ raise AssertionError(f"unexpected command {cmd}")
+
+
+def builds(night, runner, *, free=100.0):
+ return (nightly.build_web(night, runner, pages=False, free_gb=lambda p: free),
+ nightly.build_web(night, runner, pages=True, free_gb=lambda p: free))
+
+
+def test_builds_follow_releasing_step_5(night, env):
+ r = WebRunner(night)
+ gz, pg = builds(night, r)
+ clone = night.cfg.clone
+ assert gz == clone / "unity/Builds/Web-gzip" and pg == clone / "unity/Builds/Web-pages"
+ gz_cmd = next(c for c in r.calls if "-executeMethod" in c and "-decompressionFallback" not in c)
+ pg_cmd = next(c for c in r.calls if "-decompressionFallback" in c)
+ gz_log = str(night.run_dir / "unity-build-web-gz.log")
+ pg_log = str(night.run_dir / "unity-build-web-pages.log")
+ method = ["-quit", "-buildTarget", "WebGL", "-executeMethod", "Statecraft.Game.EditorTools.Build.Web"]
+ i = gz_cmd.index("-quit")
+ assert gz_cmd[i:] == [*method, "-compression", "gzip", "-shareable", "-logFile", gz_log]
+ j = pg_cmd.index("-quit")
+ assert pg_cmd[j:] == [*method, "-compression", "gzip", "-decompressionFallback", "-shareable", "-out",
+ "Builds/Web-pages", "-logFile", pg_log]
+ for c in (gz_cmd, pg_cmd):
+ assert c[3] == "--webgl" and c[0] == "python3" and "--wait-unity" not in c
+ envs = [e for cmd, e, h in r.envs if "-executeMethod" in cmd]
+ assert all(Path(e["UNITY_MCP_SERVER_PATH"]).is_file() for e in envs)
+
+
+def test_the_stamp_is_applied_before_and_removed_after_each_build(night, env):
+ r = WebRunner(night)
+ builds(night, r)
+ assert r.stamped_at_build == [f" bundleVersion: {STAMPED}\n"] * 2
+ assert r.restores == 2 and r.settings.read_text() == " bundleVersion: 0.3.1\n"
+ kinds = ["restore" if c[0] == "git" else "build" for c in r.calls]
+ assert kinds == ["build", "restore", "build", "restore"]
+ assert r.calls[1] == RESTORE_CMD
+
+
+def test_a_build_page_without_tonights_version_refuses(night, env):
+ for wrong in ("0.3.1", "0.3.1-nightly.20261027"):
+ r = WebRunner(night, page_version=wrong)
+ with pytest.raises(Refused) as e:
+ nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
+ assert e.value.gate == "version-stamp"
+ assert r.restores == 1 and r.settings.read_text() == " bundleVersion: 0.3.1\n"
+ r = WebRunner(night)
+ (night.cfg.clone / "unity/Builds/Web-gzip").mkdir(parents=True, exist_ok=True)
+ r.build_code = 0
+ r.page_version = "none"
+ with pytest.raises(Refused):
+ nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
+
+
+def test_a_failed_build_refuses_and_restores(night, env):
+ r = WebRunner(night, build_code=1)
+ with pytest.raises(Refused) as e:
+ nightly.build_web(night, r, pages=True, free_gb=lambda p: 100.0)
+ assert e.value.gate == "build-web" and r.restores == 1
+
+
+def test_low_disk_before_the_second_build_refuses(night, env):
+ r = WebRunner(night)
+ seen = iter([100.0, 39.0])
+ nightly.build_web(night, r, pages=False, free_gb=lambda p: next(seen))
+ with pytest.raises(Refused) as e:
+ nightly.build_web(night, r, pages=True, free_gb=lambda p: next(seen))
+ assert e.value.gate == "disk"
+ assert sum("-executeMethod" in c for c in r.calls) == 1
+ assert r.settings.read_text() == " bundleVersion: 0.3.1\n"
+
+
+def test_the_exclusive_marker_refuses_a_web_build(night, env):
+ env.marker.write_text("x")
+ r = WebRunner(night)
+ with pytest.raises(Refused) as e:
+ nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
+ assert e.value.gate == "exclusive-window" and r.calls == []
+
+
+def test_a_build_timeout_restores_settings_and_refuses(night, env):
+ r = WebRunner(night, build_code=124)
+ with pytest.raises(Refused) as e:
+ nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
+ assert e.value.gate == "build-web" and "timed out" in e.value.detail
+ assert r.restores == 1 and r.settings.read_text() == " bundleVersion: 0.3.1\n" # no stamp left behind
+
+
+def test_a_failed_restore_does_not_mask_the_build_error(night, env, capsys):
+ r = WebRunner(night, build_code=124)
+ real = r.run
+
+ def run(cmd, **k):
+ return 1 if cmd[0] == "git" else real(cmd, **k)
+ r.run = run
+ with pytest.raises(Refused) as e:
+ nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
+ assert e.value.gate == "build-web"
+ assert (night.run_dir / "restore-settings.note").is_file()
+
+
+def test_packaging_needs_the_notices_line(night, env):
+ r = WebRunner(night)
+ build = night.cfg.clone / "unity/Builds/Web-gzip"
+ z = nightly.package_zip(night, r, build, False)
+ assert z == night.run_dir / f"statecraft-israel-v{STAMPED}-web.zip"
+ assert r.calls[-1] == ["bash", "scripts/oss/package_web.sh", str(build), str(z)]
+ zp = nightly.package_zip(night, r, night.cfg.clone / "unity/Builds/Web-pages", True)
+ assert zp == night.run_dir / f"statecraft-israel-v{STAMPED}-web-pages.zip"
+ for kw in (dict(package_out="PACKAGED x\n"), dict(package_out="OK: notices inside x\n"),
+ dict(package_code=1), dict(package_code=124)):
+ with pytest.raises(Refused) as e:
+ nightly.package_zip(night, WebRunner(night, **kw), build, False)
+ assert e.value.gate == "package"
+
+
+def test_the_tree_must_be_clean_after_the_builds(night, env):
+ nightly.assert_clean_tree(night, env.runner)
+ env.set(dirty=" M unity/ProjectSettings/ProjectSettings.asset\n")
+ with pytest.raises(Refused) as e:
+ nightly.assert_clean_tree(night, env.runner)
+ assert e.value.gate == "dirty-tree"
+
+
+def test_a_malformed_bundle_version_surfaces_as_a_version_stamp_refusal(night, env):
+ r = WebRunner(night)
+ r.settings.write_text(" bundleVersion: 0.3.1\n bundleVersion: 0.3.2\n")
+ with pytest.raises(Refused) as e:
+ nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
+ assert e.value.gate == "version-stamp" and "bundleVersion" in e.value.detail
+ assert r.restores == 1 and r.settings.read_text() == " bundleVersion: 0.3.1\n"
+ assert not any("-executeMethod" in c for c in r.calls)
+
+
+# --- Task 5: web checks, sizes, boot -----------------------------------------------------------------------------
+
+class CheckRunner(EnvRunner):
+ """Answers the web_check and boot runs: `answers` maps a marker in the argv to (code, text), else (0, `ok`)."""
+
+ def __init__(self, ok="PASS: saw x\n", answers=None):
+ super().__init__()
+ self.ok, self.answers, self.cwds = ok, answers or {}, []
+
+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):
+ self.envs.append((list(cmd), env, holder))
+ self.calls.append(list(cmd))
+ self.cwds.append(cwd)
+ code, text = 0, self.ok
+ for marker, answer in self.answers.items():
+ if marker in cmd:
+ code, text = answer(len(self.calls)) if callable(answer) else answer
+ Path(log).parent.mkdir(parents=True, exist_ok=True)
+ Path(log).write_text(text)
+ return code
+
+
+MANIFEST = "# c\nhash1950 aa\nsmoke5 cc\nsmoke-orders dd\n"
+
+
+def test_a_manifest_without_the_smoke_goldens_refuses(night, env):
+ r = CheckRunner()
+ with pytest.raises(Refused) as e:
+ nightly.run_web_checks(night, r, night.cfg.clone / "unity/Builds/Web-gzip") # the fixture manifest is a stub
+ assert e.value.gate == "web-check" and r.calls == []
+
+
+def test_web_checks_run_under_the_shared_lock_and_all_must_pass(night, env):
+ night.manifest = MANIFEST
+ build = night.cfg.clone / "unity/Builds/Web-gzip"
+ r = CheckRunner()
+ nightly.run_web_checks(night, r, build)
+ clone = night.cfg.clone
+ assert len(r.calls) == 7
+ for c in r.calls:
+ assert c[:8] == ["uv", "run", str(clone / "tools/machine_lock.py"), "--shared", "--", "uv", "run",
+ str(clone / "tools/web_check.py")]
+ assert c[8] == str(build) and "--wait-unity" not in c
+ assert set(r.cwds) == {clone}
+ assert (night.run_dir / "web-check-Web-gzip-7.log").is_file()
+
+
[email protected]("answer", [(1, "PASS: saw x\n"), (0, "console: nothing\n"), (0, "TIMEOUT: never saw x\n"),
+ (124, "PASS: saw x\n")])
+def test_a_failing_web_check_pass_refuses_and_stops(night, env, answer):
+ night.manifest = MANIFEST
+ r = CheckRunner(answers={"--persistence": answer, "--startscreen": answer})
+ with pytest.raises(Refused) as e:
+ nightly.run_web_checks(night, r, night.cfg.clone / "unity/Builds/Web-pages")
+ assert e.value.gate == "web-check" and "Web-pages" in e.value.detail
+ assert len(r.calls) == 3 # golden, smoke-orders, then the first startscreen pass fails
+
+
+class FakeGhSizes:
+ def __init__(self, bodies=(), error=None):
+ self.bodies, self.error, self.calls = list(bodies), error, []
+
+ def merged_pr_bodies(self, shas):
+ self.calls.append(set(shas))
+ if self.error:
+ raise self.error
+ return self.bodies
+
+
+def fake_gh():
+ return FakeGhSizes
+
+
+def sized_build(root, data):
+ from test_nightly_checks import make_build
+ return make_build(root, extra=False, data=data)
+
+
+def baseline_zip(path, data=900):
+ with zipfile.ZipFile(path, "w") as z:
+ z.writestr("index.html", 'x "Build/h1.data.gz" "Build/h1.wasm.gz" "Build/h1.framework.js.gz"')
+ z.writestr("Build/h1.data.gz", b"d" * data)
+ z.writestr("Build/h1.wasm.gz", b"w" * 90)
+ z.writestr("Build/h1.framework.js.gz", b"f" * 10)
+ return path
+
+
+def test_sizes_refuse_without_a_baseline_zip(night, env, fake_gh, tmp_path):
+ build = sized_build(tmp_path / "b", 900)
+ with pytest.raises(Refused) as e:
+ nightly.check_sizes(night, fake_gh(), build, tmp_path / "absent.zip", OLD, runner=env.runner)
+ assert e.value.gate == "sizes" and "baseline" in e.value.detail
+ bad = tmp_path / "bad.zip"
+ bad.write_text("not a zip")
+ with pytest.raises(Refused) as e:
+ nightly.check_sizes(night, fake_gh(), build, bad, OLD, runner=env.runner)
+ assert e.value.gate == "sizes"
+
+
+def test_a_budget_is_looked_up_only_when_growth_exceeds_2_percent(night, env, fake_gh, tmp_path):
+ clone = str(night.cfg.clone)
+ env.runner.add(["git", "-C", clone, "rev-list", f"{OLD}..{SHA}"], out="c1\nc2\n")
+ z = baseline_zip(tmp_path / "prev.zip")
+ gh = fake_gh()
+ assert nightly.check_sizes(night, gh, sized_build(tmp_path / "ok", 920), z, OLD, runner=env.runner) == \
+ {"data": 920, "wasm": 90, "framework": 10}
+ assert gh.calls == [] # +20 of 1000 needs no lookup
+ with pytest.raises(Refused) as e:
+ nightly.check_sizes(night, gh, sized_build(tmp_path / "big", 921), z, OLD, runner=env.runner)
+ assert e.value.gate == "sizes" and "1021" in e.value.detail and gh.calls == [{"c1", "c2"}]
+ gh = fake_gh(["Nightly size budget: +0.001 MB"])
+ assert nightly.check_sizes(night, gh, sized_build(tmp_path / "b2", 921), z, OLD, runner=env.runner)["data"] == 921
+ with pytest.raises(Refused): # the budget is too small for +500
+ nightly.check_sizes(night, fake_gh(["Nightly size budget: +0.0001 MB"]),
+ sized_build(tmp_path / "b3", 1400), z, OLD, runner=env.runner)
+
+
+def test_growth_with_an_unknown_previous_commit_refuses(night, env, fake_gh, tmp_path):
+ z = baseline_zip(tmp_path / "prev.zip")
+ with pytest.raises(Refused) as e:
+ nightly.check_sizes(night, fake_gh(), sized_build(tmp_path / "big", 1400), z, None, runner=env.runner)
+ assert e.value.gate == "sizes"
+
+
+def test_a_truncated_pr_list_refuses(night, env, fake_gh, tmp_path):
+ env.runner.add(["git", "-C", str(night.cfg.clone), "rev-list"], out="c1\n")
+ gh = fake_gh(error=Refused("sizes", "500 merged PRs, the list may be truncated"))
+ with pytest.raises(Refused) as e:
+ nightly.check_sizes(night, gh, sized_build(tmp_path / "big", 1400), baseline_zip(tmp_path / "p.zip"), OLD,
+ runner=env.runner)
+ assert e.value.gate == "sizes" and "truncated" in e.value.detail
+
+
+def boot_text(ms):
+ return f"console: BOOT phase=screens ready at={ms} ms dt=40 ms\nconsole: GAME OK 1948 turn 0 hash ab\nPASS: saw GAME OK\n"
+
+
+def test_boot_takes_the_exclusive_lock_from_the_main_checkout_three_times(night, env):
+ times = iter([8100, 8300, 8200])
+
+ class BootRunner(CheckRunner):
+ def run(self, cmd, **k):
+ self.ok = boot_text(next(times))
+ return super().run(cmd, **k)
+
+ r = BootRunner()
+ build = night.cfg.clone / "unity/Builds/Web-gzip"
+ assert nightly.measure_boot(night, r, build) == 8200.0
+ clone = night.cfg.clone
+ assert len(r.calls) == 3 and set(r.cwds) == {night.cfg.main_repo}
+ assert r.calls[0] == ["uv", "run", str(clone / "tools/machine_lock.py"), "--exclusive", "--wait-unity",
+ "--timeout", "2700", "--", "uv", "run", str(clone / "tools/web_check.py"), str(build),
+ "--query", "bootlog", "--expect", "GAME OK", "--timeout", "300", "--stall", "90"]
+
+
[email protected]("answer,word", [((3, ""), "Unity"), ((124, ""), "timed out"), ((1, boot_text(1)), "exited 1"),
+ ((0, "PASS: saw GAME OK\n"), "BOOT"), ((0, "TIMEOUT\n"), "pass")])
+def test_a_bad_boot_run_refuses_with_gate_boot(night, env, answer, word):
+ r = CheckRunner(answers={"--exclusive": answer})
+ with pytest.raises(Refused) as e:
+ nightly.measure_boot(night, r, night.cfg.clone / "unity/Builds/Web-gzip")
+ assert e.value.gate == "boot" and word in e.value.detail
+ assert len(r.calls) == 1
+
+
+# --- Task 6: publish_night, the stage wiring, the clients ---------------------------------------------------------
+
+BOOT_MS = 8200.0
+SIZES = {"data": 1000, "wasm": 90, "framework": 10}
+
+
+def pub(night, env, tmp_path):
+ """A night plus two zips, a git log answer and a fake demo check."""
+ clone = str(night.cfg.clone)
+ env.runner.add(["git", "-C", clone, "log", "--format=%s"], out="Fix a thing\nAdd a thing\n")
+ zips = (tmp_path / "web.zip", tmp_path / "pages.zip")
+ for z in zips:
+ z.write_bytes(b"zip")
+ return zips
+
+
+def served(monkeypatch):
+ calls = []
+ monkeypatch.setattr(nightly, "demo_serves", lambda url, version, *, deadline: calls.append((url, version)))
+ return calls
+
+
+def last_published():
+ return ns.Published("v0.3.0-nightly.20261027", OLD, "0.3.0-nightly.20261027", {}, None)
+
+
+PREVIOUS = ("v0.3.0-nightly.20261027", OLD)
+
+
+def publish(night, state, gh, zips, env, itch=None, save=lambda: None, previous=PREVIOUS):
+ nightly.publish_night(night, state, gh, itch, zips, SIZES, BOOT_MS, previous=previous, save=save,
+ runner=env.runner)
+
+
+def test_release_targets_the_preflight_commit(night, env, pub, served):
+ clone = str(night.cfg.clone)
+ gh, st = FakeGH(), ns.State(last_published=last_published())
+ publish(night, st, gh, pub, env) # origin/main may move on after preflight: nothing may follow it
+ create = next(c for c in gh.calls if c[0] == "create_draft")
+ assert create[1:3] == (TAG, night.sha) and create[4] == list(pub)
+ assert ["git", "-C", clone, "log", "--format=%s", f"{OLD}..{night.sha}"] in env.runner.calls
+ assert not any("ls-remote" in c and "refs/heads/main" in c for c in env.runner.calls)
+ notes = (night.run_dir / "release-notes.md").read_text()
+ assert "- Fix a thing" in notes and "- Add a thing" in notes and night.sha[:12] in notes
+ assert gh.names() == ["create_draft", "verify_draft", "publish", "dispatch_site"]
+
+
+def test_the_first_night_fetches_the_release_tag_before_resolving_it(night, env):
+ clone = str(night.cfg.clone)
+ env.runner.add(["git", "-C", clone, "fetch"])
+ env.runner.add(["git", "-C", clone, "rev-list", "-n", "1", "refs/tags/v0.3.1"], out=OLD + "\n")
+ gh = FakeGH()
+ assert nightly.previous_build(night, ns.State(), gh, env.runner) == ("v0.3.1", OLD)
+ fetch = ["git", "-C", clone, "fetch", "--no-tags", "origin", "refs/tags/v0.3.1:refs/tags/v0.3.1"]
+ assert env.runner.calls.index(fetch) < [c[3] for c in env.runner.calls].index("rev-list")
+
+
+def test_a_failed_tag_fetch_on_the_first_night_refuses(night, env):
+ env.runner.add(["git", "-C", str(night.cfg.clone), "fetch"], code=128)
+ with pytest.raises(ns.Refused):
+ nightly.previous_build(night, ns.State(), FakeGH(), env.runner)
+
+
+def test_later_nights_use_the_published_commit_and_fetch_nothing(night, env):
+ assert nightly.previous_build(night, ns.State(last_published=last_published()), FakeGH(), env.runner) == \
+ ("v0.3.0-nightly.20261027", OLD)
+ assert not any("fetch" in c for c in env.runner.calls)
+
+
+def test_the_notes_log_runs_from_the_previous_commit_or_tag(night, env, pub, served):
+ clone = str(night.cfg.clone)
+ publish(night, ns.State(), FakeGH(), pub, env, previous=("v0.3.1", None))
+ assert ["git", "-C", clone, "log", "--format=%s", f"v0.3.1..{night.sha}"] in env.runner.calls
+
+
[email protected]("which", ["verify_draft", "create_draft"])
+def test_a_failed_draft_check_deletes_the_draft_and_refuses(night, env, pub, served, which):
+ gh = FakeGH(fail={which: ns.Refused("github-draft", "hash differs")})
+ st = ns.State(last_published=last_published())
+ with 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 st.open_draft is None and st.last_published.sha == OLD and served == []
+
+
+def test_a_non_refusal_error_in_the_draft_check_still_deletes_the_draft(night, env, pub, served):
+ gh = 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
+
+
+def 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"))
+ st = ns.State(last_published=last_published())
+ with pytest.raises(ns.Refused) as e:
+ publish(night, st, gh, pub, env)
+ assert e.value.gate == "github-draft" and st.open_draft == TAG and "offline" in capsys.readouterr().err
+
+
+def test_a_failed_publish_deletes_a_draft_that_is_still_one(night, env, pub, served):
+ gh = FakeGH(fail={"publish": ns.Refused("github-publish", "tag at the wrong commit")})
+ st = 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 st.last_published.sha == OLD and served == []
+
+
+def test_a_failed_publish_check_on_a_public_release_is_never_deleted(night, env, pub, served):
+ class Public(FakeGH):
+ def publish(self, tag, sha):
+ self.release = "published"
+ raise ns.Refused("github-publish", f"{tag} became the Latest release")
+ gh = Public()
+ st = 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 "by hand" in e.value.detail
+ assert "delete_draft" not in gh.names() and st.open_draft == TAG
+
+
+def test_a_site_failure_after_publish_retries_once_then_refuses_and_marks_site_pending(night, env, pub, served):
+ err = ns.Refused("site", "run failed")
+ gh = FakeGH(fail={"dispatch_site": [err, err]})
+ st = ns.State(last_published=last_published())
+ with pytest.raises(ns.Refused) as e:
+ publish(night, st, gh, pub, env)
+ assert e.value.gate == "site" and "public" in e.value.detail and "unchanged" in e.value.detail
+ assert gh.names().count("dispatch_site") == 2 and "delete_draft" not in gh.names()
+ assert st.last_published.tag == TAG and st.last_published.sha == night.sha # the release is public
+ assert st.site_pending == night.version and st.open_draft is None
+
+
[email protected]("how", ["incomplete-read", "key-error"])
+def test_an_unexpected_error_in_the_site_step_still_gets_the_second_attempt(night, env, pub, monkeypatch, how):
+ import http.client
+ import nightly_publish as gp
+ def broken(url, timeout):
+ raise http.client.IncompleteRead(b"x")
+ monkeypatch.setattr(nightly, "demo_serves", lambda url, version, *, deadline: gp.demo_serves(
+ url, version, deadline=deadline, fetch=broken, sleep=lambda s: None, now=iter(range(0, 10**9, 10**8)).__next__))
+ fail = {"dispatch_site": [KeyError("databaseId"), KeyError("databaseId")]} if how == "key-error" else None
+ gh, st = FakeGH(fail=fail), ns.State(last_published=last_published())
+ with pytest.raises(ns.Refused) as e:
+ publish(night, st, gh, pub, env)
+ assert e.value.gate == "site" and gh.names().count("dispatch_site") == 2
+ assert st.site_pending == night.version and st.last_published.tag == TAG
+
+
+def test_site_pending_is_marked_before_the_site_step_and_saved_with_the_publish(night, env, pub, monkeypatch):
+ seen = []
+ monkeypatch.setattr(nightly, "demo_serves", lambda *a, **k: None)
+ gh, st = FakeGH(), ns.State(last_published=last_published())
+ gh.dispatch_site = lambda deadline: seen.append(st.site_pending)
+ publish(night, st, gh, pub, env)
+ assert seen == [night.version] and st.site_pending is None
+
+
+class Crash(BaseException):
+ pass
+
+
+def test_state_is_saved_right_after_create_draft_and_right_after_publish(night, env, pub, served, tmp_path):
+ path = tmp_path / "state.json"
+ saves = []
+
+ def save(crash_on):
+ def f():
+ ns.save_state(path, st)
+ saves.append((st.open_draft, st.last_published.tag))
+ if len(saves) == crash_on:
+ raise Crash()
+ return f
+ 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 ns.load_state(path).open_draft == TAG and saves[0] == (TAG, last_published().tag)
+ saves.clear()
+ st = ns.State(last_published=last_published())
+ with pytest.raises(Crash):
+ publish(night, st, FakeGH(), pub, env, save=save(2)) # killed right after publish
+ disk = ns.load_state(path)
+ assert disk.last_published.tag == TAG and disk.open_draft is None and disk.last_published.sha == night.sha
+
+
+def test_a_failing_checkpoint_save_does_not_stop_the_night(env, monkeypatch, capsys):
+ monkeypatch.setattr(nightly, "save_state", lambda p, st: (_ for _ in ()).throw(OSError("full")))
+ seen = {}
+ def stages(night, state, runner, gh, itch, *, no_publish, free_gb, save):
+ save()
+ seen["ok"] = True
+ return True
+ monkeypatch.setattr(nightly, "run_stages", stages)
+ assert env.night() == "PUBLISHED" and seen and "could not save state" in capsys.readouterr().err
+
+
+def test_a_failed_checkpoint_save_notifies_so_it_is_never_silent(env, monkeypatch):
+ monkeypatch.setattr(nightly, "save_state", lambda p, st: (_ for _ in ()).throw(OSError("full")))
+ monkeypatch.setattr(nightly, "run_stages", lambda night, state, runner, gh, itch, *, no_publish, free_gb, save:
+ save() or True)
+ assert env.night() == "PUBLISHED"
+ assert any("not saved" in a[0].lower() and "full" in a[1] for a in env_notes)
+
+
+def test_a_failing_demo_check_is_retried_once_and_a_second_success_clears_pending(night, env, pub, monkeypatch):
+ results = [ns.Refused("site", "old page"), None]
+
+ def demo(url, version, *, deadline):
+ r = results.pop(0)
+ if r:
+ raise r
+ monkeypatch.setattr(nightly, "demo_serves", demo)
+ gh, st = FakeGH(), ns.State(last_published=last_published(), site_pending="0.2.9")
+ publish(night, st, gh, pub, env)
+ assert gh.names().count("dispatch_site") == 2 and st.site_pending is None
+
+
+def test_a_published_night_updates_state_and_boot_baseline(night, env, pub, served):
+ gh, st = FakeGH(), ns.State(last_published=last_published(), boot_baseline=[8000.0, 8100.0], open_draft="x")
+ publish(night, st, gh, pub, env)
+ assert st.last_published == ns.Published(TAG, night.sha, night.version, SIZES, BOOT_MS)
+ assert st.boot_baseline == [8000.0, 8100.0, BOOT_MS] and st.open_draft is None and st.site_pending is None
+ assert served == [(night.cfg.site_demo_url, night.version)]
+ full = ns.State(last_published=last_published(), boot_baseline=[1.0, 2.0, 3.0, 4.0, 5.0])
+ publish(night, full, FakeGH(), pub, env)
+ assert full.boot_baseline == [1.0, 2.0, 3.0, 4.0, 5.0]
+
+
+def test_itch_is_skipped_with_a_logged_reason_when_there_is_no_client(night, env, pub, served, capsys):
+ publish(night, ns.State(last_published=last_published()), FakeGH(), pub, env)
+ assert "itch: skipped (save test not passed)" in capsys.readouterr().out
+
+
+# --- Task 7: itch.io, behind itch_enabled ---------------------------------------------------------------------------------
+
+PREV_TAG = "v0.3.0-nightly.20261027"
+PREV_VERSION = "0.3.0-nightly.20261027"
+
+
+class FakeItch:
+ """The itch client as the night uses it; every call lands in `log`, which tests share with FakeGH.calls."""
+
+ def __init__(self, log, *, fail=None):
+ self.log, self.fail = log, fail or {}
+
+ def _call(self, name, *args):
+ self.log.append((f"itch.{name}", *args))
+ err = self.fail.get(name)
+ if isinstance(err, list):
+ err = err.pop(0) if err else None
+ if err is not None:
+ raise err
+
+ def push(self, folder, version):
+ self._call("push", Path(folder).name, version)
+
+ def wait_live(self, version, deadline):
+ self._call("wait_live", version)
+
+ def matches(self, folder, dest):
+ self._call("matches", Path(folder).name)
+
+
+def zip_of(path, name):
+ with zipfile.ZipFile(path, "w") as z:
+ z.writestr("index.html", name)
+ return path
+
+
+def itch_night(night, env, tmp_path, served):
+ """An itch-enabled night with real zips for tonight and the previous build."""
+ night.cfg = dataclasses.replace(night.cfg, itch_enabled=True)
+ 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"))
+ gh = FakeGH()
+ gh.baseline = zip_of(tmp_path / "previous-web.zip", "previous")
+ return night, zips, gh, FakeItch(gh.calls)
+
+
+def run_itch(itch_night, env, itch="fake", st=None):
+ night, zips, gh, fake = itch_night
+ st = st or ns.State(last_published=last_published())
+ publish(night, st, gh, zips, env, itch=fake if itch == "fake" else itch)
+ return gh, st
+
+
+def refused_itch(itch_night, env, itch="fake"):
+ st = ns.State(last_published=last_published())
+ with pytest.raises(ns.Refused) as e:
+ run_itch(itch_night, env, itch, st)
+ return e.value, itch_night[2], st
+
+
+def test_itch_disabled_is_logged_and_never_calls_the_client(night, env, pub, served, capsys):
+ gh = FakeGH()
+ publish(night, ns.State(last_published=last_published()), gh, pub, env, itch=FakeItch(gh.calls))
+ assert "itch: skipped (save test not passed)" in capsys.readouterr().out
+ assert gh.names() == ["create_draft", "verify_draft", "publish", "dispatch_site"]
+
+
+def test_itch_enabled_without_a_client_refuses_before_any_store_change(itch_night, env):
+ err, gh, st = refused_itch(itch_night, env, itch=None)
+ assert err.gate == "itch" and "create_draft" not in gh.names() and st.open_draft is None
+
+
+def test_the_itch_push_sits_between_verify_and_publish_and_the_rollback_is_ready_first(itch_night, env):
+ gh, st = run_itch(itch_night, env)
+ version = itch_night[0].version
+ assert gh.calls[2][:3] == ("download", PREV_TAG, "*-web.zip") # after create_draft, verify_draft, before the push
+ assert [c[0] for c in gh.calls if c[0] not in ("release_state",)] == [
+ "create_draft", "verify_draft", "download", "itch.push", "itch.wait_live", "itch.matches", "publish",
+ "dispatch_site"]
+ assert ("itch.push", "itch-push", version) in gh.calls and st.last_published.tag == TAG
+ night = itch_night[0]
+ assert (night.run_dir / "itch-push/index.html").read_text() == "tonight"
+ assert (night.run_dir / "itch-rollback/index.html").read_text() == "previous"
+
+
[email protected]("how", ["download", "bad-zip"])
+def test_an_unusable_rollback_target_refuses_before_any_push(itch_night, env, how):
+ night, zips, gh, fake = itch_night
+ if how == "download":
+ gh.fail["download"] = ns.Refused("github-download", "0 files matching")
+ else:
+ gh.baseline.write_bytes(b"not a zip")
+ err, 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
+
+
[email protected]("step", ["push", "wait_live", "matches"])
+def test_an_itch_failure_rolls_back_and_deletes_the_draft(itch_night, env, step):
+ night, zips, gh, fake = itch_night
+ fake.fail[step] = [ns.Refused("itch", f"{step} failed")]
+ err, gh, st = refused_itch(itch_night, env)
+ assert err.gate == "itch" and f"{step} failed" in err.detail
+ itch_calls = [c for c in gh.calls if c[0].startswith("itch.")]
+ assert ("itch.push", "itch-rollback", PREV_VERSION) in itch_calls and ("itch.wait_live", PREV_VERSION) in itch_calls
+ names = [n for n in gh.names() if n != "release_state"]
+ assert names[-2:] == ["itch.wait_live", "delete_draft"]
+ assert "publish" not in names and "dispatch_site" not in names
+ assert st.open_draft is None and st.last_published.sha == OLD
+
+
+def test_a_failed_rollback_is_named_in_the_refusal_and_notified(itch_night, env):
+ night, zips, gh, fake = itch_night
+ fake.fail["wait_live"] = [ns.Refused("itch", "never live"), None]
+ fake.fail["push"] = [None, ns.Refused("itch", "butler push exited 1")]
+ err, gh, st = refused_itch(itch_night, env)
+ assert err.gate == "itch" and "never live" in err.detail
+ assert "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 any("itch" in a[0].lower() and "rollback" in a[1].lower() for a in env_notes)
+
+
+def test_a_github_publish_failure_after_itch_rolls_itch_back(itch_night, env):
+ night, zips, gh, fake = itch_night
+ gh.fail["publish"] = ns.Refused("github-publish", "tag at the wrong commit")
+ 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
+
+
+def test_a_failed_rollback_after_a_publish_failure_is_named_and_notified(itch_night, env):
+ night, zips, gh, fake = itch_night
+ gh.fail["publish"] = ns.Refused("github-publish", "tag at the wrong commit")
+ fake.fail["push"] = [None, ns.Refused("itch", "butler push exited 1")]
+ err, gh, st = refused_itch(itch_night, env)
+ assert err.gate == "github-publish" and "tag at the wrong commit" in err.detail
+ assert "rollback" in err.detail and "butler push exited 1" in err.detail
+ assert any("rollback" in a[1].lower() for a in env_notes)
+
+
+def test_an_interrupt_during_publish_rolls_itch_back_and_cleans_the_draft(itch_night, env):
+ night, zips, gh, fake = itch_night
+ gh.fail["publish"] = KeyboardInterrupt()
+ st = ns.State(last_published=last_published())
+ with 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
+
+
+def test_the_itch_skip_reason_is_noted_on_the_night(night, env, pub, served):
+ publish(night, ns.State(last_published=last_published()), FakeGH(), pub, env)
+ assert night.notes == ["itch: skipped (save test not passed)"]
+
+
+def test_the_night_notes_reach_the_log_line(env, monkeypatch):
+ def stages(night, state, runner, gh, itch, *, no_publish, free_gb, save):
+ night.notes.append("itch: skipped (save test not passed)")
+ return True
+ monkeypatch.setattr(nightly, "run_stages", stages)
+ assert env.night() == "PUBLISHED"
+ assert "PUBLISHED" in env.log() and "itch: skipped (save test not passed)" in env.log()
+
+
+def test_a_site_failure_after_publish_does_not_roll_itch_back(itch_night, env):
+ night, zips, gh, fake = itch_night
+ err_site = ns.Refused("site", "run failed")
+ gh.fail["dispatch_site"] = [err_site, err_site]
+ err, gh, st = refused_itch(itch_night, env)
+ assert err.gate == "site"
+ assert [c[0] for c in gh.calls if c[0].startswith("itch.")] == ["itch.push", "itch.wait_live", "itch.matches"]
+ assert "delete_draft" not in gh.names()
+
+
+# --- the stage wiring ---------------------------------------------------------------------------------------------------
+
+def stages(night, env, tmp_path, monkeypatch):
+ """Every stage replaced by a recorder, so the order and the arguments are what is tested."""
+ order = []
+ gz, pages = tmp_path / "Web-gzip", tmp_path / "Web-pages"
+ zips = {False: tmp_path / "web.zip", True: tmp_path / "pages.zip"}
+ prev = tmp_path / "prev.zip"
+
+ def rec(name, result=None):
+ def f(*a, **k):
+ order.append((name, a, k))
+ return result(a, k) if callable(result) else result
+ monkeypatch.setattr(nightly, name, f)
+
+ rec("run_gates")
+ rec("run_editmode")
+ rec("build_web", lambda a, k: pages if k["pages"] else gz)
+ rec("assert_clean_tree")
+ rec("package_zip", lambda a, k: zips[a[3]])
+ rec("run_web_checks")
+ rec("check_sizes", SIZES)
+ rec("measure_boot", BOOT_MS)
+ rec("publish_night")
+ gh = FakeGH()
+ gh.baseline = prev
+ return type("S", (), dict(order=order, gz=gz, pages=pages, zips=zips, prev=prev, gh=gh,
+ names=lambda self: [o[0] for o in order]))()
+
+
+def test_the_stages_run_in_the_brief_order(night, env, stages, capsys):
+ st = ns.State(last_published=last_published())
+ assert nightly.run_stages(night, st, env.runner, stages.gh, None, no_publish=False, free_gb=lambda p: 100.0)
+ assert stages.names() == ["run_gates", "run_editmode", "build_web", "build_web", "assert_clean_tree",
+ "package_zip", "package_zip", "run_web_checks", "run_web_checks", "check_sizes",
+ "measure_boot", "publish_night"]
+ builds = [o for o in stages.order if o[0] == "build_web"]
+ assert [b[2]["pages"] for b in builds] == [False, True]
+ checks = [o for o in stages.order if o[0] == "run_web_checks"]
+ assert [c[1][2] for c in checks] == [stages.gz, stages.pages] # web checks on BOTH builds
+ sizes = next(o for o in stages.order if o[0] == "check_sizes")
+ assert sizes[1][2:5] == (stages.gz, stages.prev, OLD) and sizes[2]["runner"] is env.runner
+ assert stages.gh.calls[-1][:3] == ("download", "v0.3.0-nightly.20261027", "*-web.zip")
+ pub_call = stages.order[-1]
+ assert pub_call[1][4] == (stages.zips[False], stages.zips[True]) and pub_call[1][5:7] == (SIZES, BOOT_MS)
+ assert pub_call[2]["previous"] == ("v0.3.0-nightly.20261027", OLD) and callable(pub_call[2]["save"])
+ assert stages.gh.names().count("previous_build_tag") == 1 # once a night
+
+
+def test_no_publish_stops_before_any_store_call(night, env, stages, capsys):
+ st = ns.State(last_published=last_published())
+ assert nightly.run_stages(night, st, env.runner, stages.gh, None, no_publish=True,
+ free_gb=lambda p: 100.0) is False
+ assert "publish_night" not in stages.names() and "NO-PUBLISH: all gates passed for v0.3.1-nightly.20261028\n" in \
+ capsys.readouterr().out
+ assert stages.gh.names() == ["previous_build_tag", "download"] # reads only
+
+
+def test_a_no_publish_night_touches_no_record_and_no_state(env, monkeypatch, capsys):
+ monkeypatch.setattr(nightly, "run_stages", lambda *a, **k: (print(f"NO-PUBLISH: all gates passed for {TAG}")
+ or False))
+ assert env.night(no_publish=True) == "NO-PUBLISH"
+ assert env.log() == "" and not env.state_path.exists() and not env.cfg.handoff.exists()
+ assert f"NO-PUBLISH: all gates passed for {TAG}" in capsys.readouterr().out and env_notes == []
+
+
+def test_a_published_night_is_recorded_as_published(env, monkeypatch):
+ monkeypatch.setattr(nightly, "run_stages", lambda *a, **k: True)
+ assert env.night() == "PUBLISHED"
+ assert "PUBLISHED" in env.log() and f"tag={TAG}" in env.log()
+
+
+def test_a_boot_slowdown_refuses_and_a_collecting_baseline_passes(night, env, stages):
+ st = ns.State(last_published=last_published(), boot_baseline=[8000.0, 8100.0, 8050.0, 8100.0, 8000.0])
+ nightly.run_stages(night, st, env.runner, stages.gh, None, no_publish=True, free_gb=lambda p: 100.0) # 8200 <= limit
+ st.boot_baseline = [1000.0, 1000.0, 1000.0, 1000.0, 1000.0]
+ with pytest.raises(ns.Refused) as e:
+ nightly.run_stages(night, st, env.runner, stages.gh, None, no_publish=True, free_gb=lambda p: 100.0)
+ assert e.value.gate == "boot" and "publish_night" not in stages.names()
+
+
+def test_a_failed_build_still_checks_the_tree_before_the_refusal(night, env, stages, monkeypatch):
+ def boom(n, r, *, pages, free_gb):
+ if pages:
+ raise ns.Refused("build-web", "the Unity build exited 1")
+ return stages.gz
+ monkeypatch.setattr(nightly, "build_web", boom)
+ with pytest.raises(ns.Refused) as e:
+ nightly.run_stages(night, ns.State(last_published=last_published()), env.runner, stages.gh, None,
+ no_publish=False, free_gb=lambda p: 100.0)
+ assert e.value.gate == "build-web" and "assert_clean_tree" in stages.names()
+ assert "package_zip" not in stages.names() and "publish_night" not in stages.names()
+
+
+def test_a_dirty_tree_after_a_failed_build_is_noted_not_substituted(night, env, stages, monkeypatch, capsys):
+ monkeypatch.setattr(nightly, "build_web", lambda *a, **k: (_ for _ in ()).throw(ns.Refused("build-web", "x")))
+ def dirty(n, r):
+ raise ns.Refused("dirty-tree", "settings still changed")
+ monkeypatch.setattr(nightly, "assert_clean_tree", dirty)
+ with pytest.raises(ns.Refused) as e:
+ nightly.run_stages(night, ns.State(last_published=last_published()), env.runner, stages.gh, None,
+ no_publish=False, free_gb=lambda p: 100.0)
+ assert e.value.gate == "build-web"
+ assert "settings still changed" in (night.run_dir / "dirty-tree.note").read_text()
+ assert "not clean" in capsys.readouterr().err
+
+
+def test_a_dirty_tree_after_good_builds_refuses(night, env, stages, monkeypatch):
+ def dirty(n, r):
+ raise ns.Refused("dirty-tree", "changed")
+ monkeypatch.setattr(nightly, "assert_clean_tree", dirty)
+ with pytest.raises(ns.Refused) as e:
+ nightly.run_stages(night, ns.State(last_published=last_published()), env.runner, stages.gh, None,
+ no_publish=False, free_gb=lambda p: 100.0)
+ assert e.value.gate == "dirty-tree" and "package_zip" not in stages.names()
+
+
+class LoggingWebRunner(WebRunner):
+ def run(self, cmd, **k):
+ if "-executeMethod" in cmd and "-logFile" in cmd:
+ Path(cmd[cmd.index("-logFile") + 1]).write_text(
+ "boring\nAssets/X.cs(3,4): error CS0103: The name 'y' does not exist\nmore\nBuildFailedException: nope\n")
+ return super().run(cmd, **k)
+
+
+def test_a_failed_build_names_the_unity_errors_in_its_refusal(night, env):
+ r = LoggingWebRunner(night, build_code=1)
+ with pytest.raises(ns.Refused) as e:
+ nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
+ assert e.value.gate == "build-web" and "error CS0103" in e.value.detail and "BuildFailedException" in e.value.detail
+ assert "boring" not in e.value.detail
+
+
+def test_a_failed_build_without_a_unity_log_says_so(night, env):
+ r = WebRunner(night, build_code=1)
+ with pytest.raises(ns.Refused) as e:
+ nightly.build_web(night, r, pages=False, free_gb=lambda p: 100.0)
+ assert "no Unity log" in e.value.detail
+
+
+# --- the clients ----------------------------------------------------------------------------------------------------------
+
+def test_clients_are_a_github_for_the_configured_repo_and_no_itch(env, monkeypatch):
+ monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/gh")
+ gh, itch = nightly._clients(env.cfg)
+ assert isinstance(gh, nightly.GitHub) and gh.slug == env.cfg.repo_slug and gh.cwd == env.cfg.clone and itch is None
+
+
+def test_an_itch_client_exists_only_when_itch_is_enabled(env, monkeypatch, tmp_path):
+ monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/gh")
+ butler = tmp_path / "butler"
+ butler.write_text("x")
+ cfg = dataclasses.replace(env.cfg, itch_enabled=True, butler=butler)
+ gh, itch = nightly._clients(cfg)
+ assert isinstance(itch, nightly.Itch) and itch.target == cfg.itch_target and itch.butler == butler
+
+
+def test_enabled_itch_without_butler_is_a_recorded_refusal(env, monkeypatch, tmp_path):
+ monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/gh")
+ with pytest.raises(ns.Refused) as e:
+ nightly._clients(dataclasses.replace(env.cfg, itch_enabled=True, butler=tmp_path / "missing"))
+ assert e.value.gate == "itch-client"
+
+
+def test_a_missing_gh_is_a_github_client_refusal(env, monkeypatch):
+ monkeypatch.setattr(nightly.shutil, "which", lambda name: None)
+ with pytest.raises(ns.Refused) as e:
+ nightly._clients(env.cfg)
+ assert e.value.gate == "github-client"
+
+
+def test_an_unusable_client_is_a_recorded_github_client_refusal_not_internal(env):
+ err = ns.Refused("github-client", "gh is not on PATH")
+ out = nightly.run_night(env.cfg, env.state_path, env.job, env.runner, None, None, now=NOW, manual=False,
+ no_publish=False, client_error=err, free_gb=lambda p: 100.0)
+ assert out == "REFUSED" and "gate=github-client" in env.log() and "gh is not on PATH" in env.log()
+ assert env.runner.calls == [] and len(env_notes) == 1
+
+
+# --- Task 8: the two-upload itch save test ----------------------------------------------------------------------------
+
+PAGE_URL = "https://example.invalid/statecraft-israel"
+ITCH_HOST = "https://html-classic.itch.zone"
+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):
+ self.calls, self.fail, self.pushes, self.build = calls, fail or {}, 0, 100
+
+ def push(self, folder, version):
+ self.calls.append(("itch.push", Path(folder).name, version))
+ if "push" in self.fail:
+ raise self.fail["push"]
+ self.pushes += 1
+ self.build += 1
+
+ def wait_live(self, version, deadline):
+ self.calls.append(("itch.wait_live", version))
+ if "wait_live" in self.fail:
+ raise self.fail["wait_live"]
+
+ def live_build_id(self):
+ return self.build
+
+
+class SaveRunner(FakeRunner):
+ """Answers the web_check runs: the first-save run prints `saved`, a --expect run answers `loads` (one per call)."""
+
+ def __init__(self, *, saved=(0, "PASS: saw x\n" + SAVED), loads=((0, "PASS: saw GAME OK\n"),) * 2):
+ super().__init__()
+ self.saved, self.loads, self.runs = saved, list(loads), []
+
+ def run(self, cmd, *, cwd, log, deadline, env=None, holder=None):
+ self.runs.append(list(cmd))
+ code, text = self.saved if "--first-save" in cmd else self.loads.pop(0)
+ Path(log).parent.mkdir(parents=True, exist_ok=True)
+ Path(log).write_text(text)
+ return code
+
+
+class Page:
+ def __init__(self, text):
+ self.text = text
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ def read(self):
+ 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`."""
+ 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="&lt;iframe src=&quot;{inner}&quot;&gt;">')
+ return fetch
+
+
+class 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, **runner_kw):
+ self.job = tmp_path / "job"
+ self.job.mkdir()
+ self.config = self.job / "config.json"
+ self.config.write_text('{"itch_page_url": "%s"}\n' % page_url)
+ 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.runner = SaveRunner(**runner_kw)
+ monkeypatch.setattr(nightly, "find_chrome", lambda: Path("/fake/chrome"))
+
+ def run(self, fetch=None, tag=TAG):
+ 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=lambda s: None)
+
+ def evidence(self):
+ return json.loads(next((self.job / "savetest").glob("*/evidence.json")).read_text())
+
+ def enabled(self):
+ return json.loads(self.config.read_text()).get("itch_enabled", False)
+
+ def log(self):
+ return (self.job / "LOG.md").read_text()
+
+
+def saved(tmp_path, monkeypatch, no_processes):
+ return lambda **kw: Saved(tmp_path, monkeypatch, **kw)
+
+
+def test_savetest_passes_only_with_matching_tuple_new_url_same_origin(saved):
+ t = saved()
+ assert t.run() == "PASS"
+ 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")]
+ first, b1, b2 = t.runner.runs
+ profile = first[first.index("--profile") + 1]
+ assert first[first.index("--url") + 1] == f"{ITCH_HOST}/html/19840947-101/index.html" and "--first-save" in first
+ for run in (b1, b2): # B twice, same frame URL, same kept profile, the full tuple
+ assert run[run.index("--url") + 1] == f"{ITCH_HOST}/html/19840947-102/index.html"
+ assert run[run.index("--profile") + 1] == profile
+ 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["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"
+ assert not t.enabled() and len(t.runner.runs) == 1 # B is never loaded
+ assert "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_savetest_mismatch_fails_and_keeps_itch_off(saved):
+ t = saved(loads=((1, "TIMEOUT: never saw GAME OK\n"),))
+ assert t.run() == "FAIL" and not t.enabled() and "SAVETEST FAIL" in t.log()
+ assert len(t.runner.runs) == 2 # A, then the first load of B: no second load after a failure
+
+
+def test_savetest_second_load_failing_is_a_fail(saved):
+ t = saved(loads=((0, "PASS: saw x\n"), (1, "TIMEOUT\n")))
+ assert t.run() == "FAIL" and not t.enabled()
+
+
+def test_savetest_a_timed_out_load_is_inconclusive(saved):
+ t = saved(loads=((124, ""),))
+ assert t.run() == "INCONCLUSIVE" and not t.enabled()
+
+
[email protected]("saved_run", [(1, "FAIL: x\n"), (0, "PASS: saw x\n"), (0, "no pass\n" + SAVED)])
+def test_savetest_without_a_durable_first_save_is_inconclusive(saved, saved_run):
+ t = saved(saved=saved_run)
+ assert t.run() == "INCONCLUSIVE" and not t.enabled() and len(t.runner.runs) == 1
+ 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):
+ 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 == []
+ assert "SAVETEST INCONCLUSIVE" 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('&quot;%s/html/19840947-101/index.html&quot;' % ITCH_HOST)
+ assert t.run(fetch) == "PASS" and seen.count(2) == 3
+
+
[email protected]("step", ["push", "wait_live"])
+def test_savetest_an_itch_failure_is_inconclusive_and_recorded(saved, step):
+ t = saved()
+ t.itch.fail[step] = ns.Refused("itch", f"{step} failed")
+ 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):
+ t = saved()
+ def fetch(url, timeout=30):
+ raise OSError("offline")
+ assert t.run(fetch) == "INCONCLUSIVE" and not t.enabled() and "offline" in t.log()
+
+
+def test_savetest_without_chrome_pushes_nothing(saved, monkeypatch):
+ t = saved()
+ monkeypatch.setattr(nightly, "find_chrome", lambda: sys.exit("Chrome for Testing not found"))
+ assert t.run() == "INCONCLUSIVE" and not any(c[0].startswith("itch.") for c in t.gh.calls)
+
+
+def test_the_savetest_command_takes_a_tag_and_exits_zero_only_on_a_pass(tmp_path, monkeypatch, no_processes):
+ monkeypatch.setattr(nightly, "JOB", tmp_path / "job")
+ got = []
+ for result, code in (("PASS", 0), ("FAIL", 1), ("INCONCLUSIVE", 1)):
+ monkeypatch.setattr(nightly, "run_savetest", lambda cfg, job, tag, r=result: got.append(tag) or (0 if r == "PASS" else 1))
+ assert nightly.main(["savetest", "--tag", TAG]) == code
+ assert got == [TAG] * 3
+ with pytest.raises(SystemExit):
+ nightly.main(["savetest"])
+
+
+def test_the_restore_also_resets_the_prickly_pear_material(night):
+ r = FakeRunner()
+ r.add(("git", "checkout", "--"))
+ nightly.restore_settings(night, r)
+ assert r.calls == [["git", "checkout", "--", "unity/ProjectSettings", "unity/Assets/Settings",
+ "unity/Assets/Art/HexTiles/Props/arab_village_prickly_pear/prickly_pear-rock.mat"]]
+ assert (Path(__file__).resolve().parents[2] / r.calls[0][-1]).is_file() # the path is a real tracked file
+
+
+def test_a_corrupt_config_on_the_savetest_path_is_recorded_not_an_attribute_error(tmp_path, monkeypatch):
+ job = tmp_path / "job"
+ job.mkdir()
+ (job / "config.json").write_text("{not json")
+ monkeypatch.setattr(nightly, "JOB", job)
+ monkeypatch.setattr(nightly, "Config", lambda: ns.Config(handoff=tmp_path / "HANDOFF.md"))
+ monkeypatch.setattr(nightly, "notify", lambda *a, **k: None)
+ assert nightly.main(["savetest", "--tag", "v0.3.1-nightly.20261028"]) == 1
+ assert "gate=config" in (job / "LOG.md").read_text()
diff --git a/tools/tests/test_nightly_checks.py b/tools/tests/test_nightly_checks.py
new file mode 100644
index 000000000..83316bdc7
--- /dev/null
+++ b/tools/tests/test_nightly_checks.py
@@ -0,0 +1,158 @@
+import zipfile
+
+import pytest
+
+import nightly_checks as nc
+
+PASSED = "Passed! - Failed: 0, Passed: 3216, Skipped: 0, Total: 3216, Duration: 1 m" # format seen in real logs
+
+
+def test_dotnet_totals_sum_every_project():
+ assert nc.dotnet_totals(PASSED + "\n" + PASSED.replace("3216", "12")) == (0, 3228)
+ assert nc.dotnet_totals("Failed! - Failed: 5, Passed: 3211, Skipped: 0, Total: 3216") == (5, 3216)
+ assert nc.dotnet_totals("Build succeeded.") == (0, 0)
+
+
+def test_check_sh_must_pass_and_must_have_compiled_unity():
+ ok = "== unity compile (dotnet, outside Unity)\n...\nALL CHECKS PASSED\n"
+ assert nc.check_sh_verdict(ok, 0) is None
+ assert "SKIPPED" in nc.check_sh_verdict("== unity compile: SKIPPED, no unity/Library ...\nALL CHECKS PASSED", 0)
+ assert nc.check_sh_verdict(ok, 1) is not None
+ assert nc.check_sh_verdict("== unity compile (dotnet, outside Unity)\n...", 0) is not None # no pass line
+ assert nc.check_sh_verdict("ALL CHECKS PASSED\n", 0) is not None # the compile step never ran
+
+
+def test_release_gate_needs_its_ok_line_and_exit_0():
+ assert nc.release_gate_verdict("...\n\nRELEASE GATE OK\n", 0) is None
+ assert nc.release_gate_verdict("...\nRELEASE GATE FAILED\n", 1) is not None
+ assert nc.release_gate_verdict("RELEASE GATE OK\n", 1) is not None
+ assert nc.release_gate_verdict("", 0) is not None
+
+
+def test_product_version_reads_the_built_page():
+ assert nc.product_version('productName: "S",\n productVersion: "0.3.1-nightly.20261028",') == "0.3.1-nightly.20261028"
+ assert nc.product_version("<html></html>") is None
+
+
+MANIFEST = "# c\nhash1950 aa\nhash1952 bb\nsmoke5 cc\nsmoke-orders dd\n"
+
+
+def test_expects_come_from_the_manifest():
+ assert nc.golden_expects(MANIFEST) == ["GOLDEN OK hash1950 aa", "GOLDEN OK hash1952 bb", "GOLDEN OK smoke5 cc",
+ "GOLDEN OK smoke-orders dd"]
+ assert nc.smoke_expect(MANIFEST) == "SMOKE OK 5 turns 1948-10-15 cc"
+ assert nc.smoke_orders_expect(MANIFEST) == "SMOKE ORDERS OK 1948-06-15 dd"
+ with pytest.raises(ValueError):
+ nc.smoke_expect("hash1950 aa\n")
+ with pytest.raises(ValueError):
+ nc.smoke_orders_expect("smoke-orders\n")
+
+
+def test_the_passes_are_releasing_step_5_plus_smoke_orders(tmp_path):
+ p = nc.web_check_passes(tmp_path, MANIFEST)
+ assert len(p) == 7 and p[0][1:3] == ["--query", "golden&smoke=5"] and p[1][1:3] == ["--query", "smoke-orders"]
+ assert all(x[0] == str(tmp_path) for x in p)
+ assert [x[x.index("--startscreen") + 1] for x in p if "--startscreen" in x] == ["new", "recording", "new",
+ "recording"]
+ assert sum("lang=he" in x for x in p) == 2 and "--persistence" in p[6]
+ assert all(x[x.index("--stall") + 1] == "90" and x[x.index("--timeout") + 1] == "300" for x in p[2:])
+ assert p[4][1:] == ["--startscreen", "new", "--query", "lang=he", "--timeout", "300", "--stall", "90"]
+ assert p[0].count("--expect") == 5 and p[0][-1] == "SMOKE OK 5 turns 1948-10-15 cc"
+
+
+def make_build(root, *, extra=True, data=900, wasm=90, fw=10):
+ root.mkdir(parents=True, exist_ok=True)
+ (root / "Build").mkdir(exist_ok=True)
+ (root / "index.html").write_text(
+ 'var dataUrl = "Build/h1.data.gz"; var w = "Build/h1.wasm.gz"; src="Build/h1.framework.js.gz"; '
+ 'loader = "Build/h1.loader.js";')
+ (root / "Build/h1.data.gz").write_bytes(b"d" * data)
+ (root / "Build/h1.wasm.gz").write_bytes(b"w" * wasm)
+ (root / "Build/h1.framework.js.gz").write_bytes(b"f" * fw)
+ if extra:
+ (root / "Build/old.data.gz").write_bytes(b"x" * 5000) # a stale file index.html does not name
+ return root
+
+
+def test_sizes_sum_data_wasm_framework_named_by_index_html(tmp_path):
+ build = make_build(tmp_path / "b")
+ assert nc.web_sizes(build) == {"data": 900, "wasm": 90, "framework": 10}
+
+
+def test_sizes_refuse_a_missing_or_ambiguous_file(tmp_path):
+ build = make_build(tmp_path / "b")
+ (build / "Build/h1.wasm.gz").unlink()
+ with pytest.raises(ValueError):
+ nc.web_sizes(build)
+ build = make_build(tmp_path / "c")
+ (build / "index.html").write_text('"Build/a.data.gz" "Build/b.data.gz" "Build/h.wasm.gz" "Build/h.framework.js.gz"')
+ with pytest.raises(ValueError):
+ nc.web_sizes(build)
+
+
+def test_zip_and_folder_sizes_agree(tmp_path):
+ build = make_build(tmp_path / "b")
+ z = tmp_path / "w.zip"
+ with zipfile.ZipFile(z, "w", zipfile.ZIP_DEFLATED) as zf:
+ zf.write(build / "index.html", "index.html")
+ for f in (build / "Build").iterdir():
+ zf.write(f, f"Build/{f.name}")
+ assert nc.web_sizes_from_zip(z) == nc.web_sizes(build)
+ with zipfile.ZipFile(z, "w") as zf:
+ zf.writestr("other.txt", "x")
+ with pytest.raises(ValueError):
+ nc.web_sizes_from_zip(z)
+
+
+def test_size_growth_within_2_percent_passes_and_beyond_refuses():
+ old = {"data": 900, "wasm": 90, "framework": 10}
+ assert nc.size_verdict(old, {"data": 920, "wasm": 90, "framework": 10}, 0) is None # +20 = 2.0%
+ assert "1021" in nc.size_verdict(old, {"data": 921, "wasm": 90, "framework": 10}, 0) # +21 > 2%
+ assert nc.size_verdict(old, {"data": 921, "wasm": 90, "framework": 10}, 1) is None # budgeted
+ assert nc.size_verdict(old, {"data": 100, "wasm": 90, "framework": 10}, 0) is None # shrinking is fine
+
+
+def test_size_math_stays_exact_for_huge_totals():
+ big = 10**30
+ old = {"data": big, "wasm": 0, "framework": 0}
+ assert nc.size_verdict(old, {"data": big + big // 50, "wasm": 0, "framework": 0}, 0) is None
+ assert nc.size_verdict(old, {"data": big + big // 50 + 1, "wasm": 0, "framework": 0}, 0) is not None
+
+
+def test_the_budget_line_is_exact_and_summed():
+ bodies = ["x\nNightly size budget: +1.5 MB\n", "Nightly size budget: +2 MB", "nightly size budget +9 MB",
+ "Nightly size budget: -3 MB"]
+ assert nc.size_budget_bytes(bodies) == 3_500_000
+ assert nc.size_budget_bytes([]) == 0
+
+
+REAL_BOOT = "console: BOOT phase=screens ready at=8123 ms dt=40 ms\nconsole: GAME OK 1948-05-15 turn 0 hash ab\nPASS: saw GAME OK\n"
+
+
+def test_boot_reads_screens_ready_and_needs_a_pass():
+ assert nc.boot_ms(REAL_BOOT) == 8123
+ assert nc.boot_ms(REAL_BOOT.replace("console: ", "")) == 8123
+ for bad in (REAL_BOOT.replace("PASS: saw GAME OK", "TIMEOUT: never saw GAME OK"),
+ REAL_BOOT.replace("PASS: saw GAME OK", "FAIL: BOOT FAIL"),
+ REAL_BOOT.replace("screens ready", "map ready"), "", "PASS: saw GAME OK\n"):
+ with pytest.raises(ValueError):
+ nc.boot_ms(bad)
+
+
+def test_the_boot_bound_is_the_baseline_spread():
+ assert nc.boot_verdict(9000, [8000, 8100]) == ("collecting", None)
+ base = [8000, 8100, 8050, 8200, 8150] # max 8200, spread 200 -> limit 8400
+ assert nc.boot_verdict(8400, base) == ("checked", None)
+ assert "8401" in nc.boot_verdict(8401, base)[1]
+
+
+def test_notices_missing_from_a_zip(tmp_path):
+ z = tmp_path / "w.zip"
+ with zipfile.ZipFile(z, "w") as zf:
+ for n in ("LICENSE", "NOTICE", "THIRD-PARTY-NOTICES.md", "OFL-EBGaramond.txt", "OFL-FrankRuhlLibre.txt"):
+ zf.writestr(n, "x")
+ assert nc.zip_missing_notices(z) == []
+ with zipfile.ZipFile(z, "w") as zf:
+ zf.writestr("LICENSE", "x")
+ assert nc.zip_missing_notices(z) == ["NOTICE", "THIRD-PARTY-NOTICES.md", "OFL-EBGaramond.txt", "OFL-FrankRuhlLibre.txt"]
+ assert len(nc.zip_missing_notices(tmp_path / "absent.zip")) == 5
diff --git a/tools/tests/test_nightly_launch.py b/tools/tests/test_nightly_launch.py
new file mode 100644
index 000000000..a405fc8bc
--- /dev/null
+++ b/tools/tests/test_nightly_launch.py
@@ -0,0 +1,150 @@
+import plistlib
+import subprocess
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+# nightly_launch locks with flock (through nightly_state); fcntl does not exist on Windows.
+pytest.importorskip("fcntl", reason="fcntl is POSIX-only (nightly_state uses flock); not on Windows")
+
+import nightly_launch as nl # noqa: E402
+import nightly_state as ns # noqa: E402
+import unity_postmerge as up # noqa: E402
+
+TOOLS = Path(__file__).resolve().parents[1]
+NOW = datetime(2026, 10, 28, 3, 0, tzinfo=ns.TZ)
+
+
+class Recorder:
+ """Stands in for git and cp: records (cwd, args) and never starts a process."""
+
+ def __init__(self, fail_on: str | None = None):
+ self.calls: list[tuple[Path, tuple]] = []
+ self.fail_on = fail_on
+
+ def git(self, cwd, *args):
+ self.calls.append((cwd, args))
+ if self.fail_on and args[0] == self.fail_on:
+ raise subprocess.CalledProcessError(128, ["git", *args], stderr="fatal: boom")
+ return ""
+
+ def copy(self, cwd, src, dest):
+ self.calls.append((cwd, ("cp", "-c", "-R", str(src), str(dest))))
+
+
+def cfg_for(tmp_path, *, clone=True, library=False):
+ main, clone_dir = tmp_path / "main", tmp_path / "clone"
+ (main / "unity/Library").mkdir(parents=True) if library else main.mkdir(parents=True)
+ if clone:
+ (clone_dir / ".git").mkdir(parents=True)
+ return ns.Config(main_repo=main, clone=clone_dir, handoff=tmp_path / "HANDOFF.md")
+
+
+def write_config(home, cfg):
+ home.mkdir(parents=True, exist_ok=True)
+ (home / "config.json").write_text(f'{{"clone": "{cfg.clone}", "main_repo": "{cfg.main_repo}", '
+ f'"handoff": "{cfg.handoff}"}}')
+
+
+def test_the_plist_runs_at_0300_and_never_on_an_interval():
+ filled = up.fill_plist((TOOLS / "nightly.plist.in").read_text(), uv="/opt/uv", repo="/r", home="/h", path="/usr/bin:/bin")
+ p = plistlib.loads(filled.encode())
+ assert p["Label"] == "com.statecraft.nightly" and p["StartCalendarInterval"] == {"Hour": 3, "Minute": 0}
+ assert "StartInterval" not in p and not p.get("RunAtLoad") and "@" not in filled
+ assert p["ProgramArguments"][:3] == ["/opt/uv", "run", "/h/nightly_launch.py"]
+ assert p["StandardOutPath"] == p["StandardErrorPath"] == "/h/launchd.log"
+
+
+def test_the_launcher_keeps_what_the_postmerge_job_keeps():
+ assert nl.KEEP == up.KEEP
+
+
+def test_prepare_clone_resets_only_the_clones_own_main_and_keeps_the_library(tmp_path):
+ cfg, rec = cfg_for(tmp_path, library=True), Recorder()
+ nl.prepare_clone(cfg, rec.git, rec.copy)
+ clone = cfg.clone
+ assert rec.calls == [
+ (clone, ("fetch", "--quiet", "--tags", "origin", "+refs/heads/main:refs/remotes/origin/main")),
+ (clone, ("checkout", "--quiet", "main")),
+ (clone, ("reset", "--hard", "refs/remotes/origin/main")),
+ (clone, ("clean", "-ffdx", "-e", "/unity/Library/", "-e", "/unity/Assets/Plugins/NuGet/",
+ "-e", "/unity/Assets/Plugins/NuGet.meta")),
+ (cfg.main_repo, ("cp", "-c", "-R", str(cfg.main_repo / "unity/Library"), str(clone / "unity/Library"))),
+ ]
+ assert all(cwd != cfg.main_repo for cwd, args in rec.calls if args[0] != "cp")
+
+
+def test_the_library_is_cloned_once_and_only_when_the_main_checkout_has_one(tmp_path):
+ cfg, rec = cfg_for(tmp_path, library=True), Recorder()
+ (cfg.clone / "unity/Library").mkdir(parents=True)
+ nl.prepare_clone(cfg, rec.git, rec.copy)
+ assert not any(args[0] == "cp" for _, args in rec.calls)
+ cfg2, rec2 = cfg_for(tmp_path / "b"), Recorder()
+ nl.prepare_clone(cfg2, rec2.git, rec2.copy)
+ assert not any(args[0] == "cp" for _, args in rec2.calls)
+
+
+def test_a_git_failure_is_a_refused_clone_gate(tmp_path):
+ cfg, rec = cfg_for(tmp_path), Recorder(fail_on="reset")
+ with pytest.raises(ns.Refused) as e:
+ nl.prepare_clone(cfg, rec.git, rec.copy)
+ assert e.value.gate == "clone" and "fatal: boom" in e.value.detail
+ assert not any(args[0] == "clean" for _, args in rec.calls) # nothing is cleaned after a failed reset
+
+
+def test_a_missing_clone_is_refused_and_recorded_not_cloned(tmp_path, monkeypatch):
+ home = tmp_path / "job"
+ cfg = cfg_for(tmp_path, clone=False)
+ write_config(home, cfg)
+ monkeypatch.setattr(nl, "notify", lambda *a, **k: None)
+ rec, ran = Recorder(), []
+ code = nl.main(["--uv", "/opt/uv", "--home", str(home)], git=rec.git, copy=rec.copy, call=ran.append, now=NOW)
+ assert code == 1 and rec.calls == [] and ran == []
+ log = (home / "LOG.md").read_text()
+ assert "REFUSED" in log and "gate=clone" in log and "2026-10-28 03:00" in log
+ assert "gate=clone" in cfg.handoff.read_text()
+ assert not cfg.clone.exists()
+
+
+def test_a_corrupt_config_is_refused_not_a_night_on_defaults(tmp_path, monkeypatch):
+ home = tmp_path / "job"
+ home.mkdir()
+ (home / "config.json").write_text("{not json")
+ monkeypatch.setattr(nl, "notify", lambda *a, **k: None)
+ monkeypatch.setattr(nl, "Config", lambda: ns.Config(handoff=tmp_path / "HANDOFF.md"))
+ rec, ran = Recorder(), []
+ assert nl.main(["--uv", "/opt/uv", "--home", str(home)], git=rec.git, copy=rec.copy, call=ran.append, now=NOW) == 1
+ assert rec.calls == [] and ran == [] and "gate=config" in (home / "LOG.md").read_text()
+
+
+def test_a_run_in_progress_exits_0_and_touches_nothing(tmp_path, capsys):
+ home = tmp_path / "job"
+ rec, ran = Recorder(), []
+ with ns.run_lock(home) as held:
+ assert held
+ code = nl.main(["--uv", "/opt/uv", "--home", str(home)], git=rec.git, copy=rec.copy, call=ran.append, now=NOW)
+ assert code == 0 and rec.calls == [] and ran == []
+ assert "a run is in progress" in capsys.readouterr().out
+ assert not (home / "LOG.md").exists()
+
+
+def test_a_prepared_clone_runs_the_clones_own_nightly_script_with_the_lock_free(tmp_path):
+ home = tmp_path / "job"
+ cfg = cfg_for(tmp_path)
+ write_config(home, cfg)
+ rec, seen = Recorder(), []
+
+ def call(cmd):
+ with ns.run_lock(home) as held: # nightly.py takes this lock itself, so the launcher must have let go
+ seen.append((cmd, held))
+ return 7
+
+ assert nl.main(["--uv", "/opt/uv", "--home", str(home)], git=rec.git, copy=rec.copy, call=call, now=NOW) == 7
+ assert seen == [(["/opt/uv", "run", str(cfg.clone / "tools" / "nightly.py"), "run"], True)]
+
+
+def test_no_nightly_module_pushes_merges_or_deletes_tags():
+ src = "".join((TOOLS / n).read_text() for n in ("nightly.py", "nightly_publish.py", "nightly_state.py", "nightly_checks.py", "nightly_launch.py"))
+ for banned in ("git push", "\"push\", \"--force\"", "--cleanup-tag", "\"tag\", \"-d\"", "pr merge", "push --force"):
+ assert banned not in src
diff --git a/tools/tests/test_nightly_publish.py b/tools/tests/test_nightly_publish.py
new file mode 100644
index 000000000..51f31f92e
--- /dev/null
+++ b/tools/tests/test_nightly_publish.py
@@ -0,0 +1,650 @@
+import hashlib
+import io
+import json
+import zipfile
+from pathlib import Path
+
+import pytest
+
+import nightly_publish as gp
+from conftest import FakeRunner
+from nightly_state import Refused
+
+SLUG = "eyalgolan/statecraft-israel"
+SHA = "a" * 40
+OTHER = "c" * 40
+TAG = "v0.3.1-nightly.20261028"
+VERSION = "0.3.1-nightly.20261028"
+DEMO = "https://example.invalid/demo/"
+NOTICES = ("LICENSE", "NOTICE", "THIRD-PARTY-NOTICES.md", "OFL-EBGaramond.txt", "OFL-FrankRuhlLibre.txt")
+
+
+class Script(FakeRunner):
+ """Answers `capture` from a script: `on(prefix, *answers)` pops one answer per matching call (the last one
+ repeats). An answer is the stdout text, a Refused to raise, or a callable(cmd) returning the text."""
+
+ def __init__(self):
+ super().__init__()
+ self.scripts = []
+
+ def on(self, prefix, *answers):
+ self.scripts.append((tuple(prefix), list(answers)))
+
+ def capture(self, cmd, *, cwd, timeout=300):
+ self.calls.append(list(cmd))
+ for prefix, answers in self.scripts:
+ if tuple(cmd[:len(prefix)]) == prefix:
+ answer = answers.pop(0) if len(answers) > 1 else answers[0]
+ if isinstance(answer, Exception):
+ raise answer
+ return answer(cmd) if callable(answer) else answer
+ raise AssertionError(f"unexpected command {cmd}")
+
+
+def runner():
+ return Script()
+
+
+def gh(runner, tmp_path):
+ return gp.GitHub(runner, SLUG, tmp_path, sleep=lambda s: None, now=iter(range(0, 10_000, 5)).__next__)
+
+
+def make_zip(path: Path, *, notices=NOTICES, extra=b"x") -> Path:
+ with zipfile.ZipFile(path, "w") as z:
+ for n in notices:
+ z.writestr(n, "text")
+ z.writestr("index.html", extra)
+ return path
+
+
+def zips(tmp_path):
+ return [make_zip(tmp_path / f"statecraft-israel-v{VERSION}-web.zip"),
+ make_zip(tmp_path / f"statecraft-israel-v{VERSION}-web-pages.zip", extra=b"pages")]
+
+
+def view_json(*, draft=True, pre=True, names=()):
+ return json.dumps({"isDraft": draft, "isPrerelease": pre, "assets": [{"name": n} for n in names]})
+
+
+def not_found():
+ return Refused("command", "gh release view exited 1: release not found")
+
+
+# --- release state ---------------------------------------------------------------------------------------------------
+
+def test_release_state_is_draft_published_or_none(gh, runner):
+ runner.on(["gh", "release", "view", TAG, "--repo", SLUG, "--json", "isDraft"], '{"isDraft": true}')
+ assert gh.release_state(TAG) == "draft"
+ runner.scripts.clear()
+ runner.on(["gh", "release", "view", TAG], '{"isDraft": false}')
+ assert gh.release_state(TAG) == "published"
+ runner.scripts.clear()
+ runner.on(["gh", "release", "view", TAG], not_found())
+ assert gh.release_state(TAG) is None
+
+
+def test_release_state_refuses_on_any_other_error_or_garbage(gh, runner):
+ runner.on(["gh", "release", "view", TAG], Refused("command", "gh release view exited 4: auth required"))
+ with pytest.raises(Refused) as e:
+ gh.release_state(TAG)
+ assert e.value.gate == "github-state"
+ runner.scripts.clear()
+ runner.on(["gh", "release", "view", TAG], "not json")
+ with pytest.raises(Refused):
+ gh.release_state(TAG)
+
+
+# --- create, verify, publish, delete --------------------------------------------------------------------------------
+
+def test_the_draft_is_a_prerelease_never_latest_targeting_the_commit(gh, runner, tmp_path, zips):
+ 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", "--prerelease",
+ "--latest=false", "--target", SHA, "--title", f"{TAG} (nightly)",
+ "--notes-file", str(tmp_path / "notes.md"), str(zips[0]), str(zips[1])]
+
+
+def draft_script(runner, zips, tmp_path, *, view=None, downloaded=None):
+ names = [z.name for z in zips]
+ runner.on(["gh", "release", "view", TAG, "--repo", SLUG, "--json", "isDraft,isPrerelease,assets"],
+ view or view_json(names=names))
+
+ def download(cmd):
+ dest = Path(cmd[cmd.index("--dir") + 1])
+ dest.mkdir(parents=True, exist_ok=True)
+ for z in (downloaded or zips):
+ (dest / z.name).write_bytes(z.read_bytes())
+ return ""
+ runner.on(["gh", "release", "download"], download)
+
+
+def test_verify_draft_passes_when_everything_matches(gh, runner, zips, tmp_path):
+ draft_script(runner, zips, tmp_path)
+ gh.verify_draft(TAG, zips, tmp_path / "dl")
+ assert runner.calls[-1] == ["gh", "release", "download", TAG, "--repo", SLUG, "--dir", str(tmp_path / "dl"),
+ "--pattern", "*.zip"]
+
+
+def test_verify_draft_refuses_different_bytes(gh, runner, zips, tmp_path):
+ other = make_zip(tmp_path / "other.zip", extra=b"tampered")
+ swapped = [type("F", (), {"name": zips[0].name, "read_bytes": other.read_bytes}), zips[1]]
+ draft_script(runner, zips, tmp_path, downloaded=swapped)
+ with pytest.raises(Refused) as e:
+ gh.verify_draft(TAG, zips, tmp_path / "dl")
+ assert e.value.gate == "github-draft" and zips[0].name in e.value.detail
+
+
+def test_verify_draft_refuses_a_zip_without_the_licence(gh, runner, zips, tmp_path):
+ bare = make_zip(tmp_path / "bare.zip", notices=[n for n in NOTICES if n != "LICENSE"])
+ bare_local = [type("F", (), {"name": zips[0].name, "read_bytes": bare.read_bytes}), zips[1]]
+ # the local file is the same bare zip, so the hashes agree and only the notices check can fail
+ zips[0].write_bytes(bare.read_bytes())
+ draft_script(runner, zips, tmp_path, downloaded=bare_local)
+ with pytest.raises(Refused) as e:
+ gh.verify_draft(TAG, zips, tmp_path / "dl")
+ assert e.value.gate == "github-draft" and "LICENSE" in e.value.detail
+
+
[email protected]("view", [view_json(draft=False, names=["a"]), view_json(pre=False, names=["a"]),
+ view_json(names=["only-one.zip"]), "{}", "[]"])
+def test_verify_draft_refuses_a_wrong_state_or_asset_list(gh, runner, zips, tmp_path, view):
+ names = [z.name for z in zips]
+ if "a" in view:
+ view = view.replace('"a"', json.dumps(names[0])).replace("]}", f", {json.dumps(names[1])}]}}")
+ draft_script(runner, zips, tmp_path, view=view)
+ with pytest.raises(Refused) as e:
+ gh.verify_draft(TAG, zips, tmp_path / "dl")
+ assert e.value.gate == "github-draft"
+
+
+def publish_script(runner, *, draft=False, pre=True, latest="v0.3.1", remote=SHA):
+ runner.on(["gh", "release", "edit"], "")
+ runner.on(["gh", "release", "view"], json.dumps({"isDraft": draft, "isPrerelease": pre}))
+ runner.on(["gh", "api", f"repos/{SLUG}/releases/latest"], latest + "\n")
+ runner.on(["git", "-C"], f"{remote}\trefs/tags/{TAG}\n" if remote else "")
+
+
+def test_publish_checks_draft_off_prerelease_on_latest_unchanged_and_tag_at_sha(gh, runner, tmp_path):
+ publish_script(runner)
+ gh.publish(TAG, SHA)
+ assert runner.calls[0] == ["gh", "release", "edit", TAG, "--repo", SLUG, "--draft=false", "--latest=false"]
+ assert ["gh", "api", f"repos/{SLUG}/releases/latest", "--jq", ".tag_name"] in runner.calls
+ assert ["git", "-C", str(tmp_path), "ls-remote", "origin", f"refs/tags/{TAG}"] in runner.calls
+
+
[email protected]("kw", [dict(draft=True), dict(pre=False), dict(latest=TAG), dict(remote=OTHER),
+ dict(remote="")])
+def test_publish_refuses_any_mismatch(gh, runner, kw):
+ publish_script(runner, **kw)
+ with pytest.raises(Refused) as e:
+ gh.publish(TAG, SHA)
+ assert e.value.gate == "github-publish"
+
+
+def test_a_latest_nightly_is_named_as_such_and_needs_a_manual_fix(gh, runner):
+ publish_script(runner, latest=TAG)
+ with pytest.raises(Refused) as e:
+ gh.publish(TAG, SHA)
+ assert "now the Latest release" in e.value.detail and "manual fix" in e.value.detail
+
+
+def test_demo_serves_survives_a_broken_http_response():
+ import http.client
+ calls = []
+
+ def fetch(u, timeout):
+ calls.append(u)
+ if len(calls) == 1:
+ raise http.client.IncompleteRead(b"x")
+ return io.BytesIO(b'productVersion: "0.3.1-nightly.20261028"')
+ gp.demo_serves(DEMO, VERSION, deadline=100, fetch=fetch, sleep=lambda s: None,
+ now=iter(range(0, 1000, 30)).__next__)
+ assert len(calls) == 2
+
+
+def test_publish_prefers_the_peeled_tag_commit(gh, runner):
+ publish_script(runner, remote=None)
+ runner.scripts = [s for s in runner.scripts if s[0] != ("git", "-C")]
+ runner.on(["git", "-C"], f"{OTHER}\trefs/tags/{TAG}\n{SHA}\trefs/tags/{TAG}^{{}}\n")
+ gh.publish(TAG, SHA)
+
+
+def test_a_failing_gh_edit_is_a_publish_refusal(gh, runner):
+ runner.on(["gh", "release", "edit"], Refused("command", "gh release edit exited 1: boom"))
+ with pytest.raises(Refused) as e:
+ gh.publish(TAG, SHA)
+ assert e.value.gate == "github-publish"
+
+
+def test_delete_draft_removes_a_draft_and_never_cleans_tags(gh, runner):
+ runner.on(["gh", "release", "view"], '{"isDraft": true}')
+ runner.on(["gh", "release", "delete"], "")
+ gh.delete_draft(TAG)
+ assert runner.calls[-1] == ["gh", "release", "delete", TAG, "--repo", SLUG, "--yes"]
+ 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}')
+ with pytest.raises(Refused):
+ gh.delete_draft(TAG)
+ assert not any(c[:3] == ["gh", "release", "delete"] for c in runner.calls)
+ assert 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)
+
+
+# --- previous build, download -----------------------------------------------------------------------------------------
+
+def test_previous_build_is_state_tag_else_newest_release_with_a_web_zip(gh, runner):
+ assert gh.previous_build_tag("v0.3.0-nightly.20261027") == "v0.3.0-nightly.20261027"
+ assert runner.calls == []
+ runner.on(["gh", "release", "list", "--repo", SLUG, "--exclude-drafts", "--limit", "30", "--json", "tagName"],
+ json.dumps([{"tagName": "v0.3.2"}, {"tagName": "v0.3.1"}]))
+ runner.on(["gh", "release", "view", "v0.3.2"], view_json(draft=False, names=["notes.txt"]))
+ runner.on(["gh", "release", "view", "v0.3.1"],
+ view_json(draft=False, names=["statecraft-israel-v0.3.1-web-pages.zip", "statecraft-israel-v0.3.1-web.zip"]))
+ assert gh.previous_build_tag(None) == "v0.3.1"
+
+
+def test_no_release_with_a_web_zip_refuses(gh, runner):
+ runner.on(["gh", "release", "list"], json.dumps([{"tagName": "v0.3.2"}]))
+ runner.on(["gh", "release", "view"], view_json(names=["statecraft-israel-v0.3.2-web-pages.zip"]))
+ with pytest.raises(Refused) as e:
+ gh.previous_build_tag(None)
+ assert e.value.gate == "sizes"
+
+
+def test_download_returns_the_one_matching_file(gh, runner, tmp_path):
+ def fetch(cmd):
+ d = Path(cmd[cmd.index("--dir") + 1])
+ d.mkdir(parents=True, exist_ok=True)
+ (d / "statecraft-israel-v0.3.1-web.zip").write_bytes(b"z")
+ return ""
+ runner.on(["gh", "release", "download"], fetch)
+ got = gh.download("v0.3.1", "*-web.zip", tmp_path / "prev")
+ assert got == tmp_path / "prev/statecraft-israel-v0.3.1-web.zip"
+ assert runner.calls[-1] == ["gh", "release", "download", "v0.3.1", "--repo", SLUG, "--dir",
+ str(tmp_path / "prev"), "--pattern", "*-web.zip"]
+
+
+def test_download_refuses_zero_matches(gh, runner, tmp_path):
+ runner.on(["gh", "release", "download"], "")
+ with pytest.raises(Refused) as e:
+ gh.download("v0.3.1", "*-web.zip", tmp_path / "prev")
+ assert e.value.gate == "github-download"
+
+
+# --- merged PR bodies -------------------------------------------------------------------------------------------------
+
+def pr_rows(*pairs):
+ return json.dumps([{"body": b, "mergeCommit": ({"oid": o} if o else None)} for b, o in pairs])
+
+
+def test_merged_pr_bodies_filter_by_merge_commit_squash_and_merge_commit_alike(gh, runner, tmp_path):
+ squash, merge = "1" * 40, "2" * 40
+ runner.on(["git", "-C", str(tmp_path), "log", "--no-walk", "--format=%cs"], "2026-10-27\n2026-10-26\n")
+ runner.on(["gh", "pr", "list"], pr_rows(("squashed body", squash), ("merged body", merge),
+ ("older PR", "9" * 40), ("never merged", None)))
+ assert gh.merged_pr_bodies({squash, merge}) == ["squashed body", "merged body"]
+ cmd = [c for c in runner.calls if c[:3] == ["gh", "pr", "list"]][0]
+ assert cmd == ["gh", "pr", "list", "--repo", SLUG, "--state", "merged", "--limit", "500",
+ "--search", "merged:>=2026-10-25", "--json", "body,mergeCommit"]
+
+
+def test_merged_pr_bodies_refuse_a_possibly_truncated_list(gh, runner, tmp_path):
+ runner.on(["git", "-C"], "2026-10-27\n")
+ runner.on(["gh", "pr", "list"], pr_rows(*[("b", None)] * 500))
+ with pytest.raises(Refused) as e:
+ gh.merged_pr_bodies({"1" * 40})
+ assert e.value.gate == "sizes"
+
+
+def test_merged_pr_bodies_of_no_commits_ask_nothing(gh, runner):
+ assert gh.merged_pr_bodies(set()) == []
+ assert runner.calls == []
+
+
+def test_merged_pr_bodies_refuse_garbage_and_an_unknown_commit_date(gh, runner):
+ runner.on(["git", "-C"], "2026-10-27\n")
+ runner.on(["gh", "pr", "list"], "{}")
+ with pytest.raises(Refused) as e:
+ gh.merged_pr_bodies({"1" * 40})
+ assert e.value.gate == "sizes"
+ runner.scripts.clear()
+ runner.on(["git", "-C"], "\n")
+ with pytest.raises(Refused):
+ gh.merged_pr_bodies({"1" * 40})
+
+
+# --- the site -------------------------------------------------------------------------------------------------------------
+
+RUN_LIST = ["gh", "run", "list", "--repo", SLUG, "--workflow", "site.yml", "--event", "workflow_dispatch",
+ "--limit", "5", "--json", "databaseId,createdAt"]
+
+
+def test_site_dispatch_finds_the_new_run_and_watches_it(gh, runner):
+ old = json.dumps([{"databaseId": 7, "createdAt": "2026-10-27T01:00:00Z"}])
+ new = json.dumps([{"databaseId": 9, "createdAt": "2026-10-28T01:00:00Z"},
+ {"databaseId": 7, "createdAt": "2026-10-27T01:00:00Z"}])
+ runner.on(RUN_LIST, old, old, new)
+ runner.on(["gh", "workflow", "run"], "")
+ runner.on(["gh", "run", "watch"], "")
+ gh.dispatch_site(1000)
+ assert ["gh", "workflow", "run", "site.yml", "--repo", SLUG, "--ref", "main"] in runner.calls
+ assert runner.calls[-1] == ["gh", "run", "watch", "9", "--repo", SLUG, "--exit-status"]
+ assert runner.calls.index(RUN_LIST) < runner.calls.index(["gh", "workflow", "run", "site.yml", "--repo", SLUG,
+ "--ref", "main"])
+
+
+def test_a_failed_site_run_is_a_site_refusal(gh, runner):
+ runner.on(RUN_LIST, "[]", json.dumps([{"databaseId": 9, "createdAt": "x"}]))
+ runner.on(["gh", "workflow", "run"], "")
+ runner.on(["gh", "run", "watch"], Refused("command", "gh run watch exited 1: failed"))
+ with pytest.raises(Refused) as e:
+ gh.dispatch_site(1000)
+ assert e.value.gate == "site"
+
+
+def test_a_dispatch_that_never_shows_a_new_run_refuses_at_the_deadline(gh, runner):
+ runner.on(RUN_LIST, "[]")
+ runner.on(["gh", "workflow", "run"], "")
+ with pytest.raises(Refused) as e:
+ gh.dispatch_site(30)
+ assert e.value.gate == "site" and "did not appear" in e.value.detail
+ assert not any(c[:3] == ["gh", "run", "watch"] for c in runner.calls)
+
+
+def test_a_failed_dispatch_is_a_site_refusal(gh, runner):
+ runner.on(RUN_LIST, "[]")
+ runner.on(["gh", "workflow", "run"], Refused("command", "gh workflow run exited 1: 403"))
+ with pytest.raises(Refused) as e:
+ gh.dispatch_site(1000)
+ assert e.value.gate == "site"
+
+
+def test_demo_serves_polls_until_the_version_appears():
+ pages = iter([b'productVersion: "0.3.1"', b'productVersion: "0.3.1-nightly.20261028"'])
+ urls = []
+
+ def fetch(u, timeout):
+ urls.append(u)
+ return io.BytesIO(next(pages))
+ gp.demo_serves(DEMO, VERSION, deadline=100, fetch=fetch, sleep=lambda s: None,
+ now=iter(range(0, 1000, 30)).__next__)
+ assert len(urls) == 2 and all(u.startswith(DEMO) for u in urls)
+
+
+def test_demo_serves_refuses_at_the_deadline_and_survives_fetch_errors():
+ def broken(u, timeout):
+ raise OSError("down")
+ with pytest.raises(Refused) as e:
+ gp.demo_serves(DEMO, VERSION, deadline=100, fetch=broken, sleep=lambda s: None,
+ now=iter(range(0, 1000, 30)).__next__)
+ assert e.value.gate == "site"
+ with pytest.raises(Refused):
+ gp.demo_serves(DEMO, VERSION, deadline=100, fetch=lambda u, timeout: io.BytesIO(b"no version here"),
+ sleep=lambda s: None, now=iter(range(0, 1000, 30)).__next__)
+
+
+# --- notes and unzip ------------------------------------------------------------------------------------------------------
+
+def test_release_notes_list_commits_and_hashes_and_say_nightly():
+ text = gp.release_notes(version=VERSION, sha=SHA, since="b" * 40, subjects=["Fix a thing", "Add a thing"],
+ sha256_lines=["abc one.zip", "def two.zip"])
+ assert f"Automated nightly build of `main` at {SHA[:12]}. A pre-release, not a versioned release." in text
+ assert "- Fix a thing\n- Add a thing" in text and "abc one.zip\ndef two.zip" in text
+ assert VERSION in text and ("b" * 12) in text and ("b" * 40) not in text
+ assert "\u2014" not in text
+
+
+def test_release_notes_with_no_commits_say_so():
+ text = gp.release_notes(version=VERSION, sha=SHA, since="v0.3.1", subjects=[], sha256_lines=[])
+ assert "v0.3.1" in text and "no commits" in text.lower()
+
+
+def test_unzip_extracts_into_the_folder(tmp_path):
+ z = make_zip(tmp_path / "a.zip")
+ out = gp.unzip_to(z, tmp_path / "out")
+ assert out == tmp_path / "out" and (out / "LICENSE").read_text() == "text" and (out / "index.html").is_file()
+
+
+def test_unzip_refuses_a_path_that_leaves_the_folder(tmp_path):
+ z = tmp_path / "evil.zip"
+ with zipfile.ZipFile(z, "w") as zf:
+ zf.writestr("../escape.txt", "x")
+ with pytest.raises(Refused):
+ gp.unzip_to(z, tmp_path / "out")
+ assert not (tmp_path / "escape.txt").exists()
+
+
+def test_sha256_lines_match_shasum_format(zips):
+ lines = gp.sha256_lines(zips)
+ assert lines[0] == f"{hashlib.sha256(zips[0].read_bytes()).hexdigest()} {zips[0].name}"
+
+
+# --- itch.io (butler) ------------------------------------------------------------------------------------------------
+
+DATA = Path(__file__).resolve().parent / "data"
+TOOLS = Path(__file__).resolve().parents[1]
+BUTLER = Path("/fake/butler")
+ITCH_TARGET = "eyalgolan/statecraft-israel:html5"
+ITCH_PROJECT = "eyalgolan/statecraft-israel"
+
+
+def live_text() -> str:
+ return (DATA / "butler_status_live.txt").read_text(encoding="utf-8")
+
+
+def status_with(build="✓ #2217587 (from #2211125)", version="0.3.1", channel="html5") -> str:
+ return ("+---------+-----------+----------------------------+---------+\n"
+ "| CHANNEL | UPLOAD | BUILD | VERSION |\n"
+ "+---------+-----------+----------------------------+---------+\n"
+ f"| {channel} | #19840947 | {build} | {version} |\n"
+ "+---------+-----------+----------------------------+---------+\n")
+
+
+def test_live_version_reads_the_channel_row():
+ assert gp.Itch.live_version(live_text()) == "0.3.1"
+ assert gp.Itch.build_id(live_text()) == "2217587"
+
+
+def test_a_build_cell_without_the_live_mark_is_not_live():
+ unmarked = live_text().replace("✓ ", "")
+ assert "#2217587 (from #2211125)" in unmarked and "✓" not in unmarked
+ assert gp.Itch.live_version(unmarked) is None
+ assert gp.Itch.build_id(unmarked) is None
+
+
[email protected](strict=True, reason="pending fixture not captured")
+def test_a_processing_build_is_not_live():
+ # butler's text for a build that is still processing has not been captured yet (it needs a real push), so
+ # there is no fixture to read; until then the fail-closed rule above is what keeps it from counting as live
+ text = (DATA / "butler_status_pending.txt").read_text(encoding="utf-8")
+ assert gp.Itch.live_version(text) is None
+
+
[email protected]("text", ["", "garbage", status_with(channel="webgl"), status_with(version=""),
+ status_with(build="")])
+def test_a_missing_empty_or_other_channel_row_is_not_live(text):
+ assert gp.Itch.live_version(text) is None
+
+
+def test_two_rows_for_the_channel_are_not_live():
+ row = status_with().splitlines()[3]
+ assert gp.Itch.live_version(status_with() + row + "\n") is None
+
+
+def test_live_version_reads_the_given_channel():
+ assert gp.Itch.live_version(status_with(channel="html5-beta", version="9"), "html5-beta") == "9"
+
+
+def test_a_target_must_be_user_project_channel(runner):
+ for bad in ("", "eyalgolan/statecraft-israel", "statecraft:html5", "a/b:", ":c"):
+ with pytest.raises(Refused) as e:
+ gp.Itch(runner, BUTLER, bad)
+ assert e.value.gate == "itch"
+
+
+def test_push_uses_the_folder_target_and_userversion(runner, tmp_path):
+ runner.on([str(BUTLER), "push"], "")
+ runner.on([str(BUTLER), "status", ITCH_PROJECT], live(100, "0.3.1"))
+ gp.Itch(runner, BUTLER, ITCH_TARGET).push(tmp_path, "0.3.1-nightly.20261028")
+ assert runner.calls[-1] == [str(BUTLER), "push", str(tmp_path), ITCH_TARGET, "--userversion",
+ "0.3.1-nightly.20261028"]
+
+
+def test_a_failed_push_is_an_itch_refusal(runner, tmp_path):
+ runner.on([str(BUTLER), "push"], Refused("command", "butler push exited 1"))
+ runner.on([str(BUTLER), "status", ITCH_PROJECT], live(100, "0.3.1"))
+ with pytest.raises(Refused) as e:
+ gp.Itch(runner, BUTLER, ITCH_TARGET).push(tmp_path, "1")
+ assert e.value.gate == "itch" and "exited 1" in e.value.detail
+
+
+def live(build_id, version):
+ return status_with(build=f"\u2713 #{build_id} (from #1)", version=version)
+
+
+def itch_after_push(runner, tmp_path, *answers, before=None):
+ """An Itch that has pushed once: the status before the push is `before`, then `answers` follow."""
+ runner.on([str(BUTLER), "push"], "")
+ runner.on([str(BUTLER), "status", ITCH_PROJECT], before or live(100, "0.3.1"), *answers)
+ itch = gp.Itch(runner, BUTLER, ITCH_TARGET)
+ itch.push(tmp_path, "0.3.2")
+ return itch
+
+
+def clock():
+ return iter(range(0, 10_000, 10)).__next__
+
+
+def test_push_reads_the_build_id_first(runner, tmp_path):
+ itch_after_push(runner, tmp_path)
+ assert runner.calls[0][:3] == [str(BUTLER), "status", ITCH_PROJECT] and runner.calls[1][1] == "push"
+
+
+def test_push_without_a_readable_build_id_fails_closed_and_pushes_nothing(runner, tmp_path):
+ runner.on([str(BUTLER), "push"], "")
+ runner.on([str(BUTLER), "status", ITCH_PROJECT], status_with(build="#1 (processing)"))
+ with pytest.raises(Refused) as e:
+ gp.Itch(runner, BUTLER, ITCH_TARGET).push(tmp_path, "0.3.2")
+ assert e.value.gate == "itch" and not any(c[1] == "push" for c in runner.calls)
+
+
+def test_wait_live_without_a_push_first_fails_closed(runner):
+ with pytest.raises(Refused) as e:
+ gp.Itch(runner, BUTLER, ITCH_TARGET).wait_live("0.3.2", deadline=1000)
+ assert e.value.gate == "itch" and runner.calls == []
+
+
+def test_wait_live_polls_until_the_version_is_live_with_a_newer_build(runner, tmp_path):
+ itch = itch_after_push(runner, tmp_path, status_with(build="#101 (processing)", version="0.3.1"),
+ live(100, "0.3.1"), live(101, "0.3.2"))
+ sleeps = []
+ itch.wait_live("0.3.2", deadline=1000, sleep=sleeps.append, now=clock())
+ assert sleeps == [30, 30]
+
+
+def test_the_expected_version_on_the_old_build_id_is_not_live(runner, tmp_path):
+ itch = itch_after_push(runner, tmp_path, live(100, "0.3.2")) # a stale row that already shows the version
+ sleeps = []
+ with pytest.raises(Refused) as e:
+ itch.wait_live("0.3.2", deadline=100, sleep=sleeps.append, now=iter(range(0, 1000, 60)).__next__)
+ assert e.value.gate == "itch" and "0.3.2" in e.value.detail and sleeps
+
+
+def test_a_rollback_is_live_only_with_a_build_newer_than_the_failed_push(runner, tmp_path):
+ itch = itch_after_push(runner, tmp_path, live(100, "0.3.1")) # the forward build never goes live
+ with pytest.raises(Refused):
+ itch.wait_live("0.3.2", deadline=0, sleep=lambda s: None, now=clock())
+ # the rollback push reads the status while the forward build is still processing: no live id, floor kept
+ runner.scripts[1][1][:] = [status_with(build="#101 (processing)", version="0.3.1")]
+ itch.push(tmp_path, "0.3.1")
+ runner.scripts[1][1][:] = [live(100, "0.3.1"), live(100, "0.3.1"), live(102, "0.3.1")]
+ sleeps = []
+ itch.wait_live("0.3.1", deadline=1000, sleep=sleeps.append, now=clock())
+ assert len(sleeps) == 2 # the old row (id 100, the very version being restored) did not count
+
+
+def test_wait_live_gives_up_at_the_deadline(runner, tmp_path):
+ itch = itch_after_push(runner, tmp_path, live(100, "0.3.1"))
+ with pytest.raises(Refused) as e:
+ itch.wait_live("0.3.2", deadline=100, sleep=lambda s: None, now=iter(range(0, 1000, 60)).__next__)
+ assert e.value.gate == "itch" and "0.3.2" in e.value.detail and "0.3.1" in e.value.detail
+
+
+def test_wait_live_treats_a_status_error_as_not_live_until_the_deadline(runner, tmp_path):
+ itch = itch_after_push(runner, tmp_path, Refused("command", "butler status exited 1"))
+ with pytest.raises(Refused) as e:
+ itch.wait_live("0.3.2", deadline=100, sleep=lambda s: None, now=iter(range(0, 1000, 60)).__next__)
+ assert e.value.gate == "itch"
+
+
+def fetch_writes(files: dict[str, bytes]):
+ def effect(cmd):
+ dest = Path(cmd[3])
+ for name, data in files.items():
+ (dest / name).parent.mkdir(parents=True, exist_ok=True)
+ (dest / name).write_bytes(data)
+ return ""
+ return effect
+
+
+def pushed_folder(tmp_path) -> Path:
+ folder = tmp_path / "pushed"
+ (folder / "Build").mkdir(parents=True)
+ (folder / "index.html").write_bytes(b"page")
+ (folder / "Build" / "a.data.gz").write_bytes(b"data")
+ return folder
+
+
+def test_fetch_compare_accepts_identical_content(runner, tmp_path):
+ runner.on([str(BUTLER), "fetch"], fetch_writes({"index.html": b"page", "Build/a.data.gz": b"data"}))
+ gp.Itch(runner, BUTLER, ITCH_TARGET).matches(pushed_folder(tmp_path), tmp_path / "fetched")
+ assert runner.calls[-1] == [str(BUTLER), "fetch", ITCH_TARGET, str(tmp_path / "fetched")]
+
+
[email protected]("files", [{"index.html": b"page"}, # a file is missing
+ {"index.html": b"page", "Build/a.data.gz": b"DATA"}, # changed bytes
+ {"index.html": b"page", "Build/a.data.gz": b"data", "x": b"1"}]) # an extra file
+def test_fetch_compare_refuses_any_difference(runner, tmp_path, files):
+ runner.on([str(BUTLER), "fetch"], fetch_writes(files))
+ with pytest.raises(Refused) as e:
+ gp.Itch(runner, BUTLER, ITCH_TARGET).matches(pushed_folder(tmp_path), tmp_path / "fetched")
+ assert e.value.gate == "itch"
+
+
+def test_a_failed_fetch_refuses(runner, tmp_path):
+ runner.on([str(BUTLER), "fetch"], Refused("command", "butler fetch exited 1"))
+ with pytest.raises(Refused) as e:
+ gp.Itch(runner, BUTLER, ITCH_TARGET).matches(pushed_folder(tmp_path), tmp_path / "fetched")
+ assert e.value.gate == "itch"
+
+
+def test_no_butler_command_names_the_credentials_file():
+ src = "".join((TOOLS / n).read_text() for n in ("nightly_publish.py", "nightly.py", "nightly_state.py"))
+ assert "butler_creds" not in src and "--identity" not in src and "auth token" not in src
+ assert "GH_TOKEN" not in src
+ assert not any(w in src for w in ('"login"', '"logout"'))
+
+
+# --- Task 8: the itch page's game frame -----------------------------------------------------------------------------
+
+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("&quot;", "") # 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_a_frame_of_another_host_is_not_a_game_frame():
+ assert gp.itch_frame_url('data-iframe="&lt;iframe src=&quot;https://evil.example/html/1-2/index.html&quot;') is None
diff --git a/tools/tests/test_nightly_state.py b/tools/tests/test_nightly_state.py
new file mode 100644
index 000000000..fffc66976
--- /dev/null
+++ b/tools/tests/test_nightly_state.py
@@ -0,0 +1,172 @@
+import json
+from datetime import date, datetime, timezone
+from pathlib import Path
+
+import pytest
+
+# nightly_state locks with flock; fcntl does not exist on Windows, so the module skips there.
+fcntl = pytest.importorskip("fcntl", reason="fcntl is POSIX-only (nightly_state uses flock); not on Windows")
+
+import nightly_state as ns # noqa: E402
+from conftest import FakeRunner # noqa: E402
+
+
+def test_version_and_tag_follow_the_spec():
+ assert ns.base_version('public const string Version = "0.3.1";') == "0.3.1"
+ assert ns.nightly_version("0.3.1", date(2026, 10, 28)) == "0.3.1-nightly.20261028"
+ assert ns.tag_for("0.3.1-nightly.20261028") == "v0.3.1-nightly.20261028"
+ with pytest.raises(ValueError):
+ ns.base_version('Version = "0.3"')
+
+
+def test_the_night_is_the_jerusalem_date():
+ assert ns.night_of(datetime(2026, 10, 28, 0, 30, tzinfo=timezone.utc)) == date(2026, 10, 28) # 02:30 IST
+ assert ns.night_of(datetime(2026, 10, 27, 21, 59, tzinfo=timezone.utc)) == date(2026, 10, 27)
+
+
+def test_a_start_after_0330_is_late():
+ il = ns.TZ
+ assert not ns.late_start(datetime(2026, 10, 28, 3, 0, tzinfo=il), "03:30")
+ assert not ns.late_start(datetime(2026, 10, 28, 3, 30, tzinfo=il), "03:30")
+ assert ns.late_start(datetime(2026, 10, 28, 3, 31, tzinfo=il), "03:30")
+
+
+def test_missed_days_are_the_dates_between_runs():
+ assert ns.missed_days("2026-10-25", date(2026, 10, 28)) == [date(2026, 10, 26), date(2026, 10, 27)]
+ assert ns.missed_days(None, date(2026, 10, 28)) == []
+
+
+def test_log_line_names_outcome_tag_sha_gate_and_log(tmp_path):
+ line = ns.log_line(datetime(2026, 10, 28, 3, 0, tzinfo=ns.TZ), "REFUSED", tag="v0.3.1-nightly.20261028",
+ sha="0123456789abcdef0123", gate="editmode", log=tmp_path / "runs/x")
+ assert line == f"2026-10-28 03:00 REFUSED tag=v0.3.1-nightly.20261028 sha=0123456789ab gate=editmode log={tmp_path}/runs/x"
+ with pytest.raises(ValueError):
+ ns.log_line(datetime.now(ns.TZ), "OK", tag=None, sha=None, gate="-", log=None)
+
+
+def test_record_appends_to_log_and_handoff(tmp_path):
+ ns.record(tmp_path / "LOG.md", tmp_path / "HANDOFF.md", "L1")
+ ns.record(tmp_path / "LOG.md", tmp_path / "HANDOFF.md", "L2")
+ assert (tmp_path / "LOG.md").read_text().splitlines()[-2:] == ["- L1", "- L2"]
+ assert (tmp_path / "HANDOFF.md").read_text().splitlines()[-1] == "- NIGHTLY: L2"
+
+
+def test_record_starts_a_new_line_after_a_handoff_without_a_final_newline(tmp_path):
+ (tmp_path / "HANDOFF.md").write_text("existing")
+ ns.record(tmp_path / "LOG.md", tmp_path / "HANDOFF.md", "L1")
+ assert (tmp_path / "HANDOFF.md").read_text().splitlines() == ["existing", "- NIGHTLY: L1"]
+
+
+def test_state_round_trips_and_a_missing_file_is_empty(tmp_path):
+ assert ns.load_state(tmp_path / "state.json") == ns.State()
+ s = ns.State(last_published=ns.Published("v0.3.1-nightly.20261028", "a" * 40, "0.3.1-nightly.20261028",
+ {"statecraft-web.zip": 123}, 4200.5),
+ boot_baseline=[1.0, 2.5], last_run_day="2026-10-28", open_draft="v0.3.1-nightly.20261029",
+ site_pending="v0.3.1-nightly.20261028")
+ ns.save_state(tmp_path / "state.json", s)
+ assert ns.load_state(tmp_path / "state.json") == s
+ assert not list(tmp_path.glob("*.tmp*"))
+
+
+def test_a_corrupt_state_or_config_refuses(tmp_path):
+ (tmp_path / "state.json").write_text("{bad")
+ (tmp_path / "config.json").write_text('{"itch_enabled": "yes"}')
+ with pytest.raises(ns.Refused) as e:
+ ns.load_state(tmp_path / "state.json")
+ assert e.value.gate == "state"
+ with pytest.raises(ns.Refused) as e:
+ ns.load_config(tmp_path / "config.json")
+ assert e.value.gate == "config"
+ (tmp_path / "config.json").write_text('{"surprise": 1}')
+ with pytest.raises(ns.Refused):
+ ns.load_config(tmp_path / "config.json")
+ (tmp_path / "state.json").write_text('{"last_published": {"tag": "t"}}')
+ with pytest.raises(ns.Refused):
+ ns.load_state(tmp_path / "state.json")
+ (tmp_path / "state.json").write_text('{"boot_baseline": "nope"}')
+ with pytest.raises(ns.Refused):
+ ns.load_state(tmp_path / "state.json")
+
+
+def test_a_missing_config_gives_the_defaults_and_paths_expand(tmp_path):
+ c = ns.load_config(tmp_path / "none.json")
+ assert c.repo_slug == "eyalgolan/statecraft-israel" and c.itch_enabled is False and c.min_free_gb == 40
+ (tmp_path / "config.json").write_text(json.dumps({"butler": "~/bin/butler", "deadline_hours": 5}))
+ c = ns.load_config(tmp_path / "config.json")
+ assert c.butler == Path.home() / "bin/butler" and c.deadline_hours == 5
+
+
+def test_only_enable_itch_flips_the_flag_and_keeps_other_keys(tmp_path):
+ p = tmp_path / "config.json"
+ p.write_text('{"itch_page_url": "https://x.itch.io/y"}')
+ assert ns.load_config(p).itch_enabled is False
+ ns.enable_itch(p, tmp_path / "evidence.json")
+ c = ns.load_config(p)
+ assert c.itch_enabled and c.itch_page_url == "https://x.itch.io/y" and c.itch_evidence.endswith("evidence.json")
+
+
+def test_notify_quotes_the_message_for_applescript():
+ calls = []
+ ns.notify("Statecraft nightly", 'gate "x" \\ y', run=lambda a, **k: calls.append(a))
+ assert calls[0][:2] == ["osascript", "-e"] and '\\"x\\"' in calls[0][2] and "\\\\ y" in calls[0][2]
+
+
+def test_the_run_lock_is_exclusive(tmp_path):
+ with ns.run_lock(tmp_path) as first:
+ with ns.run_lock(tmp_path) as second:
+ assert first is True and second is False
+ with ns.run_lock(tmp_path) as again:
+ assert again is True
+
+
+def test_stops_carry_outcome_gate_and_detail():
+ r = ns.Refused("editmode", "3 failed")
+ assert (r.outcome, r.gate, r.detail) == ("REFUSED", "editmode", "3 failed")
+ assert (ns.Skipped("no change").outcome, ns.Skipped("no change").gate) == ("SKIPPED", "-")
+ assert ns.Missed("asleep").outcome == "MISSED" and isinstance(ns.Missed("x"), ns.Stop)
+
+
+def test_the_fake_runner_matches_prefixes_and_fails_on_unknown_commands(tmp_path, no_processes):
+ fr = FakeRunner()
+ fr.add(("git", "fetch"), out="fetched")
+ fr.add(("git",), code=1, out="boom")
+ log = tmp_path / "x.log"
+ assert fr.run(["git", "fetch", "origin"], cwd=tmp_path, log=log, deadline=0.0) == 0
+ assert log.read_text() == "fetched"
+ assert fr.capture(["git", "fetch"], cwd=tmp_path) == "fetched"
+ with pytest.raises(ns.Refused):
+ fr.capture(["git", "status"], cwd=tmp_path)
+ with pytest.raises(AssertionError, match="unexpected command"):
+ fr.run(["gh", "x"], cwd=tmp_path, log=log, deadline=0.0)
+ with pytest.raises(AssertionError):
+ __import__("subprocess").run(["true"])
+
+
+ '{"last_run_day": "yesterday"}',
+ '{"last_run_day": "2026-13-45"}',
+ '{"boot_baseline": [1.0, NaN]}',
+ '{"boot_baseline": [Infinity]}',
+ '{"last_published": {"tag": "t", "sha": "s", "version": "v", "sizes": {}, "boot_ms": NaN}}',
+ '{"last_published": {"tag": "t", "sha": "s", "version": "v", "sizes": {}, "boot_ms": -Infinity}}',
+ '{"boot_baseline": [%s]}' % ("9" * 400),
+ '{"last_published": {"tag": "t", "sha": "s", "version": "v", "sizes": {}, "boot_ms": %s}}' % ("9" * 400),
+])
+def test_a_state_value_that_would_fail_later_refuses_now(tmp_path, body):
+ (tmp_path / "state.json").write_text(body)
+ with pytest.raises(ns.Refused) as e:
+ ns.load_state(tmp_path / "state.json")
+ assert e.value.gate == "state"
+
+
+def test_notify_without_run_uses_subprocess_resolved_at_call_time(no_processes):
+ with pytest.raises(AssertionError):
+ ns.notify("Statecraft nightly", "msg")
+
+
+def test_notify_default_run_is_looked_up_when_called(monkeypatch):
+ import subprocess
+ calls = []
+ monkeypatch.setattr(subprocess, "run", lambda a, **k: calls.append(a))
+ ns.notify("Statecraft nightly", "msg")
+ assert calls and calls[0][:2] == ["osascript", "-e"]
diff --git a/tools/tests/test_web_check.py b/tools/tests/test_web_check.py
index de55e4175..f36d72ef3 100644
--- a/tools/tests/test_web_check.py
+++ b/tools/tests/test_web_check.py
@@ -3,10 +3,12 @@ import gzip
import http.client
import queue
import re
+import shutil
import socket
import threading
import time
import urllib.request
+from pathlib import Path
import pytest
@@ -741,3 +743,62 @@ def test_commit_timeout_is_polled_while_an_unrelated_expectation_is_still_missin
wc.watch(queue.Queue(), lambda: None, lambda: None, ["UNRELATED"], re.compile("BOOT FAIL"), 20,
now=lambda: clock[0], sleep=lambda seconds: clock.__setitem__(0, clock[0] + 1),
complete=lambda: check.done)
+
+
+# --- the itch.io save test: --url, --profile, --first-save ----------------------------------------------------------------
+
+def test_first_save_stops_after_the_first_durable_commit(capsys):
+ game = FakeGame()
+ check = wc.PersistenceCheck(game, _buttons(), game.tail, lambda seconds: None, first_save_only=True)
+ check.feed("GAME OK 1948-05-15 turn 0 hash aa")
+ assert not check.done
+ check.feed("TURN 1 1948-05-16 hash ab")
+ check.feed("AUTOSAVE PENDING 1 1948-05-16 turn 1 hash ab")
+ assert not check.done, "a commit that is not acknowledged is not durable yet"
+ check.feed("AUTOSAVE OK 1 1948-05-16 turn 1 hash ab")
+ assert check.done and "reload" not in game.actions
+ assert "PERSISTENCE saved 1948-05-16 turn 1 hash ab" in capsys.readouterr().out
+
+
+def test_first_save_still_fails_on_a_wrong_first_turn():
+ game = FakeGame()
+ check = wc.PersistenceCheck(game, _buttons(), game.tail, lambda seconds: None, first_save_only=True)
+ check.feed("GAME OK 1948-05-15 turn 0 hash aa")
+ with pytest.raises(ValueError, match="expected turn 1"):
+ check.feed("TURN 2 1948-05-16 hash ab")
+
+
+def test_first_save_uses_the_persistence_driver_and_navlog():
+ driver, fail, plan = _plan("--first-save")
+ assert isinstance(driver, wc.PersistenceCheck) and driver.first_save_only and plan["complete_what"].endswith("--first-save run")
+ assert wc.page_query(_args("--first-save")) == "navlog"
+ assert not _plan("--persistence")[0].first_save_only
+ with pytest.raises(ValueError, match="separate runs"):
+ _plan("--first-save", "--startscreen", "new")
+
+
+def test_url_and_build_are_exclusive_and_one_is_required(capsys):
+ ap = wc.parser()
+ for argv in ([], ["build", "--url", "https://x.invalid/index.html"]):
+ a = ap.parse_args(argv)
+ with pytest.raises(SystemExit):
+ wc.check_source(ap, a)
+ assert "exactly one of build and --url" in capsys.readouterr().err
+ wc.check_source(ap, ap.parse_args(["build"]))
+ wc.check_source(ap, ap.parse_args(["--url", "https://x.invalid/index.html"]))
+
+
+def test_a_url_takes_the_query_after_a_question_mark_or_an_ampersand():
+ assert wc.with_query("https://h/index.html", "navlog") == "https://h/index.html?navlog"
+ assert wc.with_query("https://h/index.html?v=1", "navlog") == "https://h/index.html?v=1&navlog"
+ assert wc.with_query("https://h/index.html?v=1", "") == "https://h/index.html?v=1"
+
+
+def test_a_given_profile_is_made_and_kept_and_a_default_one_is_owned(tmp_path):
+ given = tmp_path / "kept" / "profile"
+ assert wc.pick_profile(_args("--profile", str(given))) == (str(given), False) and given.is_dir()
+ own, owned = wc.pick_profile(_args())
+ try:
+ assert owned and Path(own).is_dir()
+ finally:
+ shutil.rmtree(own)
diff --git a/tools/web_check.py b/tools/web_check.py
index b7029f630..e3cb91ec5 100644
--- a/tools/web_check.py
+++ b/tools/web_check.py
@@ -22,6 +22,8 @@ recording and waits for RECORDING playing; then End turn must log TURN 1, pressi
turn selects while units still need orders (EndTurn; --persistence ends its turns so too); any console Exception, RECORDING failed or
BOOT FAIL fails the run; add --query lang=he for the Hebrew layout). Both runs add ?navlog and click the start screen's
buttons where its "start buttons" line says they are (StartButtons).
+--url URL opens that page (the itch.io game frame) instead of serving a build; --profile DIR keeps that Chrome profile
+between runs; --first-save drives --persistence only to its first durable autosave and prints PERSISTENCE saved <date> turn <n> hash <h>.
The page is opened over the DevTools protocol with its viewport fixed to 1920x1080 at the DPR before it loads
(Emulation.setDeviceMetricsOverride: --window-size alone gives a 1920x937 viewport in --headless=new), and the run
fails on any "res=" line, or any screenshot, of another size. --viewport WxH checks another window - 390x844 is the
@@ -603,8 +605,9 @@ class PersistenceCheck:
browser); a reload keeps the page's profile and origin, so its IndexedDB autosave. Each turn ends through EndTurn."""
def __init__(self, action, buttons: StartButtons, tail: ConsoleTail, settle=time.sleep, now=time.monotonic,
- save_timeout=15.0):
+ save_timeout=15.0, first_save_only=False):
self.action, self.buttons, self.settle, self.now, self.save_timeout = action, buttons, settle, now, save_timeout
+ self.first_save_only = first_save_only # stop, with the saved line printed, at the first durable commit
self.end_turn = EndTurn(action, tail, hebrew=False, settle=settle)
self.stage, self.saved, self._done = "first_boot", None, False
self.pending, self.acknowledged, self.deadline = None, None, None
@@ -624,6 +627,11 @@ class PersistenceCheck:
return
first = self.stage == "first_commit"
self.deadline = None
+ if first and self.first_save_only:
+ date, turn, digest = self.saved
+ print(f"PERSISTENCE saved {date} turn {turn} hash {digest}")
+ self.stage, self._done = "saved", True
+ return
self.stage = "settled_reload" if first else "immediate_reload"
self.buttons.clear()
self.action("reload")
@@ -818,7 +826,7 @@ DRIVER_GRACE = 3.0
def page_query(a) -> str:
"""The page's query: --query, plus ?navlog for the runs that click the start screen (StartButtons). navlog only logs:
it skips nothing, so the start screen is still the one a player meets."""
- if not (a.startscreen or a.persistence) or query_value(a.query, NAVLOG) is not None:
+ if not (a.startscreen or a.persistence or a.first_save) or query_value(a.query, NAVLOG) is not None:
return a.query
return f"{a.query}&{NAVLOG}" if a.query else NAVLOG
@@ -826,13 +834,14 @@ def page_query(a) -> str:
def run_plan(a, command, buttons: StartButtons, tail: ConsoleTail):
"""What a run drives and fails on: (driver or None, the failure regex, watch's keyword arguments). `command` is
Page.command; `buttons` and `tail` are fed the console by the caller."""
- if a.persistence and a.startscreen:
+ if (a.persistence or a.first_save) and a.startscreen:
raise ValueError("--persistence and --startscreen are separate runs")
if a.startscreen:
driver = StartScreenCheck(command, a.startscreen == "recording", query_value(a.query, "lang") == "he", buttons, tail)
fail, what = f"(?:{a.fail})|{START_SCREEN_FAILS}", f"the end of the --startscreen {a.startscreen} run"
- elif a.persistence:
- driver, fail, what = PersistenceCheck(command, buttons, tail), a.fail, "the end of the --persistence run"
+ elif a.persistence or a.first_save:
+ driver = PersistenceCheck(command, buttons, tail, first_save_only=a.first_save)
+ fail, what = a.fail, "the end of the --first-save run" if a.first_save else "the end of the --persistence run"
else:
return None, re.compile(a.fail), {}
return driver, re.compile(fail), {"complete": lambda: driver.done, "complete_what": what, "grace": DRIVER_GRACE}
@@ -840,7 +849,13 @@ def run_plan(a, command, buttons: StartButtons, tail: ConsoleTail):
def parser() -> argparse.ArgumentParser:
ap = argparse.ArgumentParser()
- ap.add_argument("build", type=Path)
+ ap.add_argument("build", type=Path, nargs="?", help="a Unity WebGL build folder, served on localhost (or use --url)")
+ ap.add_argument("--url", help="open this page instead of serving a build (the itch.io game frame); no server starts")
+ ap.add_argument("--profile", type=Path,
+ help="use and keep this Chrome profile folder (default: a new temporary one, deleted at the end)")
+ ap.add_argument("--first-save", action="store_true",
+ help="drive the persistence run to the first durable autosave, print PERSISTENCE saved <date> turn <n> "
+ "hash <h> and pass, without reloading")
ap.add_argument("--query", default="")
ap.add_argument("--expect", action="append", default=[])
ap.add_argument("--fail", default=r"GOLDEN FAIL|SMOKE FAIL|BOOT FAIL")
@@ -857,15 +872,39 @@ def parser() -> argparse.ArgumentParser:
return ap
+def check_source(ap: argparse.ArgumentParser, a) -> None:
+ """Exactly one of the build folder and --url names the page."""
+ if (a.build is None) == (a.url is None):
+ ap.error("give exactly one of build and --url")
+
+
+def with_query(url: str, query: str) -> str:
+ """`url` with `query` added: after ? or, when the URL already has a query, after &."""
+ if not query:
+ return url
+ return f"{url}{'&' if '?' in url else '?'}{query}"
+
+
+def pick_profile(a) -> tuple[str, bool]:
+ """(the Chrome profile folder, whether the run owns it). --profile is made if missing and is never deleted."""
+ if a.profile is not None:
+ Path(a.profile).mkdir(parents=True, exist_ok=True)
+ return str(a.profile), False
+ return tempfile.mkdtemp(prefix="web-check-"), True
+
+
def main() -> int:
- a = parser().parse_args()
- if not (a.build / "index.html").exists():
+ ap = parser()
+ a = ap.parse_args()
+ check_source(ap, a)
+ if a.build is not None and not (a.build / "index.html").exists():
sys.exit(f"{a.build}/index.html not found")
- server, proc, page, profile = None, None, None, tempfile.mkdtemp(prefix="web-check-")
+ server, proc, page = None, None, None
try:
w, h = parse_viewport(a.viewport)
except ValueError as e:
sys.exit(str(e))
+ profile, own_profile = pick_profile(a)
res = expected_res(w, h, a.dpr)
shots = ShotCollector(a.shots, size=(round(w * a.dpr), round(h * a.dpr)))
buttons, tail = StartButtons((w, h)), ConsoleTail()
@@ -877,9 +916,12 @@ def main() -> int:
return shots.feed(text)
try:
chrome = find_chrome()
- server = serve(a.build)
query = page_query(a)
- url = f"http://localhost:{server.server_address[1]}/index.html" + (f"?{query}" if query else "")
+ if a.url:
+ url = with_query(a.url, query)
+ else:
+ server = serve(a.build)
+ url = with_query(f"http://localhost:{server.server_address[1]}/index.html", query)
proc = subprocess.Popen([str(chrome), *chrome_flags(profile, a.swiftshader, a.dpr), "about:blank"],
stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, text=True, errors="replace")
inbox: queue.Queue = queue.Queue()
@@ -924,7 +966,8 @@ def main() -> int:
proc.kill(); proc.wait()
if server is not None:
server.shutdown(); server.server_close()
- shutil.rmtree(profile, ignore_errors=True)
+ if own_profile:
+ shutil.rmtree(profile, ignore_errors=True)
if __name__ == "__main__":