A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Release and nightly tools fail closed on four more silent all-clears (Fixes #2644) (#2670)
Eyal Golanffbbce6012b8
diff --git a/scripts/oss/release_gate.sh b/scripts/oss/release_gate.shindex 20ecc0b92..c68b9b7d3 100755--- a/scripts/oss/release_gate.sh+++ b/scripts/oss/release_gate.sh@@ -10,7 +10,13 @@ step() { echo; echo "== $1"; }step "on main, clean tree"[ "$(git rev-parse --abbrev-ref HEAD)" = "main" ] || { echo "not on main"; fail=1; }-[ -z "$(git status --porcelain --untracked-files=no)" ] || { echo "tracked changes present"; fail=1; }+if ! status="$(git status --porcelain --untracked-files=no)"; then+ echo "git status failed: cannot prove the tracked tree is clean"+ fail=1+elif [ -n "$status" ]; then+ echo "tracked changes present"+ fail=1+fistep "tip policy, release mode (open decisions D1-D12, owner-verify and unknown-licence rows refuse)"uv run scripts/oss/check_repo.py --release || fail=1@@ -28,7 +34,10 @@ step "tools tests"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 || fail=1step "history scan of main (information; rows in docs/oss/history-accepted.tsv are accepted)"-uv run scripts/oss/scan_history.py --ref main | tee "$scan_out"+if ! uv run scripts/oss/scan_history.py --ref main | tee "$scan_out"; then+ echo "HISTORY SCAN FAILED: cannot prove the history scan is complete"+ fail=1+fiif ! grep -q ' 0 open secret-shape findings' "$scan_out"; thenecho "OPEN SECRET-SHAPE FINDING: rotate it at its provider (owner), then add the row to docs/oss/history-accepted.tsv"fail=1diff --git a/scripts/oss/scan_history.py b/scripts/oss/scan_history.pyindex ad5d3a6b5..ab2f48a80 100644--- a/scripts/oss/scan_history.py+++ b/scripts/oss/scan_history.py@@ -6,7 +6,8 @@against each parent), plus every commit message and author/committer email, for secret shapes, personal emails andhome paths (the patterns in oss_policy.py). Prints commit, file and pattern type, NEVER the matched text.-Information only (owner ruling 2026-10-11: no history rewriting, no history enforcement), so the exit code is always 0.+Findings are information only (owner ruling 2026-10-11: no history rewriting, no history enforcement) and do not change+the exit code. A command failure is non-zero because the scan is incomplete.Rows already handled are listed in docs/oss/history-accepted.tsv (commit, path, kind, action, date) and are shown as"accepted", so a rotated key or a reviewed false positive never blocks anything twice. A real secret is fixed byrevoking or rotating it at its provider; history is never rewritten.@@ -47,7 +48,9 @@ def scan(repo: Path, refs: list[str]) -> list[tuple[str, str, str]]:path = line[6:] if line.startswith("+++ b/") else ""elif line.startswith("+") and path:hits.update((commit, path, k) for k in _kinds(line[1:]))- proc.wait()+ code = proc.wait()+ if code != 0:+ raise subprocess.CalledProcessError(code, cmd)meta = subprocess.run(["git", "-C", str(repo), "log", *refs, "--format=%H%x00%ae%x00%ce%x00%B%x1e"],capture_output=True, check=True).stdout.decode("utf-8", "replace")for rec in meta.split("\x1e"):@@ -80,7 +83,11 @@ def main(argv: list[str] | None = None) -> int:ap.add_argument("--all", action="store_true")args = ap.parse_args(argv)refs = [args.ref] if args.ref and not args.all else ["--all"]- hits = scan(args.repo, refs)+ try:+ hits = scan(args.repo, refs)+ except subprocess.CalledProcessError as e:+ print(f"HISTORY SCAN FAILED: git log exited {e.returncode}; the history scan is incomplete", file=sys.stderr)+ return 1done = accepted(args.repo)open_secrets = 0for commit, path, kind in hits:diff --git a/scripts/oss/tests/test_release.py b/scripts/oss/tests/test_release.pyindex 49a41c509..81d7c4c4c 100644--- a/scripts/oss/tests/test_release.py+++ b/scripts/oss/tests/test_release.py@@ -76,6 +76,51 @@ def test_release_gate_uses_a_temp_file_not_a_fixed_path():assert "mktemp" in text and "/tmp/oss-release-scan.txt" not in text+def release_gate_with_fakes(tmp_path, *, status_code=0, scan_code=0):+ bindir = tmp_path / "bin"+ bindir.mkdir()+ commands = {+ "git": """#!/bin/sh+if [ "$1" = "rev-parse" ]; then echo main; exit 0; fi+if [ "$1" = "status" ]; then exit "${FAKE_STATUS_CODE:-0}"; fi+exit 0+""",+ "uv": """#!/bin/sh+case "$*" in+ *scan_history.py*)+ echo "scanned 1 commits (main): no findings, 0 open secret-shape findings"+ exit "${FAKE_SCAN_CODE:-0}"+ ;;+esac+exit 0+""",+ "dotnet": "#!/bin/sh\nexit 0\n",+ }+ for name, source in commands.items():+ command = bindir / name+ command.write_text(source)+ command.chmod(0o755)+ env = dict(os.environ, PATH=f"{bindir}:{os.environ['PATH']}", FAKE_STATUS_CODE=str(status_code),+ FAKE_SCAN_CODE=str(scan_code))+ return subprocess.run(["bash", str(ROOT / "scripts/oss/release_gate.sh")], cwd=ROOT,+ capture_output=True, text=True, env=env)+++def test_release_gate_refuses_when_git_status_fails(tmp_path):+ r = release_gate_with_fakes(tmp_path, status_code=2)+ assert r.returncode == 1+ assert "git status failed: cannot prove the tracked tree is clean" in r.stdout+ assert "RELEASE GATE FAILED" in r.stdout and "RELEASE GATE OK" not in r.stdout+++def test_release_gate_refuses_when_history_scan_fails_after_an_all_clear_line(tmp_path):+ r = release_gate_with_fakes(tmp_path, scan_code=3)+ assert r.returncode == 1+ assert "0 open secret-shape findings" in r.stdout+ assert "HISTORY SCAN FAILED: cannot prove the history scan is complete" in r.stdout+ assert "RELEASE GATE FAILED" in r.stdout and "RELEASE GATE OK" not in r.stdout++def test_the_release_web_build_is_gzip_end_to_end():"""Owner decision on #879 (17 Oct 2026, "gzip for both"): one gzip zip for GitHub Releases and itch.io. itch.io'sCDN passes a Brotli `.data` to the player uncompressed but keeps a gzip `.data` compressed. The release recipe indiff --git a/scripts/oss/tests/test_scan_history.py b/scripts/oss/tests/test_scan_history.pyindex 9cb31e77c..cd7b231bf 100644--- a/scripts/oss/tests/test_scan_history.py+++ b/scripts/oss/tests/test_scan_history.py@@ -1,5 +1,7 @@import subprocess+import pytest+import scan_historyfrom conftest import commit_all, git@@ -80,3 +82,25 @@ def test_ref_and_all_flags_parse(tmp_path, capsys):assert scan_history.main(["--repo", str(root), "--ref", "main"]) == 0assert scan_history.main(["--repo", str(root), "--all"]) == 0assert "no findings" in capsys.readouterr().out+++class FailedLog:+ stdout = [b"COMMIT 0123456789abcdef\n", b"+++ b/partial.txt\n", b"+partial history\n"]++ def wait(self):+ return 128+++def test_a_failed_streaming_git_log_refuses_partial_results(tmp_path, monkeypatch):+ monkeypatch.setattr(scan_history.subprocess, "Popen", lambda *a, **k: FailedLog())+ with pytest.raises(subprocess.CalledProcessError) as e:+ scan_history.scan(tmp_path, ["main"])+ assert e.value.returncode == 128 and e.value.cmd[:4] == ["git", "-C", str(tmp_path), "log"]+++def test_the_cli_clearly_refuses_a_failed_streaming_git_log(tmp_path, monkeypatch, capsys):+ monkeypatch.setattr(scan_history.subprocess, "Popen", lambda *a, **k: FailedLog())+ assert scan_history.main(["--repo", str(tmp_path), "--ref", "main"]) == 1+ captured = capsys.readouterr()+ assert "HISTORY SCAN FAILED" in captured.err and "incomplete" in captured.err+ assert "scanned" not in captured.out and "open secret-shape findings" not in captured.outdiff --git a/tools/nightly.py b/tools/nightly.pyindex 2883d9d51..8e2ceef08 100644--- a/tools/nightly.py+++ b/tools/nightly.py@@ -1103,16 +1103,18 @@ def savetest(cfg: Config, config_path: Path, job: Path, runner: Runner, gh: GitHwork = Path(job) / "savetest" / stampevidence: dict = {"tag": tag, "target": cfg.savetest_itch_target}result, detail = "INCONCLUSIVE", ""- with savetest_lock(Path(job)) as held:- if not held:- detail = "another save test is running on this job (savetest.lock); nothing was pushed"- else:- try:+ try:+ with savetest_lock(Path(job)) as held:+ if not held:+ detail = "another save test is running on this job (savetest.lock); nothing was pushed"+ else: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}"+ except Stop as e:+ result = "INCONCLUSIVE"+ detail = f"{e.gate}: {e.detail}"+ except (OSError, SystemExit) as e: # find_chrome exits when there is no Chrome+ result = "INCONCLUSIVE"+ detail = f"{type(e).__name__}: {e}"try:evidence.update(result=result, detail=detail)if work.is_dir():@@ -1308,20 +1310,46 @@ def main(argv: list[str] | None = None) -> int: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, no_steam=args.no_steam)+ # #2644: run_lock raises Refused on a lock-system failure (not contention). Before the operation starts that is+ # a recorded REFUSED night; after it records its own result, a teardown failure is only an stderr note.+ operation_finished = False+ savetest_code: int | None = None+ outcome: str | None = None+ try:+ 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":+ savetest_code = run_savetest(cfg, job, args.tag)+ else:+ 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,+ no_steam=args.no_steam)+ operation_finished = True+ except Refused as e:+ if operation_finished:+ print(f"{e}; the completed operation's existing record is unchanged", file=sys.stderr)+ if savetest_code is not None:+ return savetest_code+ assert outcome is not None+ print(outcome)+ return 1 if outcome == "REFUSED" else 0+ if not getattr(args, "no_publish", False): # a by-hand --no-publish run writes no record (tools/README.md)+ line = log_line(now, "REFUSED", tag=None, sha=None, gate=e.gate, log=None)+ record(job / "LOG.md", cfg.handoff, f"{line} {e.detail}")+ notify("Nightly refused", str(e)[:200])+ print(e, file=sys.stderr)+ return 1+ if savetest_code is not None:+ return savetest_code+ assert outcome is not Noneprint(outcome)return 1 if outcome == "REFUSED" else 0diff --git a/tools/nightly_launch.py b/tools/nightly_launch.pyindex c0e5bb689..5b6c53b00 100644--- a/tools/nightly_launch.py+++ b/tools/nightly_launch.py@@ -69,7 +69,10 @@ def _refuse(cfg: Config, home: Path, e: Refused, now: datetime) -> None:evidence = Nonedetail = f"{detail}; could not write refusal log: {error}"line = log_line(now, "REFUSED", tag=None, sha=None, gate=e.gate, log=evidence)- record(home / "LOG.md", cfg.handoff, f"{line} {detail}")+ try:+ record(home / "LOG.md", cfg.handoff, f"{line} {detail}")+ except OSError as record_error:+ print(f"could not record refusal: {record_error}", file=sys.stderr)notify("Nightly refused", str(e)[:200])print(e, file=sys.stderr)@@ -82,21 +85,20 @@ def main(argv: list[str] | None = None, *, git: Callable[..., str] = _git,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:+ try:+ with run_lock(a.home) as held:+ if not held:+ print("nightly_launch: a run is in progress")+ return 0prepare_clone(cfg, git, copy)- except Refused as e:- _refuse(cfg, a.home, e, now)- return 1+ except Refused as e:+ _refuse(cfg, a.home, e, now)+ return 1try:return call([a.uv, "run", str(cfg.clone / "tools" / "nightly.py"), "run"])except OSError as e:diff --git a/tools/nightly_state.py b/tools/nightly_state.pyindex 0ae3bb222..43a657e5d 100644--- a/tools/nightly_state.py+++ b/tools/nightly_state.py@@ -16,6 +16,7 @@ import mathimport osimport reimport subprocess+import sysfrom dataclasses import asdict, dataclass, field, fieldsfrom datetime import date, datetime, time, timedeltafrom pathlib import Path@@ -356,25 +357,63 @@ def notify(title: str, message: str, run=None) -> None:@contextlib.contextmanagerdef _run_lock(job: Path, name: str = "run.lock") -> Iterator[bool]:import fcntl # POSIX only; imported here so the shared types load anywhere- job.mkdir(parents=True, exist_ok=True)- with (job / name).open("a") as fh:+ path = job / name+ try:+ job.mkdir(parents=True, exist_ok=True)+ except OSError as e:+ raise Refused("lock", f"cannot create lock directory {job}: {e}") from e+ try:+ fh = path.open("a")+ except OSError as e:+ raise Refused("lock", f"cannot open {path}: {e}") from e+ locked = False+ primary: BaseException | None = None+ try:try:fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)- except OSError:+ except BlockingIOError:yield Falsereturn+ except OSError as e:+ raise Refused("lock", f"cannot take {path}: {e}") from e+ locked = True+ yield True+ except BaseException as e:+ primary = e+ raise+ finally:+ teardown: list[Refused] = []+ if locked:+ try:+ fcntl.flock(fh, fcntl.LOCK_UN)+ except OSError as e:+ failure = Refused("lock", f"cannot release {path}: {e}")+ failure.__cause__ = e+ teardown.append(failure)try:- yield True- finally:- fcntl.flock(fh, fcntl.LOCK_UN)+ fh.close()+ except OSError as e:+ failure = Refused("lock", f"cannot close {path}: {e}")+ failure.__cause__ = e+ teardown.append(failure)+ if teardown:+ if primary is not None:+ for failure in teardown:+ print(f"{failure}; preserving {type(primary).__name__}: {primary}", file=sys.stderr)+ else:+ for failure in teardown[1:]:+ print(f"{failure}; preserving {teardown[0]}", file=sys.stderr)+ raise teardown[0]def run_lock(job: Path) -> ContextManager[bool]:- """Yields True when this process holds <job>/run.lock, False when another run already does."""+ """Yields True when this process holds <job>/run.lock, False only when another run already does.+ A lock-system failure raises Refused."""return _run_lock(job)def savetest_lock(job: Path) -> ContextManager[bool]:- """Yields True when this process holds <job>/savetest.lock, False when another save test already does: agents- may start the save test too (owner, 2 Nov 2026, "2 (a)"), and two runs must not push to the test page at once."""+ """Yields True when this process holds <job>/savetest.lock, False only when another save test already does.+ A lock-system failure raises Refused. Agents may start the save test too (owner, 2 Nov 2026, "2 (a)"), and two+ runs must not push to the test page at once."""return _run_lock(job, "savetest.lock")diff --git a/tools/package_release.py b/tools/package_release.pyindex eac200bbc..fdc870190 100644--- a/tools/package_release.py+++ b/tools/package_release.py@@ -14,8 +14,8 @@ sensitivity-reviewed (docs/event-images.md).Build.Web names the files under Build/ by their content hash (issue #437), so their names change from build to build andindex.html is what says which ones belong to this build. The zip carries exactly the Build/ files index.html names: it-is refused when one is missing, and a file it does not name (an earlier build's, left in the folder) is left out with a-"LEFT OUT Build/<name>" line.+is refused when it names none or when one is missing, and a file it does not name (an earlier build's, left in the+folder) is left out with a "LEFT OUT Build/<name>" line.The translations ship twice (#1618, step 2): as files in StreamingAssets/translations, which desktop players and the gateread, and as texts packed into StreamingAssets/content/bundle.json, which the web player reads. The zip is refused unless@@ -121,6 +121,9 @@ def package(build: Path, zip_path: Path) -> int:print(f"PACKAGE REFUSED: {build} has no StreamingAssets/content")return 1named = build_files(build)+ if not named:+ print("PACKAGE REFUSED: index.html names no Build/ files (not a usable WebGL build)")+ return 1if missing := [n for n in named if not (build / "Build" / n).is_file()]:print("PACKAGE REFUSED: index.html names files that are not in the build: " + ", ".join("Build/" + n for n in missing))return 1diff --git a/tools/tests/test_nightly.py b/tools/tests/test_nightly.pyindex 4e31cf399..55cd69a39 100644--- a/tools/tests/test_nightly.py+++ b/tools/tests/test_nightly.py@@ -14,7 +14,7 @@ from types import SimpleNamespaceimport pytest-pytest.importorskip("fcntl") # nightly imports unity_postmerge, which locks with flock+fcntl = pytest.importorskip("fcntl") # nightly imports unity_postmerge, which locks with flockimport nightlyimport nightly_state as ns@@ -2402,6 +2402,29 @@ def test_the_savetest_command_builds_its_itch_client_on_the_test_target(tmp_pathassert nightly.run_savetest(cfg, tmp_path, TAG) == 0 and built == [TEST_TARGET]+def test_a_broken_savetest_lock_is_recorded_inconclusive(tmp_path, monkeypatch, no_processes, capsys):+ butler = tmp_path / "butler"+ butler.write_text("")+ monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/" + name)+ stages = []+ monkeypatch.setattr(nightly, "_savetest", lambda *a, **k: stages.append((a, k)))++ @contextmanager+ def broken_lock(job):+ raise ns.Refused("lock", f"cannot take {job / 'savetest.lock'}: denied")+ yield True++ monkeypatch.setattr(nightly, "savetest_lock", broken_lock)+ cfg = dataclasses.replace(ns.Config(), butler=butler, handoff=tmp_path / "HANDOFF.md",+ itch_page_url="https://eyalgolan.itch.io/statecraft-israel",+ savetest_itch_target=TEST_TARGET)+ assert nightly.run_savetest(cfg, tmp_path, TAG) == 1 and stages == []+ assert "INCONCLUSIVE" in capsys.readouterr().out+ log = (tmp_path / "LOG.md").read_text()+ assert "SAVETEST INCONCLUSIVE" in log and "lock: cannot take" in log and "denied" in log+ assert "SAVETEST INCONCLUSIVE" in cfg.handoff.read_text()++def too_many_requests(retry_after=None):return http_error(frame_of(101), 429, retry_after)@@ -3284,3 +3307,86 @@ def test_the_steam_content_is_removed_after_the_stage(night, env):nightly.run_steam(night, env.runner)assert not (out / "steam").exists() and not list(out.glob("*.zip"))assert (out / "build-record.json").is_file()+++def test_a_run_lock_open_failure_in_main_is_a_recorded_refusal(tmp_path, monkeypatch, capsys):+ """#2644 review: a real run.lock open failure is recorded by nightly.main, not raised as a traceback."""+ job = tmp_path / "job"+ job.mkdir()+ (job / "run.lock").mkdir()+ monkeypatch.setattr(nightly, "JOB", job)+ monkeypatch.setattr(nightly, "load_config", lambda p: ns.Config(handoff=tmp_path / "HANDOFF.md"))+ monkeypatch.setattr(nightly, "notify", lambda *a, **k: None)+ assert nightly.main(["run"]) == 1+ assert "gate=lock" in (job / "LOG.md").read_text()+ assert "REFUSED" in (tmp_path / "HANDOFF.md").read_text()+ assert "cannot open" in capsys.readouterr().err+++def test_a_run_lock_open_failure_in_a_no_publish_run_writes_no_record(tmp_path, monkeypatch, capsys):+ """#2670 review: a by-hand --no-publish run writes nothing to LOG.md or the handoff, a lock failure included."""+ job = tmp_path / "job"+ job.mkdir()+ (job / "run.lock").mkdir()+ monkeypatch.setattr(nightly, "JOB", job)+ monkeypatch.setattr(nightly, "load_config", lambda p: ns.Config(handoff=tmp_path / "HANDOFF.md"))+ sent = []+ monkeypatch.setattr(nightly, "notify", lambda *a, **k: sent.append(a))+ assert nightly.main(["run", "--no-publish"]) == 1+ assert not (job / "LOG.md").exists() and not (tmp_path / "HANDOFF.md").exists() and not sent+ assert "cannot open" in capsys.readouterr().err+++def test_a_run_lock_release_failure_does_not_add_a_second_savetest_record(tmp_path, monkeypatch, capsys):+ job = tmp_path / "job"+ job.mkdir()+ butler = tmp_path / "butler"+ butler.write_text("")+ cfg = dataclasses.replace(ns.Config(), butler=butler, handoff=tmp_path / "HANDOFF.md",+ itch_page_url="https://eyalgolan.itch.io/statecraft-israel",+ savetest_itch_target=TEST_TARGET)+ monkeypatch.setattr(nightly, "JOB", job)+ monkeypatch.setattr(nightly, "load_config", lambda p: cfg)+ monkeypatch.setattr(nightly, "notify", lambda *a, **k: None)+ monkeypatch.setattr(nightly.shutil, "which", lambda name: "/usr/bin/" + name)+ monkeypatch.setattr(nightly, "_savetest", lambda *a, **k: ("PASS", "completed"))+ unlocks = 0++ def fail_outer_release(fh, operation):+ nonlocal unlocks+ if operation == fcntl.LOCK_UN:+ unlocks += 1+ if unlocks == 2:+ raise PermissionError("denied")++ monkeypatch.setattr(fcntl, "flock", fail_outer_release)+ assert nightly.main(["savetest", "--tag", TAG]) == 0+ log = (job / "LOG.md").read_text()+ assert log.count("SAVETEST PASS") == 1 and "REFUSED" not in log and "gate=lock" not in log+ assert (tmp_path / "HANDOFF.md").read_text().count("SAVETEST PASS") == 1+ err = capsys.readouterr().err+ assert "cannot release" in err and "existing record is unchanged" in err+++def test_a_run_lock_release_failure_does_not_replace_run_nights_record(tmp_path, monkeypatch, capsys):+ job = tmp_path / "job"+ job.mkdir()+ cfg = ns.Config(handoff=tmp_path / "HANDOFF.md")+ monkeypatch.setattr(nightly, "JOB", job)+ monkeypatch.setattr(nightly, "load_config", lambda p: cfg)+ monkeypatch.setattr(nightly, "notify", lambda *a, **k: None)+ monkeypatch.setattr(nightly, "_clients", lambda cfg: (_ for _ in ()).throw(ns.Refused("github-client", "offline")))+ calls = 0++ def fail_release(*args):+ nonlocal calls+ calls += 1+ if calls == 2:+ raise PermissionError("denied")++ monkeypatch.setattr(fcntl, "flock", fail_release)+ assert nightly.main(["run"]) == 1+ log = (job / "LOG.md").read_text()+ assert log.count("REFUSED") == 1 and "gate=github-client" in log and "gate=lock" not in log+ err = capsys.readouterr().err+ assert "cannot release" in err and "existing record is unchanged" in errdiff --git a/tools/tests/test_nightly_launch.py b/tools/tests/test_nightly_launch.pyindex ff92e3d9d..f5e9f041e 100644--- a/tools/tests/test_nightly_launch.py+++ b/tools/tests/test_nightly_launch.py@@ -6,7 +6,7 @@ from pathlib import Pathimport 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")+fcntl = pytest.importorskip("fcntl", reason="fcntl is POSIX-only (nightly_state uses flock); not on Windows")import nightly_launch as nl # noqa: E402import nightly_state as ns # noqa: E402@@ -166,6 +166,54 @@ def test_a_run_in_progress_exits_0_and_touches_nothing(tmp_path, capsys):assert not (home / "LOG.md").exists()+def test_a_run_lock_open_failure_is_recorded_as_refused(tmp_path, monkeypatch, capsys):+ home = tmp_path / "job"+ cfg = cfg_for(tmp_path)+ write_config(home, cfg)+ (home / "run.lock").mkdir()+ 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 == []+ assert "REFUSED" in (home / "LOG.md").read_text() and "gate=lock" in (home / "LOG.md").read_text()+ assert "gate=lock" in cfg.handoff.read_text()+ err = capsys.readouterr().err+ assert "lock:" in err and "cannot open" in err and str(home / "run.lock") in err+++def test_a_clone_refusal_survives_a_run_lock_release_failure(tmp_path, monkeypatch, capsys):+ home = tmp_path / "job"+ cfg = cfg_for(tmp_path, clone=False)+ write_config(home, cfg)+ monkeypatch.setattr(nl, "notify", lambda *a, **k: None)+ calls = 0++ def fail_release(*args):+ nonlocal calls+ calls += 1+ if calls == 2:+ raise PermissionError("unlock denied")++ monkeypatch.setattr(fcntl, "flock", fail_release)+ assert nl.main(["--uv", "/opt/uv", "--home", str(home)], now=NOW) == 1+ log = (home / "LOG.md").read_text()+ assert log.count("REFUSED") == 1 and "gate=clone" in log and "gate=lock" not in log+ err = capsys.readouterr().err+ assert "cannot release" in err and "preserving Refused: clone:" in err+++def test_a_job_directory_setup_failure_is_a_refusal_not_a_traceback(tmp_path, monkeypatch, capsys):+ parent = tmp_path / "not-a-directory"+ parent.write_text("file")+ home = parent / "job"+ monkeypatch.setattr(nl, "notify", lambda *a, **k: None)+ assert nl.main(["--uv", "/opt/uv", "--home", str(home)], now=NOW) == 1+ err = capsys.readouterr().err+ assert "lock: cannot create lock directory" in err and str(home) in err+ assert "could not record refusal" in err++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)diff --git a/tools/tests/test_nightly_state.py b/tools/tests/test_nightly_state.pyindex d5768630b..915e7de05 100644--- a/tools/tests/test_nightly_state.py+++ b/tools/tests/test_nightly_state.py@@ -146,6 +146,80 @@ def test_the_run_lock_is_exclusive(tmp_path):assert again is True+def test_lock_contention_is_the_only_lock_failure_reported_as_held(tmp_path, monkeypatch):+ monkeypatch.setattr(fcntl, "flock", lambda *a: (_ for _ in ()).throw(BlockingIOError("held")))+ with ns.run_lock(tmp_path) as held:+ assert held is False+++def test_a_lock_system_failure_is_refused(tmp_path, monkeypatch):+ monkeypatch.setattr(fcntl, "flock", lambda *a: (_ for _ in ()).throw(PermissionError("denied")))+ with pytest.raises(ns.Refused) as e:+ with ns.savetest_lock(tmp_path):+ pass+ assert e.value.gate == "lock" and str(tmp_path / "savetest.lock") in e.value.detail and "denied" in e.value.detail+++def test_a_lock_directory_failure_is_refused(tmp_path):+ parent = tmp_path / "not-a-directory"+ parent.write_text("file")+ with pytest.raises(ns.Refused) as e:+ with ns.run_lock(parent / "job"):+ pass+ assert e.value.gate == "lock" and str(parent / "job") in e.value.detail+ assert isinstance(e.value.__cause__, OSError)+++def test_a_lock_release_failure_is_refused(tmp_path, monkeypatch):+ calls = 0++ def fail_release(*args):+ nonlocal calls+ calls += 1+ if calls == 2:+ raise PermissionError("denied")++ monkeypatch.setattr(fcntl, "flock", fail_release)+ with pytest.raises(ns.Refused) as e:+ with ns.run_lock(tmp_path) as held:+ assert held is True+ assert e.value.gate == "lock" and "cannot release" in e.value.detail and "denied" in e.value.detail+ assert isinstance(e.value.__cause__, PermissionError)+++def test_a_lock_release_failure_does_not_replace_the_protected_exception(tmp_path, monkeypatch, capsys):+ calls = 0++ def fail_release(*args):+ nonlocal calls+ calls += 1+ if calls == 2:+ raise PermissionError("unlock denied")++ monkeypatch.setattr(fcntl, "flock", fail_release)+ original = RuntimeError("clone failed")+ with pytest.raises(RuntimeError) as e:+ with ns.run_lock(tmp_path):+ raise original+ assert e.value is original+ err = capsys.readouterr().err+ assert "cannot release" in err and "preserving RuntimeError: clone failed" in err+++def test_a_lock_file_close_failure_is_refused(tmp_path, monkeypatch):+ class CannotClose:+ def close(self):+ raise OSError("close denied")++ monkeypatch.setattr(Path, "open", lambda *a, **k: CannotClose())+ monkeypatch.setattr(fcntl, "flock", lambda *a: None)+ with pytest.raises(ns.Refused) as e:+ with ns.run_lock(tmp_path) as held:+ assert held is True+ assert e.value.gate == "lock" and "cannot close" in e.value.detail and "close denied" in e.value.detail+ assert isinstance(e.value.__cause__, OSError)++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")diff --git a/tools/tests/test_package_release.py b/tools/tests/test_package_release.pyindex 9e46201e5..fc38d4f65 100644--- a/tools/tests/test_package_release.py+++ b/tools/tests/test_package_release.py@@ -6,6 +6,8 @@ import shutilimport zipfilefrom pathlib import Path+import pytest+import package_releaseREPO = Path(package_release.REPO)@@ -28,7 +30,9 @@ def fake_build(tmp_path, reviewed, photos_reviewed=True, forces_checked=True, alalternates_reviewed: TEST-ONLY fictional review of the two #939 copies. No real content file is changed."""build = tmp_path / "Web-brotli"(build / "StreamingAssets").mkdir(parents=True)- (build / "index.html").write_text("<html></html>")+ (build / "Build").mkdir()+ (build / "Build/game.loader.js").write_bytes(b"\x00")+ (build / "index.html").write_text('<script src="Build/game.loader.js"></script>')content = build / "StreamingAssets" / "content"shutil.copytree(REPO / "content", content)status = "sensitivity-reviewed" if reviewed else "fact-checked" # the owner's sign-off (D11), or its absence@@ -163,7 +167,7 @@ def hashed_build(tmp_path):f'<html><script src="Build/{loader}"></script><script>var config = {{\n dataUrl: "Build/{data}",\n'f' frameworkUrl: "Build/{framework}",\n codeUrl: "Build/{code}",\n streamingAssetsUrl: "StreamingAssets",\n}};'"</script></html>")- (build / "Build").mkdir()+ (build / "Build").mkdir(exist_ok=True)for name in HASHED:(build / "Build" / name).write_bytes(b"\x00")return build@@ -171,7 +175,14 @@ def hashed_build(tmp_path):def test_the_build_files_are_read_from_index_html(tmp_path):assert package_release.build_files(hashed_build(tmp_path)) == sorted(HASHED)- assert package_release.build_files(fake_build(tmp_path / "plain", reviewed=True)) == []+ assert package_release.build_files(fake_build(tmp_path / "plain", reviewed=True)) == ["game.loader.js"]++[email protected]("page", ["<html></html>", "<script src='Build/game.loader.js'></script>"])+def test_a_build_whose_index_names_no_recognised_build_file_is_refused(tmp_path, capsys, page):+ build = fake_build(tmp_path, reviewed=True)+ (build / "index.html").write_text(page)+ assert "index.html names no Build/ files" in refused(build, tmp_path, capsys)def test_the_zip_carries_the_hashed_files_index_html_names(tmp_path, capsys):