Skip to content

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

repo: stable rule IDs and a check for untested or dead ones (refs #286) (#307)

agamrafaeli-instinctf04269a641bd
diff --git a/AGENTS.md b/AGENTS.md
index b8eb5e617..a21b105b4 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -76,6 +76,9 @@ For changes under `sim/`, `tools/`, `scripts/` or `unity/`, not only content.
- CI runs them as `Sim (dotnet test)`, `Tools (pytest)` and `Repo policy`, plus `Changelog`. Unity EditMode tests, WebGL builds and `tools/web_check.py` need Unity and are not in CI. If your change touches `unity/` or code Unity compiles and you cannot run them, say so in the PR; do not claim they passed.
- When you do run Unity: wrap the command in `uv run tools/machine_lock.py --shared --wait-unity -- ...`, never add `-nographics` to an editor run, and stop a stuck Unity by its PID. Afterwards drop the settings churn with `git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset`, and never commit the `UNITY_MCP_*` scripting defines.
+**Rule IDs** (`docs/rules/README.md`)
+- A rule with an ID like `R-ECON-014` is cited by that ID in its test (`// R-ECON-014`), in YAML comments and in the PR body ("implements R-ECON-014"). Run `uv run scripts/oss/rule_ids.py`; it fails on an untested rule and on a cited ID no rule defines.
+
**Determinism** (`docs/determinism.md`)
- The sim must give the same state, bit for bit, on .NET, Mono and IL2CPP: no new RNG, no trigonometry, no unordered iteration into state, no culture-dependent formatting.
- `GoldenRun.Hash1950` and `Hash1952` must not move unless the change is a deliberate rules or content change. The browser smoke value also moves when the UI path changes; re-record it then. If they move, update every place the doc lists in the same commit and say why in the message and the PR.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 7508b1f0f..4d61fda06 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -47,7 +47,8 @@ Follow [docs/dev-setup.md](docs/dev-setup.md). In short:
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 line under `## [Unreleased]` in [CHANGELOG.md](CHANGELOG.md). CI's `Changelog` job checks it; the maintainer can add the `no-changelog` label to a change no player would notice.
-7. **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.
+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.
## History and content rules
diff --git a/docs/rules/README.md b/docs/rules/README.md
new file mode 100644
index 000000000..8b24cd5a6
--- /dev/null
+++ b/docs/rules/README.md
@@ -0,0 +1,27 @@
+# Rule IDs
+
+Every rule in the game design gets a stable ID, like `R-ECON-014`: `R-`, a 2 to 6 letter area, a three digit number.
+Rewording a rule keeps its ID. A removed rule's ID is not reused.
+
+**Where an ID is written.** A rule is defined in a Markdown file in this folder (`docs/rules/*.md`, not this README), on a line that
+starts with the ID:
+
+```
+R-ECON-014: Each turn the treasury gains tax per head times the population share of the year.
+- **R-ECON-015** Spending per head is paid the same way.
+## R-ECON-016 Debt interest
+```
+
+**How an ID is cited.** Write the ID in a comment next to the thing that builds or checks the rule: a C# test
+(`// R-ECON-014`), a YAML comment in `content/`, or the PR body ("implements R-ECON-014").
+A comment in `content/` is still a content change: it moves the content hash, so an older save loads with the
+"different game content" warning, and the PR needs a `CHANGELOG.md` line or the `no-changelog` label. The goldens do not move.
+
+**What the check does.** `uv run scripts/oss/rule_ids.py` fails when:
+
+- a rule defined here has no citing test in `sim/Statecraft.Sim.Tests` (untested),
+- an ID cited in `sim/`, `unity/Assets/` or `content/` is defined nowhere (dead), or
+- an ID is defined twice.
+
+Only `sim/Statecraft.Sim.Tests` counts as a test, because CI does not run the Unity tests.
+It runs in CI as one of the policy checker tests (`pytest scripts/oss/tests`) and in `scripts/check.sh`. Prose that only mentions an ID mid-line is not a definition.
diff --git a/scripts/check.sh b/scripts/check.sh
index 0c50209e6..8a44d7b26 100755
--- a/scripts/check.sh
+++ b/scripts/check.sh
@@ -37,6 +37,7 @@ run() {
run "changelog (against $base)" uv run scripts/oss/changelog_check.py --base "$base" --skip-label "$skip"
run "policy checker tests" uv run --with pytest==9.1.1 --with pyyaml==6.0.3 --with requests==2.32.5 pytest scripts/oss/tests -q
run "repo policy" uv run scripts/oss/check_repo.py
+run "rule ids" uv run scripts/oss/rule_ids.py
run "sim build, warnings as errors" dotnet build sim/Statecraft.sln -c Release --nologo -warnaserror
run "sim and content tests" dotnet test sim/Statecraft.sln -c Release --nologo
run "data tool tests" uv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 --with pyproj==3.8.0 pytest tools/tests -q
diff --git a/scripts/oss/rule_ids.py b/scripts/oss/rule_ids.py
new file mode 100644
index 000000000..73d9bf4e4
--- /dev/null
+++ b/scripts/oss/rule_ids.py
@@ -0,0 +1,80 @@
+#!/usr/bin/env python3
+"""Stable rule IDs (#286). A rule is defined in docs/rules/*.md on a line that starts with its ID, like
+`R-ECON-014: text`, `- **R-ECON-014** text` or `## R-ECON-014 Tax`. A test, a sim or Unity file or a content YAML file
+cites it by writing the ID anywhere (a comment is enough).
+
+Reports, one line each, and exits 1 if any:
+ untested an ID defined in docs/rules with no citation in sim/Statecraft.Sim.Tests
+ dead an ID cited in sim/, unity/Assets/ or content/ that no rule defines
+ duplicate an ID defined twice
+
+Usage: uv run scripts/oss/rule_ids.py [--root DIR]"""
+from __future__ import annotations
+
+import argparse
+import re
+import sys
+from pathlib import Path
+
+ID = r"R-[A-Z]{2,6}-\d{3}"
+DEFINITION = re.compile(rf"^\s*(?:#{{1,6}}\s+|[-*]\s+)?\**({ID})\**(?=[\s:.]|$)")
+CITATION = re.compile(rf"\b({ID})\b")
+
+
+def definitions(root: Path) -> tuple[dict[str, str], list[str]]:
+ found: dict[str, str] = {}
+ problems: list[str] = []
+ for f in sorted((root / "docs" / "rules").glob("**/*.md")):
+ if f.name == "README.md":
+ continue
+ rel = f.relative_to(root).as_posix()
+ for n, line in enumerate(f.read_text(encoding="utf-8").splitlines(), 1):
+ m = DEFINITION.match(line)
+ if not m:
+ continue
+ if m.group(1) in found:
+ problems.append(f"duplicate: {m.group(1)} at {rel}:{n} (first at {found[m.group(1)]})")
+ else:
+ found[m.group(1)] = f"{rel}:{n}"
+ return found, problems
+
+
+def citations(root: Path, patterns: list[str]) -> dict[str, list[str]]:
+ found: dict[str, list[str]] = {}
+ for pattern in patterns:
+ for f in sorted(root.glob(pattern)):
+ rel = f.relative_to(root).as_posix()
+ if "/bin/" in rel or "/obj/" in rel:
+ continue
+ for n, line in enumerate(f.read_text(encoding="utf-8", errors="replace").splitlines(), 1):
+ for m in CITATION.finditer(line):
+ found.setdefault(m.group(1), []).append(f"{rel}:{n}")
+ return found
+
+
+def check(root: Path) -> list[str]:
+ defined, problems = definitions(root)
+ tests = citations(root, ["sim/Statecraft.Sim.Tests/**/*.cs"])
+ anywhere = citations(root, ["sim/**/*.cs", "unity/Assets/**/*.cs", "content/**/*.yaml"])
+ for rule, where in defined.items():
+ if rule not in tests:
+ problems.append(f"untested: {rule} ({where}) has no citing test in sim/Statecraft.Sim.Tests")
+ for rule, where in anywhere.items():
+ if rule not in defined:
+ problems.append(f"dead: {rule} is cited at {where[0]} but no rule in docs/rules defines it")
+ return problems
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--root", default=str(Path(__file__).resolve().parents[2]))
+ problems = check(Path(ap.parse_args().root))
+ for p in problems:
+ print(p)
+ if not problems:
+ print("OK: every defined rule ID has a citing test and every cited ID is defined")
+ return 1 if problems else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/oss/tests/test_rule_ids.py b/scripts/oss/tests/test_rule_ids.py
new file mode 100644
index 000000000..fd81b6d8e
--- /dev/null
+++ b/scripts/oss/tests/test_rule_ids.py
@@ -0,0 +1,74 @@
+"""Rule ID report (#286): untested, dead and duplicate IDs."""
+import importlib.util
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[3]
+SPEC = importlib.util.spec_from_file_location('rule_ids', ROOT / 'scripts/oss/rule_ids.py')
+m = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(m)
+
+
+def tree(tmp_path, rules='', test='', content=''):
+ (tmp_path / 'docs/rules').mkdir(parents=True)
+ (tmp_path / 'docs/rules/economy.md').write_text(rules)
+ (tmp_path / 'sim/Statecraft.Sim.Tests').mkdir(parents=True)
+ (tmp_path / 'sim/Statecraft.Sim.Tests/T.cs').write_text(test)
+ (tmp_path / 'content').mkdir()
+ (tmp_path / 'content/a.yaml').write_text(content)
+ return tmp_path
+
+
+def test_clean_tree(tmp_path):
+ t = tree(tmp_path, 'R-ECON-014: tax is collected.\n- **R-ECON-015** spending.\n',
+ '// R-ECON-014\n// R-ECON-015\n')
+ assert m.check(t) == []
+
+
+def test_defined_rule_with_no_test_is_untested(tmp_path):
+ t = tree(tmp_path, 'R-ECON-014: tax is collected.\n', '// nothing here\n')
+ assert [p.split(':')[0] for p in m.check(t)] == ['untested']
+
+
+def test_a_citation_in_content_does_not_count_as_a_test(tmp_path):
+ t = tree(tmp_path, 'R-ECON-014: tax.\n', '', '# R-ECON-014\n')
+ assert any(p.startswith('untested: R-ECON-014') for p in m.check(t))
+
+
+def test_citing_an_id_no_rule_defines_is_dead(tmp_path):
+ t = tree(tmp_path, '', '// R-ECON-099\n', '# R-ECON-098\n')
+ out = m.check(t)
+ assert len(out) == 2 and all(p.startswith('dead: ') for p in out)
+
+
+def test_the_same_id_defined_twice_is_reported(tmp_path):
+ t = tree(tmp_path, 'R-ECON-014: a.\nR-ECON-014: b.\n', '// R-ECON-014\n')
+ assert [p.split(':')[0] for p in m.check(t)] == ['duplicate']
+
+
+def test_a_heading_that_starts_with_an_id_is_a_definition(tmp_path):
+ t = tree(tmp_path, '## R-ECON-014 Tax\n', '// R-ECON-014\n')
+ assert m.check(t) == []
+
+
+def test_a_unity_file_citing_an_id_no_rule_defines_is_dead(tmp_path):
+ t = tree(tmp_path)
+ (t / 'unity/Assets/Tests/EditMode').mkdir(parents=True)
+ (t / 'unity/Assets/Tests/EditMode/U.cs').write_text('// R-MAP-001\n')
+ assert [p.split(':')[0] for p in m.check(t)] == ['dead']
+
+
+def test_build_output_is_skipped_even_under_a_bin_folder(tmp_path):
+ t = tree(tmp_path / 'bin' / 'repo', 'R-ECON-014: tax.\n', '// R-ECON-014\n')
+ (t / 'sim/Statecraft.Sim/obj').mkdir(parents=True)
+ (t / 'sim/Statecraft.Sim/obj/G.cs').write_text('// R-ECON-099\n')
+ assert m.check(t) == []
+
+
+def test_prose_mentioning_an_id_is_not_a_definition(tmp_path):
+ t = tree(tmp_path, 'See R-ECON-014 for tax.\n', '')
+ assert m.check(t) == []
+
+
+def test_this_repository_has_no_untested_dead_or_duplicate_rule_ids():
+ # The policy checker tests run in CI, so this is the CI gate for the real tree.
+ assert m.check(ROOT) == []