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: each nightly is the next patch version and marked Latest (#1916)

Eyal Golane93d6ee7ec55
diff --git a/.github/workflows/site.yml b/.github/workflows/site.yml
index 9cdee1586..d68dc529f 100644
--- a/.github/workflows/site.yml
+++ b/.github/workflows/site.yml
@@ -59,8 +59,8 @@ jobs:
set -euo pipefail
# Lookup failures (auth, network, rate limit) must fail the step, not deploy without the demo: no
# error swallowing. Only two quiet skips: no releases at all, and a latest release without the zip.
- # `gh release view/download` without a tag resolve the latest non-prerelease, and every release is a
- # prerelease (docs/RELEASING.md step 6), so read the tag from the list and pass it to both calls.
+ # Historic prereleases and normal nightly releases can both carry the demo, so read the newest
+ # published tag from the list and pass it explicitly to both view and download.
tag="$(gh release list --limit 1 --exclude-drafts --json tagName --jq '.[0].tagName // empty')"
if [ -z "$tag" ]; then
echo "No releases yet: deploying without the demo."
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index 383d86971..8ad4bad8e 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -174,15 +174,23 @@ macOS IL2CPP parity check is not an MVP release gate.
## 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
+game: a normal GitHub release marked **Latest**, tagged `vX.Y.Z`, which the website's `/demo/` serves, and, once itch
+pushes are enabled, the itch.io page. X.Y.Z is one patch above the numerically highest published release tag matching
+`^v[0-9]+\.[0-9]+\.[0-9]+$`; drafts, `-nightly` tags and other names do not choose the version. With v0.3.1 and
+v0.3.1-nightly.20261028 published, the next nightly is v0.3.2. 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 owner-run release steps above (steps 1-7). Published nightlies are never deleted.
+
+Owner rulings, 28 Oct 2026: "the nighttly release needs to be vx.y.z +0.0.1 every time";
+"Mark each Latest (Recommended)"; "Stamp the build only (Recommended)". The build's `bundleVersion` and in-game label
+are X.Y.Z, stamped only in the nightly worktree after the gates pass and never committed.
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.
+ tonight's tag, and no local or remote git tag of that name. First delete a stranded draft only when its tag
+ matches this job's saved `open_draft`, then check availability. Foreign drafts and published releases refuse.
+ With `--no-publish`, leave the draft and state alone and refuse the collision.
2. `build-sim`, then `scripts/check.sh origin/main` (`check`) and `scripts/oss/release_gate.sh` (`release-gate`), the
same bar as a release.
3. The sim tests under `he_IL` and `en_US` (`sim-he_IL`, `sim-en_US`).
@@ -207,13 +215,28 @@ 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
+**Publishing** (only after every gate): a normal draft 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.
+rolled back to the previous build if publication or its verification fails), the release made public with `--latest` and checked for
+`isPrerelease: false` and Latest, then `site.yml` started and the demo checked for the new version. Creation also uses
+`--latest`, without `--prerelease`. Right before create, the tag is checked again (no release, no local or remote git
+tag), so a release made during the build is refused and not touched; only then is ownership recorded and saved. A
+create that fails after leaving a draft (an asset upload failing) has that draft cleaned; rollback deletes only that
+run's unpublished draft, and only while GitHub shows it as a draft. Ownership is by tag: a draft someone else creates
+with the same tag in the second between that check and create would be treated as this run's. Owning a draft by its
+release ID, and retrying a failed Latest restore on the next run, are tracked in #1917. A saved stranded draft is cleaned before the next
+attempt; it never reaches `/demo/`, because `site.yml` skips drafts.
+Before publishing, read the current Latest separately from the previous nightly asset baseline and record it in
+`latest-before-publish.txt`. On any later failure, including publication verification or both site attempts, and only
+while the failed release is still Latest, restore that previous tag with `gh release edit <previous> --latest` and
+verify it; a Latest someone else set in the meantime is left alone and reported. The REFUSED line and
+`latest-rollback.log` name the previous Latest and the recovery result. With no previous Latest, explicitly report
+that fact and remove the failed release's Latest mark; report any failed recovery for manual repair. Published
+releases and tags are preserved. A site-only failure retains the new itch build and the public release, records
+the site deploy as pending, and restores the previous Latest after the second attempt.
+Numeric tag components accept leading zeros: `v0.03.1` ties with `v0.3.1` and yields the normalized next tag `v0.3.2`.
+The no-change skip compares `state.json`'s last published SHA with `origin/main`, regardless of its saved tag name.
**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>`:
diff --git a/docs/superpowers/specs/2026-10-27-nightly-release-design.md b/docs/superpowers/specs/2026-10-27-nightly-release-design.md
index 1aa5f2c90..527a1766e 100644
--- a/docs/superpowers/specs/2026-10-27-nightly-release-design.md
+++ b/docs/superpowers/specs/2026-10-27-nightly-release-design.md
@@ -2,6 +2,10 @@
Status: Approved by the owner on 27 October 2026 ("Approve as written"). Built from docs/superpowers/plans/2026-10-27-nightly-release-plan.md.
+Amended by owner rulings, 28 Oct 2026: "the nighttly release needs to be vx.y.z +0.0.1 every time";
+"Mark each Latest (Recommended)"; "Stamp the build only (Recommended)". These replace the original nightly naming
+and Latest policy. The owner-run release steps in docs/RELEASING.md remain as written.
+
## 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).
@@ -18,21 +22,21 @@ So every night at 03:00 the newest `main` becomes the public game: the website's
## 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 change to the owner-run release process in docs/RELEASING.md; automated nightlies also use vX.Y.Z.
- 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.
+- A nightly that is not a normal release marked "Latest" on GitHub (owner ruling, 28 Oct 2026), 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.
+- `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. As of 28 Oct 2026 v0.3.1 is Latest; the next nightly v0.3.2 becomes a normal Latest release under the amended owner policy, and the site serves its web zip.
- 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".
@@ -46,17 +50,19 @@ Nightly job, `tools/nightly.py`, started by a `launchd` agent at 03:00:
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.
+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 X.Y.Z in `bundleVersion` and the in-game label. Choose the numerically highest published release tag matching `^v[0-9]+\.[0-9]+\.[0-9]+$` and add one to its patch component; ignore drafts, `-nightly` and other tags. No matching release refuses. With today's v0.3.1 and v0.3.1-nightly.20261028, choose v0.3.2. Leading-zero components are numeric: v0.03.1 ties with v0.3.1, and the next version is normalized to v0.3.2. Read every release page through the existing gh runner. Before checking availability, delete a stranded draft only if its tag matches the saved `open_draft`, then clear that field. Under `--no-publish`, leave it alone and refuse the collision. Refuse every remaining release or local/remote git tag of that name; never overwrite it. Stamp only in the nightly worktree AFTER `release_gate.sh` passed on the clean tree, never commit it (owner rulings, 28 Oct 2026). The no-change skip still compares the saved published SHA, independent of its tag.
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.
+ a. `gh release create vX.Y.Z --draft --latest` with the web zips and generated notes (commits since the previous nightly), without `--prerelease`; verify `isDraft: true` and `isPrerelease: false`, download the draft's assets and diff them against the local zips.
+ Immediately before create, check the tag again (no release, no local or remote git tag), then record and save `open_draft`. A release made since preflight is refused and not deleted. A create that fails after leaving a draft has that draft cleaned; rollback deletes only this run's draft while it is still a draft; a saved owned draft remains recognizable on a rerun. Ownership is by tag, so a same-tag draft created by someone else in the second between the check and create would be treated as this run's; release-ID ownership and a persisted Latest-recovery retry are deferred to #1917.
+ 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`, then `butler status` must show the new build live.
+ c. Publish the draft (`gh release edit vX.Y.Z --draft=false --latest`), verify `isDraft: false`, `isPrerelease: false`, Latest and the tag's commit, 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.
+ Immediately before the public edit, read the current Latest through gh and record its tag (or no previous Latest) in `latest-before-publish.txt`, separately from the previous nightly asset baseline.
+ d. On a publication or verification failure after (b): push the previous nightly's (or release's) web build back to itch, delete only this run's unpublished draft, and record REFUSED. On ANY failure after the public edit, including verification, saves, interrupts and site checks, and only while the failed release is still Latest, restore the saved previous Latest with `gh release edit <previous> --latest` and verify it; a Latest set by someone else in the meantime is left alone and reported. Record the prior tag and recovery result in the REFUSED line and `latest-rollback.log`; if there was no previous Latest, say so and remove the failed release's Latest mark. Recovery failures explicitly request manual repair. Preserve published releases and tags. If (c)'s site deploy fails after the release is public, re-run `site.yml` once; if it still fails, retain the new itch build and public release, mark the site pending, restore the previous Latest, and record REFUSED with an alert. Pages switches deployments only on success.
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.
diff --git a/tools/nightly.py b/tools/nightly.py
index 2ba236e0e..4c3af7e53 100644
--- a/tools/nightly.py
+++ b/tools/nightly.py
@@ -31,9 +31,9 @@ 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,
+from nightly_state import (JOB, TZ, Config, Missed, Published, Refused, Runner, Skipped, State, Stop,
enable_itch, late_start, load_config, load_state, log_line, missed_days, night_of,
- nightly_version, notify, record, run_lock, save_state, tag_for)
+ notify, record, run_lock, save_state, tag_for)
from web_check import find_chrome
HOLDER_ENV = unity_postmerge.machine_lock.HOLDER_ENV
@@ -189,16 +189,13 @@ def preflight(cfg: Config, state: State, runner: Runner, gh: GitHub, *, job: Pat
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)
+ version = gh.next_version()
tag = tag_for(version)
- release = gh.release_state(tag)
- if release == "draft" and state.open_draft == tag:
+ if gh.release_state(tag) == "draft" and state.open_draft == tag:
if not no_publish: # --no-publish makes no store write, not even this cleanup
- gh.delete_draft(tag) # this job's own draft from an earlier run tonight
+ gh.delete_draft(tag) # this job's own draft from an earlier run
state.open_draft = None
- elif release is not None:
- raise Refused("tag-exists", f"a {release} release already has the tag {tag}")
+ gh.ensure_tag_available(tag)
run_dir = job / "runs" / f"{now.astimezone(TZ):%Y%m%d-%H%M%S}"
manifest = (clone / "sim/Statecraft.Sim.Tests/golden/manifest.txt").read_text(encoding="utf-8")
return Night(now, day, sha, version, tag, run_dir, time.monotonic() + cfg.deadline_hours * 3600, job, cfg,
@@ -516,6 +513,8 @@ def previous_build(night: Night, state: State, gh: GitHub, runner: Runner) -> tu
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."""
+ if state.open_draft != night.tag:
+ return
try:
present = gh.release_state(night.tag)
if present == "draft":
@@ -548,6 +547,29 @@ def _itch_rollback(night: Night, itch, folder: Path, version: str) -> str:
return note
+def _restore_latest(night: Night, gh: GitHub, previous: str | None) -> str:
+ target = f"previous Latest {previous}" if previous is not None else "no previous Latest"
+ try:
+ acted, current = gh.restore_latest(previous, night.tag)
+ if acted:
+ note = (f"restored {target}" if previous is not None else
+ "no previous Latest; removed the failed release's Latest mark")
+ elif current is None:
+ note = f"there is no Latest now, so {night.tag} is not Latest: left alone"
+ elif current == previous:
+ note = f"{target} still stands; nothing to restore"
+ else:
+ note = f"Latest is now {current}, not {night.tag}: left alone"
+ except Exception as e:
+ note = f"Latest recovery failed ({target}): {_detail(e)}; check by hand"
+ print(note, file=sys.stderr)
+ try:
+ (night.run_dir / "latest-rollback.log").write_text(note + "\n", encoding="utf-8")
+ except OSError as e:
+ print(f"could not write Latest recovery log: {e}", file=sys.stderr)
+ 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:
@@ -564,10 +586,11 @@ def publish_night(night: Night, state: State, gh: GitHub, itch, zips: tuple[Path
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
+ gh.ensure_tag_available(night.tag) # again just before create: a release made since preflight is never ours
+ state.open_draft = night.tag # set before create: a draft a failed upload leaves behind is then cleaned
+ save()
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)
@@ -605,46 +628,54 @@ def publish_night(night: Night, state: State, gh: GitHub, itch, zips: tuple[Path
_itch_rollback(night, itch, rollback_folder, rollback_version)
_drop_draft(night, state, gh)
raise
+ previous_latest = None
+ publish_started = verified = False
try:
+ previous_latest = gh.latest_tag()
+ (night.run_dir / "latest-before-publish.txt").write_text(
+ previous_latest + "\n" if previous_latest is not None else "no previous Latest\n", encoding="utf-8")
+ publish_started = True # an edit can reach GitHub even if the command then fails
gh.publish(night.tag, night.sha)
- except Exception as e:
+ verified = True
+ 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 retry the site once before restoring Latest
+ 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:
+ failure = _detail(e)
+ raise Refused("site", f"{night.tag} is public and the demo is unchanged: {failure}")
+ except BaseException 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)
+ if publish_started:
+ detail += _restore_latest(night, gh, previous_latest)
+ if not verified:
+ 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)"
+ if isinstance(e, Exception):
+ raise Refused(e.gate if isinstance(e, Stop) else "github-publish", detail) from e
+ night.notes.append(detail) # run_night records recovery even when it re-raises an interrupt
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 --------------------------------------------------------------------------------------------------
diff --git a/tools/nightly_publish.py b/tools/nightly_publish.py
index 5707c86c8..3327f679e 100644
--- a/tools/nightly_publish.py
+++ b/tools/nightly_publish.py
@@ -2,7 +2,7 @@
# 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.
+"""GitHub and the site for the nightly release job: the draft-first 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."""
@@ -22,7 +22,7 @@ from pathlib import Path
from typing import Callable
import nightly_checks
-from nightly_state import Refused, Runner
+from nightly_state import Refused, Runner, next_version
SHA_SHOWN = 12
PR_LIMIT = 500 # `gh pr list` returns at most this many rows; a full page may be a truncated one
@@ -47,7 +47,7 @@ def sha256_lines(files: list[Path]) -> list[str]:
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.", "",
+ lines = [f"Automated nightly build of `main` at {sha[:SHA_SHOWN]}.", "",
f"Version {version}.", "", f"Changes since {shown}:", ""]
lines += [f"- {s}" for s in subjects] or ["- (no commits)"]
lines += ["", "SHA-256:", "", "```", *sha256_lines, "```", ""]
@@ -221,6 +221,25 @@ class GitHub:
# --- release state ---------------------------------------------------------------------------------------------
+ def next_version(self) -> str:
+ """Read every release page through gh; drafts and non-version tags cannot choose the version."""
+ pages = self._json("version", ["gh", "api", f"repos/{self.slug}/releases?per_page=100",
+ "--paginate", "--slurp"], list)
+ if not all(isinstance(page, list) for page in pages):
+ raise Refused("version", "gh returned release pages of the wrong shape")
+ return next_version([row for page in pages for row in page])
+
+ def ensure_tag_available(self, tag: str) -> None:
+ """Refuse every remaining release or local/remote tag after owned-draft cleanup."""
+ release = self.release_state(tag)
+ if release is not None:
+ raise Refused("tag-exists", f"a {release} release already has the tag {tag}")
+ local = self._run("tag-exists", ["git", "-C", str(self.cwd), "tag", "--list", tag]).strip()
+ remote = self._run("tag-exists", ["git", "-C", str(self.cwd), "ls-remote", "origin",
+ f"refs/tags/{tag}", f"refs/tags/{tag}^{{}}"]).strip()
+ if local or remote:
+ raise Refused("tag-exists", f"the git tag {tag} already exists; never reused or overwritten")
+
def release_state(self, tag: str) -> str | None:
"""'draft', 'published', or None when no release has this tag."""
try:
@@ -234,6 +253,33 @@ class GitHub:
raise Refused("github-state", f"gh did not say whether {tag} is a draft")
return "draft" if flag else "published"
+ def latest_tag(self) -> str | None:
+ """The current public Latest, independently of the previous nightly asset baseline."""
+ try:
+ tag = self._run("github-latest", ["gh", "api", f"repos/{self.slug}/releases/latest", "--jq",
+ ".tag_name"]).strip()
+ except Refused as e:
+ if "HTTP 404" in e.detail:
+ return None
+ raise
+ if not tag or tag == "null":
+ raise Refused("github-latest", "gh returned no usable Latest tag")
+ return tag
+
+ def restore_latest(self, previous: str | None, failed: str) -> tuple[bool, str | None]:
+ """Only while the failed release is still Latest: restore and verify the saved Latest (without one, remove the
+ failed release's explicit Latest mark). Returns (acted, the Latest now); a Latest that is not the failed
+ release, or no Latest at all, is left untouched."""
+ current = self.latest_tag()
+ if current != failed:
+ return False, current
+ self._run("github-latest", ["gh", "release", "edit", previous if previous is not None else failed,
+ "--repo", self.slug, "--latest" if previous is not None else "--latest=false"])
+ latest = self.latest_tag()
+ if (previous is not None and latest != previous) or (previous is None and latest == failed):
+ raise Refused("github-latest", f"Latest recovery did not take effect (Latest is {latest})")
+ return True, latest
+
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:
@@ -271,15 +317,15 @@ class GitHub:
# --- 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)",
+ """A normal draft marked Latest, whose tag will be created at exactly `sha` when it is published."""
+ self._run("github-draft", ["gh", "release", "create", tag, "--repo", self.slug, "--draft",
+ "--latest", "--target", sha, "--title", f"{tag} (nightly)",
"--notes-file", str(notes), *[str(a) for a in assets]], UPLOAD_TIMEOUT)
def 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")
+ if data.get("isDraft") is not True or data.get("isPrerelease") is not False:
+ raise Refused("github-draft", f"{tag} is not a normal draft release")
names = sorted(self._asset_names("github-draft", data))
want = sorted(Path(p).name for p in local)
if names != want:
@@ -296,7 +342,7 @@ class GitHub:
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`."""
+ """Make the draft public, then check it is normal, Latest, and its tag points at `sha`."""
try:
self._publish(tag, sha)
except Refused as e:
@@ -304,15 +350,14 @@ class GitHub:
def _publish(self, tag: str, sha: str) -> None:
self._run("github-publish", ["gh", "release", "edit", tag, "--repo", self.slug, "--draft=false",
- "--latest=false"])
+ "--latest"])
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")
+ if data.get("isDraft") is not False or data.get("isPrerelease") is not False:
+ raise Refused("github-publish", f"{tag} is not a public normal 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")
+ if latest != tag:
+ raise Refused("github-publish", f"{tag} is not the Latest release after publishing (Latest is {latest})")
refs: dict[str, str] = {}
for line in self._run("github-publish", ["git", "-C", str(self.cwd), "ls-remote", "origin",
f"refs/tags/{tag}"]).splitlines():
diff --git a/tools/nightly_state.py b/tools/nightly_state.py
index ff658b38e..e207432d9 100644
--- a/tools/nightly_state.py
+++ b/tools/nightly_state.py
@@ -234,15 +234,20 @@ def save_state(path: Path, state: State) -> None:
# --- 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 next_version(releases: list[dict]) -> str:
+ """One patch above the numerically highest published exact vX.Y.Z tag, regardless of release type."""
+ versions = []
+ for row in releases:
+ if (not isinstance(row, dict) or not isinstance(row.get("tag_name"), str)
+ or not isinstance(row.get("draft"), bool)):
+ raise Refused("version", "gh returned a release without a tag or draft flag")
+ match = re.fullmatch(r"v([0-9]+)\.([0-9]+)\.([0-9]+)", row["tag_name"])
+ if match and not row["draft"]:
+ versions.append(tuple(int(part) for part in match.groups()))
+ if not versions:
+ raise Refused("version", "no published vX.Y.Z release to increment")
+ major, minor, patch = max(versions)
+ return f"{major}.{minor}.{patch + 1}"
def tag_for(version: str) -> str:
diff --git a/tools/tests/test_nightly.py b/tools/tests/test_nightly.py
index 285919cf9..8a54dc67b 100644
--- a/tools/tests/test_nightly.py
+++ b/tools/tests/test_nightly.py
@@ -18,7 +18,7 @@ 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"
+TAG = "v0.3.2"
class FakeGH:
@@ -29,6 +29,7 @@ class FakeGH:
self.release = release
self.fail = fail or {}
self.previous_tag = previous_tag
+ self.latest = "v0.3.1" # deliberately different from the previous nightly asset tag
self.calls = []
self.baseline = None # a zip the download hands out
@@ -43,6 +44,15 @@ class FakeGH:
self.calls.append(("release_state", tag))
return self.release
+ def next_version(self):
+ self.calls.append(("next_version",))
+ return "0.3.2"
+
+ def ensure_tag_available(self, tag):
+ self.calls.append(("ensure_tag_available", tag))
+ if self.release is not None:
+ raise ns.Refused("tag-exists", f"a {self.release} release already has the tag {tag}")
+
def delete_draft(self, tag):
self.calls.append(("delete_draft", tag))
self.release = None
@@ -62,8 +72,8 @@ class FakeGH:
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")
+ self.release = "draft"
def verify_draft(self, tag, local, dest):
self.calls.append(("verify_draft", tag, list(local), dest))
@@ -71,9 +81,23 @@ class FakeGH:
def publish(self, tag, sha):
self.calls.append(("publish", tag, sha))
+ self.latest = tag # the edit may succeed before verification fails
self._maybe_fail("publish")
self.release = "published"
+ def latest_tag(self):
+ self.calls.append(("latest_tag",))
+ self._maybe_fail("latest_tag")
+ return self.latest
+
+ def restore_latest(self, previous, failed):
+ self.calls.append(("restore_latest", previous, failed))
+ self._maybe_fail("restore_latest")
+ if self.latest != failed:
+ return False, self.latest
+ self.latest = previous
+ return True, previous
+
def merged_pr_bodies(self, shas):
self.calls.append(("merged_pr_bodies", set(shas)))
return []
@@ -157,12 +181,29 @@ def gate_of(env, **kw):
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.sha, n.version, n.tag, n.day) == (SHA, "0.3.2", 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_preflight_selects_the_numeric_max_across_scripted_release_pages(env):
+ from nightly_publish import GitHub
+ cmd = ["gh", "api", f"repos/{env.cfg.repo_slug}/releases?per_page=100", "--paginate", "--slurp"]
+ env.runner.add(cmd, out=json.dumps([
+ [{"tag_name": "v0.9.9", "draft": False}, {"tag_name": "v99.0.0", "draft": True}],
+ [{"tag_name": "v0.10.0", "draft": False}, {"tag_name": "v99.0.0-nightly.20261028", "draft": False}],
+ ]))
+ env.runner.add(["gh", "release", "view"], code=1,
+ effect=lambda cmd: (_ for _ in ()).throw(ns.Refused("command", "release not found")))
+ env.runner.add(["git", "-C", str(env.cfg.clone), "tag", "--list", "v0.10.1"])
+ env.runner.add(["git", "-C", str(env.cfg.clone), "ls-remote", "origin", "refs/tags/v0.10.1",
+ "refs/tags/v0.10.1^{}"])
+ gh = GitHub(env.runner, env.cfg.repo_slug, env.cfg.clone)
+ n = env.pre(gh=gh)
+ assert (n.version, n.tag) == ("0.10.1", "v0.10.1") and cmd in env.runner.calls
+
+
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"
@@ -171,6 +212,23 @@ def test_an_unchanged_main_is_skipped(env):
assert env.state_path.exists() and ns.load_state(env.state_path).last_run_day == "2026-10-28"
[email protected]("tag", ["v0.3.1-nightly.20261027", "v0.3.2", "unrelated"])
+def test_skip_uses_the_saved_sha_before_looking_up_a_version(env, tag):
+ gh = FakeGH()
+ st = ns.State(last_published=ns.Published(tag, SHA, "0.3.2", {}, None))
+ ns.save_state(env.state_path, st)
+ with pytest.raises(ns.Skipped):
+ env.pre(ns.load_state(env.state_path), gh)
+ assert gh.calls == []
+
+
+def test_changed_sha_builds_even_when_the_saved_tag_matches(env):
+ gh = FakeGH()
+ st = ns.State(last_published=ns.Published(TAG, OLD, "0.3.2", {}, None))
+ assert env.pre(st, gh).sha == SHA
+ assert gh.calls == [("next_version",), ("release_state", TAG), ("ensure_tag_available", TAG)]
+
+
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"
@@ -225,6 +283,27 @@ def test_same_day_rerun_cleans_its_draft_and_refuses_a_published_tag(env):
assert e.value.gate == "tag-exists" and ("delete_draft", TAG) not in gh.calls
+def test_a_stranded_own_draft_is_cleaned_and_the_night_proceeds(env):
+ class Releases(FakeGH):
+ def next_version(self):
+ self.calls.append(("next_version",))
+ return ns.next_version([{"tag_name": "v0.3.1", "draft": False},
+ {"tag_name": TAG, "draft": True}])
+ gh, st = Releases("draft"), ns.State(open_draft=TAG)
+ assert env.pre(st, gh).tag == TAG
+ assert gh.calls == [("next_version",), ("release_state", TAG), ("delete_draft", TAG),
+ ("ensure_tag_available", TAG)]
+ assert st.open_draft is None
+
+
+def test_a_foreign_draft_with_the_next_tag_refuses_without_deletion(env):
+ gh, st = FakeGH("draft"), ns.State(open_draft="v0.3.0")
+ with pytest.raises(ns.Refused) as e:
+ env.pre(st, gh)
+ assert e.value.gate == "tag-exists" and "delete_draft" not in gh.names()
+ assert st.open_draft == "v0.3.0"
+
+
def test_a_missing_tool_is_refused_and_recorded(env):
def gone(cmd):
raise FileNotFoundError("gh")
@@ -296,7 +375,9 @@ def test_no_publish_never_retries_the_site(env, monkeypatch):
def test_no_publish_leaves_its_own_draft_alone(env):
gh = FakeGH("draft")
st = ns.State(open_draft=TAG)
- env.pre(st, gh, no_publish=True)
+ with pytest.raises(ns.Refused) as e:
+ env.pre(st, gh, no_publish=True)
+ assert e.value.gate == "tag-exists"
assert ("delete_draft", TAG) not in gh.calls and st.open_draft == TAG
@@ -617,7 +698,7 @@ def test_a_restore_only_failure_is_not_swallowed_inside_a_caller_except_block(ni
# --- the stamp, the two web builds and packaging ----------------------------------------------------------------
-STAMPED = "0.3.1-nightly.20261028"
+STAMPED = "0.3.2"
RESTORE_CMD = nightly.RESTORE_ARGV
@@ -1012,7 +1093,9 @@ def test_release_targets_the_preflight_commit(night, env, pub, served):
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"]
+ assert gh.names() == ["ensure_tag_available", "create_draft", "verify_draft", "latest_tag", "publish", "dispatch_site"]
+ assert gh.latest == TAG and "restore_latest" not in gh.names()
+ assert (night.run_dir / "latest-before-publish.txt").read_text() == "v0.3.1\n"
def test_the_first_night_fetches_the_release_tag_before_resolving_it(night, env):
@@ -1043,9 +1126,8 @@ def test_the_notes_log_runs_from_the_previous_commit_or_tag(night, env, pub, ser
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")})
+def test_a_failed_draft_check_deletes_the_draft_and_refuses(night, env, pub, served):
+ gh = FakeGH(fail={"verify_draft": 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)
@@ -1054,6 +1136,40 @@ def test_a_failed_draft_check_deletes_the_draft_and_refuses(night, env, pub, ser
assert st.open_draft is None and st.last_published.sha == OLD and served == []
[email protected]("open_draft", [None, TAG, "v0.3.0"])
+def test_a_release_made_after_preflight_refuses_before_create_and_is_never_deleted(night, env, pub, served, open_draft):
+ gh = FakeGH("draft")
+ st = ns.State(last_published=last_published(), open_draft=open_draft)
+ with pytest.raises(ns.Refused) as e:
+ publish(night, st, gh, pub, env)
+ assert e.value.gate == "tag-exists"
+ assert gh.names() == ["ensure_tag_available"] and gh.release == "draft"
+ assert st.open_draft == open_draft and st.last_published.sha == OLD
+
+
+def test_a_create_that_fails_after_leaving_a_draft_cleans_that_draft(night, env, pub, served):
+ class HalfMade(FakeGH):
+ def create_draft(self, tag, sha, notes, assets):
+ self.calls.append(("create_draft", tag, sha, notes, list(assets)))
+ self.release = "draft" # gh made the release, then an asset upload failed
+ raise ns.Refused("github-draft", "upload timed out")
+ gh = HalfMade()
+ st = ns.State(last_published=last_published())
+ with pytest.raises(ns.Refused, match="upload timed out"):
+ publish(night, st, gh, pub, env)
+ assert [c for c in gh.calls if c[0] == "delete_draft"] == [("delete_draft", TAG)]
+ assert gh.release is None and st.open_draft is None and st.last_published.sha == OLD
+
+
+def test_rollback_after_create_deletes_only_the_created_tag(night, env, pub, served):
+ gh = FakeGH(fail={"verify_draft": ns.Refused("github-draft", "hash differs")})
+ st = ns.State(open_draft="v0.3.0", last_published=last_published())
+ with pytest.raises(ns.Refused):
+ publish(night, st, gh, pub, env)
+ assert [c for c in gh.calls if c[0] == "delete_draft"] == [("delete_draft", TAG)]
+ assert st.open_draft is None
+
+
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:
@@ -1083,13 +1199,46 @@ def test_a_failed_publish_check_on_a_public_release_is_never_deleted(night, env,
class Public(FakeGH):
def publish(self, tag, sha):
self.release = "published"
- raise ns.Refused("github-publish", f"{tag} became the Latest release")
+ self.latest = tag
+ raise ns.Refused("github-publish", f"{tag} points at the wrong commit")
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
+ assert gh.latest == "v0.3.1" and ("restore_latest", "v0.3.1", TAG) in gh.calls
+ assert "restored previous Latest v0.3.1" in e.value.detail
+ assert "v0.3.1" in (night.run_dir / "latest-rollback.log").read_text()
+
+
+def test_with_no_latest_at_all_the_recovery_reports_it_left_latest_alone(night, env, pub, served):
+ class NoLatest(FakeGH):
+ def publish(self, tag, sha): # the edit never reached GitHub, and the repository has no Latest
+ self.calls.append(("publish", tag, sha))
+ raise ns.Refused("github-publish", "gh release edit failed")
+ gh = NoLatest()
+ gh.latest = None
+ with pytest.raises(ns.Refused) as e:
+ publish(night, ns.State(last_published=last_published()), gh, pub, env)
+ assert ("restore_latest", None, TAG) in gh.calls and gh.latest is None
+ assert "there is no Latest now" in e.value.detail and "left alone" in e.value.detail
+ assert "restored" not in e.value.detail and "removed the failed release's Latest mark" not in e.value.detail
+
+
+def test_a_newer_latest_published_meanwhile_is_never_overwritten_by_the_recovery(night, env, pub, served):
+ err = ns.Refused("site", "run failed")
+ gh = FakeGH(fail={"dispatch_site": [err, err]})
+ real_dispatch = gh.dispatch_site
+
+ def dispatch(deadline):
+ gh.latest = "v0.4.0" # the owner publishes a release while the site deploy runs
+ real_dispatch(deadline)
+ gh.dispatch_site = dispatch
+ with pytest.raises(ns.Refused) as e:
+ publish(night, ns.State(last_published=last_published()), gh, pub, env)
+ assert e.value.gate == "site" and gh.latest == "v0.4.0"
+ assert "Latest is now v0.4.0, not " + TAG + ": left alone" in e.value.detail
def test_a_site_failure_after_publish_retries_once_then_refuses_and_marks_site_pending(night, env, pub, served):
@@ -1102,6 +1251,76 @@ def test_a_site_failure_after_publish_retries_once_then_refuses_and_marks_site_p
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
+ assert gh.latest == "v0.3.1" and ("restore_latest", "v0.3.1", TAG) in gh.calls
+ assert "restored previous Latest v0.3.1" in e.value.detail
+
+
+def test_a_site_refusal_records_the_restored_latest_in_the_nightly_log(env, pub, served, monkeypatch):
+ err = ns.Refused("site", "run failed")
+ gh = FakeGH(fail={"dispatch_site": [err, err]})
+ def stages(night, state, runner, client, itch, **kw):
+ night.run_dir.mkdir(parents=True, exist_ok=True)
+ publish(night, state, client, pub, env, save=kw["save"])
+ monkeypatch.setattr(nightly, "run_stages", stages)
+ assert env.night(ns.State(last_published=last_published()), gh) == "REFUSED"
+ assert "REFUSED" in env.log() and "restored previous Latest v0.3.1" in env.log()
+
+
+def test_no_previous_latest_is_explicit_in_the_refusal_and_log(night, env, pub, served):
+ gh = FakeGH(fail={"publish": ns.Refused("github-publish", "wrong commit")})
+ gh.latest = None
+ with pytest.raises(ns.Refused) as e:
+ publish(night, ns.State(), gh, pub, env)
+ assert ("restore_latest", None, TAG) in gh.calls and gh.latest is None
+ assert "no previous Latest" in e.value.detail
+ assert "no previous Latest" in (night.run_dir / "latest-rollback.log").read_text()
+
+
+def test_a_latest_recovery_failure_names_the_previous_latest(night, env, pub, served):
+ gh = FakeGH(fail={"publish": ns.Refused("github-publish", "wrong commit"),
+ "restore_latest": OSError("offline")})
+ with pytest.raises(ns.Refused) as e:
+ publish(night, ns.State(), gh, pub, env)
+ assert "wrong commit" in e.value.detail and "Latest recovery failed (previous Latest v0.3.1)" in e.value.detail
+ assert "offline" in (night.run_dir / "latest-rollback.log").read_text()
+
+
+def test_an_interrupt_after_publish_restores_latest_and_records_the_result(night, env, pub, served):
+ gh = FakeGH(fail={"dispatch_site": KeyboardInterrupt()})
+ with pytest.raises(KeyboardInterrupt):
+ publish(night, ns.State(), gh, pub, env)
+ assert gh.latest == "v0.3.1" and "delete_draft" not in gh.names()
+ assert any("restored previous Latest v0.3.1" in note for note in night.notes)
+
+
+def test_a_failed_latest_lookup_refuses_before_the_public_edit(night, env, pub, served):
+ gh = FakeGH(fail={"latest_tag": ns.Refused("github-latest", "offline")})
+ with pytest.raises(ns.Refused, match="offline"):
+ publish(night, ns.State(), gh, pub, env)
+ assert "publish" not in gh.names() and "restore_latest" not in gh.names()
+ assert ("delete_draft", TAG) in gh.calls
+
+
+def test_a_failed_save_after_publish_restores_latest(night, env, pub, served):
+ gh = FakeGH()
+ saves = []
+ def save():
+ saves.append(True)
+ if len(saves) == 2: # the save right after publish; _try_save swallows only OSError, so this one escapes
+ raise TypeError("Object of type Path is not JSON serializable")
+ with pytest.raises(ns.Refused, match="restored previous Latest v0.3.1"):
+ publish(night, ns.State(), gh, pub, env, save=save)
+ assert gh.latest == "v0.3.1" and "delete_draft" not in gh.names()
+
+
+def test_a_disk_error_saving_state_after_publish_keeps_the_good_release_latest(night, env, pub, served, tmp_path,
+ monkeypatch):
+ monkeypatch.setattr(nightly, "notify", lambda *a: None)
+ blocked = tmp_path / "state.json"
+ blocked.mkdir() # writing the state file fails with an OSError, which production's _try_save reports and absorbs
+ gh, st = FakeGH(), ns.State(last_published=last_published())
+ publish(night, st, gh, pub, env, save=lambda: nightly._try_save(blocked, st))
+ assert gh.latest == TAG and "restore_latest" not in gh.names() and st.last_published.tag == TAG
@pytest.mark.parametrize("how", ["incomplete-read", "key-error"])
@@ -1270,7 +1489,7 @@ def test_itch_disabled_is_logged_and_never_calls_the_client(night, env, pub, ser
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"]
+ assert gh.names() == ["ensure_tag_available", "create_draft", "verify_draft", "latest_tag", "publish", "dispatch_site"]
def test_itch_enabled_without_a_client_refuses_before_any_store_change(itch_night, env):
@@ -1281,9 +1500,9 @@ def test_itch_enabled_without_a_client_refuses_before_any_store_change(itch_nigh
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 gh.calls[3][:3] == ("download", PREV_TAG, "*-web.zip") # after the tag check, 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",
+ "ensure_tag_available", "create_draft", "verify_draft", "download", "itch.push", "itch.wait_live", "itch.matches", "latest_tag", "publish",
"dispatch_site"]
assert ("itch.push", "itch-push", version) in gh.calls and st.last_published.tag == TAG
night = itch_night[0]
@@ -1436,7 +1655,7 @@ 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 \
+ assert "publish_night" not in stages.names() and f"NO-PUBLISH: all gates passed for {TAG}\n" in \
capsys.readouterr().out
assert stages.gh.names() == ["previous_build_tag", "download"] # reads only
diff --git a/tools/tests/test_nightly_publish.py b/tools/tests/test_nightly_publish.py
index 51f31f92e..7eee94fb6 100644
--- a/tools/tests/test_nightly_publish.py
+++ b/tools/tests/test_nightly_publish.py
@@ -13,8 +13,8 @@ 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"
+TAG = "v0.3.2"
+VERSION = "0.3.2"
DEMO = "https://example.invalid/demo/"
NOTICES = ("LICENSE", "NOTICE", "THIRD-PARTY-NOTICES.md", "OFL-EBGaramond.txt", "OFL-FrankRuhlLibre.txt")
@@ -65,7 +65,7 @@ def zips(tmp_path):
make_zip(tmp_path / f"statecraft-israel-v{VERSION}-web-pages.zip", extra=b"pages")]
-def view_json(*, draft=True, pre=True, names=()):
+def view_json(*, draft=True, pre=False, names=()):
return json.dumps({"isDraft": draft, "isPrerelease": pre, "assets": [{"name": n} for n in names]})
@@ -99,11 +99,63 @@ def test_release_state_refuses_on_any_other_error_or_garbage(gh, runner):
# --- create, verify, publish, delete --------------------------------------------------------------------------------
-def test_the_draft_is_a_prerelease_never_latest_targeting_the_commit(gh, runner, tmp_path, zips):
+def test_next_version_reads_all_release_pages_through_the_runner(gh, runner):
+ cmd = ["gh", "api", f"repos/{SLUG}/releases?per_page=100", "--paginate", "--slurp"]
+ runner.on(cmd, json.dumps([
+ [{"tag_name": "v0.9.9", "draft": False}, {"tag_name": "v99.0.0", "draft": True}],
+ [{"tag_name": "v0.10.0", "draft": False},
+ {"tag_name": "v99.0.0-nightly.20261028", "draft": False}],
+ ]))
+ assert gh.next_version() == "0.10.1"
+ assert runner.calls == [cmd]
+
+
[email protected]("answer", ["not json", "{}", "[{}]", "[[{}]]", "[]"])
+def test_next_version_refuses_unknown_release_data(gh, runner, answer):
+ runner.on(["gh", "api"], answer)
+ with pytest.raises(Refused) as e:
+ gh.next_version()
+ assert e.value.gate == "version"
+
+
[email protected]("release", ["draft", "published"])
+def test_existing_release_refuses_without_deletion_even_without_a_git_tag(gh, runner, release):
+ runner.on(["gh", "release", "view"], json.dumps({"isDraft": release == "draft"}))
+ with pytest.raises(Refused, match="already has the tag") as e:
+ gh.ensure_tag_available(TAG)
+ assert e.value.gate == "tag-exists"
+ assert len(runner.calls) == 1
+
+
[email protected]("local,remote", [(TAG + "\n", ""), ("", f"{SHA}\trefs/tags/{TAG}\n"),
+ ("", f"{SHA}\trefs/tags/{TAG}^{{}}\n"), ("", "")])
+def test_tag_collision_checks_local_and_remote_tags(gh, runner, tmp_path, local, remote):
+ runner.on(["gh", "release", "view"], not_found())
+ runner.on(["git", "-C", str(tmp_path), "tag", "--list", TAG], local)
+ runner.on(["git", "-C", str(tmp_path), "ls-remote", "origin", f"refs/tags/{TAG}",
+ f"refs/tags/{TAG}^{{}}"], remote)
+ if local or remote:
+ with pytest.raises(Refused, match="git tag.*already exists") as e:
+ gh.ensure_tag_available(TAG)
+ assert e.value.gate == "tag-exists"
+ else:
+ gh.ensure_tag_available(TAG)
+ assert not any(c[:3] in (["gh", "release", "delete"], ["gh", "release", "edit"]) for c in runner.calls)
+
+
+def test_tag_lookup_error_refuses_instead_of_assuming_absence(gh, runner):
+ runner.on(["gh", "release", "view"], not_found())
+ runner.on(["git", "-C"], Refused("command", "cannot read tags"))
+ with pytest.raises(Refused) as e:
+ gh.ensure_tag_available(TAG)
+ assert e.value.gate == "tag-exists"
+
+
+def test_the_draft_is_normal_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)",
+ assert runner.calls[-1] == ["gh", "release", "create", TAG, "--repo", SLUG, "--draft",
+ "--latest", "--target", SHA, "--title", f"{TAG} (nightly)",
"--notes-file", str(tmp_path / "notes.md"), str(zips[0]), str(zips[1])]
@@ -148,47 +200,99 @@ def test_verify_draft_refuses_a_zip_without_the_licence(gh, runner, zips, tmp_pa
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):
[email protected]("flags", [dict(draft=False), dict(pre=True), dict(draft="true"), dict(pre="false")])
+def test_verify_draft_refuses_wrong_flags_with_valid_matching_assets(gh, runner, zips, tmp_path, flags):
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])}]}}")
+ view = view_json(names=names, **flags)
+ 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" and "not a normal draft release" in e.value.detail
+ assert not any(c[:3] == ["gh", "release", "download"] for c in runner.calls)
+
+
[email protected]("view,why", [
+ (view_json(names=["only-one.zip"]), "the draft's assets are"),
+ ("{}", "not a normal draft release"),
+ ("[]", "JSON of the wrong shape"),
+ (json.dumps({"isDraft": True, "isPrerelease": False, "assets": {"name": "a"}}), "no usable asset list")])
+def test_verify_draft_refuses_a_wrong_state_or_asset_list(gh, runner, zips, tmp_path, view, why):
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"
+ assert e.value.gate == "github-draft" and why in e.value.detail # each case reaches its own guard
-def publish_script(runner, *, draft=False, pre=True, latest="v0.3.1", remote=SHA):
+def test_latest_tag_reads_through_the_runner_and_only_404_means_none(gh, runner):
+ cmd = ["gh", "api", f"repos/{SLUG}/releases/latest", "--jq", ".tag_name"]
+ runner.on(cmd, "v0.3.1\n", Refused("command", "HTTP 404: Not Found"),
+ Refused("command", "HTTP 403: Forbidden"))
+ assert gh.latest_tag() == "v0.3.1"
+ assert gh.latest_tag() is None
+ with pytest.raises(Refused) as e:
+ gh.latest_tag()
+ assert e.value.gate == "github-latest" and runner.calls == [cmd, cmd, cmd]
+
+
[email protected]("previous,observed", [("v0.3.1", "v0.3.1"), (None, "v0.2.0")])
+def test_restore_latest_edits_the_saved_tag_and_verifies_it(gh, runner, previous, observed):
+ cmd = ["gh", "release", "edit", previous if previous is not None else TAG, "--repo", SLUG,
+ "--latest" if previous is not None else "--latest=false"]
+ latest = ["gh", "api", f"repos/{SLUG}/releases/latest", "--jq", ".tag_name"]
+ runner.on(cmd, "")
+ runner.on(["gh", "api"], TAG + "\n", observed + "\n")
+ assert gh.restore_latest(previous, TAG) == (True, observed)
+ assert runner.calls == [latest, cmd, latest]
+
+
[email protected]("current", ["v0.4.0", "v0.3.1"])
+def test_restore_latest_leaves_a_latest_that_is_not_the_failed_release_alone(gh, runner, current):
+ runner.on(["gh", "api"], current + "\n")
+ assert gh.restore_latest("v0.3.1", TAG) == (False, current)
+ assert not any(c[:3] == ["gh", "release", "edit"] for c in runner.calls)
+
+
[email protected]("previous", ["v0.3.1", None])
+def test_restore_latest_refuses_if_the_failed_release_stays_latest(gh, runner, previous):
+ runner.on(["gh", "release", "edit"], "")
+ runner.on(["gh", "api"], TAG + "\n", TAG + "\n")
+ with pytest.raises(Refused, match="recovery did not take effect"):
+ gh.restore_latest(previous, TAG)
+
+
+def publish_script(runner, *, draft=False, pre=False, latest=TAG, 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):
+def test_publish_checks_draft_off_prerelease_off_latest_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 runner.calls[0] == ["gh", "release", "edit", TAG, "--repo", SLUG, "--draft=false", "--latest"]
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)
[email protected]("kw,why", [
+ (dict(draft=True), "is not a public normal release"),
+ (dict(pre=True), "is not a public normal release"),
+ (dict(latest="v0.3.1"), "is not the Latest release"),
+ (dict(remote=OTHER), f"points at {OTHER}, not at {SHA}"),
+ (dict(remote=""), f"points at None, not at {SHA}")])
+def test_publish_refuses_any_mismatch(gh, runner, kw, why):
+ publish_script(runner, **kw) # every other field valid, so each case reaches its own guard
with pytest.raises(Refused) as e:
gh.publish(TAG, SHA)
- assert e.value.gate == "github-publish"
+ assert e.value.gate == "github-publish" and why in e.value.detail
-def test_a_latest_nightly_is_named_as_such_and_needs_a_manual_fix(gh, runner):
- publish_script(runner, latest=TAG)
+def test_a_nightly_that_is_not_latest_is_refused(gh, runner):
+ publish_script(runner, latest="v0.3.1")
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
+ assert "is not the Latest release" in e.value.detail
def test_demo_serves_survives_a_broken_http_response():
@@ -199,7 +303,7 @@ def test_demo_serves_survives_a_broken_http_response():
calls.append(u)
if len(calls) == 1:
raise http.client.IncompleteRead(b"x")
- return io.BytesIO(b'productVersion: "0.3.1-nightly.20261028"')
+ return io.BytesIO(b'productVersion: "0.3.2"')
gp.demo_serves(DEMO, VERSION, deadline=100, fetch=fetch, sleep=lambda s: None,
now=iter(range(0, 1000, 30)).__next__)
assert len(calls) == 2
@@ -372,7 +476,7 @@ def test_a_failed_dispatch_is_a_site_refusal(gh, runner):
def test_demo_serves_polls_until_the_version_appears():
- pages = iter([b'productVersion: "0.3.1"', b'productVersion: "0.3.1-nightly.20261028"'])
+ pages = iter([b'productVersion: "0.3.1"', b'productVersion: "0.3.2"'])
urls = []
def fetch(u, timeout):
@@ -400,7 +504,8 @@ def test_demo_serves_refuses_at_the_deadline_and_survives_fetch_errors():
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 f"Automated nightly build of `main` at {SHA[:12]}." in text
+ assert "pre-release" not 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
diff --git a/tools/tests/test_nightly_state.py b/tools/tests/test_nightly_state.py
index fffc66976..fe075166d 100644
--- a/tools/tests/test_nightly_state.py
+++ b/tools/tests/test_nightly_state.py
@@ -12,11 +12,38 @@ 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"')
+ assert ns.next_version([{"tag_name": "v0.3.1", "draft": False}]) == "0.3.2"
+ assert ns.tag_for("0.3.2") == "v0.3.2"
+
+
[email protected]("tags,expected", [
+ (["v0.3.9", "v0.3.1"], "0.3.10"),
+ (["v0.9.9", "v0.10.0"], "0.10.1"),
+ (["v0.03.1"], "0.3.2"),
+ (["v0.03.1", "v0.3.1"], "0.3.2"),
+ (["v0.3.1", "v0.03.1"], "0.3.2"),
+ (["v9.99.99", "v10.12.19"], "10.12.20"),
+ (["v0.3.1", "v99.0.0-nightly.20261028", "0.9.9", "v1.2.3-extra", "v9.9.9\n"], "0.3.2"),
+])
+def test_next_version_compares_only_exact_release_tags_numerically(tags, expected):
+ rows = [{"tag_name": tag, "draft": False} for tag in tags]
+ rows.append({"tag_name": "v99.99.99", "draft": True})
+ assert ns.next_version(rows) == expected
+
+
[email protected]("rows", [[], [{"tag_name": "v0.3.1-nightly.20261028", "draft": False}],
+ [{"tag_name": "v0.3.1", "draft": True}]])
+def test_next_version_refuses_without_a_published_exact_tag(rows):
+ with pytest.raises(ns.Refused, match="no published vX.Y.Z release"):
+ ns.next_version(rows)
+
+
[email protected]("row", [{}, {"draft": False}, {"tag_name": 3, "draft": False},
+ {"tag_name": "v0.3.1", "draft": "false"}, None])
+def test_next_version_refuses_malformed_release_rows(row):
+ with pytest.raises(ns.Refused) as e:
+ ns.next_version([row])
+ assert e.value.gate == "version"
def test_the_night_is_the_jerusalem_date():