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.

Id references: every place a record id is read (refs #346) (#347)

agamrafaeli-instinct4325ba7e9b32
diff --git a/docs/dev-setup.md b/docs/dev-setup.md
index 52995f0d1..288cc1687 100644
--- a/docs/dev-setup.md
+++ b/docs/dev-setup.md
@@ -29,6 +29,7 @@ Unity, a Unity licence and macOS are only needed for `unity/`. The sim, the cont
| Dead relative links in Markdown files (also run by the policy checker tests) | `uv run scripts/oss/md_links.py` | Repo policy |
| Every script this table names exists (also run by the policy checker tests) | `uv run scripts/oss/dev_setup_commands.py` | Repo policy |
| New event file (skeleton with every required field) | `uv run scripts/new_event.py <id> [--from D] [--to D]` | none (helper) |
+| Every place a record id is read, in content and code | `uv run scripts/id_references.py <id>` | none (helper) |
| Changelog line | `uv run scripts/oss/changelog_check.py --base origin/main` | Changelog |
`scripts/check.sh` runs all the checks in one go, cheapest first, plus a sim build with warnings as errors. It stops at the first failure and shows the end of its output. It takes the base ref as its argument (default `origin/main`); set `CHECK_NO_CHANGELOG=1` if the PR has the `no-changelog` label.
diff --git a/scripts/id_references.py b/scripts/id_references.py
new file mode 100644
index 000000000..ed9ad20b2
--- /dev/null
+++ b/scripts/id_references.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python3
+# /// script
+# requires-python = ">=3.10"
+# ///
+"""Show every place a record id is read (#346): `uv run scripts/id_references.py <id> [--root DIR]`.
+
+Runs `git grep -n -w` for the id over the tracked files in content/, sim/ and unity/Assets and prints one line per
+hit (file:line: text), grouped as content, sim, tests and unity. Code reads some ids by name, which a YAML-only search
+misses. Prints `no references` and exits 0 when there are none; a git error prints git's message and exits 1.
+Read-only, offline."""
+import argparse
+import subprocess
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+AREAS = [("content", "content/"), ("sim", "sim/Statecraft.Sim/"), ("tests", "sim/Statecraft.Sim.Tests/"), ("unity", "unity/Assets/")]
+
+
+def hits(root: Path, record_id: str) -> list[tuple[str, str]]:
+ """(area, "file:line: text") per hit; a path belongs to the first area whose prefix matches."""
+ r = subprocess.run(["git", "-C", str(root), "grep", "-n", "-w", "-F", "-e", record_id, "--", "content", "sim", "unity/Assets"],
+ capture_output=True, text=True)
+ if r.returncode > 1: # 1 means no match; anything above is a git error, never "no references"
+ raise SystemExit(r.stderr.strip() or "git grep failed")
+ out = r.stdout
+ rows = []
+ for line in out.splitlines():
+ path = line.split(":", 1)[0]
+ area = next((a for a, prefix in sorted(AREAS, key=lambda x: -len(x[1])) if path.startswith(prefix)), "other")
+ rows.append((area, line))
+ return rows
+
+
+def render(rows: list[tuple[str, str]]) -> str:
+ if not rows:
+ return "no references"
+ lines = []
+ for area in [a for a, _ in AREAS] + ["other"]:
+ mine = [text for a, text in rows if a == area]
+ if mine:
+ lines += [f"== {area} ({len(mine)})"] + mine
+ return "\n".join(lines)
+
+
+def main(argv: list[str] | None = None) -> int:
+ p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
+ p.add_argument("id")
+ p.add_argument("--root", type=Path, default=ROOT)
+ a = p.parse_args(argv)
+ print(render(hits(a.root, a.id)))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/oss/tests/test_id_references.py b/scripts/oss/tests/test_id_references.py
new file mode 100644
index 000000000..4574b5b78
--- /dev/null
+++ b/scripts/oss/tests/test_id_references.py
@@ -0,0 +1,46 @@
+"""Id references (#346): hits grouped by area, whole-word matching, no hits, and the real repo."""
+import importlib.util
+
+import pytest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[3]
+SPEC = importlib.util.spec_from_file_location('id_references', ROOT / 'scripts/id_references.py')
+m = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(m)
+
+
+def test_groups_hits_by_area_and_matches_whole_words(make_repo):
+ root = make_repo({
+ 'content/model.yaml': '- { id: morale }\n- { id: morale_extra }\n',
+ 'sim/Statecraft.Sim/A.cs': 'Shift(c, s, "morale", 1);\n',
+ 'sim/Statecraft.Sim.Tests/B.cs': '// morale\n',
+ 'unity/Assets/Scripts/Hud.cs': 'var m = "morale";\n',
+ 'docs/x.md': 'morale\n',
+ })
+ rows = m.hits(root, 'morale')
+ assert sorted(a for a, _ in rows) == ['content', 'sim', 'tests', 'unity']
+ out = m.render(rows)
+ assert '== content (1)' in out and 'content/model.yaml:1:' in out and 'morale_extra' not in out
+ assert 'docs/x.md' not in out
+
+
+def test_no_references(make_repo, capsys):
+ root = make_repo({'content/model.yaml': 'x\n'})
+ assert m.main(['nothing_here', '--root', str(root)]) == 0
+ assert capsys.readouterr().out.strip() == 'no references'
+
+
+def test_a_git_error_is_an_error_not_no_references(tmp_path, monkeypatch, capsys):
+ """`no references` tells an agent a record is safe to delete, so a failed `git grep` must never print it."""
+ monkeypatch.setenv('GIT_CEILING_DIRECTORIES', str(tmp_path.parent)) # tmp_path is not inside any checkout
+ with pytest.raises(SystemExit) as e:
+ m.main(['morale', '--root', str(tmp_path)])
+ assert e.value.code not in (0, None)
+ assert 'not a git repository' in str(e.value.code)
+ assert 'no references' not in capsys.readouterr().out
+
+
+def test_real_repo_finds_a_code_named_indicator():
+ areas = {a for a, _ in m.hits(ROOT, 'food_supply')}
+ assert {'content', 'sim'} <= areas