A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
repo: GDD feature template and linter (fixes #285) (#308)
agamrafaeli-instinct6c28d17588df
diff --git a/docs/dev-setup.md b/docs/dev-setup.mdindex c961d876c..ad6bdd83e 100644--- a/docs/dev-setup.md+++ b/docs/dev-setup.md@@ -22,9 +22,10 @@ Unity, a Unity licence and macOS are only needed for `unity/`. The sim, the cont| Repository policy | `uv run scripts/oss/check_repo.py` | Repo policy || 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` | Repo policy || Data tool tests (one runs the sim's release gate, so they need the .NET SDK too) | `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` | Tools (pytest) |+| GDD feature sections (also run by the policy checker tests) | `uv run scripts/oss/gdd_lint.py` | Repo policy || Changelog line | `uv run scripts/oss/changelog_check.py --base origin/main` | Changelog |-`scripts/check.sh` runs all five 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.+`scripts/check.sh` runs all of them 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.To try a rules.yaml change without editing it, use the writer preview: `dotnet run --project sim/Statecraft.Cli -- --preview --set tax_per_capita_per_year=0.00007 --show morale,treasury,fx`. It plays the historical run on the real content and on the same content with the change applied in memory, then prints the changed final-state lines (grouped like a golden failure) and a table of the values you ask for. Other options: `--until YYYY-MM-DD` (default 1950-01-01), `--seed N`, `--every N` (turns between table rows, default 8). It takes single-value top-level keys of `rules.yaml` (an era's own `content/rules/<era>.yaml` value still wins in that era) and writes nothing. A typo fails with the key named, a wrong type with the line.diff --git a/docs/gdd/README.md b/docs/gdd/README.mdnew file mode 100644index 000000000..37f287c23--- /dev/null+++ b/docs/gdd/README.md@@ -0,0 +1,18 @@+# GDD feature sections++One file per feature in this folder, copied from [TEMPLATE.md](TEMPLATE.md). The shape (player story, rules, data touched,+done-when, out of scope, sources, open questions) is a starting point; the maintainers and the GDD writers own it. Change the+template and the linter together.++`uv run scripts/oss/gdd_lint.py` fails a file when:++- a section is missing or empty, or "Done when" has no bullet;+- TBD, TODO, FIXME or ??? is left in the text, or a `<...>` placeholder from the template;+- a number in Rules or Done when has no unit (`3 turns`, `5%`, `IL 2m`; add `(unitless)` to a line where it truly has none);+- a line holding a year or a date has no `[S<n>]` source, or cites one that "Sources" does not define with a link or a path;+- a source's link has no checked date (`checked 2026-10-12`), as `docs/CONTENT_POLICY.md` asks.++HTML comments are not checked, so the template's comments can stay.++[example-turn-grid.md](example-turn-grid.md) passes. `TEMPLATE.md` and this README are not linted.+It runs in CI as one of the policy checker tests (`pytest scripts/oss/tests`) and in `scripts/check.sh`.diff --git a/docs/gdd/TEMPLATE.md b/docs/gdd/TEMPLATE.mdnew file mode 100644index 000000000..8ea9b9f5d--- /dev/null+++ b/docs/gdd/TEMPLATE.md@@ -0,0 +1,40 @@+# <Feature name>++<!-- Copy this file to docs/gdd/<feature>.md. `uv run scripts/oss/gdd_lint.py` checks it. Replace every <...> below; the linter fails a file that still has one. -->++## Player story++As a <player role>, I want <what>, so that <why>.++## Rules++<!-- One rule per bullet. Every number has a unit ("3 turns", "5%", "IL 2m"); write (unitless) on a line where a number truly has none.+ Every year or date has a source on its line: [S1]. -->++- <rule with numbers and units>++## Data touched++<!-- The files, fields and state this changes, for example content/rules.yaml `attention_per_turn`. -->++- <file or field>++## Done when++<!-- Checks an agent can run. At least one bullet. -->++- <observable result>++## Out of scope++- <what this does not do>++## Sources++<!-- One per line: a link with the day you checked it (docs/CONTENT_POLICY.md), or a repo path. -->++- [S1] <title>, <https://...>, checked <YYYY-MM-DD>++## Open questions++- <a question for the owner, or None.>diff --git a/docs/gdd/example-turn-grid.md b/docs/gdd/example-turn-grid.mdnew file mode 100644index 000000000..7bd4ad09b--- /dev/null+++ b/docs/gdd/example-turn-grid.md@@ -0,0 +1,37 @@+# Example: the turn grid reaches an era boundary++<!-- A filled-in example of the template, built from a rule the chapters design already sets (§4.1). Not a new design. -->++## Player story++As a player in a chapter, I want each turn to end exactly on the date the next chapter begins, so that I never get a turn of a few days with a full turn of attention.++## Rules++- The founding chapter begins on 15 May 1948 [S1].+- A turn that would cross the next chapter's start date ends on that date.+- A turn that would leave under 14 days before the start date is lengthened to end on it, so a weekly turn lasts between 7 and 21 days.+- Rates that scale with time use the turn's real days divided by the days in a 365 day year.++## Data touched++- `content/eras.yaml`: each era's `from` and `to`.+- `GameState.Date` and `GameState.Turn`.++## Done when++- A two-era test lands on the boundary date and the game goes on.+- An adjusted weekly turn is never shorter than 7 days or longer than 21 days.+- The golden hashes do not move.++## Out of scope++- What carries from one chapter into the next.++## Sources++- [S1] Chapters architecture, decision D3, docs/superpowers/specs/2026-10-10-chapters-architecture-design.md++## Open questions++- None.diff --git a/scripts/check.sh b/scripts/check.shindex 8a44d7b26..296e503db 100755--- a/scripts/check.sh+++ b/scripts/check.sh@@ -35,6 +35,7 @@ run() {}run "changelog (against $base)" uv run scripts/oss/changelog_check.py --base "$base" --skip-label "$skip"+run "gdd lint" uv run scripts/oss/gdd_lint.pyrun "policy checker tests" uv run --with pytest==9.1.1 --with pyyaml==6.0.3 --with requests==2.32.5 pytest scripts/oss/tests -qrun "repo policy" uv run scripts/oss/check_repo.pyrun "rule ids" uv run scripts/oss/rule_ids.pydiff --git a/scripts/oss/gdd_lint.py b/scripts/oss/gdd_lint.pynew file mode 100644index 000000000..ea05478a9--- /dev/null+++ b/scripts/oss/gdd_lint.py@@ -0,0 +1,153 @@+#!/usr/bin/env python3+"""GDD feature-section linter (#285). Checks every docs/gdd/*.md except TEMPLATE.md and README.md against the template+in docs/gdd/TEMPLATE.md, so the writer finds an incomplete spec at write time. One line per finding, exit 1 if any.++ missing-section a template section is absent or empty+ no-done-when the Done when section has no bullet+ tbd TBD, TODO, FIXME or ??? is left in the text+ placeholder a <...> placeholder from the template is left in the text+ no-unit a number in Rules or Done when has no unit (put `(unitless)` on the line if it truly has none)+ no-source a line with a year or a dated claim has no [S<n>] source, or cites an [S<n>] that Sources does not define,+ or a source's link has no checked date (docs/CONTENT_POLICY.md)++HTML comments are ignored, so the template's guidance comments may stay in a copy.++Usage: uv run scripts/oss/gdd_lint.py [--root DIR] [FILE ...]"""+from __future__ import annotations++import argparse+import re+import sys+from pathlib import Path++SECTIONS = ["Player story", "Rules", "Data touched", "Done when", "Out of scope", "Sources", "Open questions"]+UNIT_SECTIONS = {"Rules", "Done when"}+CLAIM_SECTIONS = {"Player story", "Rules", "Data touched", "Done when"}+UNITS = {"turn", "turns", "day", "days", "week", "weeks", "month", "months", "quarter", "quarters", "year", "years",+ "il", "percent", "point", "points", "pp", "person", "people", "persons", "event", "events", "hex", "hexes",+ "settlement", "settlements", "test", "tests", "line", "lines", "option", "options", "era", "eras", "seat",+ "seats", "member", "members", "second", "seconds", "ms", "minute", "minutes", "hour", "hours", "mb", "kb",+ "x", "per", "unit", "units", "command", "commands", "attention", "bit", "bits", "word", "words", "file", "files",+ "s", "warning", "warnings", "error", "errors", "brigade", "brigades", "immigrant", "immigrants", "vote", "votes",+ "percentage"}+SCALE = {"thousand", "million", "billion", "m", "bn", "k"} # "1.6 million people": the unit is the word after+ORDINAL = {"st", "nd", "rd", "th"}+MONTHS = ("January|February|March|April|May|June|July|August|September|October|November|December"+ "|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sept|Sep|Oct|Nov|Dec")+YEAR = re.compile(r"\b(1[89]\d\d|20\d\d)s?\b") # 1950 and the 1950s+ISO_DATE = re.compile(r"\b\d{4}-\d{2}-\d{2}\b")+DATE = re.compile(rf"\b\d{{1,2}} (?:{MONTHS})\b|\b(?:{MONTHS}) \d{{1,2}}\b")+TBD = re.compile(r"\b(TBD|TODO|FIXME)\b|\?\?\?")+PLACEHOLDER = re.compile(r"<(?!https?://[^\s<>]+>)[^<>\n]+>") # <player role>, but not an autolink <https://...>+COMMENT = re.compile(r"<!--.*?-->", re.S)+SOURCE_REF = re.compile(r"\[S(\d+)\]")+SOURCE_DEF = re.compile(r"^\s*[-*]\s+\[S(\d+)\]\s+(.*)$")+NUMBER = re.compile(r"(?<![\w.])(\d+(?:[.,]\d+)?)(%?)(?:\s*([A-Za-z$]+))?")+STRIP = [re.compile(r"`[^`]*`"), re.compile(r"\[S\d+\]"), re.compile(r"\bR-[A-Z]{2,6}-\d{3}\b"),+ re.compile(r"https?://\S+"), ISO_DATE, re.compile(r"\b(?:1[89]|20)\d\d[–-]\d\d\b"), # 1948-49+ re.compile(r"§\s*\d+(?:\.\d+)*"),+ re.compile(rf"\b\d{{1,2}} (?:{MONTHS})(?: \d{{4}})?\b"),+ re.compile(rf"\b(?:{MONTHS}) \d{{1,2}}(?:, \d{{4}})?\b"), YEAR, re.compile(r"^\s*(?:[-*]|\d+\.)\s+"),+ re.compile(r"#\d+\b"), re.compile(r"\bS\d+\b")]+++def sections(text: str) -> dict[str, list[tuple[int, str]]]:+ out: dict[str, list[tuple[int, str]]] = {}+ current = None+ for n, line in enumerate(text.splitlines(), 1):+ m = re.match(r"^##\s+(.+?)\s*$", line)+ if m:+ current = m.group(1)+ out.setdefault(current, [])+ elif current is not None:+ out[current].append((n, line))+ return out+++def uncomment(text: str) -> str:+ """Blanks out HTML comments, keeping the line count so findings keep their line numbers."""+ return COMMENT.sub(lambda c: "\n" * c.group(0).count("\n"), text)+++def lint(path: Path, rel: str) -> list[str]:+ text = uncomment(path.read_text(encoding="utf-8"))+ found: list[str] = []+ secs = sections(text)+ for name in SECTIONS:+ body = [l for _, l in secs.get(name, []) if l.strip()]+ if not body:+ found.append(f"{rel}: missing-section: '{name}' is absent or empty")+ done = [l for _, l in secs.get("Done when", []) if re.match(r"^\s*[-*]\s+\S", l)]+ if secs.get("Done when") and not done:+ found.append(f"{rel}: no-done-when: 'Done when' has no bullet")+ for n, line in enumerate(text.splitlines(), 1):+ if TBD.search(line):+ found.append(f"{rel}:{n}: tbd: leftover TBD/TODO/FIXME/???")+ if PLACEHOLDER.search(re.sub(r"`[^`]*`", "", line)):+ found.append(f"{rel}:{n}: placeholder: a <...> placeholder from the template is left in")+ defined = {m.group(1) for _, l in secs.get("Sources", []) if (m := SOURCE_DEF.match(l)) and+ ("://" in m.group(2) or "/" in m.group(2))}+ for n, line in secs.get("Sources", []):+ m = SOURCE_DEF.match(line)+ if m and "://" in m.group(2) and not ISO_DATE.search(m.group(2)):+ found.append(f"{rel}:{n}: no-source: [S{m.group(1)}] has a link but no checked date (checked YYYY-MM-DD)")+ for name, lines in secs.items():+ for n, line in lines:+ if name in CLAIM_SECTIONS:+ refs = set(SOURCE_REF.findall(line))+ bad = refs - defined+ if bad:+ found.append(f"{rel}:{n}: no-source: cites [S{sorted(bad)[0]}] but Sources does not define it with a link or path")+ if (YEAR.search(re.sub(r"`[^`]*`", "", line)) or DATE.search(line)) and not (refs & defined):+ found.append(f"{rel}:{n}: no-source: a year or date with no [S<n>] source on the line")+ if name in UNIT_SECTIONS and "(unitless)" not in line:+ bare = line+ for rx in STRIP:+ bare = rx.sub(" ", bare)+ for m in NUMBER.finditer(bare):+ unit = (m.group(3) or "").lower()+ if unit in SCALE:+ after = re.match(r"\s*([A-Za-z]+)", bare[m.end():])+ unit = after.group(1).lower() if after else ""+ if m.group(2) == "%" or unit in UNITS or unit in ORDINAL:+ continue+ if unit in ("and", "to", "or", "of", "in") and re.match(r"\s*(?:and|to|or|of|in)\s+\d", bare[m.end(1):]):+ continue # a range or a share ("7 to 21 days", "61 of 120 seats"): the last number carries the unit+ if bare[max(0, m.start() - 3):m.start()].strip() in ("IL", "$") or bare[max(0, m.start() - 1):m.start()] == "$":+ continue+ found.append(f"{rel}:{n}: no-unit: '{m.group(1)}' has no unit")+ return found+++def files(root: Path, given: list[str]) -> list[Path]:+ if given:+ return [Path(g) for g in given]+ return [f for f in sorted((root / "docs" / "gdd").glob("*.md")) if f.name not in ("TEMPLATE.md", "README.md")]+++def check(root: Path, given: list[str] | None = None) -> list[str]:+ out: list[str] = []+ for f in files(root, given or []):+ try:+ rel = f.resolve().relative_to(root.resolve()).as_posix()+ except ValueError:+ rel = f.as_posix()+ out += lint(f, rel)+ return out+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--root", default=str(Path(__file__).resolve().parents[2]))+ ap.add_argument("files", nargs="*")+ a = ap.parse_args()+ problems = check(Path(a.root), a.files)+ for p in problems:+ print(p)+ if not problems:+ print("OK: every GDD section has its parts, a done-when, units, sources and no TBD")+ return 1 if problems else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/oss/tests/test_gdd_lint.py b/scripts/oss/tests/test_gdd_lint.pynew file mode 100644index 000000000..24bb18992--- /dev/null+++ b/scripts/oss/tests/test_gdd_lint.py@@ -0,0 +1,134 @@+"""GDD feature-section linter (#285): each failure, and a passing example."""+import importlib.util+from pathlib import Path++ROOT = Path(__file__).resolve().parents[3]+SPEC = importlib.util.spec_from_file_location('gdd_lint', ROOT / 'scripts/oss/gdd_lint.py')+m = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(m)++GOOD = """# F++## Player story++As a player, I want a thing, so that it works.++## Rules++- A turn lasts 7 days.+- The budget is cut by 5% and costs IL 2m.++## Data touched++- `content/rules.yaml`++## Done when++- 3 tests pass.++## Out of scope++- Nothing else.++## Sources++- [S1] The spec, docs/superpowers/specs/x.md++## Open questions++- None.+"""+++def kinds(tmp_path, text):+ f = tmp_path / 'f.md'+ f.write_text(text)+ return [p.split(': ')[1] if ':' in p else p for p in m.lint(f, 'f.md')]+++def test_a_complete_section_passes(tmp_path):+ assert kinds(tmp_path, GOOD) == []+++def test_no_done_when_bullet(tmp_path):+ out = kinds(tmp_path, GOOD.replace('- 3 tests pass.', 'Just prose.'))+ assert out == ['no-done-when']+++def test_a_missing_section(tmp_path):+ out = kinds(tmp_path, GOOD.replace('## Out of scope\n\n- Nothing else.\n\n', ''))+ assert out == ['missing-section']+++def test_a_leftover_tbd(tmp_path):+ for word in ('TBD', 'TODO', '???'):+ assert kinds(tmp_path, GOOD.replace('- None.', f'- {word} later')) == ['tbd']+++def test_a_number_without_a_unit(tmp_path):+ out = kinds(tmp_path, GOOD.replace('lasts 7 days', 'lasts 7'))+ assert out == ['no-unit']+++def test_unitless_marker_and_ranges_and_ids_are_not_flagged(tmp_path):+ ok = GOOD.replace('- A turn lasts 7 days.', '- A turn lasts between 7 and 21 days.\n- Rank 3 (unitless)\n- R-ECON-014 holds.')+ assert kinds(tmp_path, ok) == []+++def test_a_year_without_a_source(tmp_path):+ out = kinds(tmp_path, GOOD.replace('- A turn lasts 7 days.', '- The war ended in 1949.'))+ assert out == ['no-source']+++def test_a_dated_claim_with_a_defined_source_passes(tmp_path):+ ok = GOOD.replace('- A turn lasts 7 days.', '- It starts on 15 May 1948 [S1].')+ assert kinds(tmp_path, ok) == []+++def test_citing_an_undefined_source(tmp_path):+ out = kinds(tmp_path, GOOD.replace('- A turn lasts 7 days.', '- It starts on 15 May 1948 [S2].'))+ assert out == ['no-source', 'no-source']+++def test_a_source_with_no_link_or_path_does_not_count(tmp_path):+ bad = GOOD.replace('docs/superpowers/specs/x.md', 'a book').replace('- A turn lasts 7 days.', '- It starts in 1948 [S1].')+ assert 'no-source' in kinds(tmp_path, bad)+++def test_this_repository_gdd_files_lint_clean():+ # Runs in CI with the other policy checker tests; includes the shipped example.+ assert m.check(ROOT) == []+ assert (ROOT / 'docs/gdd/example-turn-grid.md').exists()+++def test_an_unfilled_copy_of_the_template_fails():+ # The likeliest mistake: the template copied and a placeholder left in.+ found = m.lint(ROOT / 'docs/gdd/TEMPLATE.md', 'TEMPLATE.md')+ assert any(': placeholder:' in p for p in found)+ assert 'placeholder' in kinds_of(GOOD.replace('- Nothing else.', '- <what this does not do>'))+ assert kinds_of(GOOD.replace('- Nothing else.', '- See <https://example.org/x>.')) == []+++def test_a_section_with_only_a_comment_is_empty(tmp_path):+ out = kinds(tmp_path, GOOD.replace('- Nothing else.', '<!-- Say what\n this does not do. -->'))+ assert out == ['missing-section']+++def test_dates_ordinals_and_scales_as_the_specs_write_them(tmp_path):+ ok = GOOD.replace('- A turn lasts 7 days.', '- The 13th government falls on 26 Jun 1963 [S1] (spec §4.1).\n'+ '- In the 1950s [S1] it grows to 1.6 million people, 61 of 120 seats.\n- The check ran 2026-10-10 [S1].')+ assert kinds(tmp_path, ok) == []+ assert kinds(tmp_path, GOOD.replace('- A turn lasts 7 days.', '- Ben-Gurion resigns on 7 Dec 1953.')) == ['no-source']+ assert kinds(tmp_path, GOOD.replace('- A turn lasts 7 days.', '- It ran short in the 1950s.')) == ['no-source']+++def test_a_linked_source_needs_a_checked_date(tmp_path):+ linked = GOOD.replace('docs/superpowers/specs/x.md', 'https://example.org/x')+ assert kinds(tmp_path, linked) == ['no-source']+ assert kinds(tmp_path, linked.replace('https://example.org/x', 'https://example.org/x, checked 2026-10-12')) == []+++def kinds_of(text):+ import tempfile+ with tempfile.TemporaryDirectory() as d:+ return kinds(Path(d), text)