A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Tools: read YAML by the 1.2 core schema (tools/yaml12.py), not PyYAML's 1.1 (refs #601) (#606)
Eyal Golanb541fbea0b8d
diff --git a/.github/skills/statecraft-historical-content/scripts/check_source_coverage.py b/.github/skills/statecraft-historical-content/scripts/check_source_coverage.pyindex fb5d93a53..93bf8e678 100644--- a/.github/skills/statecraft-historical-content/scripts/check_source_coverage.py+++ b/.github/skills/statecraft-historical-content/scripts/check_source_coverage.py@@ -18,6 +18,8 @@ except Exception as exc: # pragma: no coverraise SystemExit(1)ROOT = Path(__file__).resolve().parents[4]+sys.path.insert(0, str(ROOT / "tools"))+import yaml12 # noqa: E402 (tools/yaml12.py: YAML 1.2, no 1.1 coercions)EVENTS = ROOT / "content" / "events"@@ -30,7 +32,7 @@ def main() -> int:for path in sorted(EVENTS.glob("*.yaml")):with path.open("r", encoding="utf-8") as fh:try:- data = yaml.safe_load(fh) or {}+ data = yaml12.load(fh.read()) or {}except Exception as exc: # pragma: no coverproblems.append(f"{path.name}: YAML parse error ({exc})")continuediff --git a/scripts/event_timeline.py b/scripts/event_timeline.pyindex 853474be9..fd85ca74d 100644--- a/scripts/event_timeline.py+++ b/scripts/event_timeline.py@@ -11,7 +11,8 @@ import argparseimport sysfrom pathlib import Path-import yaml+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) # tools/yaml12.py+import yaml12 # noqa: E402ROOT = Path(__file__).resolve().parents[1]# The sim's defaults for a missing key (GameEvent in sim/Statecraft.Sim/Content.cs; a test keeps them equal).@@ -20,10 +21,10 @@ DEFAULT_STATUS = "draft"def load(root: Path) -> list[dict]:- eras = yaml.safe_load((root / "content/eras.yaml").read_text(encoding="utf-8"))["eras"]+ eras = yaml12.load((root / "content/eras.yaml").read_text(encoding="utf-8"))["eras"]rows = []for f in sorted((root / "content/events").glob("*.yaml")):- e = yaml.safe_load(f.read_text(encoding="utf-8"))+ e = yaml12.load(f.read_text(encoding="utf-8"))start = str(e["from"])era = next((x["id"] for x in erasif str(x["from"]) <= start and (not x.get("to") or start < str(x["to"]))), "-")diff --git a/scripts/oss/ai_disclosure.py b/scripts/oss/ai_disclosure.pyindex 616af5606..cd7c4f690 100644--- a/scripts/oss/ai_disclosure.py+++ b/scripts/oss/ai_disclosure.py@@ -6,8 +6,11 @@"""Generate review text only from explicit AI flags in the two asset manifests."""from __future__ import annotationsimport argparse+import sysfrom pathlib import Path-import yaml++sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) # tools/yaml12.py+import yaml12 # noqa: E402KINDS = {'Images': {'.png', '.jpg', '.jpeg', '.webp', '.gif', '.ico', '.svg', '.tif', '.tiff'},@@ -20,7 +23,7 @@ KINDS = {def read_manifests(root: Path):rows = []for name in ('ASSETS.yaml', 'ASSETS.portraits.yaml'):- data = yaml.safe_load((root / name).read_text(encoding='utf-8'))+ data = yaml12.load((root / name).read_text(encoding='utf-8'))if not isinstance(data, dict) or not isinstance(data.get('rules'), list):raise ValueError(f'{name}: rules must be a list')rows.extend((name, row) for row in data['rules'])diff --git a/scripts/oss/check_repo.py b/scripts/oss/check_repo.pyindex f18cc1377..6ea9f8614 100755--- a/scripts/oss/check_repo.py+++ b/scripts/oss/check_repo.py@@ -22,11 +22,12 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Callable-import yaml-sys.path.insert(0, str(Path(__file__).resolve().parent))import oss_policy as P # noqa: E402+sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) # tools/yaml12.py+import yaml12 # noqa: E402+ALLOW_FILE = "scripts/oss/allow.yaml"ASSET_FILES = ("ASSETS.yaml", "ASSETS.portraits.yaml")@@ -125,7 +126,7 @@ def load_asset_rules(root: Path) -> tuple[list[dict], list[dict]]:for name in ASSET_FILES:p = root / nameif p.is_file():- doc = yaml.safe_load(p.read_text(encoding="utf-8")) or {}+ doc = yaml12.load(p.read_text(encoding="utf-8")) or {}rules += [dict(r, _file=name) for r in doc.get("rules") or []]removed += doc.get("removed") or []return rules, removed@@ -183,7 +184,7 @@ def apply_allowlist(root: Path, findings: list[Finding], checks: list[str]) -> lp = root / ALLOW_FILErows: list[dict] = []if p.is_file():- rows = (yaml.safe_load(p.read_text(encoding="utf-8")) or {}).get("allow") or []+ rows = (yaml12.load(p.read_text(encoding="utf-8")) or {}).get("allow") or []kept, used = [], set()for f in findings:hit = next((i for i, r in enumerate(rows)diff --git a/scripts/oss/commons_licences.py b/scripts/oss/commons_licences.pyindex d53cb6b1c..7bbbd684e 100644--- a/scripts/oss/commons_licences.py+++ b/scripts/oss/commons_licences.py@@ -86,7 +86,9 @@ def _commons(title: str, session) -> tuple[str, list[str], str]:def main() -> int:import requestsimport yaml- people = yaml.safe_load((ROOT / "content/people.yaml").read_text(encoding="utf-8"))["people"]+ sys.path.insert(0, str(ROOT / "tools"))+ import yaml12 # tools/yaml12.py+ people = yaml12.load((ROOT / "content/people.yaml").read_text(encoding="utf-8"))["people"]pairs: list[tuple[str, str]] = []for p in people:portrait = p.get("portrait")diff --git a/scripts/oss/tests/test_ai_disclosure.py b/scripts/oss/tests/test_ai_disclosure.pyindex 2dd0bb0f0..b7e7f0e33 100644--- a/scripts/oss/tests/test_ai_disclosure.py+++ b/scripts/oss/tests/test_ai_disclosure.py@@ -55,3 +55,14 @@ def test_checked_in_output_matches_current_manifests():def test_incomplete_flagged_rule_fails():with pytest.raises(ValueError, match='requires source'):module().render([('A', {'glob': 'a.png', 'ai_generated': True, 'status': 'verified'})])++[email protected]('flag', ['no', 'yes', 'off', 'y'])+def test_a_yaml_1_1_bool_word_fails_closed(tmp_path, flag):+ # The site reads the manifests as YAML 1.2, where `no` is the text "no", not False (review of #606). Read the same+ # way here, such a flag is not a boolean and is refused, instead of a YAML 1.1 False silently dropping the row.+ (tmp_path / 'ASSETS.yaml').write_text(f'rules:\n - {{glob: a.png, ai_generated: {flag}, source: s}}\n', encoding='utf-8')+ (tmp_path / 'ASSETS.portraits.yaml').write_text('rules: []\n', encoding='utf-8')+ m = module()+ with pytest.raises(ValueError, match='ai_generated must be a boolean'):+ m.render(m.read_manifests(tmp_path))diff --git a/scripts/oss/tests/test_new_event.py b/scripts/oss/tests/test_new_event.pyindex cca529325..c49ca455d 100644--- a/scripts/oss/tests/test_new_event.py+++ b/scripts/oss/tests/test_new_event.py@@ -2,11 +2,12 @@import importlib.utilimport jsonimport re+import sysfrom pathlib import Path-import yaml-ROOT = Path(__file__).resolve().parents[3]+sys.path.insert(0, str(ROOT / 'tools'))+import yaml12 # noqa: E402 (tools/yaml12.py: YAML 1.2, no 1.1 coercions)SPEC = importlib.util.spec_from_file_location('new_event', ROOT / 'scripts/new_event.py')m = importlib.util.module_from_spec(SPEC)SPEC.loader.exec_module(m)@@ -14,7 +15,7 @@ SPEC.loader.exec_module(m)def test_writes_every_required_field(tmp_path):assert m.main(['my_event', '--from', '1949-01-01', '--to', '1949-02-01'], root=tmp_path) == 0- doc = yaml.safe_load((tmp_path / 'content/events/my_event.yaml').read_text())+ doc = yaml12.load((tmp_path / 'content/events/my_event.yaml').read_text())required = json.loads((ROOT / 'content/schema/event.schema.json').read_text())['required']assert all(k in doc for k in required)assert doc['id'] == 'my_event' and doc['sources'] == [] and doc['status'] == 'draft'@@ -26,7 +27,7 @@ def test_ids_match_the_schema_pattern(tmp_path):schema = json.loads((ROOT / 'content/schema/event.schema.json').read_text())pattern = schema['definitions']['id']['pattern']m.main(['e1'], root=tmp_path)- doc = yaml.safe_load((tmp_path / 'content/events/e1.yaml').read_text())+ doc = yaml12.load((tmp_path / 'content/events/e1.yaml').read_text())assert all(re.search(pattern, i) for i in [doc['id']] + [o['id'] for o in doc['options']])# an office placeholder fails the loader on an open window (no holder on every day), so the default has noneassert '{' not in doc['text'] + doc['title']@@ -34,7 +35,7 @@ def test_ids_match_the_schema_pattern(tmp_path):def test_no_to_means_no_to_key(tmp_path):m.main(['e1'], root=tmp_path)- assert 'to' not in yaml.safe_load((tmp_path / 'content/events/e1.yaml').read_text())+ assert 'to' not in yaml12.load((tmp_path / 'content/events/e1.yaml').read_text())def test_refuses_overwrite_bad_id_and_bad_dates(tmp_path):diff --git a/scripts/pr_content_summary.py b/scripts/pr_content_summary.pyindex 7f3fa9a12..a72f2a160 100644--- a/scripts/pr_content_summary.py+++ b/scripts/pr_content_summary.py@@ -14,7 +14,8 @@ import subprocessimport sysfrom pathlib import Path-import yaml+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) # tools/yaml12.py+import yaml12 # noqa: E402ROOT = Path(__file__).resolve().parents[1]# The dated model records: the sim's ModelView (sim/Statecraft.Sim/Content.cs; a test keeps them equal).@@ -31,10 +32,10 @@ def records(root: Path, ref: str) -> dict[str, dict]:out: dict[str, dict] = {}for path in git(root, "ls-tree", "-r", "--name-only", ref, "content/events/").split():if path.endswith(".yaml"):- e = yaml.safe_load(git(root, "show", f"{ref}:{path}")) or {}+ e = yaml12.load(git(root, "show", f"{ref}:{path}")) or {}if "id" in e:out[f"event:{e['id']}"] = {"from": str(e.get("from", "")), "to": str(e.get("to", ""))}- model = yaml.safe_load(git(root, "show", f"{ref}:content/model.yaml")) or {}+ model = yaml12.load(git(root, "show", f"{ref}:content/model.yaml")) or {}for key in LISTS:for r in model.get(key) or []:if isinstance(r, dict) and "id" in r:diff --git a/scripts/source_report.py b/scripts/source_report.pyindex 3b22e6157..24b18c289 100644--- a/scripts/source_report.py+++ b/scripts/source_report.py@@ -15,7 +15,8 @@ import sysfrom datetime import datefrom pathlib import Path-import yaml+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) # tools/yaml12.py+import yaml12 # noqa: E402ROOT = Path(__file__).resolve().parents[1]@@ -52,7 +53,7 @@ def collect(root: Path, today: date) -> list[dict]:rows = []for f in sorted((root / "content").rglob("*.yaml")):found: list[dict] = []- walk(yaml.safe_load(f.read_text(encoding="utf-8")), found, set())+ walk(yaml12.load(f.read_text(encoding="utf-8")), found, set())for s in found:d = to_date(s["checked"])rows.append({"file": str(f.relative_to(root)), "url": str(s["url"]), "checked": d,diff --git a/tools/README.md b/tools/README.mdindex f437f3129..8a35aa81a 100644--- a/tools/README.md+++ b/tools/README.md@@ -62,6 +62,13 @@ Offline data tools (uv inline-script Python). Run from the repo root.profile deleted on exit): `boot` (?bootlog phase timings, optional CPU throttling), `navpairs` (same-frame click pairsunder ?navlog), `loadshot` (screenshots during the load) and `profile` (visual v1's `?vprofile` in a headed window at achosen DPR); `boot --runs N --baseline MS` checks the boot budget. Its browser test runs only with `pytest --headed`.+- `yaml12.py` is how the tools, scripts and their tests read YAML. `yaml12.load` resolves plain scalars by the YAML 1.2+ core schema and refuses duplicate keys, where `yaml.safe_load` follows YAML 1.1 (`yes` becomes True, `1:30` becomes+ 90, `2026-10-15` becomes a date). That matches YamlDotNet's reads into string fields, not its bool and int fields,+ which also take `yes`, `y`, `off`, `017`, `1_000` and `1:30`. `yaml12.ambiguous` lists those scalars, and+ `test_yaml12_data.py` keeps them out of the game's YAML. `load_raw` keeps every scalar as its text, and+ `uv run tools/yaml12.py FILE...` lists both kinds of hit. `test_yaml12_guard.py` fails on a new PyYAML load in+ `tools/`, `scripts/` or `.github/` outside its allowlist.## Running the testsdiff --git a/tools/borders_bake.py b/tools/borders_bake.pyindex 6e89e7e89..acc951d67 100644--- a/tools/borders_bake.py+++ b/tools/borders_bake.py@@ -40,12 +40,12 @@ import sysfrom pathlib import Pathimport numpy as np-import yamlsys.path.insert(0, str(Path(__file__).resolve().parent))import heightmap_codec # noqa: E402import hexgrid # noqa: E402from geo import KM_PER_DEG_LAT, KM_PER_DEG_LON_EQ # noqa: E402+import yaml12 # noqa: E402ROOT = Path(__file__).resolve().parents[1]MAP = ROOT / "content" / "map"@@ -296,7 +296,7 @@ def build() -> str:source = json.loads(SOURCE.read_text(encoding="utf-8"))hexes = json.loads((MAP / "hexes.json").read_text())elev, meta = load_elevation()- settlements = yaml.safe_load((MAP / "settlements_1948.yaml").read_text(encoding="utf-8"))["settlements"]+ settlements = yaml12.load((MAP / "settlements_1948.yaml").read_text(encoding="utf-8"))["settlements"]regions, cells = bake(source, hexes, water_mask(elev, meta), meta, listed_places(settlements))armistice = json.loads(ARMISTICE.read_text(encoding="utf-8")) if ARMISTICE.exists() else Nonereturn render(source, regions, cells, armistice)diff --git a/tools/control_bake.py b/tools/control_bake.pyindex 3f1000204..4633a2236 100644--- a/tools/control_bake.py+++ b/tools/control_bake.py@@ -35,12 +35,12 @@ import sysfrom pathlib import Pathimport numpy as np-import yamlsys.path.insert(0, str(Path(__file__).resolve().parent))import borders_bake as bb # noqa: E402import hexgrid # noqa: E402from geo import KM_PER_DEG_LAT, KM_PER_DEG_LON_EQ # noqa: E402+import yaml12 # noqa: E402ROOT = Path(__file__).resolve().parents[1]MAP = ROOT / "content" / "map"@@ -60,7 +60,7 @@ HEADER = ("# Generated by tools/control_bake.py from control_1948_49.geojson (thdef mandate_hexes() -> dict:"""{(q, r): sub-district id} for the land hexes in Mandatory Palestine (the sub-district layer's regions but 'outside')."""- doc = yaml.safe_load(SUBDISTRICTS.read_text(encoding="utf-8"))+ doc = yaml12.load(SUBDISTRICTS.read_text(encoding="utf-8"))outside = {r["id"] for r in doc["regions"] if r["key"] == bb.OUTSIDE}return {(q, r): rid for q, r, rid in doc["hexes"] if rid not in outside}diff --git a/tools/encode_event_videos.py b/tools/encode_event_videos.pyindex a7a0d48d2..332621741 100644--- a/tools/encode_event_videos.py+++ b/tools/encode_event_videos.py@@ -32,7 +32,9 @@ import sysimport tempfilefrom pathlib import Path-import yaml+sys.path.insert(0, str(Path(__file__).resolve().parent)) # under python -I the script's folder is not on sys.path+import yaml12 # noqa: E402+REPO = Path(__file__).resolve().parents[1]MAPPING = REPO / "unity/Assets/Resources/EventVideos/event-videos.yaml"@@ -45,7 +47,7 @@ FFMPEG_VIDEO = ["-c:v", "libx264", "-profile:v", "high", "-preset", "slow", "-crdef load_rows(mapping: Path = MAPPING) -> list[dict]:"""The card loops (clips) and the End Turn outcome clips (outcomes), in that order."""- doc = yaml.safe_load(mapping.read_text(encoding="utf-8"))+ doc = yaml12.load(mapping.read_text(encoding="utf-8"))return doc["clips"] + doc.get("outcomes", [])diff --git a/tools/event_images.py b/tools/event_images.pyindex b9503f622..f171e43d6 100644--- a/tools/event_images.py+++ b/tools/event_images.py@@ -21,9 +21,11 @@ import ioimport sysfrom pathlib import Path-import yamlfrom PIL import Image+sys.path.insert(0, str(Path(__file__).resolve().parent)) # under python -I the script's folder is not on sys.path+import yaml12 # noqa: E402+REPO = Path(__file__).resolve().parents[1]FOLDER = REPO / "unity/Assets/UI/EventImages"MAPPING = FOLDER / "event-images.yaml"@@ -96,7 +98,7 @@ def encode(im: Image.Image) -> bytes:def load_rows(mapping: Path = MAPPING) -> list[dict]:- return yaml.safe_load(mapping.read_text(encoding="utf-8"))["images"]+ return yaml12.load(mapping.read_text(encoding="utf-8"))["images"]def isolated() -> bool:diff --git a/tools/land_bake.py b/tools/land_bake.pyindex 559c7b2c9..cb6efda20 100644--- a/tools/land_bake.py+++ b/tools/land_bake.py@@ -23,14 +23,16 @@ The geography is real (slope, rain, towns); the parcels are procedural. Determinimport jsonimport mathimport warnings+import sysfrom pathlib import Pathimport numpy as np-import yamlfrom PIL import Image-import hexgrid-import terrain_bake as tb+sys.path.insert(0, str(Path(__file__).resolve().parent)) # under python -I the script's folder is not on sys.path+import hexgrid # noqa: E402+import terrain_bake as tb # noqa: E402+import yaml12 # noqa: E402ROOT = Path(__file__).resolve().parents[1]MAP_DIR = ROOT / "unity" / "Assets" / "StreamingAssets" / "map"@@ -132,7 +134,7 @@ def biome_at(xk: np.ndarray, yk: np.ndarray, hexes: dict) -> np.ndarray:def settlements_km(meta: dict) -> list[tuple[str, float, float]]:- doc = yaml.safe_load((CONTENT / "settlements_1948.yaml").read_text())+ doc = yaml12.load((CONTENT / "settlements_1948.yaml").read_text())return [(s["id"], *hexgrid.lonlat_to_km(s["lon"], s["lat"], meta)) for s in doc["settlements"]]diff --git a/tools/localities_bake.py b/tools/localities_bake.pyindex 69c892572..181705431 100644--- a/tools/localities_bake.py+++ b/tools/localities_bake.py@@ -24,7 +24,9 @@ import argparseimport sysfrom pathlib import Path-import yaml+sys.path.insert(0, str(Path(__file__).resolve().parent)) # under python -I the script's folder is not on sys.path+import yaml12 # noqa: E402+ROOT = Path(__file__).resolve().parents[1]SOURCE = ROOT / "content" / "map" / "localities_1948.yaml"@@ -49,7 +51,7 @@ def _number(value, where: str) -> str:def bake(text: str) -> str:"""The runtime file for the YAML text: deterministic, so a fresh bake equals the committed file."""- doc = yaml.safe_load(text)+ doc = yaml12.load(text)out = ["# Generated by tools/localities_bake.py from localities_1948.yaml. Do not edit: edit the YAML and rerun the tool.","# The runtime form the map reads at boot (presentation only, outside the content hash). Sources: the YAML.",diff --git a/tools/preview_map.py b/tools/preview_map.pyindex 0e582403f..a28cf2fd7 100644--- a/tools/preview_map.py+++ b/tools/preview_map.py@@ -12,11 +12,11 @@ import sysfrom pathlib import Pathimport numpy as np-import yamlfrom PIL import Image, ImageDraw, ImageFontsys.path.insert(0, str(Path(__file__).resolve().parent))import hexgrid as hg # noqa: E402+import yaml12 # noqa: E402ROOT = Path(__file__).resolve().parents[1]BIOME_RGB = {"sea": (70, 130, 180), "lake": (40, 110, 200), "coastal_plain": (175, 215, 120),@@ -67,7 +67,7 @@ def main() -> None:out.parent.mkdir(parents=True, exist_ok=True)hexes = json.loads((ROOT / "content" / "map" / "hexes.json").read_text())towns_file = ROOT / "content" / "map" / "settlements_1948.yaml"- towns = yaml.safe_load(towns_file.read_text())["settlements"] if towns_file.exists() else []+ towns = yaml12.load(towns_file.read_text())["settlements"] if towns_file.exists() else []render(hg.MAP_DIR, hexes, towns, out)print(f"wrote {out}")diff --git a/tools/route_paths_bake.py b/tools/route_paths_bake.pyindex e39aac419..a7b8725c3 100644--- a/tools/route_paths_bake.py+++ b/tools/route_paths_bake.py@@ -32,7 +32,8 @@ import structimport sysfrom pathlib import Path-import yaml+sys.path.insert(0, str(Path(__file__).resolve().parent)) # under python -I the script's folder is not on sys.path+import yaml12 # noqa: E402ROOT = Path(__file__).resolve().parents[1]SOURCE = ROOT / "content" / "map" / "route_paths_1948.yaml"@@ -69,7 +70,7 @@ def _field(value, where: str) -> str:def bake(data: bytes) -> str:"""The runtime file for the YAML file's bytes: deterministic, so a fresh bake equals the committed file."""- doc = yaml.safe_load(data.decode("utf-8"))+ doc = yaml12.load(data.decode("utf-8"))out = ["# Generated by tools/route_paths_bake.py from route_paths_1948.yaml. Do not edit: edit the YAML (tools/routes_1948.py)","# and rerun the tool. The runtime form the map reads at boot (map-only, outside the content hash).",diff --git a/tools/routes_1948.py b/tools/routes_1948.pyindex 2044cd50c..8649b2785 100644--- a/tools/routes_1948.py+++ b/tools/routes_1948.py@@ -38,9 +38,11 @@ import urllib.requestfrom pathlib import Pathimport numpy as np-import yamlfrom PIL import Image+sys.path.insert(0, str(Path(__file__).resolve().parent)) # under python -I the script's folder is not on sys.path+import yaml12 # noqa: E402+ROOT = Path(__file__).resolve().parents[1]ROUTES = ROOT / "content" / "map" / "routes_1948.yaml"PATHS = ROOT / "content" / "map" / "route_paths_1948.yaml"@@ -416,7 +418,7 @@ def trace_route(route: dict, fetch: bool, preview: Path | None = None) -> list[t# --- files -------------------------------------------------------------------------------------------------------def load_routes(path: Path = ROUTES) -> dict:- doc = yaml.safe_load(path.read_text(encoding="utf-8"))+ doc = yaml12.load(path.read_text(encoding="utf-8"))validate_routes(doc, json_bounds())return doc@@ -518,7 +520,7 @@ def main(argv: list[str] | None = None) -> int:routes = doc["routes"]old = {}if PATHS.exists():- for r in (yaml.safe_load(PATHS.read_text(encoding="utf-8")) or {}).get("routes", []):+ for r in (yaml12.load(PATHS.read_text(encoding="utf-8")) or {}).get("routes", []):old[r["id"]] = rlines = {}for r in routes:diff --git a/tools/routes_accuracy.py b/tools/routes_accuracy.pyindex 4db57932e..e14df3ce7 100644--- a/tools/routes_accuracy.py+++ b/tools/routes_accuracy.py@@ -25,9 +25,11 @@ import urllib.requestfrom pathlib import Pathimport numpy as np-import yamlfrom scipy.spatial import cKDTree+sys.path.insert(0, str(Path(__file__).resolve().parent)) # under python -I the script's folder is not on sys.path+import yaml12 # noqa: E402+ROOT = Path(__file__).resolve().parents[1]PATHS = ROOT / "content" / "map" / "route_paths_1948.yaml"CACHE = ROOT / "tools" / ".cache" / "routes-accuracy"@@ -110,7 +112,7 @@ def main(argv: list[str] | None = None) -> int:}print("| Route | Reference | Median distance | 90th percentile | Within 300 m |")print("|---|---|---|---|---|")- for r in yaml.safe_load(PATHS.read_text(encoding="utf-8"))["routes"]:+ for r in yaml12.load(PATHS.read_text(encoding="utf-8"))["routes"]:line = densify([tuple(p) for p in r["points"]], 50)names = ["OHM rail by 1948", "OSM rail, current and abandoned"] if r["kind"] == "rail" else ["OHM roads valid in 1948"]for name in names:diff --git a/tools/settlement_hexes.py b/tools/settlement_hexes.pyindex 94144c8af..fbf4230ac 100644--- a/tools/settlement_hexes.py+++ b/tools/settlement_hexes.py@@ -13,10 +13,10 @@ import jsonimport sysfrom pathlib import Path-import yamlsys.path.insert(0, str(Path(__file__).resolve().parent))import hexgrid as hg # noqa: E402+import yaml12 # noqa: E402ROOT = Path(__file__).resolve().parents[1]MAP = ROOT / "content" / "map"@@ -36,7 +36,7 @@ def render(hexes: dict, settlements: list[dict]) -> str:def main() -> None:hexes = json.loads((MAP / "hexes.json").read_text())- settlements = yaml.safe_load((MAP / "settlements_1948.yaml").read_text())["settlements"]+ settlements = yaml12.load((MAP / "settlements_1948.yaml").read_text())["settlements"]OUT.write_text(render(hexes, settlements))print(f"wrote {OUT.relative_to(ROOT)} ({len(settlements)} settlements)")diff --git a/tools/tests/test_armistice.py b/tools/tests/test_armistice.pyindex 413faf636..398ef002d 100644--- a/tools/tests/test_armistice.py+++ b/tools/tests/test_armistice.py@@ -8,7 +8,7 @@ from pathlib import Pathimport numpy as npimport pytest-import yaml+import yaml12import armistice_bake as abimport armistice_digitise as ad@@ -17,8 +17,8 @@ import borders_bake as bbROOT = Path(__file__).resolve().parents[2]MAP = ROOT / "content" / "map"SOURCE = json.loads((MAP / "armistice_lines_1949.geojson").read_text(encoding="utf-8"))-BAKED = yaml.safe_load((MAP / "armistice_hexes_1949.yaml").read_text(encoding="utf-8"))-SUBD = yaml.safe_load((MAP / "subdistrict_hexes_1948.yaml").read_text(encoding="utf-8"))+BAKED = yaml12.load((MAP / "armistice_hexes_1949.yaml").read_text(encoding="utf-8"))+SUBD = yaml12.load((MAP / "subdistrict_hexes_1948.yaml").read_text(encoding="utf-8"))HEXES = json.loads((MAP / "hexes.json").read_text())FEATS = {f["properties"]["id"]: f for f in SOURCE["features"]}DATES = {"egypt": "1949-02-24", "lebanon": "1949-03-23", "jordan": "1949-04-03", "syria": "1949-07-20"}diff --git a/tools/tests/test_benzvi_portrait.py b/tools/tests/test_benzvi_portrait.pyindex f3345393d..8312b270d 100644--- a/tools/tests/test_benzvi_portrait.py+++ b/tools/tests/test_benzvi_portrait.py@@ -3,21 +3,21 @@ from pathlib import Pathimport refrom PIL import Image-import yaml+import yaml12ROOT = Path(__file__).resolve().parents[2]SOURCE = "https://commons.wikimedia.org/wiki/File:President_Isaac_Ben_Zwi_,_president_van_Israel_en_echtgenote_ontvangen_door_het_,_Bestanddeelnr_909-7131.jpg"def portrait():- return next(p for p in yaml.safe_load((ROOT / "content/people.yaml").read_text())["people"] if p["id"] == "ben_zvi")["portrait"]+ return next(p for p in yaml12.load((ROOT / "content/people.yaml").read_text())["people"] if p["id"] == "ben_zvi")["portrait"]def test_ben_zvi_has_legal_portrait_with_cc0_provenance():p = portrait()assert p["license"] == "CC0" and p["source"] == SOURCEassert p["focus_y"] == 0.32- rules = yaml.safe_load((ROOT / "ASSETS.portraits.yaml").read_text())["rules"]+ rules = yaml12.load((ROOT / "ASSETS.portraits.yaml").read_text())["rules"]for path in (p["file"], "unity/Assets/UI/Portraits/ben_zvi.jpg"):r = next(r for r in rules if r["glob"] == path)assert r["source"] == SOURCE and r["status"] == "verified"diff --git a/tools/tests/test_borders.py b/tools/tests/test_borders.pyindex 235e57bdf..0f6be28b8 100644--- a/tools/tests/test_borders.py+++ b/tools/tests/test_borders.py@@ -6,7 +6,7 @@ from pathlib import Pathimport numpy as npimport pytest-import yaml+import yaml12import borders_bake as bbimport borders_digitise as bd@@ -16,8 +16,8 @@ ROOT = Path(__file__).resolve().parents[2]MAP = ROOT / "content" / "map"SOURCE = json.loads((MAP / "subdistricts_1948.geojson").read_text(encoding="utf-8"))HEXES = json.loads((MAP / "hexes.json").read_text())-BAKED = yaml.safe_load((MAP / "subdistrict_hexes_1948.yaml").read_text(encoding="utf-8"))-TOWNS = {t["id"]: t for t in yaml.safe_load((MAP / "settlements_1948.yaml").read_text())["settlements"]}+BAKED = yaml12.load((MAP / "subdistrict_hexes_1948.yaml").read_text(encoding="utf-8"))+TOWNS = {t["id"]: t for t in yaml12.load((MAP / "settlements_1948.yaml").read_text())["settlements"]}# The 1947 Schedule (Palestine Gazette No. 1552, Supplement No. 2): six districts, sixteen sub-districts.GAZETTE_1947 = {"Galilee District": ["Acre Sub-District", "Beisan Sub-District", "Nazareth Sub-District", "Safad Sub-District", "Tiberias Sub-District"],diff --git a/tools/tests/test_control.py b/tools/tests/test_control.pyindex ad38d3c26..40ccf1d37 100644--- a/tools/tests/test_control.py+++ b/tools/tests/test_control.py@@ -7,7 +7,7 @@ import refrom pathlib import Pathimport pytest-import yaml+import yaml12import borders_bake as bbimport control_bake as cb@@ -17,7 +17,7 @@ import hexgrid as hgROOT = Path(__file__).resolve().parents[2]MAP = ROOT / "content" / "map"SOURCE = json.loads((MAP / "control_1948_49.geojson").read_text(encoding="utf-8"))-BAKED = yaml.safe_load((MAP / "control_hexes_1948_49.yaml").read_text(encoding="utf-8"))+BAKED = yaml12.load((MAP / "control_hexes_1948_49.yaml").read_text(encoding="utf-8"))HEXES = json.loads((MAP / "hexes.json").read_text())META = SOURCE["statecraft"]PERIODS = [p["id"] for p in BAKED["periods"]]diff --git a/tools/tests/test_dori_portrait.py b/tools/tests/test_dori_portrait.pyindex 84913ef1b..6074431c2 100644--- a/tools/tests/test_dori_portrait.py+++ b/tools/tests/test_dori_portrait.py@@ -3,21 +3,21 @@ from pathlib import Pathimport refrom PIL import Image-import yaml+import yaml12ROOT = Path(__file__).resolve().parents[2]SOURCE = "https://commons.wikimedia.org/wiki/File:Stafchef_Dori_houdt_toespraak_tijdens_de_militaire_parade_bij_gelegenheid_van_de,_Bestanddeelnr_255-0981.jpg"def portrait():- return next(p for p in yaml.safe_load((ROOT / "content/people.yaml").read_text())["people"] if p["id"] == "dori")["portrait"]+ return next(p for p in yaml12.load((ROOT / "content/people.yaml").read_text())["people"] if p["id"] == "dori")["portrait"]def test_dori_has_legal_portrait_with_cc0_provenance():p = portrait()assert p["license"] == "CC0" and p["source"] == SOURCEassert p["focus_y"] == 0.3- rules = yaml.safe_load((ROOT / "ASSETS.portraits.yaml").read_text())["rules"]+ rules = yaml12.load((ROOT / "ASSETS.portraits.yaml").read_text())["rules"]for path in (p["file"], "unity/Assets/UI/Portraits/dori.jpg"):r = next(r for r in rules if r["glob"] == path)assert r["source"] == SOURCE and r["status"] == "verified"diff --git a/tools/tests/test_dp_portraits.py b/tools/tests/test_dp_portraits.pyindex 35ca4f5db..2b41b67e8 100644--- a/tools/tests/test_dp_portraits.py+++ b/tools/tests/test_dp_portraits.py@@ -5,7 +5,7 @@ from pathlib import Pathimport refrom PIL import Image-import yaml+import yaml12ROOT = Path(__file__).resolve().parents[2]# person id: (Commons file, promo/ref source crop, focus_y, artist, people.yaml licence, ASSETS licence, Commons template,@@ -20,8 +20,8 @@ BATCH = {}OLD_GPO = {"promo/ref/people/Yehuda_Leib_Maimon.jpg", "promo/ref/people/Mordechai_Bentov.jpg","promo/ref/people/Haim-Moshe_Shapira.jpg"}-PEOPLE = {p["id"]: p for p in yaml.safe_load((ROOT / "content/people.yaml").read_text(encoding="utf-8"))["people"]}-RULES = yaml.safe_load((ROOT / "ASSETS.portraits.yaml").read_text(encoding="utf-8"))["rules"]+PEOPLE = {p["id"]: p for p in yaml12.load((ROOT / "content/people.yaml").read_text(encoding="utf-8"))["people"]}+RULES = yaml12.load((ROOT / "ASSETS.portraits.yaml").read_text(encoding="utf-8"))["rules"]def source(name):diff --git a/tools/tests/test_encode_event_videos.py b/tools/tests/test_encode_event_videos.pyindex 6016ea45a..77bb56e35 100644--- a/tools/tests/test_encode_event_videos.py+++ b/tools/tests/test_encode_event_videos.py@@ -41,10 +41,10 @@ def test_the_encode_is_pinned_silent_and_has_no_burned_in_caption():def test_provenance_stays_ai_generated_on_every_row():"""The caption goes; the provenance stays: every row of the mapping, and every clip's ASSETS.yaml row, saysai_generated: true."""- import yaml+ import yaml12rows = ev.load_rows()assert rows and all(r["ai_generated"] is True for r in rows)- assets = {r["glob"]: r for r in yaml.safe_load((ev.REPO / "ASSETS.yaml").read_text(encoding="utf-8"))["rules"]}+ assets = {r["glob"]: r for r in yaml12.load((ev.REPO / "ASSETS.yaml").read_text(encoding="utf-8"))["rules"]}for r in rows:assert assets["unity/Assets/StreamingAssets/video/" + r["file"]]["ai_generated"] is True, r["file"]diff --git a/tools/tests/test_event_images.py b/tools/tests/test_event_images.pyindex 90182de73..55924409b 100644--- a/tools/tests/test_event_images.py+++ b/tools/tests/test_event_images.py@@ -2,6 +2,7 @@navy-sepia tone) and nothing else; downloads are checked by SHA-1 before they are read."""import hashlibimport io+from pathlib import Pathimport pytestfrom PIL import Image@@ -103,3 +104,28 @@ def test_every_row_has_a_shipped_file_and_a_crop():assert len(r["crop"]) == 3 and len(r["sha1"]) == 40with Image.open(ei.FOLDER / r["file"]) as im:assert im.size[0] * 9 == im.size[1] * 16++++ISOLATED_IMPORT = ("import importlib.util, sys; s = importlib.util.spec_from_file_location('m', sys.argv[1]); "+ "s.loader.exec_module(importlib.util.module_from_spec(s))")+++# routes_accuracy.py has the same fix but needs scipy, which the tools tests do not install[email protected]("tool", ["event_images.py", "encode_event_videos.py", "localities_bake.py", "land_bake.py",+ "routes_1948.py"])+def test_imports_under_python_isolated(tool):+ """`python -I` (the documented way to run event_images.py, which reads untrusted downloads) leaves the script's own+ folder off sys.path, so a tool must add it itself to import its siblings (yaml12, hexgrid). Imported, not run."""+ import subprocess+ import sys+ path = Path(ei.__file__).with_name(tool)+ r = subprocess.run([sys.executable, "-I", "-c", ISOLATED_IMPORT, str(path)], capture_output=True, text=True, cwd="/")+ assert r.returncode == 0, r.stderr[-400:]+++def test_documented_isolated_command_starts():+ import subprocess+ import sys+ r = subprocess.run([sys.executable, "-I", str(Path(ei.__file__)), "--help"], capture_output=True, text=True, cwd="/")+ assert r.returncode == 0 and "--originals" in r.stdout, r.stderr[-400:]diff --git a/tools/tests/test_hebrew_ui.py b/tools/tests/test_hebrew_ui.pyindex 8166cd324..459e86bef 100644--- a/tools/tests/test_hebrew_ui.py+++ b/tools/tests/test_hebrew_ui.py@@ -2,13 +2,13 @@from pathlib import Pathimport refrom collections import Counter-import yaml+import yaml12ROOT = Path(__file__).resolve().parents[2]UI = ROOT / 'unity/Assets/UI'def strings(name):- return yaml.safe_load((UI / name).read_text(encoding='utf-8'))+ return yaml12.load((UI / name).read_text(encoding='utf-8'))def test_hebrew_keys_match_english_and_every_value_is_nonempty():diff --git a/tools/tests/test_localities.py b/tools/tests/test_localities.pyindex 8141000c9..65f659dfc 100644--- a/tools/tests/test_localities.py+++ b/tools/tests/test_localities.py@@ -6,6 +6,7 @@ from pathlib import Pathimport pytestimport yaml+import yaml12import hexgrid as hg@@ -13,14 +14,14 @@ ROOT = Path(__file__).resolve().parents[2]MAP = ROOT / "content" / "map"HEXES = json.loads((MAP / "hexes.json").read_text())BY_QR = {(h["q"], h["r"]): h for h in HEXES["hexes"]}-DOC = yaml.safe_load((MAP / "localities_1948.yaml").read_text())+DOC = yaml12.load((MAP / "localities_1948.yaml").read_text())PLACES = DOC["places"]CAMPS = DOC["encampments"]-GAME_IDS = {s["id"] for s in yaml.safe_load((MAP / "settlements_1948.yaml").read_text())["settlements"]}+GAME_IDS = {s["id"] for s in yaml12.load((MAP / "settlements_1948.yaml").read_text())["settlements"]}TYPES = {"town", "kibbutz", "moshav", "arab_town", "village"}KINDS = {"arab_town": "arab_town", "arab_village": "village", "jewish_town": "town", "moshava": "town","kibbutz": "kibbutz", "moshav": "moshav", "mixed_locality": "town"}-SUBDISTRICTS = yaml.safe_load((MAP / "subdistrict_hexes_1948.yaml").read_text())+SUBDISTRICTS = yaml12.load((MAP / "subdistrict_hexes_1948.yaml").read_text())NO_TODAY = {line.strip() for line in (ROOT / "tools" / "tests" / "data" / "localities_no_today_qids.txt").read_text().splitlines()if line.strip() and not line.startswith("#")}LANDMARKS = {"mosque", "church", "none", "water_tower", "mosque_and_water_tower"}diff --git a/tools/tests/test_meitar_portraits.py b/tools/tests/test_meitar_portraits.pyindex 81cf94484..3f165cda0 100644--- a/tools/tests/test_meitar_portraits.py+++ b/tools/tests/test_meitar_portraits.py@@ -3,7 +3,7 @@ from pathlib import Pathimport refrom PIL import Image-import yaml+import yaml12ROOT = Path(__file__).resolve().parents[2]BATCH = {@@ -13,8 +13,8 @@ BATCH = {"dov_yosef": ("Dov_Yosef_(997008137381905171).jpg", "promo/ref/people/Dov_Yosef_CCBY_1949.jpg", 0.36,"Benno Rothenberg"),}-PEOPLE = {p["id"]: p for p in yaml.safe_load((ROOT / "content/people.yaml").read_text(encoding="utf-8"))["people"]}-RULES = yaml.safe_load((ROOT / "ASSETS.portraits.yaml").read_text(encoding="utf-8"))["rules"]+PEOPLE = {p["id"]: p for p in yaml12.load((ROOT / "content/people.yaml").read_text(encoding="utf-8"))["people"]}+RULES = yaml12.load((ROOT / "ASSETS.portraits.yaml").read_text(encoding="utf-8"))["rules"]def source(name):diff --git a/tools/tests/test_place_ids.py b/tools/tests/test_place_ids.pyindex 573f9bb3c..6dcf8a4a3 100644--- a/tools/tests/test_place_ids.py+++ b/tools/tests/test_place_ids.py@@ -12,7 +12,7 @@ from collections import Counterfrom pathlib import Pathimport pytest-import yaml+import yaml12ROOT = Path(__file__).resolve().parents[2]SETTLEMENTS = "content/map/settlements_1948.yaml"@@ -23,7 +23,7 @@ KEYED_BY_SETTLEMENT = ["content/map/settlement_hexes.yaml", "content/map/settlemdef yaml_ids(rel, key, root=ROOT):- return [row["id"] for row in yaml.safe_load((root / rel).read_text(encoding="utf-8"))[key]]+ return [row["id"] for row in yaml12.load((root / rel).read_text(encoding="utf-8"))[key]]def tsv_ids(rel, root=ROOT):diff --git a/tools/tests/test_route_ribbon_bake.py b/tools/tests/test_route_ribbon_bake.pyindex 857755af2..beed077a6 100644--- a/tools/tests/test_route_ribbon_bake.py+++ b/tools/tests/test_route_ribbon_bake.py@@ -18,7 +18,7 @@ import structfrom pathlib import Pathimport numpy as np-import yaml+import yaml12from test_terrain_water_bake import MAP, csharp, fingerprint, heights_check, method, unity_heights@@ -128,7 +128,7 @@ def test_every_route_is_in_the_index_once_and_its_ranges_tile_its_mesh():indices = np.array(r.take(f"<{ni}i"), dtype=np.int64)assert ni == 0 or (indices.min() >= 0 and indices.max() < nv), nameassert r.at == len(r.data), "longer than its meshes: " + REBAKE- shipped = [route["id"] for route in yaml.safe_load(ROUTES.read_text(encoding="utf-8"))["routes"]]+ shipped = [route["id"] for route in yaml12.load(ROUTES.read_text(encoding="utf-8"))["routes"]]assert sorted(ids) == sorted(shipped), "stale (route ids): " + REBAKEdiff --git a/tools/tests/test_routes_1948.py b/tools/tests/test_routes_1948.pyindex 8e7882265..39c8677d6 100644--- a/tools/tests/test_routes_1948.py+++ b/tools/tests/test_routes_1948.py@@ -7,14 +7,14 @@ from pathlib import Pathimport numpy as npimport pytest-import yaml+import yaml12import routes_1948 as rtROOT = Path(__file__).resolve().parents[2]BOUNDS = json.loads((ROOT / "content" / "map" / "hexes.json").read_text())["bounds"]-ROUTES = yaml.safe_load((ROOT / "content" / "map" / "routes_1948.yaml").read_text(encoding="utf-8"))-PATHS = yaml.safe_load((ROOT / "content" / "map" / "route_paths_1948.yaml").read_text(encoding="utf-8"))["routes"]+ROUTES = yaml12.load((ROOT / "content" / "map" / "routes_1948.yaml").read_text(encoding="utf-8"))+PATHS = yaml12.load((ROOT / "content" / "map" / "route_paths_1948.yaml").read_text(encoding="utf-8"))["routes"]BY_ID = {r["id"]: r for r in PATHS}@@ -100,14 +100,14 @@ def test_display_windows():({"to": "1900"}, "to must be after from"),])def test_validate_rejects_bad_dates(change, message):- doc = yaml.safe_load((ROOT / "content" / "map" / "routes_1948.yaml").read_text(encoding="utf-8"))+ doc = yaml12.load((ROOT / "content" / "map" / "routes_1948.yaml").read_text(encoding="utf-8"))doc["routes"][0].update(change)with pytest.raises(ValueError, match=message):rt.validate_routes(doc, BOUNDS)def test_validate_requires_from():- doc = yaml.safe_load((ROOT / "content" / "map" / "routes_1948.yaml").read_text(encoding="utf-8"))+ doc = yaml12.load((ROOT / "content" / "map" / "routes_1948.yaml").read_text(encoding="utf-8"))del doc["routes"][0]["from"]with pytest.raises(ValueError, match="from is required"):rt.validate_routes(doc, BOUNDS)diff --git a/tools/tests/test_settlement_hexes.py b/tools/tests/test_settlement_hexes.pyindex 691cb0ca4..96ccad561 100644--- a/tools/tests/test_settlement_hexes.py+++ b/tools/tests/test_settlement_hexes.py@@ -2,7 +2,7 @@import jsonfrom pathlib import Path-import yaml+import yaml12import hexgrid as hgimport settlement_hexes as sh@@ -10,7 +10,7 @@ import settlement_hexes as shROOT = Path(__file__).resolve().parents[2]MAP = ROOT / "content" / "map"HEXES = json.loads((MAP / "hexes.json").read_text())-TOWNS = yaml.safe_load((MAP / "settlements_1948.yaml").read_text())["settlements"]+TOWNS = yaml12.load((MAP / "settlements_1948.yaml").read_text())["settlements"]BY_QR = {(h["q"], h["r"]): h for h in HEXES["hexes"]}@@ -19,7 +19,7 @@ def test_committed_file_is_up_to_date():def test_every_settlement_is_on_its_rule_hex_and_that_hex_is_land():- rows = yaml.safe_load((MAP / "settlement_hexes.yaml").read_text())["settlements"]+ rows = yaml12.load((MAP / "settlement_hexes.yaml").read_text())["settlements"]assert [r["id"] for r in rows] == [t["id"] for t in TOWNS]for row, town in zip(rows, TOWNS):assert (row["q"], row["r"]) == hg.settlement_hex(town["lon"], town["lat"], HEXES), row["id"]@@ -27,12 +27,12 @@ def test_every_settlement_is_on_its_rule_hex_and_that_hex_is_land():def test_tiberias_is_moved_off_the_lake():- rows = {r["id"]: r for r in yaml.safe_load((MAP / "settlement_hexes.yaml").read_text())["settlements"]}+ rows = {r["id"]: r for r in yaml12.load((MAP / "settlement_hexes.yaml").read_text())["settlements"]}assert BY_QR[(rows["tiberias"]["q"], rows["tiberias"]["r"])]["biome"] != "lake"def test_two_known_settlements_are_pinned_literally():- rows = {r["id"]: (r["q"], r["r"]) for r in yaml.safe_load((MAP / "settlement_hexes.yaml").read_text())["settlements"]}+ rows = {r["id"]: (r["q"], r["r"]) for r in yaml12.load((MAP / "settlement_hexes.yaml").read_text())["settlements"]}assert rows["jerusalem"] == (0, 23)# jaffa and tel_aviv share this hex legitimately: Jaffa is the old port town beside Tel Aviv, inside one 5 km hex.assert rows["tel_aviv"] == (-3, 19)diff --git a/tools/tests/test_settlements.py b/tools/tests/test_settlements.pyindex eb1b8ab2f..bf7140091 100644--- a/tools/tests/test_settlements.py+++ b/tools/tests/test_settlements.py@@ -4,14 +4,14 @@ from pathlib import Pathimport numpy as npimport pytest-import yaml+import yaml12import hexgrid as hgROOT = Path(__file__).resolve().parents[2]TYPES = {"city", "town", "kibbutz", "moshav", "arab_town", "village"}HEXES = json.loads((ROOT / "content" / "map" / "hexes.json").read_text())-TOWNS = yaml.safe_load((ROOT / "content" / "map" / "settlements_1948.yaml").read_text())["settlements"]+TOWNS = yaml12.load((ROOT / "content" / "map" / "settlements_1948.yaml").read_text())["settlements"]BY_QR = {(h["q"], h["r"]): h for h in HEXES["hexes"]}@@ -40,7 +40,7 @@ def test_shore_settlement_moves_to_nearest_land_neighbour():assert (q - q0, r - r0) in hg.NEIGHBOURS-POPULATION = yaml.safe_load((ROOT / "content" / "map" / "settlement_population_1945.yaml").read_text())["settlements"]+POPULATION = yaml12.load((ROOT / "content" / "map" / "settlement_population_1945.yaml").read_text())["settlements"]def test_population_rows_match_the_settlements_and_carry_sources():diff --git a/tools/tests/test_sharett_portrait.py b/tools/tests/test_sharett_portrait.pyindex d29a9c958..a3198dea6 100644--- a/tools/tests/test_sharett_portrait.py+++ b/tools/tests/test_sharett_portrait.py@@ -3,21 +3,21 @@ from pathlib import Pathimport refrom PIL import Image-import yaml+import yaml12ROOT = Path(__file__).resolve().parents[2]SOURCE = "https://commons.wikimedia.org/wiki/File:Moshe_Sharett,_de_eerste_minister_van_buitenlandse_zaken_van_de_staat_Israel,_tu,_Bestanddeelnr_255-1438.jpg"def portrait():- return next(p for p in yaml.safe_load((ROOT / "content/people.yaml").read_text())["people"] if p["id"] == "sharett")["portrait"]+ return next(p for p in yaml12.load((ROOT / "content/people.yaml").read_text())["people"] if p["id"] == "sharett")["portrait"]def test_sharett_has_legal_portrait_with_cc0_provenance():p = portrait()assert p["license"] == "CC0" and p["source"] == SOURCEassert p["focus_y"] == 0.3- rules = yaml.safe_load((ROOT / "ASSETS.portraits.yaml").read_text())["rules"]+ rules = yaml12.load((ROOT / "ASSETS.portraits.yaml").read_text())["rules"]for path in (p["file"], "unity/Assets/UI/Portraits/sharett.jpg"):r = next(r for r in rules if r["glob"] == path)assert r["source"] == SOURCE and r["status"] == "verified"diff --git a/tools/tests/test_shazar_portrait.py b/tools/tests/test_shazar_portrait.pyindex 02105abe4..e091b2b72 100644--- a/tools/tests/test_shazar_portrait.py+++ b/tools/tests/test_shazar_portrait.py@@ -3,21 +3,21 @@ from pathlib import Pathimport refrom PIL import Image-import yaml+import yaml12ROOT = Path(__file__).resolve().parents[2]SOURCE = "https://commons.wikimedia.org/wiki/File:President_Lyndon_B._Johnson_with_President_Zalman_Shazar_of_Israel.jpg"def portrait():- return next(p for p in yaml.safe_load((ROOT / "content/people.yaml").read_text())["people"] if p["id"] == "shazar")["portrait"]+ return next(p for p in yaml12.load((ROOT / "content/people.yaml").read_text())["people"] if p["id"] == "shazar")["portrait"]def test_shazar_has_legal_portrait_with_explicit_us_provenance():p = portrait()assert p["license"] == "Public domain" and p["source"] == SOURCEassert p["focus_y"] == 0.35- rules = yaml.safe_load((ROOT / "ASSETS.portraits.yaml").read_text())["rules"]+ rules = yaml12.load((ROOT / "ASSETS.portraits.yaml").read_text())["rules"]for path in (p["file"], "unity/Assets/UI/Portraits/shazar.jpg"):r = next(r for r in rules if r["glob"] == path)assert r["source"] == SOURCE and r["status"] == "verified"diff --git a/tools/tests/test_units_1948.py b/tools/tests/test_units_1948.pyindex dea8e8b3e..c80571b85 100644--- a/tools/tests/test_units_1948.py+++ b/tools/tests/test_units_1948.py@@ -5,10 +5,10 @@ from datetime import datefrom pathlib import Pathfrom urllib.parse import urlparse-import yaml+import yaml12ROOT = Path(__file__).resolve().parents[2]-UNITS = yaml.safe_load((ROOT / 'content/map/units_1948.yaml').read_text(encoding='utf-8'))['units']+UNITS = yaml12.load((ROOT / 'content/map/units_1948.yaml').read_text(encoding='utf-8'))['units']# The signing day of each front's armistice (https://en.wikipedia.org/wiki/1949_Armistice_Agreements, checked 2026-10-11).ARMISTICE = {'egypt': date(1949, 2, 24), 'lebanon': date(1949, 3, 23), 'jordan': date(1949, 4, 3), 'syria': date(1949, 7, 20)}GAME_START = date(1948, 5, 15)diff --git a/tools/tests/test_weizmann_portrait.py b/tools/tests/test_weizmann_portrait.pyindex b4726672e..cc2969ae5 100644--- a/tools/tests/test_weizmann_portrait.py+++ b/tools/tests/test_weizmann_portrait.py@@ -3,21 +3,21 @@ from pathlib import Pathimport refrom PIL import Image-import yaml+import yaml12ROOT = Path(__file__).resolve().parents[2]SOURCE = "https://commons.wikimedia.org/wiki/File:C._(Chaim)_Weizmann_LCCN2014712248.jpg"def portrait():- return next(p for p in yaml.safe_load((ROOT / "content/people.yaml").read_text())["people"] if p["id"] == "weizmann")["portrait"]+ return next(p for p in yaml12.load((ROOT / "content/people.yaml").read_text())["people"] if p["id"] == "weizmann")["portrait"]def test_weizmann_has_legal_portrait_with_explicit_us_provenance():p = portrait()assert p["license"] == "Public domain" and p["source"] == SOURCEassert p["focus_y"] == 0.32- rules = yaml.safe_load((ROOT / "ASSETS.portraits.yaml").read_text())["rules"]+ rules = yaml12.load((ROOT / "ASSETS.portraits.yaml").read_text())["rules"]for path in (p["file"], "unity/Assets/UI/Portraits/weizmann.jpg"):r = next(r for r in rules if r["glob"] == path)assert r["source"] == SOURCE and r["status"] == "verified"diff --git a/tools/tests/test_yaml12.py b/tools/tests/test_yaml12.pynew file mode 100644index 000000000..4c3cb04c2--- /dev/null+++ b/tools/tests/test_yaml12.py@@ -0,0 +1,132 @@+"""tools/yaml12.py: a YAML 1.2 core-schema loader for the Python readers, in place of PyYAML's YAML 1.1 safe_load+(yes -> True, 1_0 -> 10, 1:30 -> 90, 2026-10-15 -> a date). It matches YamlDotNet's string reads; YamlDotNet's typed+bool and int reads accept more (yes, y, 017, 1_000), which ambiguous() flags. Refs #601."""+import math+from datetime import date++import pytest+import yaml++import yaml12+++# (plain scalar, what PyYAML's safe_load gives, what the YAML 1.2 core schema gives)+HAZARDS = [+ ("yes", True, "yes"),+ ("no", False, "no"),+ ("Off", False, "Off"),+ ("on", True, "on"),+ ("y", "y", "y"), # PyYAML leaves y/n alone (its bool resolver omits them), listed so that stays pinned+ ("1_0", 10, "1_0"),+ ("1:30", 90, "1:30"),+ ("017", 15, 17), # 1.1 reads a leading 0 as octal; 1.2 core is decimal+ ("0o17", "0o17", 15), # 1.2 core's octal; PyYAML does not know it+ ("2026-10-15", date(2026, 10, 15), "2026-10-15"),+ ("1e3", "1e3", 1000.0), # 1.2 core needs no dot in a float; PyYAML does+ ("0b101", 5, "0b101"),+]++[email protected]("raw, pyyaml, core", HAZARDS)+def test_core_schema_reads_the_1_1_hazards_as_1_2_does(raw, pyyaml, core):+ assert yaml.safe_load(f"k: {raw}")["k"] == pyyaml # the hazard is real today+ got = yaml12.load(f"k: {raw}")["k"]+ assert got == core and type(got) is type(core)++[email protected]("raw, value", [+ ("true", True), ("False", False), ("TRUE", True), ("null", None), ("~", None), ("", None),+ ("12", 12), ("-3", -3), ("+4", 4), ("0x0F", 15), ("1.5", 1.5), ("-0.25", -0.25), (".5", 0.5),+ ("1.0e+3", 1000.0), (".inf", math.inf), ("-.Inf", -math.inf), ("text", "text"), ("'yes'", "yes"),+ ('"1:30"', "1:30"),+])+def test_core_schema_agrees_where_1_1_and_1_2_agree(raw, value):+ got = yaml12.load(f"k: {raw}")["k"]+ assert got == value and type(got) is type(value)+++def test_nan():+ assert math.isnan(yaml12.load("k: .nan")["k"])+++def test_keys_are_resolved_too():+ assert yaml12.load("on: 1\nyes: 2\n2026-10-15: 3") == {"on": 1, "yes": 2, "2026-10-15": 3}+++def test_merge_key_is_a_plain_key():+ # YamlDotNet does not merge '<<' unless asked to (MergingParser); 1.2 has no merge key.+ assert yaml12.load("a: &x {b: 1}\nc:\n <<: *x") == {"a": {"b": 1}, "c": {"<<": {"b": 1}}}+++def test_explicit_tags_still_work():+ assert yaml12.load("k: !!str 12")["k"] == "12"+ assert yaml12.load("k: !!int '7'")["k"] == 7+++def test_safe_load_is_untouched():+ yaml12.load("k: yes")+ assert yaml.safe_load("k: yes")["k"] is True++[email protected]("raw", ["yes", "Off", "1_0", "1:30", "0x0F", "0o17", "2026-10-15", "~", "12", "1.5", "true",+ "null"])+def test_raw_keeps_every_scalar_as_its_text(raw):+ assert yaml12.load_raw(f"k: {raw}")["k"] == raw+++def test_raw_keeps_structure_and_quoted_text():+ assert yaml12.load_raw("a: [1, 'x', {b: no}]\nc: |\n two\n") == {"a": ["1", "x", {"b": "no"}], "c": "two\n"}+++def test_load_path(tmp_path):+ p = tmp_path / "a.yaml"+ p.write_text("k: 1:30\n", encoding="utf-8")+ assert yaml12.load_path(p) == {"k": "1:30"}+++def test_hazards_lists_every_plain_scalar_1_1_reads_differently():+ text = "a: yes\nb:\n - 1:30\n - 'no'\n - 12\nc: {d: 2026-10-15}\non: 1\n"+ got = [(h.line, h.path, h.raw, h.pyyaml, h.core) for h in yaml12.hazards(text)]+ assert got == [+ (1, "a", "yes", True, "yes"),+ (3, "b[0]", "1:30", 90, "1:30"),+ (6, "c.d", "2026-10-15", date(2026, 10, 15), "2026-10-15"),+ (7, "<key>", "on", True, "on"),+ ]+++def test_hazards_of_clean_text_is_empty():+ assert yaml12.hazards("a: 'yes'\nb: 12\nc: true\nd: 1.5\ne: ~\n") == []++[email protected]("text", ["k: 1\nk: 2\n", "a:\n - {x: 1, x: 1}\n", "? a\n: 1\n? a\n: 2\n"])+def test_duplicate_keys_are_refused(text):+ # YamlDotNet's deserializer runs WithDuplicateKeyChecking (sim ContentLoader), so a duplicate never loads in game+ with pytest.raises(yaml.constructor.ConstructorError, match="duplicate key"):+ yaml12.load(text)+ with pytest.raises(yaml.constructor.ConstructorError, match="duplicate key"):+ yaml12.load_raw(text)+++def test_distinct_keys_that_only_1_1_would_merge_load():+ # 1.1 reads both as True (and keeps one); 1.2 keeps both keys+ assert yaml12.load("yes: 1\non: 2") == {"yes": 1, "on": 2}++[email protected]("raw", ["=", "<<"])+def test_hazards_reports_scalars_safe_load_cannot_construct(raw):+ got = yaml12.hazards(f"k: {raw}\n")+ assert [(h.path, h.raw, h.core) for h in got] == [("k", raw, raw)]+ assert "error" in str(got[0].pyyaml)++[email protected]("raw", ["y", "Y", "n", "N", "yes", "No", "ON", "off", "017", "1_000", "1:30", "0b101", "0o17",+ "-0x1_F", "+012"])+def test_ambiguous_flags_what_yamldotnet_typed_reads_accept_beyond_1_2(raw):+ assert [(h.path, h.raw) for h in yaml12.ambiguous(f"k: {raw}\n")] == [("k", raw)]++[email protected]("raw", ["'y'", '"017"', "0", "10", "-3", "0x1F", "1.5", "true", "False", "yesterday", "on_hold",+ "1948-05-15", "N/A", "n2", "1:30pm"])+def test_ambiguous_leaves_unambiguous_scalars(raw):+ assert yaml12.ambiguous(f"k: {raw}\n") == []diff --git a/tools/tests/test_yaml12_data.py b/tools/tests/test_yaml12_data.pynew file mode 100644index 000000000..cfc3cd9df--- /dev/null+++ b/tools/tests/test_yaml12_data.py@@ -0,0 +1,43 @@+"""The YAML the game reads (content/, unity/Assets, the sim's test scenarios) holds no plain scalar that the readers could+take differently (refs #601, review of #606):+- no YAML 1.1 hazard (PyYAML's safe_load against the 1.2 core schema) except dates. A date-only YYYY-MM-DD is read as+ text by YamlDotNet's string fields and by every Python reader here (through tools/yaml12.py or str()), and str(date)+ is that same text;+- no scalar a YamlDotNet bool or int field accepts beyond YAML 1.2 (y, yes, off, 017, 1_000, 1:30, 0b101, 0o17): quote+ it if it is text, write true/false or a plain decimal if it is not;+- no duplicate key.+The scenarios' `on:` step key is allowed: the sim reads it as the key "on" (a string), and no Python reader loads them.+"""+import datetime+from pathlib import Path++import pytest++import yaml12++ROOT = Path(__file__).resolve().parents[2]+SCENARIOS = "sim/Statecraft.Sim.Tests/scenarios"+GAME_YAML = sorted({*ROOT.glob("content/**/*.yaml"), *ROOT.glob("unity/Assets/**/*.yaml"),+ *ROOT.glob(f"{SCENARIOS}/**/*.yaml")})+++def allowed(rel: str, h: yaml12.Hazard) -> bool:+ return rel.startswith(SCENARIOS + "/") and h.path.endswith("<key>") and h.raw == "on"+++def test_the_game_yaml_is_found():+ rels = {p.relative_to(ROOT).as_posix() for p in GAME_YAML}+ assert len(rels) > 50 and "content/people.yaml" in rels and "unity/Assets/UI/strings.en.yaml" in rels+ assert any(r.startswith(SCENARIOS + "/") for r in rels)++[email protected]("path", GAME_YAML, ids=lambda p: p.relative_to(ROOT).as_posix())+def test_no_scalar_the_readers_take_differently(path):+ rel, text = path.relative_to(ROOT).as_posix(), path.read_text(encoding="utf-8")+ bad = [f"{rel}:{h.line} {h.path} {h.raw!r}: safe_load {h.pyyaml!r}, 1.2 core {h.core!r}"+ for h in yaml12.hazards(text)+ if not (type(h.pyyaml) is datetime.date and h.core == str(h.pyyaml)) and not allowed(rel, h)]+ bad += [f"{rel}:{h.line} {h.path} {h.raw!r}: a YamlDotNet bool or int field reads it beyond YAML 1.2"+ for h in yaml12.ambiguous(text) if not allowed(rel, h)]+ assert not bad, "\n".join(bad)+ yaml12.load(text) # and no duplicate keydiff --git a/tools/tests/test_yaml12_guard.py b/tools/tests/test_yaml12_guard.pynew file mode 100644index 000000000..b9726ade7--- /dev/null+++ b/tools/tests/test_yaml12_guard.py@@ -0,0 +1,145 @@+"""Guard (refs #601): no new PyYAML YAML 1.1 load in tools/, scripts/ or .github/. Read YAML with tools/yaml12.py+(load, load_path or load_raw), which resolves plain scalars by the YAML 1.2 core schema and rejects duplicate keys. A+file that must keep a PyYAML load goes in ALLOWED with the reason.++The scan parses each file (ast): it follows `import yaml as y`, `from yaml import (safe_load as parse)` and `from yaml+import *`, and flags any reference through those names, called or not (map(yaml.safe_load, xs), parse = yaml.load,+functools.partial(yaml.load, ...)), whose yaml-side name contains "load" (safe_load, load, full_load, *_all, and the+SafeLoader classes). yaml.compose, yaml.safe_dump and yaml12 stay allowed."""+import ast+import re+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+SCANNED = ["tools", "scripts", ".github"]+SKIP_DIRS = {".cache", ".venv", "__pycache__", "node_modules"}+LOADISH = re.compile("load", re.I)+++def _calls(tree: ast.AST) -> list[int]:+ """Line numbers of every reference (a call or not) to a PyYAML load function or loader class."""+ modules: set[str] = set() # local names bound to the yaml package (or a yaml.* submodule's root)+ functions: set[str] = set() # local names bound to a load-ish name imported from yaml+ star = False+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ for alias in node.names:+ if alias.name == "yaml" or alias.name.startswith("yaml."):+ modules.add(alias.asname or "yaml")+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module and (+ node.module == "yaml" or node.module.startswith("yaml.")):+ for alias in node.names:+ if alias.name == "*":+ star = True+ elif LOADISH.search(alias.name):+ functions.add(alias.asname or alias.name)+ lines = set()+ for node in ast.walk(tree):+ # any reference, called or not: yaml.safe_load(t), map(yaml.safe_load, xs), parse = yaml.load, partial(...)+ if isinstance(node, ast.Attribute) and LOADISH.search(node.attr):+ root = node.value+ while isinstance(root, ast.Attribute):+ root = root.value+ if isinstance(root, ast.Name) and root.id in modules:+ lines.add(node.lineno)+ elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load) and (+ node.id in functions or (star and LOADISH.search(node.id))):+ lines.add(node.lineno)+ return sorted(lines)+++def offenders(root: Path) -> dict[str, list[int]]:+ """{repo-relative path: [line numbers]} of every PyYAML load call in the scanned trees."""+ found: dict[str, list[int]] = {}+ for top in SCANNED:+ for p in sorted((root / top).rglob("*.py")):+ if SKIP_DIRS & set(p.relative_to(root).parts):+ continue+ lines = _calls(ast.parse(p.read_text(encoding="utf-8"), filename=str(p)))+ if lines:+ found[p.relative_to(root).as_posix()] = lines+ return found+++ALLOWED = {+ "tools/yaml12.py": "the helper itself (yaml.load with its own SafeLoader subclasses)",+ "tools/tests/test_yaml12.py": "pins safe_load's YAML 1.1 readings on purpose, to show the hazard the helper removes",+ "scripts/oss/tests/test_policies.py": "reads .github issue forms and workflows, which GitHub parses, not the game",+ "scripts/oss/tests/test_github_config.py": "reads .github workflows, which GitHub parses; it expects PyYAML's True "+ "for the bare 'on' key",+}+++def test_no_yaml_1_1_load_outside_the_helper_and_the_allowlist():+ new = {f: lines for f, lines in offenders(ROOT).items() if f not in ALLOWED}+ assert not new, ("PyYAML loads (YAML 1.1: yes -> True, 1:30 -> 90, 2026-10-15 -> a date); use tools/yaml12.py, or "+ f"add the file to ALLOWED with the reason: {new}")+++def test_allowlist_is_not_stale():+ found = offenders(ROOT)+ stale = [f for f in ALLOWED if (ROOT / f).exists() and f not in found]+ assert not stale, f"no longer loads YAML the 1.1 way; drop it from ALLOWED: {stale}"+++def test_every_allowance_has_a_reason():+ assert all(len(reason) > 20 for reason in ALLOWED.values())+++EVASIONS = {+ "plain": "import yaml\nx = yaml.safe_load(t)\n",+ "loader_kwarg": "import yaml\nx = yaml.load(t, Loader=yaml.SafeLoader)\n",+ "full_load": "import yaml\nx = yaml.full_load(t)\n",+ "load_all": "import yaml\nx = list(yaml.safe_load_all(t))\n",+ "spaced": "import yaml\nx = yaml . safe_load (t)\n",+ "module_alias": "import yaml as y\nx = y.safe_load(t)\n",+ "module_alias_load": "import yaml as y\nx = y.load(t, Loader=y.SafeLoader)\n",+ "from_import": "from yaml import safe_load\nx = safe_load(t)\n",+ "from_import_alias": "from yaml import load as parse\nx = parse(t)\n",+ "from_import_parenthesised": "from yaml import (\n dump,\n safe_load,\n)\nx = safe_load(t)\n",+ "from_import_star": "from yaml import *\nx = safe_load(t)\n",+ "nested_import": "def f(t):\n import yaml as yy\n return yy.safe_load(t)\n",+ "submodule_import": "import yaml.constructor\nx = yaml.safe_load(t)\n",+ "map_ref": "import yaml\nxs = list(map(yaml.safe_load, texts))\n",+ "assign_ref": "import yaml\nparse = yaml.safe_load\nx = parse(t)\n",+ "partial": "import functools\nimport yaml\nparse = functools.partial(yaml.load, Loader=yaml.SafeLoader)\n",+ "from_import_ref": "from yaml import safe_load\nxs = list(map(safe_load, texts))\n",+ "loader_ref": "import yaml\nLoader = yaml.SafeLoader\n",+}+CLEAN = {+ "helper": "import yaml12\nx = yaml12.load(t)\n",+ "dump": "import yaml\ns = yaml.safe_dump(d)\n",+ "other_load": "import json\nfrom pickle import load\nx = json.load(f)\ny = load(f)\n",+ "yaml12_alias": "import yaml12 as yaml\nx = yaml.load(t)\n",+ "compose": "import yaml\nnode = yaml.compose(t)\nnodes = list(yaml.compose_all(t))\n",+ "yaml12_ref": "import yaml12\nxs = list(map(yaml12.load, texts))\n",+ "dump_ref": "import yaml\nsave = yaml.safe_dump\n",+}+++def _tree(tmp_path, files):+ for top in SCANNED:+ (tmp_path / top).mkdir(parents=True, exist_ok=True)+ for name, text in files.items():+ (tmp_path / "tools" / f"{name}.py").write_text(text, encoding="utf-8")+ return tmp_path+++def test_the_scan_catches_each_form(tmp_path):+ found = offenders(_tree(tmp_path, EVASIONS))+ assert sorted(found) == sorted(f"tools/{name}.py" for name in EVASIONS)+++def test_the_scan_passes_clean_code(tmp_path):+ assert offenders(_tree(tmp_path, CLEAN)) == {}+++def test_the_scan_skips_caches(tmp_path):+ _tree(tmp_path, {})+ (tmp_path / "tools" / ".cache").mkdir()+ (tmp_path / "tools" / ".cache" / "x.py").write_text("import yaml\nyaml.safe_load(t)\n", encoding="utf-8")+ assert offenders(tmp_path) == {}+++def test_the_scanned_directories_exist():+ assert all((ROOT / top).is_dir() for top in SCANNED)diff --git a/tools/yaml12.py b/tools/yaml12.pynew file mode 100644index 000000000..021db73c1--- /dev/null+++ b/tools/yaml12.py@@ -0,0 +1,228 @@+# /// script+# requires-python = ">=3.11"+# dependencies = ["pyyaml==6.0.3"]+# ///+"""YAML 1.2 core-schema loading for the Python tools and scripts (refs #601).++PyYAML's safe_load follows YAML 1.1, so it coerces plain scalars: yes/no/on/off become bools, 1_0 becomes 10, 1:30+becomes 90 (base 60), 017 becomes 15 (octal), 0b101 becomes 5 and 2026-10-15 becomes a date. The sim and Unity read the+same files with YamlDotNet (18.1.0), and what it does depends on the C# field's type:+- into a string (or object) field it keeps the text, as load() below does: 2026-10-15 stays "2026-10-15";+- into a bool or int field it is looser than YAML 1.2 (review of #606): bool takes yes/on/y and no/off/n, int takes+ 017 as 15, 1_000, 1:30 as 90 and 0b101, and refuses 0o17.+So load() is not "what the game reads" for every field. It removes the YAML 1.1 coercions on the Python side, and+ambiguous() lists the plain scalars where a typed C# read and load() could disagree. tools/tests/test_yaml12_data.py+keeps the game's YAML free of both kinds (dates excepted, which every reader here reads through their text).++- load(text) / load_path(path): the YAML 1.2 core schema. Bool is true/false only (any case form the spec lists), null+ is null/~/empty, ints are decimal, 0o octal or 0x hex, floats need no dot (1e3) and keep .inf/.nan. No sexagesimal, no+ underscores, no 0b, no implicit timestamps, no '<<' merge key. Everything else is a string. A duplicate key is an+ error, as in the game (YamlDotNet's WithDuplicateKeyChecking).+- load_raw(text): every scalar as its text (quoted or not, '~' stays '~'), for a reader that wants strings only.+- hazards(text): the plain scalars that safe_load reads differently from load(), with line and key path.+- ambiguous(text): the plain scalars a YamlDotNet bool or int read accepts beyond YAML 1.2 (y, yes, off, 017, 1_000,+ 1:30, 0b101, 0o17).+`uv run tools/yaml12.py FILE...` prints both lists.++Use these instead of yaml.safe_load in tools/, scripts/ and .github/; tools/tests/test_yaml12_guard.py fails on a new+PyYAML load.+"""+from __future__ import annotations++import math+import re+import sys+from dataclasses import dataclass+from pathlib import Path+from typing import Any++import yaml++INT = "tag:yaml.org,2002:int"+FLOAT = "tag:yaml.org,2002:float"+BOOL = "tag:yaml.org,2002:bool"+NULL = "tag:yaml.org,2002:null"+STR = "tag:yaml.org,2002:str"++# YAML 1.2.2, section 10.3.2 (core schema tag resolution).+CORE_RESOLVERS = [+ (NULL, re.compile(r"^(?:null|Null|NULL|~|)$"), list("nN~") + [""]),+ (BOOL, re.compile(r"^(?:true|True|TRUE|false|False|FALSE)$"), list("tTfF")),+ (INT, re.compile(r"^(?:[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+)$"), list("-+0123456789")),+ (FLOAT, re.compile(r"^(?:[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?"+ r"|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$"), list("-+.0123456789")),+]+++class _UniqueKeys:+ """Refuse a mapping that repeats a key (after resolution), as YamlDotNet's duplicate-key checking does."""++ def construct_mapping(self, node, deep=False):+ if isinstance(node, yaml.MappingNode):+ seen = set()+ for key_node, _ in node.value:+ key = self.construct_object(key_node, deep=True)+ try:+ if key in seen:+ raise yaml.constructor.ConstructorError("while constructing a mapping", node.start_mark,+ f"found duplicate key {key!r}", key_node.start_mark)+ seen.add(key)+ except TypeError:+ pass # unhashable: the base constructor reports it+ return super().construct_mapping(node, deep)+++class Core12Loader(_UniqueKeys, yaml.SafeLoader):+ """SafeLoader with the YAML 1.2 core schema's implicit resolvers and int/float constructors."""+ yaml_implicit_resolvers: dict = {}+++for _tag, _regexp, _first in CORE_RESOLVERS:+ Core12Loader.add_implicit_resolver(_tag, _regexp, _first)+++def _construct_int(loader: yaml.SafeLoader, node: yaml.ScalarNode) -> int:+ text = loader.construct_scalar(node)+ if re.fullmatch(r"0o[0-7]+", text):+ return int(text[2:], 8)+ if re.fullmatch(r"0x[0-9a-fA-F]+", text):+ return int(text[2:], 16)+ if re.fullmatch(r"[-+]?[0-9]+", text):+ return int(text, 10)+ raise yaml.constructor.ConstructorError(None, None, f"not a YAML 1.2 core int: {text!r}", node.start_mark)+++def _construct_float(loader: yaml.SafeLoader, node: yaml.ScalarNode) -> float:+ text = loader.construct_scalar(node)+ body = text.lstrip("+-")+ sign = -1.0 if text.startswith("-") else 1.0+ if body.lower() == ".inf":+ return sign * math.inf+ if body.lower() == ".nan":+ return math.nan+ try:+ return float(text)+ except ValueError:+ raise yaml.constructor.ConstructorError(None, None, f"not a YAML 1.2 core float: {text!r}",+ node.start_mark) from None+++Core12Loader.add_constructor(INT, _construct_int)+Core12Loader.add_constructor(FLOAT, _construct_float)+++class RawLoader(_UniqueKeys, yaml.SafeLoader):+ """Every scalar is a string: its text, as written (no implicit resolution at all)."""+ yaml_implicit_resolvers: dict = {}+++def _construct_raw(loader: yaml.SafeLoader, node: yaml.ScalarNode) -> str:+ return loader.construct_scalar(node)+++for _tag in (INT, FLOAT, BOOL, NULL, "tag:yaml.org,2002:timestamp"):+ RawLoader.add_constructor(_tag, _construct_raw)+++def load(text: str) -> Any:+ """Parse with the YAML 1.2 core schema (YamlDotNet's string reads agree; see ambiguous() for its typed ones)."""+ return yaml.load(text, Loader=Core12Loader) # noqa: S506 (a SafeLoader subclass)+++def load_path(path: Path | str) -> Any:+ return load(Path(path).read_text(encoding="utf-8"))+++def load_raw(text: str) -> Any:+ """Parse keeping every scalar as its text."""+ return yaml.load(text, Loader=RawLoader) # noqa: S506 (a SafeLoader subclass)+++@dataclass(frozen=True)+class Hazard:+ line: int # 1-based+ path: str # e.g. "settlements[3].checked"; "<key>" marks a mapping key+ raw: str+ pyyaml: Any # what yaml.safe_load gives+ core: Any # what load() gives+++def _value(loader_cls, node: yaml.ScalarNode) -> Any:+ """The value loader_cls gives a plain scalar with this text (a marker string when it cannot construct one, as+ safe_load cannot for a bare '=' or '<<')."""+ loader = loader_cls("")+ try:+ tag = loader.resolve(yaml.ScalarNode, node.value, (True, False))+ return loader.construct_object(yaml.ScalarNode(tag, node.value, node.start_mark, node.end_mark), deep=True)+ except yaml.YAMLError as e:+ return f"<{loader_cls.__name__} error: {getattr(e, 'problem', e)}>"+ finally:+ loader.dispose()+++def _plain_scalars(text: str):+ """(node, key path) for every plain, implicitly tagged scalar, keys included ("<key>" marks a mapping key)."""+ resolver = yaml.SafeLoader("")++ def walk(node: yaml.Node, path: str):+ if isinstance(node, yaml.ScalarNode):+ if node.style is None and node.tag == resolver.resolve(yaml.ScalarNode, node.value, (True, False)):+ yield node, path # quoted, block and explicitly tagged scalars read the same way everywhere+ elif isinstance(node, yaml.SequenceNode):+ for i, item in enumerate(node.value):+ yield from walk(item, f"{path}[{i}]")+ elif isinstance(node, yaml.MappingNode):+ for k, v in node.value:+ yield from walk(k, f"{path}.<key>" if path else "<key>")+ name = k.value if isinstance(k, yaml.ScalarNode) else "?"+ yield from walk(v, f"{path}.{name}" if path else name)++ for doc in yaml.compose_all(text, Loader=yaml.SafeLoader):+ if doc is not None:+ yield from walk(doc, "")+++def hazards(text: str) -> list[Hazard]:+ """The plain scalars whose safe_load value differs (in value or type) from the core-schema value."""+ out: list[Hazard] = []+ for node, path in _plain_scalars(text):+ old, new = _value(yaml.SafeLoader, node), _value(Core12Loader, node)+ same = type(old) is type(new) and (old == new or (isinstance(old, float) and math.isnan(old) and math.isnan(new)))+ if not same:+ out.append(Hazard(node.start_mark.line + 1, path, node.value, old, new))+ return out+++# What a YamlDotNet bool or int field accepts beyond YAML 1.2 core (review of #606, YamlDotNet 18.1.0): the YAML 1.1+# bool words, and ints with a leading zero (octal), underscores, base-60 colons, 0b, or 0o (which it refuses).+AMBIGUOUS = re.compile(r"""^(?:+ (?i:y|yes|n|no|on|off)+ | [-+]?0[0-9_]++ | [-+]?[0-9][0-9_]*_[0-9_]*(?:\.[0-9_]*)?+ | [-+]?[0-9][0-9_]*(?::[0-5]?[0-9])++ | [-+]?0b[01_]++ | [-+]?0o[0-7_]++ | [-+]?0x[0-9a-fA-F_]*_[0-9a-fA-F_]*+)$""", re.X)+++def ambiguous(text: str) -> list[Hazard]:+ """The plain scalars a YamlDotNet bool or int read could take differently from load()."""+ return [Hazard(node.start_mark.line + 1, path, node.value, _value(yaml.SafeLoader, node), _value(Core12Loader, node))+ for node, path in _plain_scalars(text) if AMBIGUOUS.match(node.value)]+++def main(argv: list[str]) -> int:+ count = 0+ for name in argv:+ text = Path(name).read_text(encoding="utf-8")+ for kind, found in (("1.1", hazards(text)), ("typed", ambiguous(text))):+ for h in found:+ count += 1+ print(f"{name}:{h.line}\t{kind}\t{h.path}\t{h.raw!r}\tsafe_load={h.pyyaml!r}\tcore={h.core!r}")+ print(f"{count} hits in {len(argv)} files", file=sys.stderr)+ return 1 if count else 0+++if __name__ == "__main__":+ sys.exit(main(sys.argv[1:]))