A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Languages: the translation contract and the Hebrew parity harness (#1618, step 1) (#1626)
moshewe9839b9bb2dbc
diff --git a/changelog.d/1618-he-contract.md b/changelog.d/1618-he-contract.mdnew file mode 100644index 000000000..dcbcd57e9--- /dev/null+++ b/changelog.d/1618-he-contract.md@@ -0,0 +1,4 @@+- The translation contract for `translations/<lang>/` (#1618, step 1): the sim can read, write and resolve the three+ files (`Translations`), and put a Hebrew set on its typed records (`HebrewOverlay`). Nothing moves yet: the game still+ reads the inline Hebrew, and tests prove every Hebrew value comes back unchanged through the contract+ (`docs/translations.md`).diff --git a/docs/translations.md b/docs/translations.mdnew file mode 100644index 000000000..ce679db5b--- /dev/null+++ b/docs/translations.md@@ -0,0 +1,101 @@+# The translation contract++How a language other than English is stored in `translations/<lang>/` (#1618; owner, 24 October 2026: option (a), "verify+it doesnt cause any bugs, degregations or gaps"). English stays the source of record in `content/` and+`unity/Assets/UI/strings.en.yaml`. This page fixes the files, their keys and their order, so the tools, the sim and Unity+read and write them the same way.++**Status (step 1 of #1618):** the contract and its tests only. The game still reads Hebrew from the inline `*_he` fields+and `strings.he.yaml`; nothing has moved. `Translations.InlineHebrew` (sim) reads today's inline Hebrew as these files,+and the tests prove every value comes back unchanged. The tools' side (`tools/translate.py`, from #1604) joins the same+fixture check once #1604 has merged.++## The files++Each language has a folder named by its code (`he`, `ro`, `pt-BR`: lowercase ISO 639, then optional `-` subtags). Each of+the three files may be missing, which means the language has none of that kind.++| File | Key | Entry |+|---|---|---|+| `ui.yaml` | the key in `strings.en.yaml` (`hud.turn`) | the text |+| `events.yaml` | the event id (`altalena`) | `title`, `text`, `options` (option id: text, in the event's order), and `review` |+| `content.yaml` | a content key (below) | `text`, `review`, and for a language other than Hebrew `sources` |++```yaml+# events.yaml+altalena:+ title: "האלטלנה"+ text: "... {defense_minister}."+ options:+ enforce: "..."+ compromise: "..."+ review: "agent-checked"+```++`review` is `agent-checked` until a native speaker has read the text, and is left out after that (#564). It is the only+value it may have.++## Content keys++`<file>#<path>.<field>`, for example `people.yaml#people.ben_gurion.name` or+`map/units_1948.yaml#units.golani.anchors.0.place`.++- `<file>` is relative to `content/`.+- Each step of `<path>` is a mapping key, or, in a list, the item's `id`. An item with no text `id` is named by its index,+ so reordering such a list moves its translations to other items.+- `<field>` is the English field the text translates. `title_f` is the feminine form of `title` (offices.yaml's+ `title_he_f`).+- A key must name exactly one record, and that record must have the English field as text. `Translations.Resolve` refuses+ anything else.++A content field is keyed when its file has a `<field>_he` (or `<field>_he_f`) beside a text `<field>` in a record of+that shape. Every record of the same shape gets a key, whether or not it has its translation yet; that is the list+`tools/translate.py` (#1604) shows.++## What stays on the English record++These fields are facts about the record or its Hebrew, so they are never keys and stay in `content/`:+`*_he_sources`, `biography_sources.name_he`, `title_he_form`, `title_he_from`, `title_he_until`, `sources`, `status`,+`reviewed_by` and `reviewed_on`. A Hebrew entry may not carry `sources`; another language may carry its own.++## Not keyed yet++`content/map/subdistricts_1948.geojson` (`name_he`, `district_he`) and `content/map/control_1948_49.geojson`+(`legend_he`) hold Hebrew map labels that their digitisers write as a sourced set, next to the Arabic+(`tools/borders_digitise.py`, `tools/control_digitise.py`). Whether they stay in place or get keys is the owner's+decision on #1618; until then `TranslationsTests` names them, and fails if any other non-YAML content file has Hebrew.++## Order and format++A file lists its entries in this order: the events by `from` date, then id; the UI strings in `strings.en.yaml`'s order,+with any others after them by key; the content fields by file (`content/*.yaml`, then `content/map/*.yaml`, each in+ordinal order) and then by their position in the file.++The body (everything after the header comment) is fixed byte for byte: block mappings, two-space indents, every+string double-quoted the way JSON writes it (`json.dumps(..., ensure_ascii=False)`), and a key plain only when it is+letters, digits, `_`, `.` and `-`. The header comment belongs to the tool that writes the file.++## What the parser checks, and what it leaves to the content rules++`Translations.Parse` checks the shape: the known fields only, keys of the right form, no key twice, every text a+non-empty string, `review` only `agent-checked`, and `sources` as a list of `{ url, checked }`. The rules about the+text itself (an event is all or none, placeholders as in the English, no stray `{` or `}`, Hebrew letters, no direction+marks, the UI's approved wording) are the content rules. They run on the text where it is used, as they do today.++## The implementations and their tests++- `sim/Statecraft.Sim/Translations.cs`: keys, parsing, writing, `Resolve` and `InlineHebrew`.+- `sim/Statecraft.Sim/HebrewOverlay.cs`: puts a Hebrew set on the sim's typed `*He` properties. Unity reads the Hebrew of+ `map/localities_1948.yaml`, `map/settlements_1948.yaml` and `map/units_1948.yaml` itself+ (`HebrewOverlay.UnityReads`).+- `sim/Statecraft.Sim.Tests/translations_fixture/`: a small checkout with the edge cases and the bodies an+ implementation must write for it. `TranslationsTests` checks the sim's; `tools/translate.py` (#1604) gets the same+ check, so the tool and the game write one format.++`TranslationsTests` also checks the real content:+- every Hebrew value writes and reads back byte for byte;+- every content key resolves to the one record whose Hebrew it is;+- the overlay holds exactly what the loader reads, and clearing the Hebrew and applying the set brings it back;+- every `*He` property of a content type is covered;+- no key names a retained field;+- the localities bake's Hebrew all comes from keyed fields.diff --git a/sim/Statecraft.Sim.Tests/TranslationsTests.cs b/sim/Statecraft.Sim.Tests/TranslationsTests.csnew file mode 100644index 000000000..d494700d5--- /dev/null+++ b/sim/Statecraft.Sim.Tests/TranslationsTests.cs@@ -0,0 +1,357 @@+using System;+using System.Collections.Generic;+using System.IO;+using System.Linq;+using System.Reflection;+using System.Text.RegularExpressions;+using Statecraft.Sim;+using YamlDotNet.RepresentationModel;+using YamlDotNet.Serialization;++/// <summary>The translation contract (#1618, step 1; docs/translations.md): translations/<lang>/{ui,events,content}.yaml,+/// their keys, and today's inline Hebrew read as those files. The game still reads the inline Hebrew; these tests prove+/// every Hebrew value survives the contract unchanged before any of it moves.</summary>+public class TranslationsTests+{+ static string Repo => Path.GetDirectoryName(RealContentTests.ContentRoot())!;+ static string Ui(string lang) => Path.Combine(Repo, "unity", "Assets", "UI", $"strings.{lang}.yaml");+ static string FixtureDir => Path.Combine(Repo, "sim", "Statecraft.Sim.Tests", "translations_fixture");++ /// <summary>Content files with Hebrew the contract does not key, pending the owner's decision on #1618: map labels+ /// their digitisers write as a sourced set, beside the Arabic (tools/borders_digitise.py, tools/control_digitise.py).+ /// The sim never reads them (test_borders.py, test_control.py), so they are named here, not in the sim.</summary>+ static readonly string[] NotKeyed = { "map/control_1948_49.geojson", "map/subdistricts_1948.geojson" };++ static readonly Lazy<TranslationSet> Inline = new Lazy<TranslationSet>(() =>+ Translations.InlineHebrew(RealContentTests.ContentRoot(), Ui("en"), Ui("he")));++ static TranslationSet ParseBack(TranslationSet set)+ {+ var (ui, events, content) = Translations.Write(set);+ return Translations.Parse(set.Lang, ui, events, content);+ }++ static YamlNode Yaml(string rel)+ {+ var stream = new YamlStream();+ stream.Load(new StringReader(File.ReadAllText(Path.Combine(RealContentTests.ContentRoot(), rel))));+ return stream.Documents[0].RootNode;+ }++ static Dictionary<string, (string Text, string Review)> ByKey(IEnumerable<ContentTranslation> list) =>+ list.ToDictionary(t => t.Key, t => (t.Text, t.Review));++ static string Events(TranslationSet set) => Translations.Write(set).Events;++ // ---- one contract, two implementations ----++ [Fact]+ public void TheFixtureWritesTheBodiesTranslatePyWrites()+ {+ // tools/translate.py (#1604) gets the same check, so the tool and the game write one format.+ var set = Translations.InlineHebrew(Path.Combine(FixtureDir, "content"),+ Path.Combine(FixtureDir, "ui", "strings.en.yaml"), Path.Combine(FixtureDir, "ui", "strings.he.yaml"));+ var (ui, events, content) = Translations.Write(set);+ string Expected(string file) => File.ReadAllText(Path.Combine(FixtureDir, "expected", "he", file));+ Assert.Equal(Expected(Translations.UiFile), ui);+ Assert.Equal(Expected(Translations.EventsFile), events);+ Assert.Equal(Expected(Translations.ContentFile), content);+ }++ // ---- the real Hebrew, read through the contract ----++ [Fact]+ public void EveryHebrewValueReadsBackUnchanged()+ {+ var once = Translations.Write(Inline.Value);+ var back = ParseBack(Inline.Value);+ Assert.Equal(once, Translations.Write(back)); // byte for byte, every key, value, flag and position+ Assert.Equal(Inline.Value.Ui, back.Ui);+ Assert.Equal(ByKey(Inline.Value.Content), ByKey(back.Content));+ }++ [Fact]+ public void NoHebrewFieldIsMissedOrCountedTwice()+ {+ // A plain scan, independent of Fields(): every non-empty *_he / *_he_f text in content/*.yaml and+ // content/map/*.yaml, and every event's title_he and options' text_he. The inventory must have exactly these.+ var root = RealContentTests.ContentRoot();+ static bool Text(YamlNode n) => n is YamlScalarNode s && !string.IsNullOrEmpty(s.Value)+ && (s.Style != YamlDotNet.Core.ScalarStyle.Plain || !Regex.IsMatch(s.Value, "^(?:null|Null|NULL|~|true|True|TRUE|false|False|FALSE|[-+]?[0-9][0-9.eE+-]*)$"));+ int Count(YamlNode n, Func<string, bool> key) => n switch+ {+ YamlMappingNode m => m.Children.Sum(kv => (kv.Key is YamlScalarNode k && key(k.Value!) && Text(kv.Value) ? 1 : 0) + Count(kv.Value, key)),+ YamlSequenceNode q => q.Children.Sum(x => Count(x, key)),+ _ => 0,+ };+ var files = Directory.GetFiles(root, "*.yaml").Concat(Directory.GetFiles(Path.Combine(root, "map"), "*.yaml"));+ var scanned = files.Sum(f => Count(Yaml(Path.GetRelativePath(root, f)), k => Regex.IsMatch(k, "_he(_f)?$")));+ Assert.Equal(scanned, Inline.Value.Content.Count);+ Assert.Equal(Inline.Value.Content.Count, Inline.Value.Content.Select(t => t.Key).Distinct().Count());+ var events = Directory.GetFiles(Path.Combine(root, "events"), "*.yaml").Select(f => Yaml(Path.GetRelativePath(root, f))).ToList();+ Assert.Equal(events.Sum(e => Count(e, k => k == "title_he")), Inline.Value.Events.Count);+ Assert.Equal(events.Sum(e => Count(e, k => k == "text_he")), Inline.Value.Events.Sum(e => 1 + e.Options.Count));+ Assert.Equal(35, Inline.Value.Events.Count);+ }++ [Fact]+ public void AKeyThatYamlWouldTypeIsQuotedAndReadsBackAsText()+ {+ // An id or key spelt like null, a boolean or a number must survive every YAML reader as that text.+ var set = new TranslationSet { Lang = "he" };+ foreach (var k in new[] { "1948", "1e3", "null", "true", "on", "yes", "plain_key" })+ set.Ui.Add(new KeyValuePair<string, string>(k, "א"));+ set.Events.Add(new EventTranslation { Id = "no", Title = "א", Text = "ב",+ Options = { new KeyValuePair<string, string>("off", "ג"), new KeyValuePair<string, string>("y", "ד") } });+ var (ui, events, _) = Translations.Write(set);+ Assert.Contains("\"1948\": ", ui);+ Assert.Contains("\"on\": ", ui);+ Assert.Contains("\nplain_key: ", "\n" + ui);+ Assert.Contains("\"no\":\n", events);+ Assert.Contains(" \"off\": ", events);+ var back = ParseBack(set);+ Assert.Equal(set.Ui, back.Ui);+ Assert.Equal(new[] { "off", "y" }, back.Events.Single().Options.Select(o => o.Key));+ }++ [Theory]+ [InlineData("1948: \"א\"\n")]+ [InlineData("true: \"א\"\n")]+ [InlineData("null: \"א\"\n")]+ public void APlainKeyYamlWouldTypeIsRefused(string ui)+ {+ var e = Assert.Throws<ContentException>(() => Translations.Parse("he", ui, null, null));+ Assert.Contains("must be quoted", e.Message);+ Assert.Equal("1948", Translations.Parse("he", "\"1948\": \"א\"\n", null, null).Ui.Single().Key);+ }++ [Fact]+ public void TheUiStringsAreStringsHeYamlExactly()+ {+ var he = new DeserializerBuilder().Build().Deserialize<Dictionary<string, string>>(File.ReadAllText(Ui("he")));+ var en = new DeserializerBuilder().Build().Deserialize<Dictionary<string, string>>(File.ReadAllText(Ui("en")));+ Assert.Equal(he.OrderBy(kv => kv.Key, StringComparer.Ordinal), ParseBack(Inline.Value).Ui.OrderBy(kv => kv.Key, StringComparer.Ordinal));+ Assert.Equal(en.Keys, Inline.Value.Ui.Select(kv => kv.Key)); // in strings.en.yaml's order+ }++ [Fact]+ public void EveryContentKeyNamesOneRecordWhoseHebrewIsTheText()+ {+ var files = new Dictionary<string, YamlNode>();+ foreach (var t in Inline.Value.Content)+ {+ var key = ContentKey.TryParse(t.Key);+ Assert.NotNull(key);+ Assert.Equal(t.Key, key!.ToString());+ if (!files.TryGetValue(key.File, out var root)) files[key.File] = root = Yaml(key.File);+ var (record, english, hebrew) = Translations.Resolve(root, key);+ Assert.Equal(t.Text, ((YamlScalarNode)record.Children[new YamlScalarNode(hebrew)]).Value);+ var flag = record.Children.TryGetValue(new YamlScalarNode(hebrew + "_review"), out var r) ? ((YamlScalarNode)r).Value : "";+ Assert.Equal(flag, t.Review);+ Assert.True(record.Children.ContainsKey(new YamlScalarNode(english)), t.Key);+ }+ }++ [Fact]+ public void TheEventsAreTheEventFilesHebrew()+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ var withHebrew = c.Events.Where(e => e.TitleHe != "").ToList();+ Assert.Equal(withHebrew.Select(e => e.Id).OrderBy(x => x, StringComparer.Ordinal),+ Inline.Value.Events.Select(e => e.Id).OrderBy(x => x, StringComparer.Ordinal));+ Assert.Equal(withHebrew.OrderBy(e => e.From).ThenBy(e => e.Id, StringComparer.Ordinal).Select(e => e.Id),+ Inline.Value.Events.Select(e => e.Id)); // by date, then id+ }++ // ---- the typed records: the overlay fills exactly what the loader fills ----++ [Fact]+ public void TheOverlayHoldsWhatTheLoaderReadsFromTheInlineFields()+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ var typed = HebrewOverlay.Snapshot(c);+ var simFiles = new HashSet<string>(typed.Content.Select(t => ContentKey.TryParse(t.Key)!.File));+ var inlineSim = Inline.Value.Content.Where(t => simFiles.Contains(ContentKey.TryParse(t.Key)!.File));+ Assert.Equal(ByKey(inlineSim), ByKey(typed.Content));+ Assert.Equal(Events(Inline.Value), Events(new TranslationSet { Events = typed.Events.OrderBy(e => Inline.Value.Events.FindIndex(x => x.Id == e.Id)).ToList() }));+ // No gap: every keyed file is the sim's, or one Unity reads itself.+ Assert.All(Inline.Value.Content.Select(t => ContentKey.TryParse(t.Key)!.File).Distinct(),+ f => Assert.True(simFiles.Contains(f) || HebrewOverlay.UnityReads.Contains(f), f));+ }++ [Fact]+ public void ClearedContentGetsItsHebrewBackFromTheSet()+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ var before = Translations.Write(HebrewOverlay.Snapshot(c));+ HebrewOverlay.Clear(c);+ var empty = HebrewOverlay.Snapshot(c);+ Assert.Empty(empty.Events);+ Assert.Empty(empty.Content);+ HebrewOverlay.Apply(c, ParseBack(Inline.Value));+ Assert.Equal(before, Translations.Write(HebrewOverlay.Snapshot(c)));+ }++ [Fact]+ public void EveryHebrewPropertyOfTheContentTypesIsCovered()+ {+ // A new *He field on a content type must join the overlay, or its Hebrew would be lost when it moves.+ var covered = new HashSet<(Type, string)>(HebrewOverlay.Covered);+ var all = typeof(Content).Assembly.GetTypes()+ .Where(t => t.IsPublic && t.Namespace == "Statecraft.Sim")+ .SelectMany(t => t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)+ .Where(p => p.PropertyType == typeof(string) && p.CanWrite && Regex.IsMatch(p.Name, "He(F)?$"))+ .Select(p => (t, p.Name)))+ .ToList();+ Assert.NotEmpty(all);+ Assert.All(all, p => Assert.True(covered.Contains(p), $"{p.t.Name}.{p.Name} is not in HebrewOverlay"));+ }++ // ---- what stays on the record, and what the contract does not key yet ----++ [Fact]+ public void NoKeyNamesARetainedField()+ {+ var retained = new[] { "_sources", "_form", "_from", "_until", "status", "reviewed_by", "reviewed_on" };+ Assert.All(Inline.Value.Content, t =>+ Assert.DoesNotContain(retained, r => ContentKey.TryParse(t.Key)!.Field.EndsWith(r, StringComparison.Ordinal)));+ // The retained fields really are in the content, so this checks something.+ var people = File.ReadAllText(Path.Combine(RealContentTests.ContentRoot(), "people.yaml"));+ Assert.Contains("title_he_form:", people);+ Assert.Contains("biography_sources:", people);+ }++ [Fact]+ public void OnlyTheNamedGeoJsonFilesHaveHebrewTheContractDoesNotKey()+ {+ var root = RealContentTests.ContentRoot();+ var withHebrew = Directory.GetFiles(root, "*", SearchOption.AllDirectories)+ .Where(f => !f.EndsWith(".yaml", StringComparison.Ordinal) && !f.EndsWith(".tsv", StringComparison.Ordinal))+ .Where(f => !Path.GetRelativePath(root, f).Replace('\\', '/').StartsWith("schema/", StringComparison.Ordinal)) // field names, not content+ .Where(f => Regex.IsMatch(File.ReadAllText(f), "\"[a-z_]+_he(_f)?\"\\s*:"))+ .Select(f => Path.GetRelativePath(root, f).Replace('\\', '/'))+ .OrderBy(f => f, StringComparer.Ordinal);+ Assert.Equal(NotKeyed, withHebrew);+ }++ [Fact]+ public void TheLocalitiesBakeIsGeneratedFromKeyedFields()+ {+ // localities_1948.tsv is baked from the YAML (tools/localities_bake.py), so its Hebrew comes from keyed fields.+ var tsv = File.ReadAllText(Path.Combine(RealContentTests.ContentRoot(), "map", "localities_1948.tsv"));+ var keyed = new HashSet<string>(Inline.Value.Content+ .Where(t => t.Key.StartsWith("map/localities_1948.yaml#", StringComparison.Ordinal)).Select(t => t.Text));+ var lines = tsv.Split('\n');+ var header = lines.First(l => l.StartsWith("#place\t", StringComparison.Ordinal)).Substring(1).Split('\t');+ var columns = new[] { Array.IndexOf(header, "name_he"), Array.IndexOf(header, "today_he") };+ Assert.DoesNotContain(-1, columns);+ var hebrew = lines.Where(l => l.StartsWith("place\t", StringComparison.Ordinal)).Select(l => l.Split('\t'))+ .SelectMany(cells => columns.Select(i => cells[i])).Where(v => v != "").Distinct().ToList();+ Assert.All(hebrew, h => Assert.Contains(h, keyed));+ }++ // ---- the parser refuses what the contract does not allow ----++ const string GoodEvent = "vote:\n title: \"ההצבעה\"\n text: \"טקסט\"\n options:\n yes_vote: \"כן\"\n";++ [Theory]+ [InlineData("vote:\n title: \"א\"\n text: \"ב\"\n options:\n a: \"ג\"\n extra: \"x\"\n", "unknown field")]+ [InlineData("vote:\n title: \"\"\n text: \"ב\"\n options:\n a: \"ג\"\n", "empty")]+ [InlineData("vote:\n text: \"ב\"\n options:\n a: \"ג\"\n", "required")]+ [InlineData("vote:\n title: \"א\"\n text: \"ב\"\n", "required")]+ [InlineData("vote:\n title: \"א\"\n text: \"ב\"\n options:\n a: \"ג\"\n review: \"native\"\n", "must be agent-checked")]+ [InlineData("vote:\n title: [\"א\"]\n text: \"ב\"\n options:\n a: \"ג\"\n", "must be text")]+ [InlineData("vote:\n title: 12\n text: \"ב\"\n options:\n a: \"ג\"\n", "must be text")]+ [InlineData("Vote:\n title: \"א\"\n text: \"ב\"\n options:\n a: \"ג\"\n", "not an event id")]+ [InlineData(GoodEvent + GoodEvent, "")]+ public void TheEventsFileIsStrict(string events, string message)+ {+ var e = Assert.Throws<ContentException>(() => Translations.Parse("he", null, events, null));+ Assert.Contains(message, e.Message);+ }++ [Theory]+ [InlineData("\"people.yaml#people.ben_gurion.name\":\n text: \"דוד\"\n sources: [{url: \"https://x\", checked: 2026-10-24}]\n", "he", "stay on the record")]+ [InlineData("\"people.yaml#people.ben_gurion.name\":\n text: \"David\"\n sources: [{url: \"https://x\"}]\n", "fr", "required")]+ [InlineData("\"people.yaml#people.ben_gurion.name\":\n text: \"David\"\n sources: [{url: \"https://x\", checked: 24-10-2026}]\n", "fr", "a date")]+ [InlineData("\"people.yaml#name\":\n text: \"דוד\"\n", "he", "not a content key")]+ [InlineData("\"../people.yaml#people.ben_gurion.name\":\n text: \"דוד\"\n", "he", "not a content key")]+ [InlineData("\"people.yaml#people.ben_gurion.name\":\n text: \"דוד\"\n note: \"x\"\n", "he", "unknown field")]+ public void TheContentFileIsStrict(string content, string lang, string message)+ {+ var e = Assert.Throws<ContentException>(() => Translations.Parse(lang, null, null, content));+ Assert.Contains(message, e.Message);+ }++ [Theory]+ [InlineData("../he")]+ [InlineData("HE")]+ [InlineData("")]+ public void TheLanguageIsACode(string lang)+ {+ Assert.Throws<ContentException>(() => Translations.Parse(lang, null, null, null));+ }++ [Fact]+ public void ALanguageOtherThanHebrewMayCarryItsOwnSources()+ {+ var set = Translations.Parse("fr", "hud.turn: \"Tour {0}\"\n", null,+ "\"people.yaml#people.ben_gurion.name\":\n text: \"David Ben Gourion\"\n sources: [{url: \"https://example.org\", checked: 2026-10-24}]\n");+ Assert.Equal("https://example.org", set.Content.Single().Sources.Single().Url);+ Assert.Equal(set.Content.Single().Sources.Single().Url, ParseBack(set).Content.Single().Sources.Single().Url);+ }++ [Theory]+ [InlineData("hud turn: \"x\"\n", "not a UI string key")]+ [InlineData("hud.turn: \" \"\n", "empty")]+ [InlineData("hud.turn: \"א\"\nhud.turn: \"ב\"\n", "")]+ public void TheUiFileIsStrict(string ui, string message)+ {+ var e = Assert.Throws<ContentException>(() => Translations.Parse("he", ui, null, null));+ Assert.Contains(message, e.Message);+ }++ // ---- a key names exactly one record ----++ static YamlNode Doc(string yaml)+ {+ var s = new YamlStream();+ s.Load(new StringReader(yaml));+ return s.Documents[0].RootNode;+ }++ [Theory]+ [InlineData("people:\n - id: a\n name: A\n", "people.yaml#people.b.name", "no record 'b'")]+ [InlineData("people:\n - id: a\n name: A\n - id: a\n name: B\n", "people.yaml#people.a.name", "2 records")]+ [InlineData("people:\n - id: a\n born: 1886\n", "people.yaml#people.a.name", "no English 'name'")]+ [InlineData("people:\n - id: a\n name: 1948\n", "people.yaml#people.a.name", "no English 'name'")]+ [InlineData("other:\n - id: a\n name: A\n", "people.yaml#people.a.name", "no 'people'")]+ public void AKeyThatNamesNoSingleRecordIsRefused(string yaml, string key, string message)+ {+ var e = Assert.Throws<ContentException>(() => Translations.Resolve(Doc(yaml), ContentKey.TryParse(key)!));+ Assert.Contains(message, e.Message);+ }++ [Fact]+ public void TheFeminineTitleIsTitleF()+ {+ var (_, english, hebrew) = Translations.Resolve(Doc("offices:\n - id: pm\n title: Prime Minister\n title_he_f: x\n"),+ ContentKey.TryParse("offices.yaml#offices.pm.title_f")!);+ Assert.Equal(("title", "title_he_f"), (english, hebrew));+ }++ // ---- the overlay refuses a set that does not fit the content ----++ [Theory]+ [InlineData("nope:\n title: \"א\"\n text: \"ב\"\n options:\n a: \"ג\"\n", null, "no event has this id")]+ [InlineData("altalena:\n title: \"א\"\n text: \"ב\"\n options:\n nope: \"ג\"\n", null, "no such option")]+ [InlineData(null, "\"people.yaml#people.nobody.name\":\n text: \"א\"\n", "no record 'nobody'")]+ [InlineData(null, "\"rules.yaml#map_actions.capture.name\":\n text: \"א\"\n", "holds no Hebrew")]+ [InlineData(null, "\"sites.yaml#sites.mefalsim.name\":\n text: \"מפלסים\"\n review: \"agent-checked\"\n", "no review flag")]+ public void TheOverlayRefusesWhatDoesNotFit(string? events, string? content, string message)+ {+ var c = ContentLoader.Load(RealContentTests.ContentRoot());+ var e = Assert.Throws<ContentException>(() => HebrewOverlay.Apply(c, Translations.Parse("he", null, events, content)));+ Assert.Contains(message, e.Message);+ }+}diff --git a/sim/Statecraft.Sim.Tests/translations_fixture/README.md b/sim/Statecraft.Sim.Tests/translations_fixture/README.mdnew file mode 100644index 000000000..027048764--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/README.md@@ -0,0 +1,14 @@+# translations_fixture++A small checkout for the translation contract (#1618, [docs/translations.md](../../../docs/translations.md)): `content/`+and `ui/` hold inline Hebrew with the cases the contract must handle, and `expected/he/` holds the bodies (the files+without their header comment) an implementation must write for it. `TranslationsTests` (sim) checks the sim writes+exactly these bytes; once #1604 has merged, `tools/tests/test_translate.py` checks `tools/translate.py` does too, so the+tool and the game stay one contract.++The cases: events ordered by date, then id (`alpha` before `vote` on the same day; `quiet` has no Hebrew); a review flag+and none; text with `'`, `"` and `\`; an office's feminine title (`title_f`) beside its retained sources and date window;+a person whose `name_he` source sits in `biography_sources` (a list, so not a field); a record keyed by a mapping key+(`regions.north`); a list item with no id (keyed by its index); an English value that is not text (skipped); a Hebrew+field with no English (skipped); UI strings in strings.en.yaml's order with one only in Hebrew last, and a separator+whose spaces count.diff --git a/sim/Statecraft.Sim.Tests/translations_fixture/content/events/a_late.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/content/events/a_late.yamlnew file mode 100644index 000000000..852da440c--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/content/events/a_late.yaml@@ -0,0 +1,11 @@+id: late+title: Late+text: Later.+title_he: מאוחר+text_he: מאוחר יותר.+from: 1948-07-01+options:+ - id: continue+ text: Continue+ text_he: להמשיך+status: draftdiff --git a/sim/Statecraft.Sim.Tests/translations_fixture/content/events/b_vote.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/content/events/b_vote.yamlnew file mode 100644index 000000000..ea8171a3c--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/content/events/b_vote.yaml@@ -0,0 +1,15 @@+id: vote+title: The vote+text: '{prime_minister} asks the cabinet to vote.'+title_he: ההצבעה+text_he: '{prime_minister} מבקש מהממשלה להצביע על "התוכנית".'+text_he_review: agent-checked+from: 1948-06-01+options:+ - id: yes_vote+ text: Vote+ text_he: להצביע+ - id: wait+ text: Wait+ text_he: 'לחכות לצה"ל'+status: draftdiff --git a/sim/Statecraft.Sim.Tests/translations_fixture/content/events/c_quiet.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/content/events/c_quiet.yamlnew file mode 100644index 000000000..3794abcb1--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/content/events/c_quiet.yaml@@ -0,0 +1,8 @@+id: quiet+title: Quiet+text: Nothing happens.+from: 1948-05-15+options:+ - id: continue+ text: Continue+status: draftdiff --git a/sim/Statecraft.Sim.Tests/translations_fixture/content/events/d_alpha.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/content/events/d_alpha.yamlnew file mode 100644index 000000000..4bd05366d--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/content/events/d_alpha.yaml@@ -0,0 +1,12 @@+id: alpha+title: Alpha+text: First on the day.+title_he: אלפא+text_he: 'ראשון ביום: \ ולא שני.'+text_he_review: agent-checked+from: 1948-06-01+options:+ - id: continue+ text: Continue+ text_he: להמשיך+status: draftdiff --git a/sim/Statecraft.Sim.Tests/translations_fixture/content/map/units_1948.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/content/map/units_1948.yamlnew file mode 100644index 000000000..ad4aec57d--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/content/map/units_1948.yaml@@ -0,0 +1,10 @@+units:+ - id: golani+ name: Golani Brigade+ name_he: חטיבת גולני+ sector: The Galilee+ sector_he: הגליל+ anchors:+ - place: Yavne'el+ place_he: יבנאל+ - place: Tiberiasdiff --git a/sim/Statecraft.Sim.Tests/translations_fixture/content/offices.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/content/offices.yamlnew file mode 100644index 000000000..5c42c0be1--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/content/offices.yaml@@ -0,0 +1,10 @@+offices:+ - id: prime_minister+ title: Prime Minister+ title_he: ראש הממשלה+ title_he_sources: [{ url: "https://example.org/pm", checked: 2026-10-24 }]+ title_he_f: ראש הממשלה+ title_he_f_review: agent-checked+ title_he_from: 1948-05-14+ - id: foreign_minister+ title: Foreign Ministerdiff --git a/sim/Statecraft.Sim.Tests/translations_fixture/content/people.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/content/people.yamlnew file mode 100644index 000000000..cf08137ab--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/content/people.yaml@@ -0,0 +1,10 @@+people:+ - id: ben_gurion+ name: David Ben-Gurion+ name_he: דוד בן-גוריון+ name_he_review: agent-checked+ title_he_form: masculine+ biography_sources:+ name_he: [{ url: "https://example.org/bg", checked: 2026-10-24 }]+ - id: sharett+ name: Moshe Sharettdiff --git a/sim/Statecraft.Sim.Tests/translations_fixture/content/zeta.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/content/zeta.yamlnew file mode 100644index 000000000..42fd36f0e--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/content/zeta.yaml@@ -0,0 +1,15 @@+things:+ - id: line+ name: 'Line "A"'+ name_he: 'קו "א" \ ב'+ - id: year+ name: 1948+ name_he: שנה+ - id: hebrew_only+ name_he: רק בעברית+regions:+ north:+ label: North+ label_he: צפון+ south:+ label: Southdiff --git a/sim/Statecraft.Sim.Tests/translations_fixture/expected/he/content.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/expected/he/content.yamlnew file mode 100644index 000000000..4a8954e16--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/expected/he/content.yaml@@ -0,0 +1,18 @@+"offices.yaml#offices.prime_minister.title":+ text: "ראש הממשלה"+"offices.yaml#offices.prime_minister.title_f":+ text: "ראש הממשלה"+ review: "agent-checked"+"people.yaml#people.ben_gurion.name":+ text: "דוד בן-גוריון"+ review: "agent-checked"+"zeta.yaml#things.line.name":+ text: "קו \"א\" \\ ב"+"zeta.yaml#regions.north.label":+ text: "צפון"+"map/units_1948.yaml#units.golani.name":+ text: "חטיבת גולני"+"map/units_1948.yaml#units.golani.sector":+ text: "הגליל"+"map/units_1948.yaml#units.golani.anchors.0.place":+ text: "יבנאל"diff --git a/sim/Statecraft.Sim.Tests/translations_fixture/expected/he/events.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/expected/he/events.yamlnew file mode 100644index 000000000..4724887fa--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/expected/he/events.yaml@@ -0,0 +1,18 @@+alpha:+ title: "אלפא"+ text: "ראשון ביום: \\ ולא שני."+ options:+ continue: "להמשיך"+ review: "agent-checked"+vote:+ title: "ההצבעה"+ text: "{prime_minister} מבקש מהממשלה להצביע על \"התוכנית\"."+ options:+ yes_vote: "להצביע"+ wait: "לחכות לצה\"ל"+ review: "agent-checked"+late:+ title: "מאוחר"+ text: "מאוחר יותר."+ options:+ continue: "להמשיך"diff --git a/sim/Statecraft.Sim.Tests/translations_fixture/expected/he/ui.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/expected/he/ui.yamlnew file mode 100644index 000000000..b98f8ea39--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/expected/he/ui.yaml@@ -0,0 +1,4 @@+a.one: "אחת {0}"+a.sep: " · "+b.two: "שתיים"+z.only: "רק בעברית"diff --git a/sim/Statecraft.Sim.Tests/translations_fixture/ui/strings.en.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/ui/strings.en.yamlnew file mode 100644index 000000000..4a6ab7010--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/ui/strings.en.yaml@@ -0,0 +1,3 @@+a.one: "One {0}"+a.sep: " · "+b.two: "Two"diff --git a/sim/Statecraft.Sim.Tests/translations_fixture/ui/strings.he.yaml b/sim/Statecraft.Sim.Tests/translations_fixture/ui/strings.he.yamlnew file mode 100644index 000000000..0f6bf219a--- /dev/null+++ b/sim/Statecraft.Sim.Tests/translations_fixture/ui/strings.he.yaml@@ -0,0 +1,5 @@+# The Hebrew strings, out of order on purpose.+b.two: "שתיים"+z.only: "רק בעברית"+a.one: "אחת {0}"+a.sep: " · "diff --git a/sim/Statecraft.Sim/HebrewOverlay.cs b/sim/Statecraft.Sim/HebrewOverlay.csnew file mode 100644index 000000000..56edff5b4--- /dev/null+++ b/sim/Statecraft.Sim/HebrewOverlay.cs@@ -0,0 +1,131 @@+using System;+using System.Collections.Generic;+using System.Linq;+using System.Reflection;++namespace Statecraft.Sim+{+ /// <summary>Hebrew from a <see cref="TranslationSet"/> on the sim's typed records (#1618): the same *He properties the+ /// loader fills from the inline fields today, so the code that reads them does not change. Step 1 uses it in tests+ /// only; the loader keeps reading the inline Hebrew until a later step of #1618 switches it.</summary>+ public static class HebrewOverlay+ {+ sealed class Binding+ {+ public string File = "", List = "", Field = "";+ public Func<Content, IEnumerable<object>> Records = c => Enumerable.Empty<object>();+ public PropertyInfo Value = null!, Id = null!;+ public PropertyInfo? Review;+ }++ static Binding Bind<T>(string file, string list, string field, Func<Content, IEnumerable<T>> records, string value, string? review)+ where T : class => new Binding+ {+ File = file, List = list, Field = field, Records = c => records(c).Cast<object>(),+ Value = typeof(T).GetProperty(value) ?? throw new InvalidOperationException(typeof(T).Name + "." + value),+ Review = review == null ? null : typeof(T).GetProperty(review) ?? throw new InvalidOperationException(typeof(T).Name + "." + review),+ Id = typeof(T).GetProperty("Id") ?? throw new InvalidOperationException(typeof(T).Name + ".Id"),+ };++ // One per content field the sim holds in Hebrew. RealContent's HebrewOverlayTests checks, by reflection, that no+ // *He property of a content type is missing here.+ static readonly Binding[] Bindings =+ {+ Bind("offices.yaml", "offices", "title", c => c.Offices, nameof(Office.TitleHe), nameof(Office.TitleHeReview)),+ Bind("offices.yaml", "offices", "title_f", c => c.Offices, nameof(Office.TitleHeF), nameof(Office.TitleHeFReview)),+ Bind("parties.yaml", "parties", "name", c => c.Parties, nameof(Party.NameHe), nameof(Party.NameHeReview)),+ Bind("people.yaml", "people", "name", c => c.People, nameof(Person.NameHe), nameof(Person.NameHeReview)),+ Bind("legislatures.yaml", "legislatures", "body", c => c.Legislatures, nameof(Legislature.BodyHe), nameof(Legislature.BodyHeReview)),+ Bind("governments.yaml", "governments", "name", c => c.Governments, nameof(Government.NameHe), nameof(Government.NameHeReview)),+ Bind("map/locations_1948.yaml", "locations", "name", c => c.MapLocations, nameof(MapLocation.NameHe), nameof(MapLocation.NameHeReview)),+ Bind("projects.yaml", "projects", "name", c => c.ProjectKinds, nameof(ProjectKind.NameHe), nameof(ProjectKind.NameHeReview)),+ Bind("sites.yaml", "sites", "name", c => c.Sites, nameof(Site.NameHe), null),+ Bind("corridors.yaml", "corridors", "name", c => c.Corridors, nameof(CorridorDef.NameHe), null),+ Bind("objectives.yaml", "objectives", "name", c => c.Objectives, nameof(Objective.NameHe), nameof(Objective.NameHeReview)),+ };++ /// <summary>Content files whose Hebrew Unity reads itself (SettlementPlacer, Localities, UnitData): the sim has no+ /// typed record for them, so their keys are checked against the YAML (<see cref="Translations.Resolve"/>) only.</summary>+ public static readonly IReadOnlyList<string> UnityReads = new[]+ {+ "map/localities_1948.yaml", "map/settlements_1948.yaml", "map/units_1948.yaml",+ };++ /// <summary>The (type, property) pairs the overlay fills, events included.</summary>+ public static IEnumerable<(Type Type, string Property)> Covered =>+ Bindings.Select(b => (b.Value.DeclaringType!, b.Value.Name))+ .Concat(new[] { (typeof(GameEvent), nameof(GameEvent.TitleHe)), (typeof(GameEvent), nameof(GameEvent.TextHe)),+ (typeof(EventOption), nameof(EventOption.TextHe)) });++ /// <summary>The Hebrew the typed records hold, as a translation set (no UI strings: those are not content).</summary>+ public static TranslationSet Snapshot(Content c)+ {+ var set = new TranslationSet { Lang = Translations.Hebrew };+ foreach (var e in c.Events)+ if (e.TitleHe != "")+ set.Events.Add(new EventTranslation+ {+ Id = e.Id, Title = e.TitleHe, Text = e.TextHe, Review = e.TextHeReview,+ Options = e.Options.Where(o => o.TextHe != "").Select(o => new KeyValuePair<string, string>(o.Id, o.TextHe)).ToList(),+ });+ foreach (var b in Bindings)+ foreach (var r in b.Records(c))+ {+ var text = (string)b.Value.GetValue(r)!;+ if (text == "") continue;+ set.Content.Add(new ContentTranslation+ {+ Key = new ContentKey(b.File, new[] { b.List, (string)b.Id.GetValue(r)! }, b.Field).ToString(),+ Text = text, Review = b.Review == null ? "" : (string)b.Review.GetValue(r)!,+ });+ }+ return set;+ }++ /// <summary>Empties every Hebrew field the overlay fills (a test starts from content with no Hebrew).</summary>+ public static void Clear(Content c)+ {+ foreach (var e in c.Events)+ {+ e.TitleHe = ""; e.TextHe = ""; e.TextHeReview = "";+ foreach (var o in e.Options) o.TextHe = "";+ }+ foreach (var b in Bindings)+ foreach (var r in b.Records(c))+ {+ b.Value.SetValue(r, "");+ b.Review?.SetValue(r, "");+ }+ }++ /// <summary>Puts a Hebrew set on the typed records. Throws on a key that names no record, an option the event does+ /// not have, or a review flag on a field that has none; keys of <see cref="UnityReads"/> files are left to Unity.</summary>+ public static void Apply(Content c, TranslationSet set)+ {+ if (set.Lang != Translations.Hebrew) throw new ArgumentException("the sim holds Hebrew only", nameof(set));+ const string file = "translations/he/";+ foreach (var t in set.Events)+ {+ var e = c.Events.FirstOrDefault(x => x.Id == t.Id)+ ?? throw new ContentException(file + Translations.EventsFile, t.Id, "no event has this id");+ e.TitleHe = t.Title; e.TextHe = t.Text;+ if (t.Review != "") e.TextHeReview = t.Review;+ foreach (var o in t.Options)+ (e.Options.FirstOrDefault(x => x.Id == o.Key)+ ?? throw new ContentException(file + Translations.EventsFile, $"{t.Id}.options.{o.Key}", "the event has no such option")).TextHe = o.Value;+ }+ foreach (var t in set.Content)+ {+ var key = ContentKey.TryParse(t.Key) ?? throw new ContentException(file + Translations.ContentFile, t.Key, "not a content key");+ if (UnityReads.Contains(key.File)) continue;+ var b = Bindings.FirstOrDefault(x => x.File == key.File && x.Field == key.Field && key.Path.Count == 2 && key.Path[0] == x.List)+ ?? throw new ContentException(file + Translations.ContentFile, t.Key, "the sim holds no Hebrew for this field");+ var r = b.Records(c).FirstOrDefault(x => (string)b.Id.GetValue(x)! == key.Path[1])+ ?? throw new ContentException(file + Translations.ContentFile, t.Key, $"no record '{key.Path[1]}'");+ b.Value.SetValue(r, t.Text);+ if (t.Review != "")+ (b.Review ?? throw new ContentException(file + Translations.ContentFile, t.Key + ".review", "this field has no review flag")).SetValue(r, t.Review);+ }+ }+ }+}diff --git a/sim/Statecraft.Sim/Translations.cs b/sim/Statecraft.Sim/Translations.csnew file mode 100644index 000000000..52279a763--- /dev/null+++ b/sim/Statecraft.Sim/Translations.cs@@ -0,0 +1,466 @@+using System;+using System.Collections.Generic;+using System.Globalization;+using System.IO;+using System.Linq;+using System.Text;+using System.Text.RegularExpressions;+using YamlDotNet.Core;+using YamlDotNet.RepresentationModel;++namespace Statecraft.Sim+{+ // The translation contract (#1618, docs/translations.md): the three files of translations/<lang>/, their keys, how a+ // content key names one record's field, and how today's inline Hebrew reads as those files. Step 1 of #1618 adds the+ // contract only: the game still reads the inline Hebrew, and these types are used by tests and, later, the loader.++ /// <summary>A content field's key in translations/<lang>/content.yaml: <c><file>#<path>.<field></c>,+ /// for example <c>people.yaml#people.ben_gurion.name</c> or <c>map/units_1948.yaml#units.golani.anchors.0.place</c>.+ /// The file is relative to content/; each path step is a mapping key, or in a list the item's <c>id</c> (its index+ /// when it has none); the field is the English field the text translates. <c>title_f</c> is the feminine form of+ /// <c>title</c> (offices.yaml's title_he_f).</summary>+ public sealed class ContentKey+ {+ static readonly Regex Shape = new Regex(@"^([a-z0-9_]+(?:/[a-z0-9_]+)*\.yaml)#((?:[A-Za-z0-9_\-]+\.)+)([a-z][a-z0-9_]*)$",+ RegexOptions.CultureInvariant);++ public string File { get; }+ public IReadOnlyList<string> Path { get; }+ public string Field { get; }++ public ContentKey(string file, IReadOnlyList<string> path, string field)+ {+ File = file; Path = path; Field = field;+ }++ /// <summary>The key, or null when <paramref name="text"/> is not one.</summary>+ public static ContentKey? TryParse(string text)+ {+ var m = Shape.Match(text ?? "");+ if (!m.Success) return null;+ return new ContentKey(m.Groups[1].Value, m.Groups[2].Value.TrimEnd('.').Split('.'), m.Groups[3].Value);+ }++ public override string ToString() => File + "#" + string.Join(".", Path) + "." + Field;+ }++ public sealed class EventTranslation+ {+ public string Id { get; set; } = "";+ public string Title { get; set; } = "";+ public string Text { get; set; } = "";+ /// <summary>Option id and text, in the event file's order.</summary>+ public List<KeyValuePair<string, string>> Options { get; set; } = new List<KeyValuePair<string, string>>();+ /// <summary><see cref="HebrewReview.AgentChecked"/> until a native speaker has read the text, else "".</summary>+ public string Review { get; set; } = "";+ }++ public sealed class ContentTranslation+ {+ public string Key { get; set; } = "";+ public string Text { get; set; } = "";+ public string Review { get; set; } = "";+ /// <summary>A language other than Hebrew may carry the text's own sources; Hebrew keeps them on the record.</summary>+ public List<Source> Sources { get; set; } = new List<Source>();+ }++ /// <summary>One language's translations, in the order the files list them.</summary>+ public sealed class TranslationSet+ {+ public string Lang { get; set; } = "";+ public List<KeyValuePair<string, string>> Ui { get; set; } = new List<KeyValuePair<string, string>>();+ public List<EventTranslation> Events { get; set; } = new List<EventTranslation>();+ public List<ContentTranslation> Content { get; set; } = new List<ContentTranslation>();+ }++ public static class Translations+ {+ public const string Hebrew = "he";+ public const string UiFile = "ui.yaml", EventsFile = "events.yaml", ContentFile = "content.yaml";++ static readonly Regex LangCode = new Regex(@"^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$", RegexOptions.CultureInvariant);+ static readonly Regex UiKey = new Regex(@"^[A-Za-z0-9_]+(\.[A-Za-z0-9_\-]+)*$", RegexOptions.CultureInvariant);+ static readonly Regex Id = new Regex(@"^[a-z][a-z0-9_]*$", RegexOptions.CultureInvariant);+ static readonly Regex HeKey = new Regex(@"^(.+)_he(_f)?$", RegexOptions.CultureInvariant);+ static readonly Regex PlainKey = new Regex(@"^[A-Za-z0-9_.\-]+$", RegexOptions.CultureInvariant);+ // YAML 1.1's booleans: text in the 1.2 core schema, but PyYAML's safe_load (and YamlDotNet's typed bool reads,+ // tools/yaml12.py) still take them as true or false, so a key spelt so is quoted too.+ static readonly Regex Yaml11Bool = new Regex(@"^(?:y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF)$", RegexOptions.CultureInvariant);++ /// <summary>Fields that stay on the English record when the Hebrew moves (#1618): the Hebrew's sources, the grammar+ /// and date-window facts about it, and the record's own review. A key never names one of these.</summary>+ public static readonly IReadOnlyList<string> Retained = new[]+ {+ "*_he_sources", "biography_sources.name_he", "title_he_form", "title_he_from", "title_he_until",+ "sources", "status", "reviewed_by", "reviewed_on",+ };++ public static bool IsLanguage(string code) => code != null && LangCode.IsMatch(code);++ // ---- parsing ----++ /// <summary>Reads one language's three files (each may be null: the language has none of that kind). Checks the+ /// shape only: the fields, the keys, non-empty text and the review flag. The text's own rules (all or none,+ /// placeholders, Hebrew letters) are the content rules, applied where the text is used.</summary>+ public static TranslationSet Parse(string lang, string? ui, string? events, string? content)+ {+ if (!IsLanguage(lang)) throw new ContentException("translations", "(language)", $"'{lang}' is not a language code (fr, ar, pt-BR)");+ var set = new TranslationSet { Lang = lang };+ string Where(string file) => $"translations/{lang}/{file}";++ foreach (var (key, node) in Entries(Root(ui, Where(UiFile)), Where(UiFile)))+ {+ if (!UiKey.IsMatch(key)) throw new ContentException(Where(UiFile), key, "not a UI string key (as in strings.en.yaml)");+ set.Ui.Add(new KeyValuePair<string, string>(key, Text(node, Where(UiFile), key)));+ }++ foreach (var (id, node) in Entries(Root(events, Where(EventsFile)), Where(EventsFile)))+ {+ if (!Id.IsMatch(id)) throw new ContentException(Where(EventsFile), id, "not an event id");+ var map = Mapping(node, Where(EventsFile), id);+ Only(map, Where(EventsFile), id, "title", "text", "options", "review");+ var e = new EventTranslation+ {+ Id = id,+ Title = Text(Get(map, "title", Where(EventsFile), id), Where(EventsFile), id + ".title"),+ Text = Text(Get(map, "text", Where(EventsFile), id), Where(EventsFile), id + ".text"),+ Review = Review(map, Where(EventsFile), id),+ };+ foreach (var (oid, text) in Entries(Mapping(Get(map, "options", Where(EventsFile), id), Where(EventsFile), id + ".options"),+ Where(EventsFile)))+ {+ if (!Id.IsMatch(oid)) throw new ContentException(Where(EventsFile), $"{id}.options.{oid}", "not an option id");+ e.Options.Add(new KeyValuePair<string, string>(oid, Text(text, Where(EventsFile), $"{id}.options.{oid}")));+ }+ set.Events.Add(e);+ }++ foreach (var (key, node) in Entries(Root(content, Where(ContentFile)), Where(ContentFile)))+ {+ if (ContentKey.TryParse(key) == null)+ throw new ContentException(Where(ContentFile), key, "not a content key (<file>#<path>.<field>, docs/translations.md)");+ var map = Mapping(node, Where(ContentFile), key);+ Only(map, Where(ContentFile), key, "text", "review", "sources");+ var t = new ContentTranslation+ {+ Key = key,+ Text = Text(Get(map, "text", Where(ContentFile), key), Where(ContentFile), key + ".text"),+ Review = Review(map, Where(ContentFile), key),+ };+ if (map.Children.TryGetValue(new YamlScalarNode("sources"), out var sources))+ {+ if (lang == Hebrew)+ throw new ContentException(Where(ContentFile), key + ".sources", "the Hebrew's sources stay on the record (name_he_sources, biography_sources.name_he)");+ t.Sources = Sources(sources, Where(ContentFile), key + ".sources");+ }+ set.Content.Add(t);+ }+ return set;+ }++ static YamlMappingNode Root(string? text, string file)+ {+ if (string.IsNullOrEmpty(text)) return new YamlMappingNode();+ var stream = new YamlStream();+ try { stream.Load(new StringReader(text)); }+ catch (YamlException e) { throw new ContentException(file, $"line {e.Start.Line}", e.InnerException?.Message ?? e.Message); }+ catch (ArgumentException e) { throw new ContentException(file, "(file)", e.Message); } // a repeated key+ if (stream.Documents.Count == 0) return new YamlMappingNode();+ if (stream.Documents.Count > 1) throw new ContentException(file, "(file)", "one YAML document only");+ var root = stream.Documents[0].RootNode;+ if (root is YamlScalarNode s && Core(s) == "null") return new YamlMappingNode();+ return root as YamlMappingNode ?? throw new ContentException(file, "(file)", "must be a mapping");+ }++ static IEnumerable<(string Key, YamlNode Value)> Entries(YamlMappingNode map, string file)+ {+ var seen = new HashSet<string>(StringComparer.Ordinal);+ foreach (var kv in map.Children)+ {+ var key = kv.Key is YamlScalarNode k ? k.Value ?? "" : throw new ContentException(file, "(key)", "a key must be text");+ // A plain key YAML reads as null, a boolean or a number would come back from tools/yaml12.py typed, not as+ // this text: it must be quoted (as the writer quotes it).+ if (Core((YamlScalarNode)kv.Key) != "str")+ throw new ContentException(file, key, "a key YAML reads as null, a boolean or a number must be quoted");+ if (!seen.Add(key)) throw new ContentException(file, key, "repeated");+ yield return (key, kv.Value);+ }+ }++ static YamlMappingNode Mapping(YamlNode node, string file, string field) =>+ node as YamlMappingNode ?? throw new ContentException(file, field, "must be a mapping");++ static YamlNode Get(YamlMappingNode map, string key, string file, string field) =>+ map.Children.TryGetValue(new YamlScalarNode(key), out var v) ? v : throw new ContentException(file, $"{field}.{key}", "required");++ static void Only(YamlMappingNode map, string file, string field, params string[] keys)+ {+ foreach (var (key, _) in Entries(map, file))+ if (Array.IndexOf(keys, key) < 0) throw new ContentException(file, $"{field}.{key}", $"unknown field (must be {string.Join(", ", keys)})");+ }++ static string Text(YamlNode node, string file, string field)+ {+ if (!(node is YamlScalarNode s) || !IsString(s)) throw new ContentException(file, field, "must be text");+ if (string.IsNullOrWhiteSpace(s.Value)) throw new ContentException(file, field, "empty: leave the key out instead");+ return s.Value!;+ }++ static string Review(YamlMappingNode map, string file, string field)+ {+ if (!map.Children.TryGetValue(new YamlScalarNode("review"), out var v)) return "";+ var text = v is YamlScalarNode s ? s.Value : null;+ if (text != HebrewReview.AgentChecked)+ throw new ContentException(file, field + ".review", $"must be {HebrewReview.AgentChecked}, or left out once a native speaker has read the text (#564)");+ return text;+ }++ static List<Source> Sources(YamlNode node, string file, string field)+ {+ var list = new List<Source>();+ if (!(node is YamlSequenceNode items)) throw new ContentException(file, field, "must be a list of { url, checked }");+ for (int i = 0; i < items.Children.Count; i++)+ {+ var at = $"{field}[{i}]";+ var map = Mapping(items.Children[i], file, at);+ Only(map, file, at, "url", "checked");+ var url = Text(Get(map, "url", file, at), file, at + ".url");+ var day = Get(map, "checked", file, at) is YamlScalarNode d ? d.Value : null;+ if (!DateTime.TryParseExact(day, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var dt))+ throw new ContentException(file, at + ".checked", "must be a date, YYYY-MM-DD");+ list.Add(new Source { Url = url, Checked = dt });+ }+ return list;+ }++ // ---- YAML 1.2 core schema, for "is this scalar text" (tools/yaml12.py reads the same files the same way) ----++ static readonly (string Tag, Regex Pattern)[] CoreResolvers =+ {+ ("null", new Regex(@"^(?:null|Null|NULL|~|)$", RegexOptions.CultureInvariant)),+ ("bool", new Regex(@"^(?:true|True|TRUE|false|False|FALSE)$", RegexOptions.CultureInvariant)),+ ("int", new Regex(@"^(?:[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+)$", RegexOptions.CultureInvariant)),+ ("float", new Regex(@"^(?:[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)(?:[eE][-+]?[0-9]+)?|[-+]?\.(?:inf|Inf|INF)|\.(?:nan|NaN|NAN))$",+ RegexOptions.CultureInvariant)),+ };++ /// <summary>The core-schema type of a scalar: "str", or null/bool/int/float for a plain scalar that resolves so.</summary>+ static string Core(YamlScalarNode s)+ {+ if (!s.Tag.IsEmpty && !s.Tag.IsNonSpecific) return s.Tag.Value == "tag:yaml.org,2002:str" ? "str" : s.Tag.Value;+ if (s.Style != ScalarStyle.Plain) return "str";+ foreach (var (tag, pattern) in CoreResolvers)+ if (pattern.IsMatch(s.Value ?? "")) return tag;+ return "str";+ }++ static bool IsString(YamlNode? node) => node is YamlScalarNode s && Core(s) == "str";++ static string? StringOf(YamlMappingNode map, string key) =>+ map.Children.TryGetValue(new YamlScalarNode(key), out var v) && IsString(v) ? ((YamlScalarNode)v).Value : null;++ // ---- writing (the body tools/translate.py, from #1604, writes under its header comment, byte for byte) ----++ /// <summary>The three files' bodies, as tools/translate.py writes them: block mappings down to double-quoted (JSON)+ /// strings, in the set's order. A language with no entries of a kind gets an empty body.</summary>+ public static (string Ui, string Events, string Content) Write(TranslationSet set)+ {+ var ui = new StringBuilder();+ foreach (var kv in set.Ui) ui.Append(Key(kv.Key)).Append(": ").Append(Json(kv.Value)).Append('\n');+ var events = new StringBuilder();+ foreach (var e in set.Events)+ {+ events.Append(Key(e.Id)).Append(":\n");+ events.Append(" title: ").Append(Json(e.Title)).Append('\n');+ events.Append(" text: ").Append(Json(e.Text)).Append('\n');+ events.Append(" options:\n");+ foreach (var o in e.Options) events.Append(" ").Append(Key(o.Key)).Append(": ").Append(Json(o.Value)).Append('\n');+ if (e.Review != "") events.Append(" review: ").Append(Json(e.Review)).Append('\n');+ }+ var content = new StringBuilder();+ foreach (var t in set.Content)+ {+ content.Append(Key(t.Key)).Append(":\n");+ content.Append(" text: ").Append(Json(t.Text)).Append('\n');+ if (t.Review != "") content.Append(" review: ").Append(Json(t.Review)).Append('\n');+ if (t.Sources.Count > 0)+ content.Append(" sources: [").Append(string.Join(", ", t.Sources.Select(s =>+ "{\"url\": " + Json(s.Url) + ", \"checked\": " + Json(s.Checked.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)) + "}")))+ .Append("]\n");+ }+ return (ui.ToString(), events.ToString(), content.ToString());+ }++ /// <summary>A key, plain only when every YAML reader takes it as this text: letters, digits, '_', '.' and '-', and+ /// not something the 1.2 core schema types (null, true, 1948, 1e3) or a YAML 1.1 boolean (on, yes).</summary>+ static string Key(string key) =>+ PlainKey.IsMatch(key) && Core(new YamlScalarNode(key) { Style = ScalarStyle.Plain }) == "str" && !Yaml11Bool.IsMatch(key) ? key : Json(key);++ /// <summary>A JSON string, as Python's json.dumps(ensure_ascii=False) writes it (a valid YAML double-quoted scalar).</summary>+ internal static string Json(string s)+ {+ var b = new StringBuilder(s.Length + 2).Append('"');+ foreach (var ch in s)+ {+ switch (ch)+ {+ case '"': b.Append("\\\""); break;+ case '\\': b.Append("\\\\"); break;+ case '\n': b.Append("\\n"); break;+ case '\r': b.Append("\\r"); break;+ case '\t': b.Append("\\t"); break;+ case '\b': b.Append("\\b"); break;+ case '\f': b.Append("\\f"); break;+ default:+ if (ch < 0x20) b.Append("\\u").Append(((int)ch).ToString("x4", CultureInfo.InvariantCulture));+ else b.Append(ch);+ break;+ }+ }+ return b.Append('"').ToString();+ }++ // ---- resolving a content key ----++ /// <summary>The record a content key names in its file's YAML, and the names of its English and Hebrew fields.+ /// Throws unless the path leads to exactly one mapping whose English field is text.</summary>+ public static (YamlMappingNode Record, string English, string Hebrew) Resolve(YamlNode root, ContentKey key)+ {+ string at = key.File + "#" + string.Join(".", key.Path);+ YamlNode node = root;+ foreach (var step in key.Path)+ {+ if (node is YamlMappingNode map)+ {+ if (!map.Children.TryGetValue(new YamlScalarNode(step), out var next))+ throw new ContentException(key.File, at, $"no '{step}' in the record");+ node = next;+ }+ else if (node is YamlSequenceNode list)+ {+ var hits = list.Children.Where((x, i) => Ident(x, i) == step).ToList();+ if (hits.Count != 1)+ throw new ContentException(key.File, at, hits.Count == 0 ? $"no record '{step}'" : $"{hits.Count} records are '{step}': the key must name one");+ node = hits[0];+ }+ else throw new ContentException(key.File, at, $"'{step}' is past the end of the record");+ }+ var record = node as YamlMappingNode ?? throw new ContentException(key.File, at, "not a record");+ if (IsString(Value(record, key.Field))) return (record, key.Field, key.Field + "_he");+ if (key.Field.EndsWith("_f", StringComparison.Ordinal) && IsString(Value(record, key.Field.Substring(0, key.Field.Length - 2))))+ return (record, key.Field.Substring(0, key.Field.Length - 2), key.Field.Substring(0, key.Field.Length - 2) + "_he_f");+ throw new ContentException(key.File, key.ToString(), $"the record has no English '{key.Field}' to translate");+ }++ static YamlNode? Value(YamlMappingNode map, string key) =>+ map.Children.TryGetValue(new YamlScalarNode(key), out var v) ? v : null;++ /// <summary>A list item's path step: its id when it has a text id, else its index.</summary>+ static string Ident(YamlNode item, int index) =>+ item is YamlMappingNode m && StringOf(m, "id") is string id ? id : index.ToString(CultureInfo.InvariantCulture);++ // ---- today's inline Hebrew, read as the contract's files ----++ /// <summary>Today's inline Hebrew (strings.he.yaml, the events' *_he fields, every content field with a _he form)+ /// as one translation set, in the order tools/translate.py lists it: the events by date and id, the UI strings in+ /// strings.en.yaml's order (any others after, by key), then the content fields by file and position.+ /// <paramref name="contentFiles"/> are the YAML files relative to content/, in order; <paramref name="eventFiles"/>+ /// the event files.</summary>+ public static TranslationSet InlineHebrew(Func<string, string?> readFile, IEnumerable<string> contentFiles,+ IEnumerable<string> eventFiles, string uiEnglish, string uiHebrew)+ {+ var set = new TranslationSet { Lang = Hebrew };+ var events = new List<(string From, string Id, YamlMappingNode Node)>();+ foreach (var rel in eventFiles)+ {+ var root = Root(readFile(rel), rel);+ if (StringOf(root, "id") is string id) events.Add((StringOf(root, "from") ?? "", id, root));+ }+ foreach (var (_, id, e) in events.OrderBy(x => x.From, StringComparer.Ordinal).ThenBy(x => x.Id, StringComparer.Ordinal))+ {+ if (string.IsNullOrEmpty(StringOf(e, "title_he"))) continue;+ var t = new EventTranslation { Id = id, Title = StringOf(e, "title_he")!, Text = StringOf(e, "text_he") ?? "" };+ if (!string.IsNullOrEmpty(StringOf(e, "text_he_review"))) t.Review = StringOf(e, "text_he_review")!;+ if (Value(e, "options") is YamlSequenceNode options)+ foreach (var o in options.Children.OfType<YamlMappingNode>())+ if (StringOf(o, "id") is string oid && !string.IsNullOrEmpty(StringOf(o, "text_he")))+ t.Options.Add(new KeyValuePair<string, string>(oid, StringOf(o, "text_he")!));+ set.Events.Add(t);+ }++ var order = Entries(Root(uiEnglish, "strings.en.yaml"), "strings.en.yaml").Select((kv, i) => (kv.Key, i))+ .ToDictionary(x => x.Key, x => x.i, StringComparer.Ordinal);+ set.Ui = Entries(Root(uiHebrew, "strings.he.yaml"), "strings.he.yaml")+ .Where(kv => IsString(kv.Value))+ .Select(kv => new KeyValuePair<string, string>(kv.Key, ((YamlScalarNode)kv.Value).Value ?? ""))+ .OrderBy(kv => order.TryGetValue(kv.Key, out var i) ? i : order.Count).ThenBy(kv => kv.Key, StringComparer.Ordinal)+ .ToList();++ foreach (var rel in contentFiles)+ foreach (var f in Fields(rel, Root(readFile(rel), rel)))+ if (f.Hebrew != "")+ set.Content.Add(new ContentTranslation { Key = f.Key.ToString(), Text = f.Hebrew, Review = f.Review });+ return set;+ }++ /// <summary><see cref="InlineHebrew(Func{string, string?}, IEnumerable{string}, IEnumerable{string}, string, string)"/>+ /// for a checkout: content/*.yaml then content/map/*.yaml, each in ordinal order.</summary>+ public static TranslationSet InlineHebrew(string contentRoot, string uiEnglishPath, string uiHebrewPath)+ {+ IEnumerable<string> Yaml(string dir, string prefix) => Directory.Exists(System.IO.Path.Combine(contentRoot, dir))+ ? Directory.GetFiles(System.IO.Path.Combine(contentRoot, dir), "*.yaml").Select(f => prefix + System.IO.Path.GetFileName(f))+ .OrderBy(f => f, StringComparer.Ordinal)+ : Enumerable.Empty<string>();+ string? Read(string rel)+ {+ var path = System.IO.Path.Combine(contentRoot, rel);+ return System.IO.File.Exists(path) ? System.IO.File.ReadAllText(path) : null;+ }+ return InlineHebrew(Read, Yaml(".", "").Concat(Yaml("map", "map/")), Yaml("events", "events/"),+ System.IO.File.ReadAllText(uiEnglishPath), System.IO.File.ReadAllText(uiHebrewPath));+ }++ /// <summary>Every field of a content file that has a Hebrew form: one entry for each record shaped like one that has+ /// the _he key, with the English beside it, whether or not that record has its Hebrew yet (tools/translate.py's+ /// catalog). Within a record the fields come in the order the file first shows them.</summary>+ public static IEnumerable<(ContentKey Key, string English, string Hebrew, string Review)> Fields(string file, YamlNode root)+ {+ var nodes = new List<(string Shape, List<string> Ids, YamlMappingNode Node)>();+ void Walk(YamlNode node, List<string> ids, string shape)+ {+ if (node is YamlMappingNode map)+ {+ nodes.Add((shape, ids, map));+ foreach (var kv in map.Children)+ {+ var k = (kv.Key as YamlScalarNode)?.Value ?? "";+ Walk(kv.Value, new List<string>(ids) { k }, shape + "\u0001" + k);+ }+ }+ else if (node is YamlSequenceNode list)+ for (int i = 0; i < list.Children.Count; i++)+ Walk(list.Children[i], new List<string>(ids) { Ident(list.Children[i], i) }, shape + "\u0001*");+ }+ Walk(root, new List<string>(), "");++ var fields = new List<(string Shape, string Key)>();+ var seen = new HashSet<(string, string)>();+ foreach (var (shape, _, node) in nodes)+ foreach (var kv in node.Children)+ if (kv.Key is YamlScalarNode k && HeKey.IsMatch(k.Value ?? "") && IsString(kv.Value) && seen.Add((shape, k.Value!)))+ fields.Add((shape, k.Value!));++ foreach (var (shape, ids, node) in nodes)+ foreach (var (s, heKey) in fields)+ {+ if (s != shape) continue;+ var m = HeKey.Match(heKey);+ var english = StringOf(node, m.Groups[1].Value);+ if (english == null) continue;+ var field = m.Groups[1].Value + (m.Groups[2].Success ? "_f" : "");+ yield return (new ContentKey(file, ids.ToArray(), field), english, StringOf(node, heKey) ?? "",+ string.IsNullOrEmpty(StringOf(node, heKey + "_review")) ? "" : StringOf(node, heKey + "_review")!);+ }+ }+ }+}