A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
CLI: report the played timeline from a save (supersedes #1998) (#2107)
Eyal Golan83dd92fc0e12
diff --git a/changelog.d/1911.md b/changelog.d/1911.mdnew file mode 100644index 000000000..030b193e3--- /dev/null+++ b/changelog.d/1911.md@@ -0,0 +1,4 @@+- Developer CLI: `Statecraft.Cli --timeline-course SAVE` prints the course a saved game took, one row per answered event+ (chosen option, the record's option, whether it left the record, and the card that rejoined it). The rows are the+ ones the timeline screen shows, read from the same `Timeline.Entries`, so the two agree after a reload too. No game+ state or save format changes; `--timeline-report` stays the authoring coverage report (#1911). Based on Avl's #1998.diff --git a/docs/dev-setup.md b/docs/dev-setup.mdindex 63bddac9f..f58868eca 100644--- a/docs/dev-setup.md+++ b/docs/dev-setup.md@@ -41,6 +41,8 @@ Unity, a Unity licence and macOS are only needed for `unity/`. The sim, the contTo 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.+To see the course a saved game took, run `dotnet run --project sim/Statecraft.Cli -- --timeline-course path/to/game.save`. It replays the save as loading it in the game does and prints a tab-separated table with one row per answered event, in the timeline screen's order: `event`, `chosen`, `historical` (the record's option, `-` if none), `diverged` (`true` when the choice left the record; it stays `true` after a rejoin) and `rejoined_by` (the consequence card that brought it back, or `-`). These are the rows the timeline screen shows. Load warnings go to stderr; a file it cannot read or a save the game refuses exits 1 with no table. It writes nothing, and it runs on its own: with `--preview`, `--release-gate`, `--timeline-report`, `--auto`, `--set`, `--show`, `--until`, `--every`, `--seed` or `--turns` it exits 1 rather than ignore the flag.+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 4dd91c707..2d0470b39 100644--- a/sim/Statecraft.Cli/Program.cs+++ b/sim/Statecraft.Cli/Program.cs@@ -8,13 +8,14 @@ using Statecraft.Sim;// 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)// dotnet run --project Statecraft.Cli -- --timeline-report [--content DIR] (each road not taken and what follows it)+// dotnet run --project Statecraft.Cli -- --timeline-course SAVE [--content DIR] (the course a saved game took)// Interactive commands: c EVENT OPTION | p POLICY LEVEL | m LEVEL | s DELTA | n (end turn) | qCultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;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", "--until", "--set", "--show", "--every" })+foreach (var flag in new[] { "--content", "--seed", "--turns", "--auto", "--until", "--set", "--show", "--every", "--timeline-course" }){var at = Array.IndexOf(args, flag);if (at >= 0 && (at + 1 >= args.Length || args[at + 1].StartsWith("--", StringComparison.Ordinal)))@@ -22,6 +23,12 @@ foreach (var flag in new[] { "--content", "--seed", "--turns", "--auto", "--unti}var autoMode = Arg("--auto");if (autoMode != null && autoMode != "historical") { Console.Error.WriteLine($"Unknown --auto mode: '{autoMode}'"); return 1; }+var coursePath = Arg("--timeline-course");+// The course replays the save as it is: another mode, or a flag that would change or extend a run, is refused, not ignored.+var otherModes = new[] { "--preview", "--release-gate", "--timeline-report", "--auto", "--set", "--show", "--until", "--every", "--seed", "--turns" }+ .Where(m => Array.IndexOf(args, m) >= 0).ToList();+if (coursePath != null && otherModes.Count > 0)+{ Console.Error.WriteLine($"--timeline-course runs on its own, not with {string.Join(", ", otherModes)}"); return 1; }string FindContent(){@@ -89,6 +96,9 @@ if (Array.IndexOf(args, "--release-gate") >= 0)return 3;}+// --timeline-course SAVE (#1911, R-ALT-011): the played course, the rows the timeline screen shows (TimelineCourse).+if (coursePath != null) return TimelineCourse.Run(content, coursePath, Console.Out, Console.Error);+// --timeline-report (R-ALT-011): one line per road not taken, in window order: who proposed it (basis), the consequence// cards that follow it, the events whose variants name it, and the record's cards it suppresses (they require the// historical option). A writer's coverage view; "-" for none.diff --git a/sim/Statecraft.Cli/TimelineCourse.cs b/sim/Statecraft.Cli/TimelineCourse.csnew file mode 100644index 000000000..18aadcbc2--- /dev/null+++ b/sim/Statecraft.Cli/TimelineCourse.cs@@ -0,0 +1,46 @@+using Statecraft.Sim;++namespace Statecraft.Cli+{+ /// <summary>`--timeline-course SAVE` (#1911, R-ALT-011): the course a saved game took, one tab-separated row per answered+ /// event: the option chosen, the record's option, whether it left the record, and the consequence card that brought it+ /// back. The rows are Timeline.Entries of the replayed state, the list the Unity timeline screen (TimelinePresenter)+ /// draws, so the two agree for the same choices, after a reload too. A developer report: it adds no state, never+ /// writes the save, and is not player text.</summary>+ public static class TimelineCourse+ {+ public const string Header = "event\tchosen\thistorical\tdiverged\trejoined_by";++ /// <summary>Writes the report to <paramref name="output"/> and returns 0. A file that cannot be read, or a save that+ /// GameSession.Load refuses, writes one "Save error" line to <paramref name="errors"/>, no report, and returns 1. Load+ /// warnings (other content, a replay that differs) go to <paramref name="errors"/> and the report still prints. A+ /// failure while writing the report is not caught here: it is not a save error.</summary>+ public static int Run(Content content, string savePath, TextWriter output, TextWriter errors)+ {+ string text;+ try { text = File.ReadAllText(savePath); }+ catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)+ {+ errors.WriteLine($"Save error: cannot read {savePath}: {e.Message}");+ return 1;+ }++ GameSession session;+ IReadOnlyList<string> warnings;+ try { session = GameSession.Load(content, text, out warnings); }+ catch (SaveException e)+ {+ errors.WriteLine($"Save error{(e.Code != null ? " (" + e.Code + ")" : "")}: {e.Message}");+ return 1;+ }++ foreach (var w in warnings) errors.WriteLine("Save warning: " + w);+ output.WriteLine(Header);+ foreach (var e in Timeline.Entries(content, session.State))+ output.WriteLine(string.Join("\t", e.Event, e.Chosen, Dash(e.Historical), e.Diverged ? "true" : "false", Dash(e.RejoinedBy)));+ return 0;+ }++ static string Dash(string id) => id.Length == 0 ? "-" : id;+ }+}diff --git a/sim/Statecraft.Sim.Tests/TimelineCourseCliTests.cs b/sim/Statecraft.Sim.Tests/TimelineCourseCliTests.csnew file mode 100644index 000000000..266feb48f--- /dev/null+++ b/sim/Statecraft.Sim.Tests/TimelineCourseCliTests.cs@@ -0,0 +1,269 @@+using System.Diagnostics;+using Statecraft.Cli;+using Statecraft.Sim;++/// <summary>#1911, R-ALT-011: `Statecraft.Cli --timeline-course SAVE` prints the played course from a save, row for row what+/// the Unity timeline screen (TimelinePresenter) shows, because both read Timeline.Entries. No new state, no save change.</summary>+public class TimelineCourseCliTests+{+ const string Header = "event\tchosen\thistorical\tdiverged\trejoined_by";++ /// <summary>The parent decision, its consequence card (whose option rejoins the record) and the record's follow-up.</summary>+ static string Root(string ruleset)+ {+ var files = ruleset == "legacy" ? new Dictionary<string, string>() : Fixture.Gdd();+ if (ruleset == "gdd-0.3")+ {+ files["eras.yaml"] = files["eras.yaml"].Replace("loop: gdd", "loop: gdd, ruleset: gdd-0.3");+ files[Gdd03BalanceCatalogue.FileName] = File.ReadAllText(Path.Combine(RealContentTests.ContentRoot(), Gdd03BalanceCatalogue.FileName));+ }+ var rejoining = AlternateTimelineTests.Consequence.Replace(" text: Hold the course\n", " text: Hold the course\n rejoin: parent\n");+ return Fixture.Write(files, new Dictionary<string, string>+ {+ ["parent.yaml"] = AlternateTimelineTests.Parent,+ ["after_road.yaml"] = rejoining,+ ["on_record.yaml"] = AlternateTimelineTests.RecordFollowUp,+ });+ }++ /// <summary>Ends turns until <paramref name="ev"/> is pending, then answers it in a turn of its own.</summary>+ static void Choose(GameSession session, string ev, string option)+ {+ for (int turn = 0; turn < 30 && !session.State.PendingEvents.Contains(ev); turn++) session.Step(Array.Empty<Command>());+ Assert.Contains(ev, session.State.PendingEvents);+ Assert.Empty(session.Step(new Command[] { new ChooseEventOption(ev, option) }).Rejected);+ }++ /// <summary>What the timeline screen lists for a state, in the report's columns ("-" for an empty field).</summary>+ static string Expected(Content c, GameState s) =>+ string.Concat(Timeline.Entries(c, s).Select(e => $"{e.Event}\t{e.Chosen}\t{(e.Historical.Length == 0 ? "-" : e.Historical)}\t"+ + $"{(e.Diverged ? "true" : "false")}\t{(e.RejoinedBy.Length == 0 ? "-" : e.RejoinedBy)}\n"));++ /// <summary>Runs the compiled CLI (no nested build); the test host already holds the machine lock.</summary>+ static async Task<(int Exit, string Out, string Err)> Cli(params string[] args)+ {+ var info = new ProcessStartInfo("dotnet") { RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false };+ info.ArgumentList.Add(typeof(InputParse).Assembly.Location);+ foreach (var a in args) info.ArgumentList.Add(a);+ using var child = Process.Start(info)!;+ child.StandardInput.Close(); // a CLI that ignored the flag would read commands; end of input makes it quit+ var stdout = child.StandardOutput.ReadToEndAsync(); var stderr = child.StandardError.ReadToEndAsync();+ using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(60));+ try { await child.WaitForExitAsync(limit.Token); }+ catch (OperationCanceledException) { child.Kill(entireProcessTree: true); throw; }+ return (child.ExitCode, (await stdout).Replace("\r\n", "\n"), (await stderr).Replace("\r\n", "\n"));+ }++ /// <summary>A writer that fails on the first write, as a closed pipe or full disk would.</summary>+ sealed class FailingWriter : StringWriter+ {+ readonly Exception failure;+ public FailingWriter(Exception failure) { this.failure = failure; }+ public override void Write(char value) => throw failure;+ public override void Write(string? value) => throw failure;+ public override void WriteLine(string? value) => throw failure;+ }++ [Theory]+ // R-ALT-011: the record, a departure, and a departure that a consequence card rejoined, under each ruleset.+ [InlineData("legacy", "record", false)]+ [InlineData("legacy", "road", false)]+ [InlineData("legacy", "road", true)]+ [InlineData("gdd-0.1", "record", false)]+ [InlineData("gdd-0.1", "road", true)]+ [InlineData("gdd-0.3", "record", false)]+ [InlineData("gdd-0.3", "road", true)]+ public void TheCourseIsTheTimelineScreensRowsAfterSaveAndReload(string ruleset, string choice, bool rejoin)+ {+ var root = Root(ruleset);+ var c = ContentLoader.Load(root);+ var played = GameSession.New(c, 1, Mode.Historical);+ Choose(played, "parent", choice);+ if (rejoin) Choose(played, "after_road", "hold");++ var parent = Timeline.Entries(c, played.State).Single(e => e.Event == "parent");+ Assert.Equal((choice, "record", choice == "road", rejoin ? "after_road" : ""), (parent.Chosen, parent.Historical, parent.Diverged, parent.RejoinedBy));++ var save = Path.Combine(root, "played.save");+ File.WriteAllText(save, played.Save.Write());+ var bytes = File.ReadAllBytes(save);+ var output = new StringWriter(); var errors = new StringWriter();+ Assert.Equal(0, TimelineCourse.Run(c, save, output, errors));+ Assert.Equal("", errors.ToString());+ Assert.Equal(Header + "\n" + Expected(c, played.State), output.ToString().Replace("\r\n", "\n"));+ Assert.Equal(bytes, File.ReadAllBytes(save)); // the report never writes the save+ var reloaded = GameSession.Load(c, played.Save.Write(), out _);+ Assert.Equal(Expected(c, played.State), Expected(c, reloaded.State)); // a reload gives the screen the same rows+ }++ [Fact]+ // R-ALT-011: a game with no answered event has a header and no rows; an unanswered card is never a row.+ public void ANewGameHasOnlyTheHeader()+ {+ var root = Root("legacy");+ var c = ContentLoader.Load(root);+ var save = Path.Combine(root, "new.save");+ File.WriteAllText(save, GameSession.New(c, 1, Mode.Historical).Save.Write());+ var output = new StringWriter();+ Assert.Equal(0, TimelineCourse.Run(c, save, output, new StringWriter()));+ Assert.Equal(Header + "\n", output.ToString().Replace("\r\n", "\n"));+ }++ [Fact]+ // R-ALT-011: a save made with other content still reports, and says so on stderr (GameSession.Load's own warning).+ public void AContentChangeWarningGoesToStderrAndTheCourseStillPrints()+ {+ var root = Root("legacy");+ var c = ContentLoader.Load(root);+ var played = GameSession.New(c, 1, Mode.Historical);+ Choose(played, "parent", "road");+ var save = Path.Combine(root, "played.save");+ File.WriteAllText(save, played.Save.Write());+ var changedRoot = Root("legacy");+ var follow = Path.Combine(changedRoot, "events", "on_record.yaml");+ File.WriteAllText(follow, File.ReadAllText(follow).Replace("The next real decision.", "The next real decision, reworded."));+ var changed = ContentLoader.Load(changedRoot);+ Assert.NotEqual(c.Hash, changed.Hash);++ var output = new StringWriter(); var errors = new StringWriter();+ Assert.Equal(0, TimelineCourse.Run(changed, save, output, errors));+ Assert.Contains("Save warning: " + GameSession.ContentChanged, errors.ToString());+ Assert.StartsWith(Header + "\nparent\troad\trecord\ttrue\t-\n", output.ToString().Replace("\r\n", "\n"));+ }++ [Fact]+ // R-ALT-011: a file that cannot be read, and a save that does not parse, print no report and exit 1.+ public void AnUnreadableOrBrokenSaveIsRefusedWithoutAReport()+ {+ var root = Root("legacy");+ var c = ContentLoader.Load(root);++ var output = new StringWriter(); var errors = new StringWriter();+ Assert.Equal(1, TimelineCourse.Run(c, Path.Combine(root, "missing.save"), output, errors));+ Assert.Equal("", output.ToString());+ Assert.StartsWith("Save error: cannot read ", errors.ToString());++ var broken = Path.Combine(root, "broken.save");+ File.WriteAllText(broken, "not a save\n");+ output = new StringWriter(); errors = new StringWriter();+ Assert.Equal(1, TimelineCourse.Run(c, broken, output, errors));+ Assert.Equal("", output.ToString());+ Assert.StartsWith("Save error", errors.ToString());+ Assert.DoesNotContain("cannot read", errors.ToString());+ }++ [Theory]+ // R-ALT-011: a failure while writing the report is not a save error; it reaches the caller as itself.+ [InlineData(typeof(IOException))]+ [InlineData(typeof(ArgumentException))]+ public void AnOutputFailureIsNotReportedAsASaveError(Type kind)+ {+ var root = Root("legacy");+ var c = ContentLoader.Load(root);+ var save = Path.Combine(root, "new.save");+ File.WriteAllText(save, GameSession.New(c, 1, Mode.Historical).Save.Write());+ var failure = (Exception)Activator.CreateInstance(kind, "the output is closed")!;+ var errors = new StringWriter();+ var thrown = Assert.ThrowsAny<Exception>(() => TimelineCourse.Run(c, save, new FailingWriter(failure), errors));+ Assert.Same(failure, thrown);+ Assert.Equal("", errors.ToString());+ }++ [Fact]+ // R-ALT-011: the command line runs the report, refuses a missing path and refuses another mode beside it.+ public async Task TheCommandLineRunsTheReportAndRefusesMixedModes()+ {+ var root = Root("legacy");+ var c = ContentLoader.Load(root);+ var played = GameSession.New(c, 1, Mode.Historical);+ Choose(played, "parent", "road");+ var save = Path.Combine(root, "played.save");+ File.WriteAllText(save, played.Save.Write());++ var run = await Cli("--content", root, "--timeline-course", save);+ Assert.True(run.Exit == 0, run.Out + run.Err);+ Assert.Equal("", run.Err);+ Assert.Equal(Header + "\n" + Expected(c, played.State), run.Out);++ var missing = await Cli("--content", root, "--timeline-course");+ Assert.Equal(1, missing.Exit);+ Assert.Contains("Missing value for --timeline-course", missing.Err);++ var mixed = await Cli("--content", root, "--timeline-course", save, "--timeline-report");+ Assert.Equal(1, mixed.Exit);+ Assert.Equal("", mixed.Out);+ Assert.Contains("--timeline-course", mixed.Err);+ }++ [Fact]+ // R-ALT-011: a card that is pending but unanswered when the game is saved is not a row (only answered events are).+ public void APendingUnansweredCardIsNotARow()+ {+ var root = Root("legacy");+ var c = ContentLoader.Load(root);+ var played = GameSession.New(c, 1, Mode.Historical);+ for (int turn = 0; turn < 30 && !played.State.PendingEvents.Contains("parent"); turn++) played.Step(Array.Empty<Command>());+ var save = Path.Combine(root, "pending.save");+ File.WriteAllText(save, played.Save.Write());+ Assert.Contains("parent", GameSession.Load(c, File.ReadAllText(save), out _).State.PendingEvents); // still pending after the reload++ var output = new StringWriter();+ Assert.Equal(0, TimelineCourse.Run(c, save, output, new StringWriter()));+ Assert.Equal(Header + "\n", output.ToString().Replace("\r\n", "\n"));+ }++ [Theory]+ // R-ALT-011: a save cut short, or one whose answer was edited to an option that does not exist, is a save error (exit 1,+ // no table), not a crash: GameSession.Load reports both as SaveException.+ [InlineData("truncated")]+ [InlineData("edited")]+ public void ATruncatedOrEditedSaveIsASaveErrorNotACrash(string damage)+ {+ var root = Root("legacy");+ var c = ContentLoader.Load(root);+ var played = GameSession.New(c, 1, Mode.Historical);+ Choose(played, "parent", "road");+ var text = played.Save.Write();+ var answer = "event parent road\n";+ Assert.Contains(answer, text);+ text = damage == "truncated"+ ? text.Substring(0, text.IndexOf(answer, StringComparison.Ordinal) + "event par".Length)+ : text.Replace(answer, "event parent nowhere\n");+ var save = Path.Combine(root, damage + ".save");+ File.WriteAllText(save, text);++ var output = new StringWriter(); var errors = new StringWriter();+ Assert.Equal(1, TimelineCourse.Run(c, save, output, errors));+ Assert.Equal("", output.ToString());+ Assert.StartsWith("Save error", errors.ToString());+ Assert.DoesNotContain("cannot read", errors.ToString());+ }++ [Theory]+ // R-ALT-011: the course replays the save as it is, so a flag that would change or extend a run is refused beside it+ // rather than silently ignored, like another mode.+ [InlineData("--set", "tax_per_capita_per_year=0.00007")]+ [InlineData("--show", "morale")]+ [InlineData("--until", "1950-01-01")]+ [InlineData("--every", "2")]+ [InlineData("--seed", "5")]+ [InlineData("--turns", "3")]+ [InlineData("--preview", null)]+ [InlineData("--release-gate", null)]+ [InlineData("--auto", "historical")]+ public async Task AFlagTheCourseWouldIgnoreIsRefused(string flag, string? value)+ {+ var root = Root("legacy");+ var c = ContentLoader.Load(root);+ var save = Path.Combine(root, "new.save");+ File.WriteAllText(save, GameSession.New(c, 1, Mode.Historical).Save.Write());+ var args = new List<string> { "--content", root, "--timeline-course", save, flag };+ if (value != null) args.Add(value);++ var run = await Cli(args.ToArray());+ Assert.True(run.Exit == 1, $"exit {run.Exit}: {run.Out}{run.Err}");+ Assert.Equal("", run.Out);+ Assert.Contains("--timeline-course", run.Err);+ Assert.Contains(flag, run.Err);+ }+}