A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Languages: the tools, the sign-off guard and the release gate read translations/he/ (#1618, step 3) (#2501)
moshewe254749944099
diff --git a/AGENTS.md b/AGENTS.mdindex 65f2a63fd..2b559dfec 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -57,7 +57,7 @@ Before writing or editing content, review:- `dotnet test sim/Statecraft.sln` loads all of `content/` and must pass with 0 warnings.- `uv run scripts/oss/check_repo.py` runs the repository policy checks that CI runs.-- If you change `sim/`, `content/` or `unity/`, add a changelog fragment `changelog.d/<branch-or-issue>.md` (`changelog.d/README.md`); a line under `## [Unreleased]` in `CHANGELOG.md` still works.+- If you change `sim/`, `content/`, `translations/` or `unity/`, add a changelog fragment `changelog.d/<branch-or-issue>.md` (`changelog.d/README.md`); a line under `## [Unreleased]` in `CHANGELOG.md` still works.- If the PR finishes a Phase 1 PR or a phase of #374, update the Roadmap table in `README.md` and `README.he.md` (`CONTRIBUTING.md`, rule 9).- `scripts/check.sh` runs every check CI runs in one command: the changelog rule, the reviewed_by guard, the GDD lint, the policy checker tests, `check_repo.py`, the rule IDs, the sim build, the sim tests and the tools tests. It stops at the first failure.@@ -99,7 +99,7 @@ For changes under `sim/`, `tools/`, `scripts/` or `unity/`, not only content.**Pull requests**- Branch from `main`, one focused change per PR, no force-push to `main`. Fill in `.github/pull_request_template.md`, including "AI assistance". Use "Fixes #N" only if the PR completes the issue, otherwise "Refs #N".-- Add a changelog fragment `changelog.d/<branch-or-issue>.md` (or a line under `## [Unreleased]` in `CHANGELOG.md`) for any change to `sim/`, `content/` or `unity/` (tests excepted).+- Add a changelog fragment `changelog.d/<branch-or-issue>.md` (or a line under `## [Unreleased]` in `CHANGELOG.md`) for any change to `sim/`, `content/`, `translations/` or `unity/` (tests excepted).- Write the test first and check it fails without the change.- A change a player can see (models, the map, characters, the UI, the website) needs before/after screenshots in the PR description: the same game state, camera and zoom, with the changed area labelled. Reviewers can't judge a visual change from the diff alone.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 9693dbf03..1cf3d66c5 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -63,7 +63,7 @@ Follow [docs/dev-setup.md](docs/dev-setup.md). In short:`"$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -projectPath unity -buildTarget OSXUniversal -runTests -testPlatform EditMode -testResults "$PWD/unity-editmode.xml" -logFile unity-tests.log`. There must be 0 `warning CS` in the log.4. **Text the player sees** has no internal ids, gives dates as "15 May 1948", and shows money as "IL 1.2m" or "$1.2m". The tests enforce this.5. **Keep the pull request focused:** one change per PR, and no unrelated refactors.-6. **Changelog.** If you change `sim/`, `content/` or `unity/` (tests excepted), add a new file `changelog.d/<branch-or-issue>.md` with your entry as a bullet ([changelog.d/README.md](changelog.d/README.md)); fragments never conflict with other pull requests. A line under `## [Unreleased]` in [CHANGELOG.md](CHANGELOG.md) still works. CI's `Changelog` job checks it; the maintainer can add the `no-changelog` label to a change no player would notice.+6. **Changelog.** If you change `sim/`, `content/`, `translations/` or `unity/` (tests excepted), add a new file `changelog.d/<branch-or-issue>.md` with your entry as a bullet ([changelog.d/README.md](changelog.d/README.md)); fragments never conflict with other pull requests. A line under `## [Unreleased]` in [CHANGELOG.md](CHANGELOG.md) still works. CI's `Changelog` job checks it; the maintainer can add the `no-changelog` label to a change no player would notice.7. **Rule IDs.** A rule that has an ID (`R-ECON-014`, defined in `docs/rules/`, see [docs/rules/README.md](docs/rules/README.md)) is cited by that ID in the test that checks it (`// R-ECON-014`), in YAML comments that depend on it, and in the PR body ("implements R-ECON-014"). `uv run scripts/oss/rule_ids.py` fails on a rule with no citing test and on a citation of an ID that does not exist.8. **Provenance.** Every new image, video, font, audio, 3D-model or map-data file gets a row in [ASSETS.yaml](ASSETS.yaml) with its source, licence and status. CI's `Repo policy` job fails on a file with no row.9. **Roadmap status.** If your PR finishes a Phase 1 PR or a whole phase of [#374](https://github.com/eyalgolan/statecraft-israel/issues/374), update the Roadmap table in [README.md](README.md#roadmap) and the same table in [README.he.md](README.he.md), and tick the item in #374 if you can (otherwise ask the maintainer in the PR). The Phase 1 count must match in both files; `test_readme.py` checks it.diff --git a/changelog.d/README.md b/changelog.d/README.mdindex e1ee2b770..a392075c3 100644--- a/changelog.d/README.md+++ b/changelog.d/README.md@@ -1,6 +1,6 @@# Changelog fragments-A pull request that changes the game (`sim/`, `content/`, `unity/`) can add its changelog entry here as a new file+A pull request that changes the game (`sim/`, `content/`, `translations/`, `unity/`) can add its changelog entry here as a new fileinstead of editing [CHANGELOG.md](../CHANGELOG.md). Two pull requests never add the same file, so they never conflict.- Name the file after the branch or the issue: `changelog.d/<branch-or-issue>.md`, for example `changelog.d/1116.md`.diff --git a/docs/translations.md b/docs/translations.mdindex 9ebf21d27..44ad6922d 100644--- a/docs/translations.md+++ b/docs/translations.md@@ -8,8 +8,9 @@ read and write them the same way.**Status (steps 1 and 2 of #1618):** the contract and its tests, and the transport that brings `translations/` to thesim, the CLI and every player (below, "Loading"). The game still shows Hebrew from the inline `*_he` fields and`strings.he.yaml`; nothing has moved. `Translations.InlineHebrew` (sim) reads today's inline Hebrew as these files,-and the tests prove every value comes back unchanged. The tools' side (`tools/translate.py`, from #1604) joins the same-fixture check once #1604 has merged.+and the tests prove every value comes back unchanged. `tools/translate.py` (#1604) has the same reader,+`inline_hebrew()`, and the same key quoting (`_yaml_key`); `tools/tests/test_translate.py` holds it to the same fixture+bytes, so the tool and the game write one format.## The files@@ -65,8 +66,28 @@ These fields are facts about the record or its Hebrew, so they are never keys an`content/map/subdistricts_1948.geojson` (`name_he`, `district_he`) and `content/map/control_1948_49.geojson`(`legend_he`) hold Hebrew map labels that their digitisers write as a sourced set, next to the Arabic-(`tools/borders_digitise.py`, `tools/control_digitise.py`). Whether they stay in place or get keys is the owner's-decision on #1618; until then `TranslationsTests` names them, and fails if any other non-YAML content file has Hebrew.+(`tools/borders_digitise.py`, `tools/control_digitise.py`). The sub-districts' Hebrew stays in place, a documented+exception (owner, 25 October 2026, on #1618: "Keep in place, document it"), because it is sourced together with the+Arabic names to the Palestine Gazette, No. 1415. The front-line legends of `control_1948_49.geojson` wait for the+owner's decision. `TranslationsTests` names both files, and fails if any other non-YAML content file has Hebrew.++## Sign-offs and the review queue++A signed row's sign-off (`reviewed_by`, `reviewed_on`) covers its Hebrew wherever it lives: inline, or as the row's+entry in `he/events.yaml` (an event, by its id) or `he/content.yaml` (a record, by its keys). Hebrew moved with the+same decoded text keeps the sign-off (owner, 25 October 2026, on #1618: "Yes, carry them over"). The inline YAML and+`translations/he/` quote differently (a folded `>-` scalar becomes a double-quoted one), so "byte-identical moved text"+is read as the same decoded text: every character the same, direction marks, nikkud and maqaf included. `scripts/oss/reviewed_by_guard.py`+holds the line. A commit with an AI co-author trailer may take a signed row's Hebrew lines out of `content/` when the+row's Hebrew, read from both places, is the same before and after. Any other change to that Hebrew, in either place,+is an edit of the signed row, and a person must sign the row again.++`tools/review_queue.py` lists an entry's `review: agent-checked` just as it lists the inline `*_he_review` flag, with+the English record's row and sources (an event's `text_he_sources`, else its own `sources`).++A change to `translations/` is a change players get, so it needs a changelog entry (`scripts/oss/changelog_check.py`;+`translations/README.md` excepted). `tools/package_release.py` refuses a build whose `StreamingAssets/translations`+files and `bundle.json`'s packed texts differ, so the release gate checks the same translations every player reads.## Order and format@@ -76,7 +97,9 @@ ordinal order) and then by their position in the file.The body (everything after the header comment) is fixed byte for byte: block mappings, two-space indents, everystring double-quoted the way JSON writes it (`json.dumps(..., ensure_ascii=False)`), and a key plain only when it is-letters, digits, `_`, `.` and `-`. The header comment belongs to the tool that writes the file.+letters, digits, `_`, `.` and `-` and no YAML reader would type it: not a value the YAML 1.2 core schema reads as null, a+boolean or a number (`null`, `~`, `true`, `1948`, `1e3`, `.inf`), and not a YAML 1.1 boolean (`y`, `yes`, `on`, `off` and+their capitalised forms). Any other key is double-quoted (`Translations.Key()`, `tools/translate.py` `_yaml_key`). The header comment belongs to the tool that writes the file.## What the parser checks, and what it leaves to the content rules@@ -142,8 +165,8 @@ The UI strings still come from `strings.en.yaml` and `strings.he.yaml`; which ca`map/localities_1948.yaml`, `map/settlements_1948.yaml` and `map/units_1948.yaml` itself(`HebrewOverlay.UnityReads`).- `sim/Statecraft.Sim.Tests/translations_fixture/`: a small checkout with the edge cases and the bodies an- implementation must write for it. `TranslationsTests` checks the sim's; `tools/translate.py` (#1604) gets the same- check, so the tool and the game write one format.+ implementation must write for it. `TranslationsTests` checks the sim's and `tools/tests/test_translate.py` checks+ `tools/translate.py`'s (`inline_hebrew()`), so the tool and the game write one format.`TranslationsTests` also checks the real content:- every Hebrew value writes and reads back byte for byte;diff --git a/scripts/oss/changelog_check.py b/scripts/oss/changelog_check.pyindex 798e13113..f651b6a73 100755--- a/scripts/oss/changelog_check.py+++ b/scripts/oss/changelog_check.py@@ -14,9 +14,10 @@ import subprocessimport sysfrom collections.abc import Sequence-USER_VISIBLE = ("content/", "sim/Statecraft.Sim/", "sim/Statecraft.Cli/", "unity/Assets/", "unity/ProjectSettings/",- "unity/Packages/")-NOT_USER_VISIBLE = ("unity/Assets/Tests/",)+# translations/ ships beside the content to every player (#1618, step 2); its README.md is not a language (TranslationLoader).+USER_VISIBLE = ("content/", "translations/", "sim/Statecraft.Sim/", "sim/Statecraft.Cli/", "unity/Assets/",+ "unity/ProjectSettings/", "unity/Packages/")+NOT_USER_VISIBLE = ("unity/Assets/Tests/", "translations/README.md")FRAGMENTS = "changelog.d/"diff --git a/scripts/oss/reviewed_by_guard.py b/scripts/oss/reviewed_by_guard.pyindex 421fdc279..c09cabddb 100644--- a/scripts/oss/reviewed_by_guard.py+++ b/scripts/oss/reviewed_by_guard.py@@ -13,6 +13,14 @@ a person has signed off. For every commit in a pull request's range this fails wsign-off; a merge commit releases nothing);3. a person's added `reviewed_on` is after the day of their own commit.+A signed row's Hebrew counts as part of the row wherever it lives (owner, 25 October 2026, on #1618: "Yes, carry them+over"): inline (title_he, text_he, name_he_review ...) or as the row's entry in translations/he/events.yaml or+content.yaml (docs/translations.md). An AI-co-authored commit that only removes Hebrew field lines from a signed row and+leaves the row's Hebrew, read from both places, exactly as its parent had it (the same decoded text: the two places quote+differently, so the YAML's bytes cannot match), has moved it, and the sign-off covers it. Any other change to that Hebrew, in either place (a moved value that differs, a lost review flag, a+dropped option, an edit after the move), is an edit of the signed row under (2). The translation files are read whole+with the game's YAML 1.2 core schema, not diffed; one that does not parse fails closed.+"Co-wrote" is the trailer test of tools/review_queue.py (AI_MARK: "Co-Authored-By: Claude / Codex / Copilot / GPT ...","Generated with [Claude Code]" or "Generated with Codex"), read from each commit's full message. For (1) any non-commentline that names either key counts, quoted or not, block or flow style. A row's span is its mapping's lines@@ -59,6 +67,7 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools"))import yaml # noqa: E402from review_queue import AI_MARK, signed_rows # noqa: E402 (one definition of the trailer test and of a signed row)+import yaml12 # noqa: E402 (translations/ is read as the game reads it: the YAML 1.2 core schema)EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"PATHSPEC = [":(glob)content/**/*.yaml", ":(glob)content/**/*.yml"]@@ -75,6 +84,10 @@ CHECK = re.compile(r"\b(?:check|checks|checked|checking|verify|verified|comparedLIST_MARK = re.compile(r"^\s*(?:(?:\d+[.)]|[-*+])\s+|\[[ xX]\]\s*)")FENCE = re.compile(r"^ {0,3}(```|~~~)")KEYS = ("reviewed_by", "reviewed_on")+HE_EVENTS, HE_CONTENT = "translations/he/events.yaml", "translations/he/content.yaml"+HE_FIELD = re.compile(r"^( *)[\"']?[a-z_]+_he(?:_f)?(?:_review)?[\"']?\s*:")+HE_KEY = re.compile(r"(.+)_he(_f)?")+HE_NAME = re.compile(r"[a-z_]+_he(?:_f)?(?:_review)?") # a Hebrew field's key, as HE_FIELD reads it on a lineclass GuardError(Exception):@@ -272,6 +285,9 @@ def check(repo: Path, base: str, head: str, ai_disclosed: bool = False) -> list[except (subprocess.CalledProcessError, ValueError) as e:raise GuardError(f"cannot read commit {sha[:10]}") from eagent = AI_MARK.search(message) is not None+ moved: set[tuple[str, str, str, str]] = set() # (file, row, parent, the file at the parent): its Hebrew moved or changed+ if agent:+ moved |= _translated_rows(repo, sha, parents)for ch in files:named = [(cols, text) for hk in ch.hunks for cols, text in hk.lines if _named(text)]if agent:@@ -299,6 +315,9 @@ def check(repo: Path, base: str, head: str, ai_disclosed: bool = False) -> list[continueinserted = [t for cols, t in hk.lines if "+" in cols]if _touches(row, hk.old[p][0], hk.old[p][1], inserted):+ if len(parents) == 1 and _moves_hebrew_out(hk):+ moved.add((ch.path, row.label, parent, old)) # judged by its Hebrew, below+ continueedited.setdefault((ch.path, row.label), sha)breakif not ai_disclosed:@@ -339,6 +358,13 @@ def check(repo: Path, base: str, head: str, ai_disclosed: bool = False) -> list[if any(row.first <= n <= row.last for n in removed)}for label in released:edited.pop((ch.path, label), None)+ for path, label, parent, old in sorted(moved):+ # Owner, 25 October 2026 (#1618): a sign-off covers its row's Hebrew moved into translations/he/ with the same+ # decoded text;+ # any other change to that Hebrew, inline or there, is an edit of the signed row.+ before = _hebrew(repo, parent, old, label)+ if before is not None and before != _hebrew(repo, sha, path, label):+ edited.setdefault((path, label), sha)for (path, label), sha in edited.items():problems.append(f"{sha[:10]}: a commit with an AI co-author trailer edits {path} row {label!r}, which a person signed "f"off (owner, 15 October 2026: \"Block it in CI\"). A person must read it again and sign it again "@@ -346,6 +372,167 @@ def check(repo: Path, base: str, head: str, ai_disclosed: bool = False) -> list[return problems+def _moves_hebrew_out(hk: Hunk) -> bool:+ """True when a one-parent hunk only removes Hebrew text fields (title_he, text_he, name_he_review ...: a key with a+ text value on its line, or a quoted or block scalar with its lines): the Hebrew may have moved into translations/he/,+ which _hebrew judges. A key holding a list or a mapping (biography_sources.name_he, a source), an anchor or an alias+ is not Hebrew text, and neither is _he_sources or the title's form and date window: removing one is an edit. A+ flow-style row ({ ... } on one line) cannot lose a field without changing its line, so moving its Hebrew is an edit+ too, and a person signs it again."""+ indent = more = None+ for cols, text in hk.lines:+ if "+" in cols:+ return False+ m = HE_FIELD.match(text)+ if m and not text.lstrip().startswith("#"):+ value = text[m.end():].strip()+ if not value or value[0] in "[{&*-":+ return False+ indent, more = len(m.group(1)), value[0] in ">|\"'"+ elif indent is None or not more or (text.strip() and len(text) - len(text.lstrip(" ")) <= indent):+ return False+ return indent is not None+++def _records(node, ids: tuple = ()):+ """Every mapping under node with its key path, as tools/translate.py keys content: a list item by its id, else by its+ index."""+ if isinstance(node, yaml.MappingNode):+ yield ids, node+ for k, v in node.value:+ yield from _records(v, ids + (_scalar(k),))+ elif isinstance(node, yaml.SequenceNode):+ for i, item in enumerate(node.value):+ ident = next((v.value for k, v in item.value if _scalar(k) == "id" and isinstance(v, yaml.ScalarNode)), None) \+ if isinstance(item, yaml.MappingNode) else None+ yield from _records(item, ids + (ident if ident is not None else str(i),))+++def _scalar(node) -> str:+ return node.value if isinstance(node, yaml.ScalarNode) else ""+++def _translations(repo: Path, rev: str, rel: str) -> dict:+ text = _show(repo, rev, rel)+ if text is None:+ return {}+ try:+ data = yaml12.load(text) or {}+ except yaml.YAMLError as e:+ raise GuardError(f"cannot parse {rel} at {rev[:10]}") from e+ if not isinstance(data, dict):+ raise GuardError(f"{rel} at {rev[:10]} is not a mapping")+ return data+++def _hebrew(repo: Path, rev: str, path: str, label: str) -> dict[str, set] | None:+ """The Hebrew a signed row carries at a revision, inline and in translations/he/, by the translation key: the value+ (and its review flag) from each place that has one, as decoded text. Equal on both sides of a commit when it moved the+ Hebrew with the same text; None when the row is not signed there. Every Hebrew field an event or one of its options+ carries counts: one with no place in translations/he/ (title_he_f, an option's text_he_review) keeps its own key, so+ removing it is an edit, never a move."""+ text = _show(repo, rev, path)+ row = next((r for r in (_signed(repo, rev, path, must_exist=False) if text is not None else []) if r.label == label), None)+ if row is None:+ return None+ out: dict[str, set] = {}++ def put(key: str, value) -> None: # a value that is not text never equals the inline Hebrew: it fails closed+ out.setdefault(key, set()).add(value if isinstance(value, str) else ("not text", repr(value)))++ rel = path.removeprefix("content/")+ root = yaml.compose(text)+ if rel.startswith("events/"):+ top = {_scalar(k): v for k, v in root.value} if isinstance(root, yaml.MappingNode) else {}+ moved = {"title_he": "title", "text_he": "text", "text_he_review": "review"}+ for field, node in top.items():+ if HE_NAME.fullmatch(field):+ put(moved.get(field, "inline:" + field), node.value if isinstance(node, yaml.ScalarNode) else repr(node))+ for i, o in enumerate(top["options"].value if isinstance(top.get("options"), yaml.SequenceNode) else []):+ kv = {_scalar(k): v for k, v in o.value} if isinstance(o, yaml.MappingNode) else {}+ oid = kv["id"].value if isinstance(kv.get("id"), yaml.ScalarNode) else f"#{i}"+ for field, node in kv.items():+ if HE_NAME.fullmatch(field):+ value = node.value if isinstance(node, yaml.ScalarNode) else repr(node)+ put(f"option:{oid}" if field == "text_he" else f"option:{oid}:inline:{field}", value)+ entry = _translations(repo, rev, HE_EVENTS).get(label)+ if isinstance(entry, dict):+ for key in ("title", "text", "review"):+ if key in entry:+ put(key, entry[key])+ options = entry.get("options")+ for oid, value in (options if isinstance(options, dict) else {"(options)": options} if options else {}).items():+ put(f"option:{oid}", value)+ return out+ inside = {".".join(ids): node for ids, node in _records(root) if row.first <= node.start_mark.line + 1 <= row.last}+ for where, node in inside.items():+ for k, v in node.value:+ m = HE_KEY.fullmatch(_scalar(k).removesuffix("_review"))+ if m and isinstance(v, yaml.ScalarNode):+ field = f"{rel}#{where}.{m.group(1)}{'_f' if m.group(2) else ''}"+ put(field + (":review" if _scalar(k).endswith("_review") else ""), v.value)+ for key, entry in _translations(repo, rev, HE_CONTENT).items():+ file, _, rest = str(key).partition("#")+ if file == rel and rest.rpartition(".")[0] in inside and isinstance(entry, dict):+ put(key, entry.get("text"))+ if "review" in entry:+ put(key + ":review", entry["review"])+ return out+++def _translated_rows(repo: Path, sha: str, parents: list[str]) -> set[tuple[str, str, str, str]]:+ """The signed rows whose entry in translations/he/events.yaml or content.yaml this commit changes against a parent+ (a merge: against every parent), as (file, row, parent, file): the content file is named by the key."""+ out = set()+ for rel in (HE_EVENTS, HE_CONTENT):+ now = _translations(repo, sha, rel)+ befores = [(p, _translations(repo, p, rel)) for p in parents]+ changed = {k for k in set(now).union(*(b for _, b in befores)) if all(now.get(k) != b.get(k) for _, b in befores)}+ for parent, before in befores:+ for key in sorted(changed, key=str):+ if rel == HE_EVENTS:+ path = _event_file(repo, parent, str(key))+ label = str(key)+ else:+ file, _, rest = str(key).partition("#")+ path, label = "content/" + file, _row_of(repo, parent, "content/" + file, rest.rpartition(".")[0])+ if path and label:+ out.add((path, label, parent, path))+ return out+++def _event_file(repo: Path, rev: str, eid: str) -> str | None:+ """The content/events/ file whose id is eid at a revision (by name first, then by reading each)."""+ guess = f"content/events/{eid}.yaml"+ names = [n for n in _git(["ls-tree", "-r", "--name-only", rev, "--", "content/events/"], repo).splitlines()+ if n.endswith((".yaml", ".yml"))]+ for name in sorted(names, key=lambda n: n != guess):+ text = _show(repo, rev, name)+ try:+ root = yaml.compose(text) if text else None+ except yaml.YAMLError as e:+ raise GuardError(f"cannot parse {name} at {rev[:10]}") from e+ if isinstance(root, yaml.MappingNode) and any(_scalar(k) == "id" and _scalar(v) == eid for k, v in root.value):+ return name+ return None+++def _row_of(repo: Path, rev: str, path: str, where: str) -> str | None:+ """The label of the signed row holding the record at this key path at a revision, if one does."""+ text = _show(repo, rev, path)+ if text is None:+ return None+ try:+ record = next((n for ids, n in _records(yaml.compose(text)) if ".".join(ids) == where), None)+ except yaml.YAMLError as e:+ raise GuardError(f"cannot parse {path} at {rev[:10]}") from e+ if record is None:+ return None+ line = record.start_mark.line + 1+ rows = [r for r in _signed(repo, rev, path, must_exist=True) if r.first <= line <= r.last]+ return min(rows, key=lambda r: r.last - r.first).label if rows else None++def main(argv: list[str] | None = None) -> int:ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])ap.add_argument("--base", required=True)diff --git a/scripts/oss/tests/test_changelog_check.py b/scripts/oss/tests/test_changelog_check.pyindex 2f33dea65..e39d1959c 100644--- a/scripts/oss/tests/test_changelog_check.py+++ b/scripts/oss/tests/test_changelog_check.py@@ -23,10 +23,15 @@ def test_tests_docs_tools_and_ci_need_no_entry():def test_every_user_visible_root_is_named():for p in ("content/people.yaml", "sim/Statecraft.Sim/Rng.cs", "sim/Statecraft.Cli/Program.cs",- "unity/Assets/UI/Game.uxml", "unity/ProjectSettings/ProjectSettings.asset", "unity/Packages/manifest.json"):+ "unity/Assets/UI/Game.uxml", "unity/ProjectSettings/ProjectSettings.asset", "unity/Packages/manifest.json",+ "translations/he/events.yaml", "translations/ro/ui.yaml"):assert cc.user_visible([p]) == [p], p+def test_the_translations_readme_is_not_a_language():+ assert cc.user_visible(["translations/README.md"]) == []++def test_an_added_fragment_satisfies_it_and_the_failure_names_that_way():ok, msg = cc.verdict(["content/people.yaml", "changelog.d/1180.md"], skip_label=False,fragments=["changelog.d/1180.md"])diff --git a/scripts/oss/tests/test_reviewed_by_guard.py b/scripts/oss/tests/test_reviewed_by_guard.pyindex 21e1f3972..96f42376c 100644--- a/scripts/oss/tests/test_reviewed_by_guard.py+++ b/scripts/oss/tests/test_reviewed_by_guard.py@@ -468,3 +468,181 @@ def test_a_heading_inside_a_code_fence_is_not_a_section():assert guard.ai_assistance(fenced) == "None" and not guard.disclosed(fenced)inside = TEMPLATE.format(ai="Claude Code drafted it; I checked each date:\n```\n# a shell comment\n```")assert "a shell comment" in guard.ai_assistance(inside) and guard.disclosed(inside)+++# ---- translations/he/ (owner, 25 October 2026, #1618: "Yes, carry them over") ----++EVENT = """id: vote+title: The vote+title_he: "ההצבעה"+text: Vote now?+text_he: >-+ להצביע+ עכשיו?+text_he_review: agent-checked+options:+ - id: yes_vote+ text: Vote+ text_he: "להצביע"+status: fact-checked+reviewed_by: eyalgolan+reviewed_on: 2026-10-15+"""+EVENT_EN = EVENT.replace('title_he: "ההצבעה"\n', "").replace("text_he: >-\n להצביע\n עכשיו?\n", "") \+ .replace("text_he_review: agent-checked\n", "").replace(' text_he: "להצביע"\n', "")+EVENT_HE = 'vote:\n title: "ההצבעה"\n text: "להצביע עכשיו?"\n options:\n yes_vote: "להצביע"\n review: "agent-checked"\n'+PERSON = SIGNED.replace(" name: A\n", ' name: A\n name_he: "א"\n name_he_review: agent-checked\n')+PERSON_HE = '"people.yaml#people.a.name":\n text: "א"\n review: "agent-checked"\n'+++def event_repo(tmp_path, text=EVENT, he=None):+ root, base = repo(tmp_path)+ (root / "content" / "events").mkdir()+ edit(root, text, "content/events/vote.yaml")+ if he is not None:+ (root / "translations" / "he").mkdir(parents=True)+ edit(root, he, "translations/he/events.yaml")+ return root, commit(root, "content: the vote")+++def move(root, en, he, rel, he_rel):+ edit(root, en, rel)+ (root / "translations" / "he").mkdir(parents=True, exist_ok=True)+ edit(root, he, he_rel)+++def test_an_agent_may_move_a_signed_events_hebrew_with_the_same_decoded_text(tmp_path):+ root, base = event_repo(tmp_path)+ move(root, EVENT_EN, EVENT_HE, "content/events/vote.yaml", "translations/he/events.yaml")+ commit(root, "languages: move the events' Hebrew" + AI)+ assert EVENT_EN.count("_he") == 0 and guard.check(root, base, "HEAD") == []++[email protected]("he", [EVENT_HE.replace("עכשיו", "כעת"), EVENT_HE.replace(' review: "agent-checked"\n', ""),+ EVENT_HE.replace(' yes_vote: "להצביע"\n', ""), ""])+def test_a_move_that_changes_drops_or_loses_the_hebrew_is_an_edit(tmp_path, he):+ root, base = event_repo(tmp_path)+ move(root, EVENT_EN, he, "content/events/vote.yaml", "translations/he/events.yaml")+ commit(root, "languages: move the events' Hebrew" + AI)+ problems = guard.check(root, base, "HEAD")+ assert len(problems) == 1 and "content/events/vote.yaml row 'vote'" in problems[0]+++def test_a_move_that_also_edits_the_english_is_an_edit(tmp_path):+ root, base = event_repo(tmp_path)+ move(root, EVENT_EN.replace("Vote now?", "Vote today?"), EVENT_HE, "content/events/vote.yaml", "translations/he/events.yaml")+ commit(root, "languages: move the events' Hebrew" + AI)+ assert len(guard.check(root, base, "HEAD")) == 1+++def test_an_agent_edit_of_a_moved_signed_translation_fails_until_a_person_signs_again(tmp_path):+ root, base = event_repo(tmp_path, EVENT_EN, EVENT_HE)+ edit(root, EVENT_HE.replace("עכשיו", "כעת"), "translations/he/events.yaml")+ sha = commit(root, "languages: reword" + AI)+ problems = guard.check(root, base, "HEAD")+ assert len(problems) == 1 and sha[:10] in problems[0] and "row 'vote'" in problems[0]+ edit(root, EVENT_EN.replace("2026-10-15", "2026-10-16"), "content/events/vote.yaml")+ commit(root, "content: read the vote again", date="2026-10-16T12:00:00+00:00")+ assert guard.check(root, base, "HEAD") == []+++def test_an_agent_may_translate_an_unsigned_event(tmp_path):+ unsigned = EVENT_EN.replace("reviewed_by: eyalgolan\nreviewed_on: 2026-10-15\n", "")+ root, base = event_repo(tmp_path, unsigned, EVENT_HE)+ edit(root, EVENT_HE.replace("עכשיו", "כעת"), "translations/he/events.yaml")+ commit(root, "languages: reword" + AI)+ assert guard.check(root, base, "HEAD") == []+++def test_an_agent_may_move_a_signed_rows_content_hebrew_but_not_edit_it(tmp_path):+ root, base = repo(tmp_path, PERSON)+ move(root, SIGNED, PERSON_HE, "content/people.yaml", "translations/he/content.yaml")+ commit(root, "languages: move the names" + AI)+ assert guard.check(root, base, "HEAD") == []+ edit(root, PERSON_HE.replace('"א"', '"אָ"'), "translations/he/content.yaml")+ sha = commit(root, "languages: a vowel" + AI)+ problems = guard.check(root, base, "HEAD")+ assert len(problems) == 1 and sha[:10] in problems[0] and "content/people.yaml row 'a'" in problems[0]+++def test_dropping_a_signed_rows_hebrew_without_moving_it_is_an_edit(tmp_path):+ root, base = repo(tmp_path, PERSON)+ edit(root, SIGNED)+ commit(root, "content: drop the name" + AI)+ assert len(guard.check(root, base, "HEAD")) == 1+++def test_an_unreadable_translation_fails_closed(tmp_path):+ root, base = event_repo(tmp_path)+ move(root, EVENT_EN, "vote: [", "content/events/vote.yaml", "translations/he/events.yaml")+ commit(root, "languages: move" + AI)+ with pytest.raises(guard.GuardError, match="cannot parse translations/he/events.yaml"):+ guard.check(root, base, "HEAD")+++def test_removing_a_hebrew_names_source_is_not_a_move(tmp_path):+ """biography_sources.name_he holds a source, not Hebrew text: dropping it from a signed row is an edit."""+ name = ' name_he: [{ url: "https://example.org/a", checked: 2026-10-14 }]\n'+ sourced = PERSON + " biography_sources:\n" + name + ' name: [{ url: "https://example.org/b", checked: 2026-10-14 }]\n'+ root, base = repo(tmp_path, sourced)+ edit(root, sourced.replace(name, ""))+ commit(root, "content: drop a source" + AI)+ assert len(guard.check(root, base, "HEAD")) == 1+ root2, base2 = repo(tmp_path / "two", PERSON + " name_he_sources:\n - https://example.org/a\n")+ edit(root2, PERSON)+ commit(root2, "content: drop a source" + AI)+ assert len(guard.check(root2, base2, "HEAD")) == 1+++# Owner review of #2501: moves that change where the text goes, or what it decodes to, are edits.+[email protected]("he", [+ EVENT_HE.replace("vote:", "other:"), # another event (row)+ EVENT_HE.replace("yes_vote:", "no_vote:"), # another option+ EVENT_HE.replace(" title: ", " text_f: "), # another field+ EVENT_HE.replace("עכשיו", "עכשיו"), # an added left-to-right mark+ EVENT_HE.replace("עכשיו", "עכשיו"), # an added right-to-left mark+ EVENT_HE.replace("להצביע עכשיו", "להצביע־עכשיו"), # a maqaf for the space+ EVENT_HE.replace('"להצביע עכשיו?"', '"להצביע\\nעכשיו?"'), # a quoting that keeps the line break+])+def test_a_move_to_another_place_or_to_other_decoded_text_is_an_edit(tmp_path, he):+ root, base = event_repo(tmp_path)+ move(root, EVENT_EN, he, "content/events/vote.yaml", "translations/he/events.yaml")+ commit(root, "languages: move the events' Hebrew" + AI)+ problems = guard.check(root, base, "HEAD")+ assert len(problems) == 1 and "row 'vote'" in problems[0], problems+++def test_a_content_name_moved_to_another_record_is_an_edit(tmp_path):+ two = PERSON + " - id: b\n name: B\n"+ root, base = repo(tmp_path, two)+ move(root, SIGNED + " - id: b\n name: B\n", PERSON_HE.replace("people.a.name", "people.b.name"),+ "content/people.yaml", "translations/he/content.yaml")+ commit(root, "languages: move the names" + AI)+ problems = guard.check(root, base, "HEAD")+ assert len(problems) == 1 and "row 'a'" in problems[0], problems+++def test_a_move_split_over_two_commits_is_an_edit(tmp_path):+ """Removing the inline Hebrew in one commit and adding the same text to translations/he/ in the next: the first+ commit drops the signed row's Hebrew, so it is an edit, whatever the next one does."""+ root, base = event_repo(tmp_path)+ edit(root, EVENT_EN, "content/events/vote.yaml")+ first = commit(root, "languages: drop the Hebrew" + AI)+ (root / "translations" / "he").mkdir(parents=True)+ edit(root, EVENT_HE, "translations/he/events.yaml")+ commit(root, "languages: add it back" + AI)+ problems = guard.check(root, base, "HEAD")+ assert len(problems) == 1 and first[:10] in problems[0], problems++[email protected]("extra", ['title_he_f: "ההצבעה"\n', # no place in translations/he/+ ' text_he_review: agent-checked\n']) # an option's own flag+def test_removing_a_hebrew_field_translations_cannot_hold_is_an_edit(tmp_path, extra):+ anchor = ' text_he: "להצביע"\n' if extra.startswith(" ") else 'title_he: "ההצבעה"\n'+ signed = EVENT.replace(anchor, anchor + extra)+ root, base = event_repo(tmp_path, signed)+ move(root, EVENT_EN, EVENT_HE, "content/events/vote.yaml", "translations/he/events.yaml")+ commit(root, "languages: move the events' Hebrew" + AI)+ problems = guard.check(root, base, "HEAD")+ assert len(problems) == 1 and "row 'vote'" in problems[0], problemsdiff --git a/sim/Statecraft.Sim.Tests/translations_fixture/README.md b/sim/Statecraft.Sim.Tests/translations_fixture/README.mdindex 027048764..697e37048 100644--- a/sim/Statecraft.Sim.Tests/translations_fixture/README.md+++ b/sim/Statecraft.Sim.Tests/translations_fixture/README.md@@ -3,7 +3,7 @@A small checkout for the translation contract (#1618, [docs/translations.md](../../../docs/translations.md)): `content/`and `ui/` hold inline Hebrew with the cases the contract must handle, and `expected/he/` holds the bodies (the fileswithout their header comment) an implementation must write for it. `TranslationsTests` (sim) checks the sim writes-exactly these bytes; once #1604 has merged, `tools/tests/test_translate.py` checks `tools/translate.py` does too, so the+exactly these bytes, and `tools/tests/test_translate.py` checks `tools/translate.py` does too, so thetool and the game stay one contract.The cases: events ordered by date, then id (`alpha` before `vote` on the same day; `quiet` has no Hebrew); a review flagdiff --git a/tools/package_release.py b/tools/package_release.pyindex 11672df41..bbe91ac9a 100644--- a/tools/package_release.py+++ b/tools/package_release.py@@ -16,6 +16,11 @@ Build.Web names the files under Build/ by their content hash (issue #437), so thindex.html is what says which ones belong to this build. The zip carries exactly the Build/ files index.html names: itis 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.++The translations ship twice (#1618, step 2): as files in StreamingAssets/translations, which desktop players and the gate+read, and as texts packed into StreamingAssets/content/bundle.json, which the web player reads. The zip is refused unless+manifest.json and bundle.json name exactly the files in StreamingAssets/translations and each packed text is that file's+text, so the gate checks the translations every player gets and a lost or changed file never falls back silently."""import argparseimport json@@ -61,6 +66,41 @@ def photo_refusal(build: Path):return None+def _shipped_translations(folder: Path) -> list[str]:+ """The language files under a build's translations folder as "<lang>/<file>", ordinal order (TranslationLoader.Collect+ and ContentManifest.Verify: top-level files and hidden names are not translations)."""+ if not folder.is_dir():+ return []+ return sorted(p.relative_to(folder).as_posix() for p in folder.rglob("*")+ if p.is_file() and p.parent != folder and not any(part.startswith(".") for part in p.relative_to(folder).parts))+++def translation_refusal(build: Path):+ """Why the build's translations do not match what its web bundle carries, or None (see the module docstring)."""+ content, folder = build / "StreamingAssets" / "content", build / "StreamingAssets" / "translations"+ try:+ listed = json.loads((content / "manifest.json").read_text(encoding="utf-8")).get("translations") or []+ bundle = json.loads((content / "bundle.json").read_text(encoding="utf-8"))+ packed, texts = bundle.get("translations") or [], bundle.get("translationTexts") or []+ if not all(isinstance(x, list) for x in (listed, packed, texts)):+ raise TypeError("translations and translationTexts must be lists")+ except (OSError, ValueError, AttributeError, TypeError) as e:+ return f"{content} has no readable manifest.json and bundle.json ({e}): build it with Build.Web, which writes them"+ found = _shipped_translations(folder)+ if not listed == packed == found:+ return (f"the translations do not match: manifest.json lists {listed}, bundle.json packs {packed}, "+ f"StreamingAssets/translations holds {found}")+ if len(texts) != len(packed):+ return f"bundle.json packs {len(packed)} translation files but {len(texts)} texts"+ try:+ changed = [f for f, text in zip(packed, texts) if (folder / f).read_text(encoding="utf-8") != text]+ except (OSError, UnicodeDecodeError) as e:+ return f"a file in StreamingAssets/translations cannot be read as UTF-8 text ({e})"+ if changed:+ return "bundle.json's text differs from StreamingAssets/translations for " + ", ".join(changed)+ return None++BUILD_FILE = re.compile(r'"Build/([^"/]+)"') # as the WebGL template writes them (src="Build/..", dataUrl: "Build/..")@@ -85,6 +125,9 @@ def package(build: Path, zip_path: Path) -> int:if (photos := photo_refusal(build)) is not None:print(f"PACKAGE REFUSED: {photos}")return 1+ if (translations := translation_refusal(build)) is not None:+ print(f"PACKAGE REFUSED: {translations}")+ return 1ok, message = gate(content)print(message)if not ok:diff --git a/tools/review_queue.py b/tools/review_queue.pyindex 26bcf125a..33f5175ca 100644--- a/tools/review_queue.py+++ b/tools/review_queue.py@@ -5,12 +5,14 @@"""Lists the content that no named person has reviewed yet and that an AI agent may have checked (CONTENT_POLICYsection 2, rule 6), so the owner can work through it: docs/review-queue.md.-Read-only on content/: it parses the YAML and asks git, and writes only the Markdown page (or prints it).+Read-only on content/ and translations/: it parses the YAML and asks git, and writes only the Markdown page (or prints it).Two kinds of entry:1. **Agent-checked Hebrew names**: every `*_review: agent-checked` flag (`name_he_review`, `title_he_review`,- `title_he_f_review`, `body_he_review`; #564). The flag itself says no person has read the name.+ `title_he_f_review`, `body_he_review`; #564), and every `review: agent-checked` entry of translations/he/content.yaml+ and events.yaml, where the Hebrew moves (#1618), listed with its English record's row and sources. The flag itself+ says no person has read the name.2. **Reviewed statuses last written by a commit with an AI co-author trailer**: every row whose `status` is`fact-checked`, `historian-reviewed` or `sensitivity-reviewed`, where the line that holds that status was lastwritten by such a commit.@@ -209,12 +211,8 @@ def scan(text: str, rel: str) -> list[Entry]:m = FLAG_KEY.match(key)if m and _scalar(node) == FLAG:name = m.group("field")- source_node = keys.get(name + "_sources")- # People keep a field's sources under biography_sources.<field> (content/people.yaml).- if source_node is None and isinstance(keys.get("biography_sources"), yaml.MappingNode):- source_node = {_scalar(k): v for k, v in keys["biography_sources"].value}.get(name)entries.append(Entry("flag", rel, node.start_mark.line + 1, label, name, _scalar(keys.get(name)) if name in keys else "",- _urls(source_node) if source_node is not None else []))+ _field_sources(keys, name)))status = keys.get("status")if status is not None and _scalar(status) in STATUSES:# A whole sign-off by a person (#375) takes the row out of the queue; a malformed one does not (fail closed).@@ -224,6 +222,72 @@ def scan(text: str, rel: str) -> list[Entry]:return entries+def _field_sources(keys: dict, name: str) -> list[str]:+ """The source URLs of a Hebrew field (name_he ...), kept on its English record: <field>_sources, or, for people,+ biography_sources.<field> (content/people.yaml)."""+ source_node = keys.get(name + "_sources")+ if source_node is None and isinstance(keys.get("biography_sources"), yaml.MappingNode):+ source_node = {_scalar(k): v for k, v in keys["biography_sources"].value}.get(name)+ return _urls(source_node) if source_node is not None else []+++def _records(node, ids: tuple = ()):+ """Every mapping under node with its key path, as tools/translate.py keys content: a list item by its id, else its+ index."""+ if isinstance(node, yaml.MappingNode):+ yield ids, node+ for k, v in node.value:+ yield from _records(v, ids + (_scalar(k),))+ elif isinstance(node, yaml.SequenceNode):+ for i, item in enumerate(node.value):+ ident = next((v.value for k, v in item.value if _scalar(k) == "id" and isinstance(v, yaml.ScalarNode)), None) \+ if isinstance(item, yaml.MappingNode) else None+ yield from _records(item, ids + (ident if ident is not None else str(i),))+++HE_TRANSLATIONS = ("translations/he/content.yaml", "translations/he/events.yaml")+++def scan_translations(repo: Path, rel: str) -> list[Entry]:+ """The agent-checked flags of a translations/he/ file (#1618; docs/translations.md): each entry whose `review` is+ agent-checked, listed as the inline flag it replaces, with the row and sources of its English record (the sources stay+ there): a content entry's record by its key; an event's by its id, with its text_he_sources, else the event's own+ sources."""+ root = yaml.compose((repo / rel).read_text(encoding="utf-8"))+ entries: list[Entry] = []+ parsed: dict[str, dict] = {}+ events: dict[str, dict] | None = None+ for k, v in root.value if isinstance(root, yaml.MappingNode) else []:+ keys = {_scalar(a): b for a, b in v.value} if isinstance(v, yaml.MappingNode) else {}+ if _scalar(keys.get("review")) != FLAG:+ continue+ key, line = _scalar(k), keys["review"].start_mark.line + 1+ if rel.endswith("events.yaml"):+ if events is None:+ events = {}+ for path in sorted((repo / "content" / "events").glob("*.yaml")):+ tree = yaml.compose(path.read_text(encoding="utf-8"))+ top = {_scalar(a): b for a, b in tree.value} if isinstance(tree, yaml.MappingNode) else {}+ if "id" in top:+ events[_scalar(top["id"])] = top+ event = events.get(key, {})+ sources = _field_sources(event, "text_he") or (_urls(event["sources"]) if "sources" in event else [])+ entries.append(Entry("flag", rel, line, key, "text_he", _scalar(keys.get("text")), sources))+ continue+ file, _, rest = key.partition("#")+ where, _, name = rest.rpartition(".")+ if file not in parsed:+ path = repo / "content" / file+ tree = yaml.compose(path.read_text(encoding="utf-8")) if path.is_file() else None+ parsed[file] = {".".join(ids): n for ids, n in _records(tree)}+ record = parsed[file].get(where)+ fields = {_scalar(a): b for a, b in record.value} if record is not None else {}+ he = name.removesuffix("_f") + "_he" + ("_f" if name.endswith("_f") else "")+ label = _scalar(fields["id"]) if "id" in fields else where+ entries.append(Entry("flag", rel, line, label, he, _scalar(keys.get("text")), _field_sources(fields, he)))+ return entries++def _git(args: list[str], cwd: Path) -> str:return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout@@ -300,6 +364,11 @@ def queue(repo: Path) -> tuple[list[Entry], int, int]:entries.append(e)else:human += 1+ for rel in HE_TRANSLATIONS:+ if (repo / rel).is_file():+ for e in scan_translations(repo, rel):+ e.checked_by = f"an AI agent (the `{FLAG}` flag)"+ entries.append(e)return entries, human, signeddiff --git a/tools/tests/test_package_release.py b/tools/tests/test_package_release.pyindex ba4d9d238..a376f3af5 100644--- a/tools/tests/test_package_release.py+++ b/tools/tests/test_package_release.py@@ -53,9 +53,23 @@ def fake_build(tmp_path, reviewed, photos_reviewed=True, forces_checked=True, al"reviewed_by: package-fixture-reviewer\nreviewed_on: 2026-10-24\n")f.write_text(text, encoding="utf-8")photo_manifest(build, reviewed=photos_reviewed)+ ship_translations(build)return build+def ship_translations(build):+ """The translations as ContentSync ships them: the files beside the content, listed in manifest.json and packed into+ bundle.json (only the fields package_release reads)."""+ folder = build / "StreamingAssets" / "translations"+ shutil.copytree(REPO / "translations", folder, dirs_exist_ok=True)+ files = package_release._shipped_translations(folder)+ content = build / "StreamingAssets" / "content"+ (content / "manifest.json").write_text(json.dumps({"files": [], "translations": files}))+ (content / "bundle.json").write_text(json.dumps(+ {"translations": files, "translationTexts": [(folder / f).read_text(encoding="utf-8") for f in files]}, ensure_ascii=False))+ return files++def test_packaging_is_refused_until_every_sensitive_event_is_reviewed(tmp_path, capsys):build, zip_path = fake_build(tmp_path, reviewed=False), tmp_path / "out.zip"assert package_release.main(["--build", str(build), "--zip", str(zip_path)]) == 1@@ -181,3 +195,35 @@ def test_a_build_missing_a_file_index_html_names_is_refused(tmp_path, capsys):build = hashed_build(tmp_path)(build / "Build" / HASHED[3]).unlink()assert "Build/" + HASHED[3] in refused(build, tmp_path, capsys)+++def test_the_zip_carries_the_translations_the_web_bundle_packs(tmp_path, capsys):+ build, zip_path = fake_build(tmp_path, reviewed=True), tmp_path / "out.zip"+ assert package_release.translation_refusal(build) is None+ assert package_release.main(["--build", str(build), "--zip", str(zip_path)]) == 0+ with zipfile.ZipFile(zip_path) as z:+ assert "StreamingAssets/translations/ro/events.yaml" in z.namelist()+++def test_a_lost_changed_or_unlisted_translation_is_refused(tmp_path, capsys):+ """#1618: the gate reads StreamingAssets/translations and the web player bundle.json; they must be one set."""+ build = fake_build(tmp_path, reviewed=True)+ folder = build / "StreamingAssets" / "translations"+ (folder / "ro" / "ui.yaml").unlink()+ assert "do not match" in refused(build, tmp_path, capsys)+ ship_translations(build)+ (folder / "ro" / "ui.yaml").write_text("ui.lang: \"xx\"\n", encoding="utf-8")+ assert "differs from StreamingAssets/translations for ro/ui.yaml" in refused(build, tmp_path, capsys)+ ship_translations(build)+ (folder / "ro" / "content.yaml").write_text("{}\n", encoding="utf-8")+ assert "do not match" in refused(build, tmp_path, capsys)+ (folder / "ro" / "content.yaml").unlink()+ ship_translations(build)+ (folder / "ro" / "ui.yaml").write_bytes(b"ui.lang: \"\xff\"\n") # not UTF-8: a refusal, not a crash+ assert "cannot be read as UTF-8 text" in refused(build, tmp_path, capsys)+ ship_translations(build)+ (folder / ".DS_Store").write_text("x") # hidden and top-level names are never translations+ (folder / "README.md").write_text("x")+ assert package_release.translation_refusal(build) is None+ (build / "StreamingAssets" / "content" / "bundle.json").unlink()+ assert "no readable manifest.json and bundle.json" in refused(build, tmp_path, capsys)diff --git a/tools/tests/test_review_queue.py b/tools/tests/test_review_queue.pyindex e87a447d1..c086c3683 100644--- a/tools/tests/test_review_queue.py+++ b/tools/tests/test_review_queue.py@@ -230,3 +230,25 @@ def test_a_row_a_person_signed_off_leaves_the_queue_and_is_counted(tmp_path):gov.write_text(gov.read_text(encoding="utf-8").replace("reviewed_by: eyalgolan", "reviewed_by: [email protected]"), encoding="utf-8")entries, human, signed = rq.queue(repo)assert [e.row for e in entries if e.kind == "status"] == ["g1"] and signed == 0+++def test_a_moved_hebrew_flag_is_listed_with_its_english_records_row_and_sources(tmp_path):+ """#1618: after the Hebrew moves into translations/he/, its agent-checked flags stay in the queue, with the row and the+ sources of the English record (the sources stay there)."""+ repo = make_repo(tmp_path)+ (repo / "content" / "people.yaml").write_text(PEOPLE.replace(" name_he: איש לדוגמה\n name_he_review: agent-checked\n", ""),+ encoding="utf-8")+ (repo / "translations" / "he").mkdir(parents=True)+ (repo / "translations" / "he" / "content.yaml").write_text(+ '"people.yaml#people.example.name":\n text: "איש לדוגמה"\n review: "agent-checked"\n'+ '"offices.yaml#offices.fm.title":\n text: "שר האוצר"\n', encoding="utf-8")+ (repo / "translations" / "he" / "events.yaml").write_text(+ 'truce:\n title: "הפוגה"\n text: "הפוגה."\n options:\n ok: "בסדר"\n review: "agent-checked"\n', encoding="utf-8")+ git(repo, "add", "-A")+ git(repo, "commit", "-q", "-m", "languages: move the Hebrew")+ entries, _, _ = rq.queue(repo)+ moved = [(e.file, e.line, e.row, e.field, e.value, e.sources) for e in entries if e.file.startswith("translations/")]+ assert moved == [("translations/he/content.yaml", 3, "example", "name_he", "איש לדוגמה", ["https://example.org/hebrew-name"]),+ ("translations/he/events.yaml", 6, "truce", "text_he", "הפוגה.", ["https://example.org/truce"])]+ assert all(e.checked_by == "an AI agent (the `agent-checked` flag)" for e in entries if e.file.startswith("translations/"))+ assert "| example | name_he | איש לדוגמה | <https://example.org/hebrew-name> |" in rq.page(entries, 0, "0123456789abcdef")diff --git a/tools/tests/test_translate.py b/tools/tests/test_translate.pyindex d40e547fd..f18de16af 100644--- a/tools/tests/test_translate.py+++ b/tools/tests/test_translate.py@@ -296,3 +296,37 @@ def test_advisors_and_encyclopedia_stay_english_or_hebrew(langs):key = next(r["key"] for r in translate.catalog() if r["key"].startswith("ui:encyclopedia."))with pytest.raises(translate.Refused, match="English or Hebrew only"):translate.save("fr", {key: "Comment jouer"}, {}, dry=True)+++FIXTURE = translate.ROOT / "sim/Statecraft.Sim.Tests/translations_fixture"+++def test_inline_hebrew_writes_the_shared_fixture_byte_for_byte():+ # The sim's TranslationsTests checks Translations.InlineHebrew + Write against the same expected bodies (#1626).+ got = translate.inline_hebrew(FIXTURE / "content", FIXTURE / "ui/strings.en.yaml", FIXTURE / "ui/strings.he.yaml")+ for name, body in zip(("ui", "events", "content"), got):+ assert body == (FIXTURE / f"expected/he/{name}.yaml").read_text(encoding="utf-8"), name+++def test_inline_hebrew_reads_back_as_the_real_hebrew():+ ui, events, content = translate.inline_hebrew(translate.CONTENT, translate.UI_EN, translate.UI_HE)+ texts, flagged = translate.load("he")+ assert {f"ui:{k}": v for k, v in yaml12.load(ui).items()} == {k: v for k, v in texts.items() if k.startswith("ui:")}+ back = {f"content:{k}": e["text"] for k, e in yaml12.load(content).items()}+ assert back == {k: v for k, v in texts.items() if k.startswith("content:")}+ assert {f"content:{k}" for k, e in yaml12.load(content).items() if e.get("review")} == \+ {k for k in flagged if k.startswith("content:")}+ assert {f"event:{k}" for k, e in yaml12.load(events).items() if e.get("review")} == \+ {k for k in flagged if k.startswith("event:")}++[email protected]("key", ["1948", "null", "Null", "~", "true", "FALSE", "1e3", ".5", "-1", "0x1f", ".inf",+ "on", "Off", "yes", "N", "y", "a b", "a:b", ""])+def test_a_key_any_yaml_reader_would_type_or_split_is_quoted(key):+ out = translate._dump("", {key: "x"})+ assert out.startswith('"') and yaml12.load(out) == {key: "x"}++[email protected]("key", ["alpha", "a.one", "first_truce", "1948-05-15", "v1", "nully", "yes_vote"])+def test_a_plain_key_stays_plain(key):+ assert translate._yaml_key(key) == keydiff --git a/tools/translate.py b/tools/translate.pyindex 9c02562c5..812ef6403 100644--- a/tools/translate.py+++ b/tools/translate.py@@ -56,6 +56,7 @@ HEBREW = re.compile("[\u05d0-\u05ea]")MAX_BODY = 4_000_000BIDI = re.compile("[\u202a-\u202e\u2066-\u2069]")REVIEW = "agent-checked"+YAML11_BOOL = re.compile(r"y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF")class Refused(ValueError):@@ -228,20 +229,20 @@ def check_unit(fields: list[tuple[str, str, str]], hebrew: bool) -> list[str]:return [w for name, value, english in filled for w in _check(name, value, english, hebrew, event=True)]-def _events() -> dict[str, tuple[Path, dict]]:+def _events(events: Path | None = None) -> dict[str, tuple[Path, dict]]:found = {}- for path in sorted(EVENTS.glob("*.yaml")):+ for path in sorted((events or EVENTS).glob("*.yaml")):data = _parse(path)found[data["id"]] = (path, data)return dict(sorted(found.items(), key=lambda kv: (kv[1][1].get("from", ""), kv[0])))-def _content() -> list[dict]:+def _content(content: Path | None = None) -> list[dict]:"""Every content field with a Hebrew form (name_he, title_he_f, sector_he ...): a row for each record of that shape- with the English beside it, whether or not that record has its Hebrew yet."""- out = []- for path in sorted(CONTENT.glob("*.yaml")) + sorted((CONTENT / "map").glob("*.yaml")):- rel, nodes = path.relative_to(CONTENT).as_posix(), []+ with the English beside it, whether or not that record has its Hebrew yet. he_review is the flag's text, "" for none."""+ out, content = [], content or CONTENT+ for path in sorted(content.glob("*.yaml")) + sorted((content / "map").glob("*.yaml")):+ rel, nodes = path.relative_to(content).as_posix(), []def walk(node, ids: list[str], shape: tuple) -> None:if isinstance(node, dict):@@ -262,10 +263,10 @@ def _content() -> list[dict]:if s != shape or not isinstance(node.get(m.group(1)), str):continuefield, where = m.group(1) + ("_f" if m.group(2) else ""), ".".join(ids)- he = node.get(he_key)+ he, review = node.get(he_key), node.get(he_key + "_review")out.append({"key": f"content:{rel}#{where}.{field}", "label": f"{where} · {field}","group": f"content:{rel}", "group_label": rel, "unit": None, "en": node[m.group(1)],- "he": he if isinstance(he, str) else "", "he_review": bool(node.get(he_key + "_review"))})+ "he": he if isinstance(he, str) else "", "he_review": review if isinstance(review, str) else ""})return out@@ -348,12 +349,17 @@ def load(lang: str) -> tuple[dict[str, str], set[str]]:def _yaml_key(key: str) -> str:- return key if re.fullmatch(r"[A-Za-z0-9_.\-]+", key) else json.dumps(key, ensure_ascii=False)+ """A key, plain only when every YAML reader takes it as this text: letters, digits, '_', '.' and '-', and not something+ the 1.2 core schema types (null, true, 1948, 1e3) or a YAML 1.1 boolean (on, yes). The sim's Translations.Key() is+ the same rule (#1626)."""+ plain = re.fullmatch(r"[A-Za-z0-9_.\-]+", key) and not any(r.match(key) for _, r, _ in yaml12.CORE_RESOLVERS) \+ and not YAML11_BOOL.fullmatch(key)+ return key if plain else json.dumps(key, ensure_ascii=False)def _dump(header: str, data: dict) -> str:"""Block mappings down to double-quoted strings; anything else (a list of sources) as one JSON flow value."""- lines = [f"# {line}".rstrip() for line in header.split("\n")]+ lines = [f"# {line}".rstrip() for line in header.split("\n")] if header else []def emit(mapping: dict, indent: int) -> None:for k, v in mapping.items():@@ -370,6 +376,31 @@ def _dump(header: str, data: dict) -> str:return out+def inline_hebrew(content: Path, ui_en: Path, ui_he: Path) -> tuple[str, str, str]:+ """Today's inline Hebrew as the bodies (no header comment) of translations/he/ui.yaml, events.yaml and content.yaml,+ byte for byte as the sim's Translations.InlineHebrew and Write give them (docs/translations.md; the shared fixture in+ sim/Statecraft.Sim.Tests/translations_fixture/). The events come by date and id, the UI strings in strings.en.yaml's+ order (any only in Hebrew last, by key), the content fields as the catalog lists them."""+ events = {}+ for eid, (_, d) in _events(content / "events").items():+ if not isinstance(d.get("title_he"), str) or not d["title_he"]:+ continue+ e = {"title": d["title_he"], "text": d.get("text_he") if isinstance(d.get("text_he"), str) else "",+ "options": {o["id"]: o["text_he"] for o in d.get("options") or []+ if isinstance(o, dict) and isinstance(o.get("id"), str) and isinstance(o.get("text_he"), str) and o["text_he"]}}+ if isinstance(d.get("text_he_review"), str) and d["text_he_review"]:+ e["review"] = d["text_he_review"]+ events[eid] = e+ order = {k: i for i, k in enumerate(yaml12.load(_read(ui_en)) or {})}+ he = {k: v for k, v in (yaml12.load(_read(ui_he)) or {}).items() if isinstance(v, str)}+ ui = dict(sorted(he.items(), key=lambda kv: (order.get(kv[0], len(order)), kv[0])))+ fields = {}+ for r in _content(content):+ if r["he"]:+ fields[r["key"].removeprefix("content:")] = {"text": r["he"], **({"review": r["he_review"]} if r["he_review"] else {})}+ return tuple(_dump("", data) if data else "" for data in (ui, events, fields))++TITLES = {"events": "Events", "ui": "UI strings", "content": "Content fields"}HEADER = """{name} ({lang}) for tools/translate.py. The English in content/ and unity/Assets/UI/ is the source of record.The game does not read this file yet. Same rules as the Hebrew (docs/WRITING_EVENTS.md): an event is all or none,