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.

feat(sim): saves (seed, command log, content hash, schema version) that replay to the same hash

eyalgolan06dc3eabdde2
diff --git a/sim/Statecraft.Sim.Tests/SaveGameTests.cs b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
new file mode 100644
index 000000000..8df6e56bf
--- /dev/null
+++ b/sim/Statecraft.Sim.Tests/SaveGameTests.cs
@@ -0,0 +1,152 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Statecraft.Sim;
+
+/// <summary>Saves: seed + command log + content hash + schema version; loading replays to the same state hash.</summary>
+public class SaveGameTests
+{
+ static Content Fixture1() => ContentLoader.Load(Fixture.Write(events: new Dictionary<string, string> { ["drought.yaml"] = ValidationTests.Event }));
+
+ /// <summary>Ten turns using every command kind, including ones the sim rejects.</summary>
+ static GameSession Played(Content c)
+ {
+ var g = GameSession.New(c, 99, Mode.Historical);
+ var orders = new List<IReadOnlyList<Command>>
+ {
+ new Command[] { new SetMobilization(0.9), new SecurityOrder(-2) },
+ new Command[] { new ChooseEventOption("drought", "ration"), new SetPolicy("rationing", 1.0 / 3) },
+ new Command[] { new AllocateBudget(new Dictionary<string, double> { ["finance_minister"] = 1.0 }) },
+ new Command[] { new Appoint("finance_minister", "pm_one"), new MapAction("housing", 2, 0) },
+ new Command[] { new SetPolicy("odd id with spaces%", 0.5), new MapAction("transit_camp", 4, 0) },
+ new Command[0], new Command[0], new Command[] { new SecurityOrder(1) }, new Command[0], new Command[0],
+ };
+ foreach (var o in orders) g.Step(o);
+ return g;
+ }
+
+ [Fact]
+ public void ASaveReplaysToTheSameStateHash()
+ {
+ var c = Fixture1();
+ var played = Played(c);
+ var text = played.Save.Write();
+ var loaded = GameSession.Load(c, text, out var warnings);
+ Assert.Empty(warnings);
+ Assert.Equal(played.State.Hash(), loaded.State.Hash());
+ Assert.Equal(10, loaded.Save.Turns.Count);
+ Assert.Equal(text, loaded.Save.Write()); // writing the loaded save gives the same text
+ Assert.Equal(played.Previous!.Hash(), loaded.Previous!.Hash()); // "since last turn" survives a load
+ }
+
+ [Fact]
+ public void TheSaveRecordsTheHeaderAndExactNumbers()
+ {
+ var c = Fixture1();
+ var text = Played(c).Save.Write();
+ var lines = text.Split('\n');
+ Assert.Equal("statecraft-save 1", lines[0]);
+ Assert.Equal("content " + c.Hash, lines[1]);
+ Assert.Equal("seed 99", lines[2]);
+ Assert.Equal("mode Historical", lines[3]);
+ Assert.Contains("policy rationing 3FD5555555555555", lines); // 1/3, bit for bit
+ Assert.Contains("policy odd%20id%20with%20spaces%25 3FE0000000000000", lines);
+ Assert.Contains("budget finance_minister=3FF0000000000000", lines);
+ Assert.Contains("map housing 2 0", lines);
+ Assert.Contains("security -2", lines);
+ Assert.StartsWith("end ", lines[lines.Length - 2]);
+ }
+
+ [Fact]
+ public void TheHistoricalPlaythroughTo1952RoundTrips()
+ {
+ var c = ContentLoader.Load(RealContentTests.ContentRoot());
+ var g = GameSession.New(c, GoldenRun.Seed, Mode.Historical);
+ while (g.State.Date < GoldenRun.Until1952) g.Step(HistoricalAI.Commands(c, g.State));
+ Assert.Equal(GoldenRun.Hash1952, g.State.Hash());
+ var loaded = GameSession.Load(c, g.Save.Write(), out var warnings);
+ Assert.Empty(warnings);
+ Assert.Equal(GoldenRun.Hash1952, loaded.State.Hash());
+ }
+
+ [Fact]
+ public void OtherContentLoadsWithAWarning()
+ {
+ var text = Played(Fixture1()).Save.Write();
+ var other = ContentLoader.Load(Fixture.Write(
+ new Dictionary<string, string> { ["rules.yaml"] = Fixture.Files["rules.yaml"].Replace("treasury_start: 100", "treasury_start: 90") },
+ new Dictionary<string, string> { ["drought.yaml"] = ValidationTests.Event }));
+ GameSession.Load(other, text, out var warnings);
+ Assert.Equal(new[] { "This save was made with different game content; the replayed game may differ.", "The replayed game differs from the saved one." }, warnings);
+ }
+
+ [Fact]
+ public void ADivergingReplayWithTheSameContentIsAnError()
+ {
+ var c = Fixture1();
+ var text = Played(c).Save.Write();
+ var lines = text.Split('\n');
+ lines[2] = "seed 100"; // same content, different game
+ var ex = Assert.Throws<SaveException>(() => GameSession.Load(c, string.Join("\n", lines), out _));
+ Assert.Contains("did not reproduce the saved game", ex.Message);
+ }
+
+ [Theory]
+ [InlineData("statecraft-save 2", 1, "line 1: save schema version 2 is newer than this game (1)")]
+ [InlineData("statecraft-save x", 1, "line 1: bad schema version")]
+ [InlineData("chess-save 1", 1, "line 1: expected 'statecraft-save'")]
+ public void BadHeadersAreRejected(string first, int line, string message)
+ {
+ var c = Fixture1();
+ var lines = Played(c).Save.Write().Split('\n');
+ lines[0] = first;
+ var ex = Assert.Throws<SaveException>(() => GameSession.Load(c, string.Join("\n", lines), out _));
+ Assert.Equal((line, message), (ex.Line, ex.Message));
+ }
+
+ [Theory]
+ [InlineData("fly me 1 2", "unknown command 'fly'")]
+ [InlineData("policy rationing 0.5", "bad number '0.5'")]
+ [InlineData("map housing two 0", "bad integer 'two'")]
+ [InlineData("event drought", "'event' needs 2 values")]
+ public void BadCommandLinesNameTheLine(string command, string message)
+ {
+ var c = Fixture1();
+ var lines = Played(c).Save.Write().Split('\n').ToList();
+ lines.Insert(5, command); // after the first "turn"
+ var ex = Assert.Throws<SaveException>(() => GameSession.Load(c, string.Join("\n", lines), out _));
+ Assert.Equal(6, ex.Line);
+ Assert.Equal("line 6: " + message, ex.Message);
+ }
+
+ [Fact]
+ public void TruncatedTextIsRejected()
+ {
+ var ex = Assert.Throws<SaveException>(() => SaveGame.Parse("statecraft-save 1\ncontent x\n"));
+ Assert.Equal("Not a Statecraft save (too short)", ex.Message);
+ }
+
+ [Fact]
+ public void TheContentHashCoversEveryFileAndIgnoresLineEndings()
+ {
+ var a = ContentLoader.Load(Fixture.Write());
+ var b = ContentLoader.Load(Fixture.Write());
+ Assert.Equal(a.Hash, b.Hash);
+ Assert.Equal(64, a.Hash.Length);
+ var crlf = ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["parties.yaml"] = Fixture.Files["parties.yaml"].Replace("\n", "\r\n") }));
+ Assert.Equal(a.Hash, crlf.Hash);
+ var map = ContentLoader.Load(Fixture.Write(new Dictionary<string, string> { ["map/settlement_hexes.yaml"] = Fixture.Files["map/settlement_hexes.yaml"] + "# note\n" }));
+ Assert.NotEqual(a.Hash, map.Hash);
+ }
+
+ /// <summary>Every command type the sim has must be savable: the played session uses each one, and a new Command type
+ /// that the save format cannot write fails here.</summary>
+ [Fact]
+ public void EveryCommandTypeIsInTheSavedSession()
+ {
+ var all = typeof(Command).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(Command)) && !t.IsAbstract).Select(t => t.Name).OrderBy(x => x).ToList();
+ var used = Played(Fixture1()).Save.Turns.SelectMany(x => x).Select(x => x.GetType().Name).Distinct().OrderBy(x => x).ToList();
+ Assert.Equal(all, used);
+ }
+}
diff --git a/sim/Statecraft.Sim/Content.cs b/sim/Statecraft.Sim/Content.cs
index c48f8c5b8..0856bf8db 100644
--- a/sim/Statecraft.Sim/Content.cs
+++ b/sim/Statecraft.Sim/Content.cs
@@ -261,6 +261,9 @@ namespace Statecraft.Sim
}
}
public List<SettlementHex> SettlementHexes = new List<SettlementHex>();
+ /// <summary>SHA-256 (lowercase hex) over every file the loader read, in read order, with CRLF read as LF. A save
+ /// records it; loading a save made with other content shows a warning (spec section 7).</summary>
+ public string Hash = "";
/// <summary>The hex at axial (q, r), or null when the map has none there.</summary>
public MapHex? HexAt(int q, int r)
diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.cs
index b7074853d..b7b382838 100644
--- a/sim/Statecraft.Sim/ContentLoader.cs
+++ b/sim/Statecraft.Sim/ContentLoader.cs
@@ -125,6 +125,14 @@ namespace Statecraft.Sim
{
if (readFile == null) throw new ArgumentNullException(nameof(readFile));
if (eventFiles == null) throw new ArgumentNullException(nameof(eventFiles));
+ var read = new List<(string rel, string text)>();
+ var inner = readFile;
+ readFile = rel =>
+ {
+ var text = inner(rel);
+ if (text != null) read.Add((rel, text));
+ return text;
+ };
var c = new Content();
c.Offices = Read<OfficesFile>(readFile, "offices.yaml").Offices;
c.Parties = Read<PartiesFile>(readFile, "parties.yaml").Parties;
@@ -147,9 +155,23 @@ namespace Statecraft.Sim
c.Events.Add(e);
}
Validate(c, settlementIds);
+ c.Hash = HashOf(read);
return c;
}
+ /// <summary>SHA-256 over "path\nlength\ntext" for each file, CRLF normalised to LF (a Windows checkout hashes alike).</summary>
+ static string HashOf(List<(string rel, string text)> files)
+ {
+ var sb = new System.Text.StringBuilder();
+ foreach (var (rel, text) in files)
+ {
+ var t = text.Replace("\r\n", "\n");
+ sb.Append(rel).Append('\n').Append(t.Length.ToString(System.Globalization.CultureInfo.InvariantCulture)).Append('\n').Append(t);
+ }
+ using var sha = System.Security.Cryptography.SHA256.Create();
+ return string.Concat(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(sb.ToString())).Select(b => b.ToString("x2", System.Globalization.CultureInfo.InvariantCulture)));
+ }
+
/// <summary>Loads content from a directory: every events/*.yaml file is an event.</summary>
public static Content Load(string contentRoot)
{
diff --git a/sim/Statecraft.Sim/GameSession.cs b/sim/Statecraft.Sim/GameSession.cs
new file mode 100644
index 000000000..22df748b5
--- /dev/null
+++ b/sim/Statecraft.Sim/GameSession.cs
@@ -0,0 +1,57 @@
+using System;
+using System.Collections.Generic;
+
+namespace Statecraft.Sim
+{
+ /// <summary>One playthrough: the current state, the turn before it, the last step's report, and the save that
+ /// records every turn. The Unity SimBridge wraps this; the CLI and tests can use it directly.</summary>
+ public sealed class GameSession
+ {
+ public Content Content { get; }
+ public GameState State { get; private set; }
+ /// <summary>The state before the last step (null before the first), for "change since last turn".</summary>
+ public GameState? Previous { get; private set; }
+ /// <summary>The last step's result (null before the first): its Why and Rejected lists.</summary>
+ public StepResult? Last { get; private set; }
+ public SaveGame Save { get; }
+
+ GameSession(Content c, GameState s, SaveGame save) { Content = c; State = s; Save = save; }
+
+ public static GameSession New(Content c, ulong seed, Mode mode)
+ {
+ if (c == null) throw new ArgumentNullException(nameof(c));
+ var s = Simulation.NewGame(c, seed, mode);
+ return new GameSession(c, s, new SaveGame(c.Hash, seed, mode, s.Hash()));
+ }
+
+ /// <summary>Runs one turn and records it in the save.</summary>
+ public StepResult Step(IReadOnlyList<Command> commands)
+ {
+ var r = Simulation.Step(Content, State, commands);
+ Save.Record(commands, r.State);
+ Previous = State; State = r.State; Last = r;
+ return r;
+ }
+
+ /// <summary>Parses and replays a save. Throws SaveException when the text is malformed, or when the content is the
+ /// same but the replay ends on a different hash (a determinism bug). Content made with other content loads with a
+ /// warning (spec section 7), and a second warning if the replay then differs from the saved game.</summary>
+ public static GameSession Load(Content c, string saveText, out IReadOnlyList<string> warnings)
+ {
+ if (c == null) throw new ArgumentNullException(nameof(c));
+ var saved = SaveGame.Parse(saveText);
+ var list = new List<string>();
+ bool sameContent = saved.ContentHash == c.Hash;
+ if (!sameContent) list.Add("This save was made with different game content; the replayed game may differ.");
+ var session = New(c, saved.Seed, saved.Mode);
+ foreach (var turn in saved.Turns) session.Step(turn);
+ if (session.State.Hash() != saved.FinalHash)
+ {
+ if (sameContent) throw new SaveException(0, "The replay did not reproduce the saved game (determinism bug): please report it with the save file.");
+ list.Add("The replayed game differs from the saved one.");
+ }
+ warnings = list;
+ return session;
+ }
+ }
+}
diff --git a/sim/Statecraft.Sim/SaveGame.cs b/sim/Statecraft.Sim/SaveGame.cs
new file mode 100644
index 000000000..b7905ea05
--- /dev/null
+++ b/sim/Statecraft.Sim/SaveGame.cs
@@ -0,0 +1,159 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+
+namespace Statecraft.Sim
+{
+ public sealed class SaveException : Exception
+ {
+ /// <summary>1-based line of the save text the error is on (0 when it concerns the whole save).</summary>
+ public int Line { get; }
+ public SaveException(int line, string message) : base(line > 0 ? FormattableString.Invariant($"line {line}: {message}") : message) { Line = line; }
+ }
+
+ /// <summary>
+ /// A save is seed + command log + content hash + schema version (spec section 3); loading replays it. Text format,
+ /// one item per line:
+ /// statecraft-save 1 schema version
+ /// content &lt;hex&gt; Content.Hash of the content it was played with
+ /// seed &lt;ulong&gt; / mode Historical
+ /// turn starts the next turn's command list (one per Simulation.Step)
+ /// &lt;command&gt; ... policy ID LEVEL | budget OFFICE=SHARE,... | event ID OPTION | mobilize LEVEL |
+ /// security DELTA | appoint OFFICE PERSON | map ACTION Q R
+ /// end &lt;hex&gt; GameState.Hash() after the last turn (checks the replay)
+ /// Doubles are IEEE bit patterns in hex, so replays are exact; strings are percent-escaped (Uri.EscapeDataString).
+ /// </summary>
+ public sealed class SaveGame
+ {
+ public const int SchemaVersion = 1;
+ const string Magic = "statecraft-save";
+
+ readonly List<IReadOnlyList<Command>> turns = new List<IReadOnlyList<Command>>();
+
+ public string ContentHash { get; }
+ public ulong Seed { get; }
+ public Mode Mode { get; }
+ public IReadOnlyList<IReadOnlyList<Command>> Turns => turns;
+ /// <summary>GameState.Hash() after the last recorded turn (the new game's hash before any turn).</summary>
+ public string FinalHash { get; private set; }
+
+ public SaveGame(string contentHash, ulong seed, Mode mode, string initialHash)
+ {
+ ContentHash = contentHash ?? throw new ArgumentNullException(nameof(contentHash));
+ Seed = seed; Mode = mode;
+ FinalHash = initialHash ?? throw new ArgumentNullException(nameof(initialHash));
+ }
+
+ /// <summary>Appends one turn: the commands passed to Simulation.Step and the state it returned.</summary>
+ public void Record(IReadOnlyList<Command> commands, GameState after)
+ {
+ if (commands == null) throw new ArgumentNullException(nameof(commands));
+ if (after == null) throw new ArgumentNullException(nameof(after));
+ turns.Add(commands.ToList());
+ FinalHash = after.Hash();
+ }
+
+ public string Write()
+ {
+ var sb = new StringBuilder();
+ sb.Append(Magic).Append(' ').Append(SchemaVersion.ToString(CultureInfo.InvariantCulture)).Append('\n');
+ sb.Append("content ").Append(ContentHash).Append('\n');
+ sb.Append("seed ").Append(Seed.ToString(CultureInfo.InvariantCulture)).Append('\n');
+ sb.Append("mode ").Append(Mode.ToString()).Append('\n');
+ foreach (var t in turns)
+ {
+ sb.Append("turn\n");
+ foreach (var cmd in t) sb.Append(Format(cmd)).Append('\n');
+ }
+ sb.Append("end ").Append(FinalHash).Append('\n');
+ return sb.ToString();
+ }
+
+ static string Esc(string s) => Uri.EscapeDataString(s);
+ static string Num(double v) => BitConverter.DoubleToInt64Bits(v).ToString("X16", CultureInfo.InvariantCulture);
+ static string Int(int v) => v.ToString(CultureInfo.InvariantCulture);
+
+ static string Format(Command cmd) => cmd switch
+ {
+ SetPolicy p => $"policy {Esc(p.Policy)} {Num(p.Level)}",
+ AllocateBudget b => "budget " + (b.Shares == null || b.Shares.Count == 0 ? "-" :
+ string.Join(",", b.Shares.OrderBy(kv => kv.Key, StringComparer.Ordinal).Select(kv => Esc(kv.Key) + "=" + Num(kv.Value)))),
+ ChooseEventOption e => $"event {Esc(e.EventId)} {Esc(e.OptionId)}",
+ SetMobilization m => $"mobilize {Num(m.Level)}",
+ SecurityOrder o => $"security {Int(o.Delta)}",
+ Appoint a => $"appoint {Esc(a.Office)} {Esc(a.Person)}",
+ MapAction m => $"map {Esc(m.Action)} {Int(m.Q)} {Int(m.R)}",
+ _ => throw new ArgumentException($"Cannot save command kind '{cmd.Kind}'", nameof(cmd)),
+ };
+
+ /// <summary>Parses save text; any malformed line throws SaveException naming the line.</summary>
+ public static SaveGame Parse(string text)
+ {
+ if (text == null) throw new ArgumentNullException(nameof(text));
+ var lines = text.Replace("\r\n", "\n").Split('\n');
+ int n = lines.Length;
+ while (n > 0 && lines[n - 1] == "") n--;
+ if (n < 5) throw new SaveException(0, "Not a Statecraft save (too short)");
+ string[] Head(int i, string key, int parts)
+ {
+ var f = lines[i].Split(' ');
+ if (f[0] != key || f.Length != parts) throw new SaveException(i + 1, $"expected '{key}'");
+ return f;
+ }
+ var magic = Head(0, Magic, 2);
+ if (!int.TryParse(magic[1], NumberStyles.None, CultureInfo.InvariantCulture, out var version)) throw new SaveException(1, "bad schema version");
+ if (version > SchemaVersion) throw new SaveException(1, FormattableString.Invariant($"save schema version {version} is newer than this game ({SchemaVersion})"));
+ if (version < 1) throw new SaveException(1, FormattableString.Invariant($"unknown save schema version {version}"));
+ var content = Head(1, "content", 2)[1];
+ if (!ulong.TryParse(Head(2, "seed", 2)[1], NumberStyles.None, CultureInfo.InvariantCulture, out var seed)) throw new SaveException(3, "bad seed");
+ if (!Enum.TryParse<Mode>(Head(3, "mode", 2)[1], false, out var mode) || !Enum.IsDefined(typeof(Mode), mode)) throw new SaveException(4, "bad mode");
+ var end = Head(n - 1, "end", 2)[1];
+ var save = new SaveGame(content, seed, mode, end);
+ List<Command>? current = null;
+ for (int i = 4; i < n - 1; i++)
+ {
+ if (lines[i] == "turn") { current = new List<Command>(); save.turns.Add(current); continue; }
+ if (current == null) throw new SaveException(i + 1, "command before the first 'turn'");
+ current.Add(ParseCommand(i + 1, lines[i]));
+ }
+ return save;
+ }
+
+ static Command ParseCommand(int line, string text)
+ {
+ var f = text.Split(' ');
+ void Arity(int count) { if (f.Length != count) throw new SaveException(line, $"'{f[0]}' needs {count - 1} values"); }
+ string Str(string s)
+ {
+ try { return Uri.UnescapeDataString(s); }
+ catch (UriFormatException) { throw new SaveException(line, $"bad text '{s}'"); }
+ }
+ double Dbl(string s) => long.TryParse(s, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var bits) && s.Length == 16
+ ? BitConverter.Int64BitsToDouble(bits) : throw new SaveException(line, $"bad number '{s}'");
+ int I(string s) => int.TryParse(s, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var v) ? v : throw new SaveException(line, $"bad integer '{s}'");
+ switch (f[0])
+ {
+ case "policy": Arity(3); return new SetPolicy(Str(f[1]), Dbl(f[2]));
+ case "budget":
+ Arity(2);
+ var shares = new Dictionary<string, double>();
+ if (f[1] != "-")
+ foreach (var pair in f[1].Split(','))
+ {
+ var kv = pair.Split('=');
+ if (kv.Length != 2) throw new SaveException(line, $"bad budget share '{pair}'");
+ shares[Str(kv[0])] = Dbl(kv[1]);
+ }
+ return new AllocateBudget(shares);
+ case "event": Arity(3); return new ChooseEventOption(Str(f[1]), Str(f[2]));
+ case "mobilize": Arity(2); return new SetMobilization(Dbl(f[1]));
+ case "security": Arity(2); return new SecurityOrder(I(f[1]));
+ case "appoint": Arity(3); return new Appoint(Str(f[1]), Str(f[2]));
+ case "map": Arity(4); return new MapAction(Str(f[1]), I(f[2]), I(f[3]));
+ default: throw new SaveException(line, $"unknown command '{f[0]}'");
+ }
+ }
+ }
+}