A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
tools: writer preview, try a rules.yaml change without Unity (fixes #295) (#298)
agamrafaeli-instinct1cdb356ccdfd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 013c9593e..35e77766e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,9 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB## [Unreleased]### Added+- Writer preview: `dotnet run --project sim/Statecraft.Cli -- --preview --set key=value` plays the historical run with a+ rules.yaml change applied in memory and prints the changed state lines and a table of chosen values, without Unity and+ without touching `content/` (fixes #295).- One golden manifest (`sim/Statecraft.Sim.Tests/golden/manifest.txt`) pins the golden hashes; `STATECRAFT_UPDATE_GOLDEN=1`now rewrites it and the `GoldenRun.cs` constants, and a test names any doc that shows an old hash (fixes #293).- Era system switches in eras.yaml (`systems`): `legislature: state | assembly` (an assembly's vote against a policy ordiff --git a/docs/dev-setup.md b/docs/dev-setup.mdindex fac4a9146..c961d876c 100644--- a/docs/dev-setup.md+++ b/docs/dev-setup.md@@ -26,6 +26,8 @@ Unity, a Unity licence and macOS are only needed for `unity/`. The sim, the cont`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.+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.+The label `needs-unity` marks an issue you cannot finish without Unity. Its acceptance needs the Unity editor, a player build or the WebGL check. The label `area: unity` is different: it says which code the issue touches, not what you must have to finish it. An issue without `needs-unity` can be finished with the commands above.Not possible without Unity and not in CI: the Unity EditMode tests, player builds, `tools/web_check.py` and the visual profiles below. If your change touches `unity/`, or `sim/` code that Unity compiles, say in the PR that you could not run them. The maintainer runs them (`CONTRIBUTING.md`, "Unity EditMode tests are not in CI").diff --git a/sim/Statecraft.Cli/Program.cs b/sim/Statecraft.Cli/Program.csindex 3cb5a700f..b380d0fb6 100644--- a/sim/Statecraft.Cli/Program.cs+++ b/sim/Statecraft.Cli/Program.cs@@ -4,6 +4,8 @@ using Statecraft.Sim;// Text front end for the headless sim.// dotnet run --project Statecraft.Cli -- [--content DIR] [--seed N] [--auto historical --turns N]+// dotnet run --project Statecraft.Cli -- --preview [--until YYYY-MM-DD] [--set key=value]... [--show id,id] [--every N]+// writer preview: the historical run with some rules.yaml values changed in memory, against the real content// dotnet run --project Statecraft.Cli -- --release-gate [--content DIR] (exit 0 when shareable, 3 when not)// Interactive commands: c EVENT OPTION | p POLICY LEVEL | m LEVEL | s DELTA | n (end turn) | qCultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;@@ -11,7 +13,7 @@ CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;string? Arg(string name) { var i = Array.IndexOf(args, name); return i >= 0 && i + 1 < args.Length ? args[i + 1] : null; }-foreach (var flag in new[] { "--content", "--seed", "--turns", "--auto" })+foreach (var flag in new[] { "--content", "--seed", "--turns", "--auto", "--until", "--set", "--show", "--every" }){var at = Array.IndexOf(args, flag);if (at >= 0 && (at + 1 >= args.Length || args[at + 1].StartsWith("--", StringComparison.Ordinal)))@@ -27,6 +29,31 @@ string FindContent()throw new DirectoryNotFoundException();}+if (Array.IndexOf(args, "--preview") >= 0)+{+ try+ {+ var sets = new List<string>();+ for (int i = 0; i + 1 < args.Length; i++) if (args[i] == "--set") sets.Add(args[i + 1]);+ var until = new DateTime(1950, 1, 1);+ var untilText = Arg("--until");+ if (untilText != null && !DateTime.TryParseExact(untilText, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out until))+ { Console.Error.WriteLine($"Invalid value for --until: '{untilText}' (use YYYY-MM-DD)"); return 1; }+ ulong pseed = GoldenRun.Seed;+ var pseedText = Arg("--seed");+ if (pseedText != null && !InputParse.TryULong(pseedText, out pseed)) { Console.Error.WriteLine($"Invalid value for --seed: '{pseedText}'"); return 1; }+ int every = 8;+ var everyText = Arg("--every");+ if (everyText != null && !InputParse.TryInt(everyText, out every)) { Console.Error.WriteLine($"Invalid value for --every: '{everyText}'"); return 1; }+ var show = (Arg("--show") ?? "morale,food_supply,treasury,fx").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();+ Console.Write(Preview.Run(Arg("--content") ?? FindContent(), until, pseed, sets, show, every));+ return 0;+ }+ catch (ArgumentException e) { Console.Error.WriteLine($"Preview error: {e.Message}"); return 1; }+ catch (DirectoryNotFoundException) { Console.Error.WriteLine("Content error: content directory not found (use --content <path>)"); return 2; }+ catch (ContentException e) { Console.Error.WriteLine($"Content error: {e.Message}"); return 2; }+}+Content content;try { content = ContentLoader.Load(Arg("--content") ?? FindContent()); }catch (DirectoryNotFoundException) { Console.Error.WriteLine("Content error: content directory not found (use --content <path>)"); return 2; }diff --git a/sim/Statecraft.Sim.Tests/GoldenSnapshot.cs b/sim/Statecraft.Sim.Tests/GoldenSnapshot.csindex 8b8a63cbf..55464eae1 100644--- a/sim/Statecraft.Sim.Tests/GoldenSnapshot.cs+++ b/sim/Statecraft.Sim.Tests/GoldenSnapshot.cs@@ -36,37 +36,6 @@ public static class GoldenSnapshotAssert.Fail(sb.ToString());}- /// <summary>Changed lines between two descriptions, grouped by section (the label before '{' or '[' or '=').</summary>- public static string Diff(string before, string after)- {- List<(string section, string line)> Parse(string text)- {- var res = new List<(string, string)>();- string section = "header";- foreach (var raw in text.Split('\n'))- {- if (raw.Length == 0) continue;- if (!raw.StartsWith(" "))- {- var end = raw.IndexOfAny(new[] { '{', '[', '=' });- section = end > 0 && raw.IndexOf(';') is var semi && (semi < 0 || end < semi) ? raw.Substring(0, end) : "header";- }- res.Add((section, raw));- }- return res;- }- var a = Parse(before); var b = Parse(after);- var aSet = new HashSet<(string, string)>(a); var bSet = new HashSet<(string, string)>(b);- var sb = new StringBuilder();- foreach (var g in a.Concat(b).Select(x => x.section).Distinct())- {- var removed = a.Where(x => x.section == g && !bSet.Contains(x)).Select(x => " - " + x.line.TrimStart()).ToList();- var added = b.Where(x => x.section == g && !aSet.Contains(x)).Select(x => " + " + x.line.TrimStart()).ToList();- if (removed.Count + added.Count == 0) continue;- sb.AppendLine($"[{g}]");- foreach (var l in removed.Take(40)) sb.AppendLine(l);- foreach (var l in added.Take(40)) sb.AppendLine(l);- }- return sb.Length == 0 ? "(the descriptions are identical)\n" : sb.ToString();- }+ /// <summary>Changed lines between two descriptions, grouped by section (see <see cref="StateDiff"/>).</summary>+ public static string Diff(string before, string after) => StateDiff.Lines(before, after);}diff --git a/sim/Statecraft.Sim.Tests/PreviewTests.cs b/sim/Statecraft.Sim.Tests/PreviewTests.csnew file mode 100644index 000000000..7fba14ec2--- /dev/null+++ b/sim/Statecraft.Sim.Tests/PreviewTests.cs@@ -0,0 +1,72 @@+using System;+using System.IO;+using System.Linq;+using Statecraft.Sim;++/// <summary>The writer preview (#295): a rule change shows its effect without touching content/.</summary>+public class PreviewTests+{+ static string Root => RealContentTests.ContentRoot();+ static readonly string[] None = new string[0];+ static readonly string[] Show = { "morale", "treasury" };++ [Fact]+ public void ANoOpPreviewMatchesTheGoldenAndHasAnEmptyDiff()+ {+ var text = Preview.Run(Root, GoldenRun.Until1950, GoldenRun.Seed, None, Show, 8);+ Assert.Contains("(the descriptions are identical)", text);+ Assert.Contains($"hash {GoldenRun.Hash1950.Substring(0, 8)} -> changed", text);+ Assert.Contains($"changed 1950-02-27 hash {GoldenRun.Hash1950.Substring(0, 8)}", text);+ }++ [Fact]+ public void ARealOverrideShowsTheChangedLinesAndTheTable()+ {+ var text = Preview.Run(Root, GoldenRun.Until1950, GoldenRun.Seed, new[] { "tax_per_capita_per_year=0.00007" }, Show, 8);+ Assert.DoesNotContain("(the descriptions are identical)", text);+ Assert.Contains("- debt=", text);+ Assert.Contains("morale", text);+ Assert.Contains("tax_per_capita_per_year=0.00007", text);+ }++ [Fact]+ public void ThePreviewWritesNothingIntoContent()+ {+ string Snapshot() => string.Join("|", Directory.GetFiles(Root, "*", SearchOption.AllDirectories).OrderBy(f => f, StringComparer.Ordinal)+ .Select(f => f + ":" + File.GetLastWriteTimeUtc(f).Ticks + ":" + new FileInfo(f).Length));+ var before = Snapshot();+ Preview.Run(Root, new DateTime(1949, 1, 1), GoldenRun.Seed, new[] { "tax_per_capita_per_year=0.00007" }, Show, 8);+ Assert.Equal(before, Snapshot());+ }++ [Theory]+ [InlineData("tax_per_capita_per_yeer=0.1", "no top-level key")]+ [InlineData("budget_start=1", "is a block")]+ [InlineData("tax_per_capita_per_year", "wants key=value")]+ [InlineData("Tax=1", "not a rules.yaml key")]+ [InlineData("tax_per_capita_per_year=", "needs a value")]+ public void BadSetsFailWithAReason(string set, string message)+ {+ var ex = Assert.Throws<ArgumentException>(() => Preview.Run(Root, new DateTime(1949, 1, 1), GoldenRun.Seed, new[] { set }, Show, 8));+ Assert.Contains(message, ex.Message);+ }++ [Fact]+ public void AValueOfTheWrongTypeFailsInTheStrictLoader() =>+ Assert.Throws<ContentException>(() => Preview.Run(Root, new DateTime(1949, 1, 1), GoldenRun.Seed, new[] { "attention_per_turn=lots" }, Show, 8));++ [Fact]+ public void AnUnknownShownNameFails() =>+ Assert.Throws<ArgumentException>(() => Preview.Run(Root, new DateTime(1949, 1, 1), GoldenRun.Seed, None, new[] { "wealth" }, 8));++ [Fact]+ public void SetRuleReplacesOnlyThatLine()+ {+ var src = "a: 1 # note\nb: 2\nblock:\n x: 1\n";+ Assert.Equal("a: 1 # note\nb: 5\nblock:\n x: 1\n", Preview.SetRule(src, "b", "5"));+ }++ [Fact]+ public void SetRuleWorksOnACrlfFile() =>+ Assert.Equal("a: 1\r\nb: 5\r\n", Preview.SetRule("a: 1\r\nb: 2\r\n", "b", "5"));+}diff --git a/sim/Statecraft.Sim/Preview.cs b/sim/Statecraft.Sim/Preview.csnew file mode 100644index 000000000..c6d67e1f2--- /dev/null+++ b/sim/Statecraft.Sim/Preview.cs@@ -0,0 +1,107 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.IO;+using System.Linq;+using System.Text;+using System.Text.RegularExpressions;++namespace Statecraft.Sim+{+ /// <summary>Writer preview (#295): plays the historical run on the real content and on the same content with some+ /// rules.yaml values changed in memory, then prints what differs. Nothing is written to content/.</summary>+ public static class Preview+ {+ /// <summary>Replaces the single-line top-level value of <paramref name="key"/> in rules.yaml text. Throws+ /// ArgumentException when the key is not a top-level single value. The loader still checks the new value with the strict Rules type.</summary>+ public static string SetRule(string rulesYaml, string key, string value)+ {+ if (!Regex.IsMatch(key, @"^[a-z][a-z0-9_]*$")) throw new ArgumentException($"'{key}' is not a rules.yaml key (use the snake_case name, for example tax_per_capita_per_year)");+ var m = Regex.Match(rulesYaml, @"(?m)^" + key + @":[ \t]*([^\r\n]*)(?=\r?$)"); // a CRLF checkout keeps its line ends+ if (!m.Success) throw new ArgumentException($"rules.yaml has no top-level key '{key}'");+ if (m.Groups[1].Value.Trim().Length == 0 || m.Groups[1].Value.TrimStart().StartsWith("#"))+ throw new ArgumentException($"'{key}' is a block, not a single value; edit it in rules.yaml");+ if (value.IndexOfAny(new[] { '\r', '\n' }) >= 0) throw new ArgumentException("a value must be one line");+ if (value.Trim().Length == 0) throw new ArgumentException($"'{key}' needs a value (an empty one would read as 0)");+ return rulesYaml.Substring(0, m.Index) + key + ": " + value + rulesYaml.Substring(m.Index + m.Length);+ }++ /// <summary>The content at <paramref name="contentRoot"/> with each "key=value" in <paramref name="sets"/> applied to rules.yaml in memory.</summary>+ public static Content LoadWith(string contentRoot, IEnumerable<string> sets)+ {+ var edits = new List<(string key, string value)>();+ foreach (var s in sets)+ {+ var eq = s.IndexOf('=');+ if (eq <= 0) throw new ArgumentException($"--set wants key=value, got '{s}'");+ edits.Add((s.Substring(0, eq).Trim(), s.Substring(eq + 1).Trim()));+ }+ var eventsDir = Path.Combine(contentRoot, "events");+ var eventFiles = Directory.Exists(eventsDir)+ ? Directory.GetFiles(eventsDir, "*.yaml").Select(f => "events/" + Path.GetFileName(f)).ToList()+ : new List<string>();+ return ContentLoader.Load(rel =>+ {+ var path = Path.Combine(contentRoot, rel);+ if (!File.Exists(path)) return null;+ var text = File.ReadAllText(path);+ if (rel == "rules.yaml") foreach (var (k, v) in edits) text = SetRule(text, k, v);+ return text;+ }, eventFiles);+ }++ /// <summary>The states after each <paramref name="every"/>th turn and the final one, playing HistoricalAI from the golden start until <paramref name="until"/>.</summary>+ public static List<GameState> Play(Content c, ulong seed, DateTime until, int every)+ {+ var s = Simulation.NewGame(c, seed, Mode.Historical);+ var states = new List<GameState> { s };+ for (int turn = 0; turn < 1000 && s.Date < until && s.GameOver == null; turn++) // the same stop as GoldenRun.Play+ {+ s = Simulation.Step(c, s, HistoricalAI.Commands(c, s)).State;+ if ((turn + 1) % every == 0 || s.Date >= until || s.GameOver != null) states.Add(s);+ }+ return states;+ }++ static string Value(GameState s, string what)+ {+ if (what == "treasury") return s.Treasury.ToString("0.0", CultureInfo.InvariantCulture);+ if (what == "debt") return s.Debt.ToString("0.0", CultureInfo.InvariantCulture);+ if (what == "fx") return s.FxReserves.ToString("0.0", CultureInfo.InvariantCulture);+ if (what == "population") return s.TotalPopulation.ToString("N0", CultureInfo.InvariantCulture);+ if (what == "stability") return s.CoalitionStability.ToString("0.00", CultureInfo.InvariantCulture);+ return s.Indicators.TryGetValue(what, out var v) ? v.ToString("0.000", CultureInfo.InvariantCulture) : "-";+ }++ /// <summary>The preview text: the changed-state diff at the end date, then a table of <paramref name="show"/> (indicator ids, or treasury, debt, fx, population, stability) as "before to after".</summary>+ public static string Run(string contentRoot, DateTime until, ulong seed, IReadOnlyList<string> sets, IReadOnlyList<string> show, int every)+ {+ if (every < 1) throw new ArgumentException("--every must be at least 1");+ var baseContent = ContentLoader.Load(contentRoot);+ var changed = LoadWith(contentRoot, sets);+ foreach (var w in show)+ if (!baseContent.Indicators.Any(i => i.Id == w) && Array.IndexOf(new[] { "treasury", "debt", "fx", "population", "stability" }, w) < 0)+ throw new ArgumentException($"--show: '{w}' is not an indicator or one of treasury, debt, fx, population, stability");+ var a = Play(baseContent, seed, until, every);+ var b = Play(changed, seed, until, every);+ var sb = new StringBuilder();+ sb.AppendLine($"Preview: seed {seed}, until {until:yyyy-MM-dd}, changes: {(sets.Count == 0 ? "(none)" : string.Join(", ", sets))}");+ sb.AppendLine("Nothing is written; content/ is untouched.");+ sb.AppendLine();+ sb.AppendLine($"Final state, base {a[a.Count - 1].Date:yyyy-MM-dd} hash {a[a.Count - 1].Hash().Substring(0, 8)} -> changed {b[b.Count - 1].Date:yyyy-MM-dd} hash {b[b.Count - 1].Hash().Substring(0, 8)}");+ sb.Append(StateDiff.Lines(a[a.Count - 1].Describe(), b[b.Count - 1].Describe()));+ if (show.Count > 0)+ {+ sb.AppendLine();+ sb.AppendLine("date " + string.Join(" ", show.Select(w => w.PadRight(22))));+ for (int i = 0; i < Math.Max(a.Count, b.Count); i++)+ {+ var x = a[Math.Min(i, a.Count - 1)]; var y = b[Math.Min(i, b.Count - 1)];+ var date = (i < b.Count ? y : x).Date;+ sb.AppendLine(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " " + string.Join(" ", show.Select(w => (Value(x, w) + " -> " + Value(y, w)).PadRight(22))));+ }+ }+ return sb.ToString();+ }+ }+}diff --git a/sim/Statecraft.Sim/StateDiff.cs b/sim/Statecraft.Sim/StateDiff.csnew file mode 100644index 000000000..3e6414888--- /dev/null+++ b/sim/Statecraft.Sim/StateDiff.cs@@ -0,0 +1,45 @@+using System.Collections.Generic;+using System.Linq;+using System.Text;++namespace Statecraft.Sim+{+ /// <summary>Changed lines between two <see cref="GameState.Describe"/> texts, grouped by section. Used by the golden+ /// tests (#270) and the writer preview (#295).</summary>+ public static class StateDiff+ {+ /// <summary>Changed lines grouped by section (the label before '{' or '[' or '='), at most 40 removed and 40 added per section.</summary>+ public static string Lines(string before, string after)+ {+ List<(string section, string line)> Parse(string text)+ {+ var res = new List<(string, string)>();+ string section = "header";+ foreach (var raw in text.Split('\n'))+ {+ if (raw.Length == 0) continue;+ if (!raw.StartsWith(" "))+ {+ var end = raw.IndexOfAny(new[] { '{', '[', '=' });+ section = end > 0 && raw.IndexOf(';') is var semi && (semi < 0 || end < semi) ? raw.Substring(0, end) : "header";+ }+ res.Add((section, raw));+ }+ return res;+ }+ var a = Parse(before); var b = Parse(after);+ var aSet = new HashSet<(string, string)>(a); var bSet = new HashSet<(string, string)>(b);+ var sb = new StringBuilder();+ foreach (var g in a.Concat(b).Select(x => x.section).Distinct())+ {+ var removed = a.Where(x => x.section == g && !bSet.Contains(x)).Select(x => " - " + x.line.TrimStart()).ToList();+ var added = b.Where(x => x.section == g && !aSet.Contains(x)).Select(x => " + " + x.line.TrimStart()).ToList();+ if (removed.Count + added.Count == 0) continue;+ sb.AppendLine($"[{g}]");+ foreach (var l in removed.Take(40)) sb.AppendLine(l);+ foreach (var l in added.Take(40)) sb.AppendLine(l);+ }+ return sb.Length == 0 ? "(the descriptions are identical)\n" : sb.ToString();+ }+ }+}