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.

180 KB
Raw Blame
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using YamlDotNet.Core;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

namespace Statecraft.Sim
{
    public static class ContentLoader
    {
        sealed class OfficesFile { public List<Office> Offices { get; set; } = null!; }
        sealed class PartiesFile { public List<Party> Parties { get; set; } = null!; }
        sealed class PeopleFile { public List<Person> People { get; set; } = null!; }
        sealed class LegislaturesFile { public List<Legislature> Legislatures { get; set; } = new List<Legislature>(); }
        sealed class ErasFile { public List<Era> Eras { get; set; } = new List<Era>(); }
        sealed class GovernmentsFile { public List<Government> Governments { get; set; } = new List<Government>(); }
        sealed class ModelFile
        {
            public List<Indicator> Indicators { get; set; } = new List<Indicator>();
            public List<Policy> Policies { get; set; } = new List<Policy>();
            public List<Effect> Effects { get; set; } = new List<Effect>();
            public List<Situation> Situations { get; set; } = new List<Situation>();
            public List<VoterGroup> VoterGroups { get; set; } = new List<VoterGroup>();
            public List<Actor> Actors { get; set; } = new List<Actor>();
            public List<MoneyAccount> Money { get; set; } = new List<MoneyAccount>();
        }
        sealed class AliyahFile
        {
            public List<Region> Regions { get; set; } = new List<Region>();
            public List<AliyahPeriod> Series { get; set; } = new List<AliyahPeriod>();
        }
        sealed class PopulationFile { public List<PopulationAnchor> Anchors { get; set; } = new List<PopulationAnchor>(); }
        sealed class HexBounds { public double Lon0 { get; set; } public double Lon1 { get; set; } public double Lat0 { get; set; } public double Lat1 { get; set; } }
        /// <summary>hexes.json is JSON, which YAML 1.2 reads as a flow mapping; every key the tool writes is declared.</summary>
        sealed class MapFile
        {
            public List<string> Attribution { get; set; } = new List<string>();
            public HexBounds Bounds { get; set; } = new HexBounds();
            public double HexSizeKm { get; set; }
            public string Layout { get; set; } = "";
            public List<MapHex> Hexes { get; set; } = new List<MapHex>();
        }
        sealed class SettlementHexesFile { public List<SettlementHex> Settlements { get; set; } = new List<SettlementHex>(); }
        sealed class LocalityHexesFile { public List<LocalityHex> Localities { get; set; } = new List<LocalityHex>(); }
        /// <summary>A map/locality_hexes.yaml row. q and r are nullable so a missing one is refused, never read as 0.</summary>
        sealed class LocalityHex { public string Id { get; set; } = ""; public int? Q { get; set; } public int? R { get; set; } }
        sealed class MapLocationsFile { public List<MapLocation> Locations { get; set; } = new List<MapLocation>(); }
        sealed class SettlementTargetsFile { public List<SettlementTarget> Targets { get; set; } = new List<SettlementTarget>(); }
        sealed class CitiesFile { public List<CityStart> Cities { get; set; } = new List<CityStart>(); }
        sealed class PlayerRegionsFile { public List<PlayerRegionDefinition> PlayerRegions { get; set; } = null!; }
        sealed class UnitTypesFile { public List<UnitType> Types { get; set; } = new List<UnitType>(); }
        sealed class SitesFile { public List<Site> Sites { get; set; } = new List<Site>(); }
        sealed class ProjectsFile { public List<ProjectKind> Projects { get; set; } = new List<ProjectKind>(); }
        sealed class CorridorsFile { public List<CorridorDef> Corridors { get; set; } = new List<CorridorDef>(); }
        sealed class ObjectivesFile { public List<Objective> Objectives { get; set; } = new List<Objective>(); }
        sealed class Gdd03EventsFile
        {
            public string Ruleset { get; set; } = "";
            public List<EventExclusion>? Exclusions { get; set; }
        }
        sealed class Gdd03StartFile
        {
            public string Ruleset { get; set; } = "";
            public List<StartCampBinding>? MilitaryCamps { get; set; }
            public List<StartFormationCombatXp>? FormationCombatXp { get; set; }
        }
        sealed class StartFormationCombatXp
        {
            public string Row { get; set; } = "";
            public int? CombatXp { get; set; }
        }
        sealed class StartCampBinding
        {
            public string City { get; set; } = "";
            public string Location { get; set; } = "";
        }
        sealed class EventExclusion
        {
            public string Id { get; set; } = "";
            public string Reason { get; set; } = "";
        }


        public const string HexesFile = "map/hexes.json";
        public const string SettlementHexesFileName = "map/settlement_hexes.yaml";
        public const string SettlementsFileName = "map/settlements_1948.yaml";
        public const string MapLocationsFileName = "map/locations_1948.yaml";
        public const string SettlementTargetsFileName = "settlement_targets.yaml";
        /// <summary>The two values of a target row's <c>residents</c> (R-CTRL-016).</summary>
        public const string Fled = "fled", Stayed = "stayed";
        /// <summary>The settlements_1948.yaml row type a settlement target must have (Q-TGT-1 (a)).</summary>
        public const string ArabTown = "arab_town";

        /// <summary>The ids and names of settlements_1948.yaml, which the tools own (its other keys are not the sim's business),
        /// so it is read as plain maps rather than through the strict content types.</summary>
        static List<(string id, string name, string type)> ReadSettlements(Func<string, string?> readFile)
        {
            string? text;
            try { text = readFile(SettlementsFileName); }
            catch (IOException e) { throw new ContentException(SettlementsFileName, "(file)", e.Message); }
            catch (UnauthorizedAccessException e) { throw new ContentException(SettlementsFileName, "(file)", e.Message); }
            if (text == null) throw new ContentException(SettlementsFileName, "(file)", "missing file");
            try
            {
                var file = new DeserializerBuilder().Build().Deserialize<Dictionary<string, List<Dictionary<string, object>>>>(text);
                if (file == null || !file.TryGetValue("settlements", out var rows)) throw new ContentException(SettlementsFileName, "settlements", "required");
                return rows.Select((r, i) =>
                {
                    var sid = r.TryGetValue("id", out var id) && id is string s0 && s0 != ""
                        ? s0 : throw new ContentException(SettlementsFileName, $"settlements[{i}].id", "required");
                    // The sim reads these rows untyped, so it checks their keys itself: a misspelt key (name_he_reveiw)
                    // would otherwise load as if absent. The same keys as Unity's SettlementPlacer.Settlement.
                    foreach (var key in r.Keys)
                        if (!SettlementKeys.Contains(key)) throw new ContentException(SettlementsFileName, $"settlements[{sid}].{key}", "unknown field");
                    var sname = r.TryGetValue("name", out var name) && name is string n0 && !string.IsNullOrWhiteSpace(n0)
                        ? n0 : throw new ContentException(SettlementsFileName, $"settlements[{i}].name", "required (the name shown to the player)");
                    HebrewName(SettlementsFileName, $"settlements[{sid}]", "name_he", r.TryGetValue("name_he", out var he) && he is string hs ? hs : "",
                        SettlementSources(r, $"settlements[{sid}].name_he_sources"),
                        r.TryGetValue("name_he_review", out var rv) && rv is string rs ? rs : "", r.ContainsKey("name_he_review"));
                    return (sid, sname, r.TryGetValue("type", out var ty) && ty is string ts ? ts : "");
                }).ToList();
            }
            catch (YamlException e) { throw ParseError(SettlementsFileName, text, e); }
        }

        static readonly HashSet<string> SettlementKeys = new HashSet<string>
        {
            "id", "name", "name_he", "name_he_sources", "name_he_review", "lon", "lat", "type", "founded", "pre_modern", "sources",
        };

        /// <summary>A settlement row's name_he_sources, read from the untyped row: a list of { url, checked } maps.</summary>
        static List<Source> SettlementSources(Dictionary<string, object> row, string field)
        {
            var list = new List<Source>();
            if (!row.TryGetValue("name_he_sources", out var v) || v == null) return list;
            if (!(v is List<object> items)) throw new ContentException(SettlementsFileName, field, "must be a list");
            for (int i = 0; i < items.Count; i++)
            {
                var m = items[i] as Dictionary<object, object>;
                var url = m != null && m.TryGetValue("url", out var u) && u is string us ? us : "";
                var day = m != null && m.TryGetValue("checked", out var d) && d is string ds
                    && DateTime.TryParseExact(ds, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var dt) ? dt : default;
                list.Add(new Source { Url = url, Checked = day });
            }
            return list;
        }

        static readonly IDeserializer Yaml = new DeserializerBuilder()
            .WithNamingConvention(UnderscoredNamingConvention.Instance)
            .WithDuplicateKeyChecking()   // two equal keys would otherwise silently keep only the last value
            .Build();

        static readonly IDeserializer NodeYaml = new DeserializerBuilder().WithDuplicateKeyChecking().Build();
        static readonly ISerializer NodeWriter = new SerializerBuilder().Build();

        /// <summary>Keys an era override may not set: the values <c>NewGame</c> reads once. A later era's start values
        /// belong in start/&lt;era&gt;.yaml (chapters spec section 6), and the set of budget lines in the carry rules (section 4).</summary>
        static readonly string[] StartOnlyKeys = { "start", "treasury_start", "fx_start", "start_rung", "initial_population", "budget_start", "budget_owners" };

        /// <summary>Era rules (#58): for each era with a content/rules/&lt;era&gt;.yaml file, rules.yaml with that file's keys
        /// merged in at the YAML-node level (maps merge key by key, a list or a value replaces), then read with the strict
        /// <see cref="Rules"/> type. The override is first read on its own with the same strict reader, so a misspelt key
        /// or a wrong type fails naming the era file and the line. An override cannot remove a key: an era cannot drop a
        /// budget_start line, a map_actions entry or an attention_cost kind. An override file is read through
        /// <paramref name="readFile"/>, so it counts in the content hash; <paramref name="baseText"/> is the text of
        /// rules.yaml already read (and hashed) once. An era with no file is left out of the map.</summary>
        static Dictionary<string, Rules> ReadEraRules(string baseText, Func<string, string?> readFile, List<Era> eras)
        {
            var result = new Dictionary<string, Rules>();
            foreach (var era in eras)
            {
                if (!Offices.OfficeId.IsMatch(era.Id ?? "")) continue;   // eras.yaml validation names a bad id
                var rel = "rules/" + era.Id + ".yaml";
                string? text;
                try { text = readFile(rel); }
                catch (IOException e) { throw new ContentException(rel, "(file)", e.Message); }
                catch (UnauthorizedAccessException e) { throw new ContentException(rel, "(file)", e.Message); }
                if (text == null) continue;
                Dictionary<object, object> over;
                try
                {
                    var alone = Yaml.Deserialize<Rules>(text) ?? throw new ContentException(rel, "(file)", "empty file: list the keys this era changes");
                    CheckNulls(rel, "", alone);
                    over = NodeYaml.Deserialize<Dictionary<object, object>>(text) ?? throw new ContentException(rel, "(file)", "empty file: list the keys this era changes");
                }
                catch (YamlException e) { throw ParseError(rel, text, e); }
                foreach (var k in StartOnlyKeys)
                    if (over.ContainsKey(k))
                        throw new ContentException(rel, k, k == "start" ? "an era cannot change the start date"
                            : "start values go in start/<era>.yaml (chapters spec section 6), not in an override");
                var merged = NodeYaml.Deserialize<Dictionary<object, object>>(baseText) ?? new Dictionary<object, object>();
                MergeNodes(merged, over);
                try { result[era.Id!] = Yaml.Deserialize<Rules>(NodeWriter.Serialize(merged)) ?? throw new ContentException(rel, "(file)", "empty file"); }
                catch (YamlException e) { throw new ContentException(rel, "(merged with rules.yaml)", e.InnerException?.Message ?? e.Message); }
            }
            return result;
        }

        static void MergeNodes(Dictionary<object, object> into, Dictionary<object, object> over)
        {
            foreach (var kv in over)
                if (into.TryGetValue(kv.Key, out var cur) && cur is Dictionary<object, object> a && kv.Value is Dictionary<object, object> b) MergeNodes(a, b);
                else into[kv.Key] = kv.Value;
        }

        internal const string ObjectivesFileName = "objectives.yaml";

        /// <summary>R-CITY-006: the locality placements, with the settlement_hexes.yaml checks (unique ids, land hexes) and
        /// q and r required. Both GDD identities' immutable geography path calls this.</summary>
        static List<SettlementHex>? LocalityHexes(Content c, LocalityHexesFile file)
        {
            const string f = PlayerRegionCatalogue.LocalityHexesFileName;
            Unique(f, "localities", file.Localities.Select(l => l.Id));
            var result = new List<SettlementHex>(file.Localities.Count);
            foreach (var l in file.Localities)
            {
                if (!l.Q.HasValue || !l.R.HasValue) throw new ContentException(f, $"localities[{l.Id}]", "q and r are required integers");
                int q = l.Q.Value, r = l.R.Value;
                if (c.HexAt(q, r)?.Land != true)
                    throw new ContentException(f, $"localities[{l.Id}]", FormattableString.Invariant($"hex q={q} r={r} is not a land hex in {HexesFile}"));
                result.Add(new SettlementHex { Id = l.Id, Q = q, R = r });
            }
            return result;
        }

        /// <summary>Like <see cref="Read{T}"/>, but a missing file is null, not an error. The file is read once.</summary>
        static T? ReadOptional<T>(Func<string, string?> readFile, string relPath) where T : class
        {
            string? text;
            try { text = readFile(relPath); }
            catch (IOException e) { throw new ContentException(relPath, "(file)", e.Message); }
            catch (UnauthorizedAccessException e) { throw new ContentException(relPath, "(file)", e.Message); }
            return text == null ? null : Read<T>(_ => text, relPath);
        }

        static T Read<T>(Func<string, string?> readFile, string relPath)
        {
            string? text;
            try { text = readFile(relPath); }
            catch (IOException e) { throw new ContentException(relPath, "(file)", e.Message); }
            catch (UnauthorizedAccessException e) { throw new ContentException(relPath, "(file)", e.Message); }
            if (text == null) throw new ContentException(relPath, "(file)", "missing file");
            T result;
            try { result = Yaml.Deserialize<T>(text) ?? throw new ContentException(relPath, "(file)", "empty file"); }
            catch (YamlException e) { throw ParseError(relPath, text, e); }
            CheckNulls(relPath, result is GameEvent ev ? $"events[{ev.Id}]" : "", result!);
            return result;
        }

        /// <summary>A strict-YAML refusal names the mapping key on the reported source line when one is available.</summary>
        static ContentException ParseError(string file, string text, YamlException e)
        {
            var key = KeyOnLine(text, (int)e.Start.Line);
            var field = key == null ? $"line {e.Start.Line}" : $"{key} (line {e.Start.Line})";
            return new ContentException(file, field, e.InnerException?.Message ?? e.Message);
        }

        internal static string? KeyOnLine(string text, int line)
        {
            if (line < 1) return null;
            var lines = text.Replace("\r\n", "\n").Split('\n');
            if (line > lines.Length) return null;
            var source = lines[line - 1].TrimStart();
            if (source.StartsWith("- ", StringComparison.Ordinal)) source = source.Substring(2).TrimStart();
            var colon = source.IndexOf(':');
            // A mapping key's colon ends the line or is followed by a space; "https://x" is a scalar, not a key "https".
            if (colon <= 0 || (colon + 1 < source.Length && source[colon + 1] != ' ')) return null;
            var key = source.Substring(0, colon).Trim();
            if (key.Length > 1 && (key[0] == '"' || key[0] == '\'') && key[key.Length - 1] == key[0]) key = key.Substring(1, key.Length - 2);   // "ruleset": in gdd03-balance.yaml
            return key.Length > 0 && key.All(ch => char.IsLetterOrDigit(ch) || ch == '_' || ch == '-' || ch == '.') ? key : null;
        }

        /// <summary>A key written with no value (`tags:`) deserialises to null. Null lists and maps become load errors
        /// naming the field; null strings become "" (the default every check already handles). Walks nested content
        /// objects, naming list entries by id when they have one, else by index.</summary>
        static void CheckNulls(string file, string path, object o)
        {
            foreach (var p in o.GetType().GetProperties().OrderBy(x => x.Name, StringComparer.Ordinal))
            {
                if (p.GetCustomAttribute<YamlIgnoreAttribute>() != null) continue;
                var key = (path == "" ? "" : path + ".") + UnderscoredNamingConvention.Instance.Apply(p.Name);
                var t = p.PropertyType;
                var v = p.GetValue(o);
                if (t == typeof(string)) { if (v == null) p.SetValue(o, ""); else Encodable(file, key, (string)v); }
                else if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
                {
                    if (v == null) throw new ContentException(file, key, "must be a list");
                    var list = (IList)v;
                    for (int i = 0; i < list.Count; i++)
                    {
                        var item = list[i];
                        if (item == null) throw new ContentException(file, FormattableString.Invariant($"{key}[{i}]"), "empty entry");
                        if (item is string si) Encodable(file, FormattableString.Invariant($"{key}[{i}]"), si);
                        if (!IsContentType(item.GetType())) continue;
                        var id = item.GetType().GetProperty("Id")?.GetValue(item) as string;
                        CheckNulls(file, string.IsNullOrEmpty(id) ? FormattableString.Invariant($"{key}[{i}]") : $"{key}[{id}]", item);
                    }
                }
                else if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>))
                {
                    if (v == null) throw new ContentException(file, key, "must be a map");
                    foreach (DictionaryEntry kv in (IDictionary)v)
                    {
                        if (kv.Value == null) throw new ContentException(file, key + "." + kv.Key, "empty entry");
                        if (kv.Key is string sk) Encodable(file, key + "." + sk, sk);
                        if (kv.Value is string sv) Encodable(file, key + "." + kv.Key, sv);
                    }
                }
                else if (v != null && IsContentType(t)) CheckNulls(file, key, v);
            }
        }

        /// <summary>Every id and text must be valid Unicode (no lone surrogate), or orders and saves that carry it would fail
        /// later. Uses the same check as the save format.</summary>
        static void Encodable(string file, string field, string s)
        {
            if (!SaveText.IsEncodable(s)) throw new ContentException(file, field, "must be valid text (no lone surrogate)");
        }

        /// <summary>A person's title_he_form: left out, or feminine with its source; and then every office the person holds
        /// has a feminine title_he_f, so the UI never falls back to the masculine title for her.</summary>
        static void TitleHeForm(Content c, Person p)
        {
            var at = $"people[{p.Id}].title_he_form";
            var sourced = p.BiographySources.ContainsKey("title_he_form");
            if (!p.TitleHeFormGiven)
            {
                if (sourced) throw new ContentException("people.yaml", at, "required: biography_sources.title_he_form is set but title_he_form is not");
                return;
            }
            if (p.TitleHeForm != TitleHeForms.Feminine)
                throw new ContentException("people.yaml", at, $"must be {TitleHeForms.Feminine}, or left out for the masculine title_he");
            if (!sourced) throw new ContentException("people.yaml", $"people[{p.Id}].biography_sources.title_he_form", "required: a feminine title_he_form needs a source (url and checked)");
            foreach (var t in p.Offices)
            {
                var o = c.Offices.FirstOrDefault(x => x.Id == t.Office);
                if (o != null && o.TitleHeF == "")
                    throw new ContentException("offices.yaml", $"offices[{o.Id}].title_he_f", $"required: {p.Id} holds this office and has title_he_form: {TitleHeForms.Feminine}");
            }
        }

        /// <summary>A Hebrew display name (#558): when set it holds Hebrew letters and has at least one source, each an https URL
        /// with its checked date; sources without a name are an error. Empty means no sourced Hebrew name (the UI keeps the English).</summary>
        static void HebrewName(string file, string at, string key, string value, List<Source> sources, string review, bool reviewGiven)
        {
            // The flag is either absent (a person has reviewed the name) or exactly agent-checked; a blank or null value is
            // neither, so it is an error rather than a silent "reviewed".
            if (reviewGiven && review != HebrewReview.AgentChecked)
                throw new ContentException(file, $"{at}.{key}_review", $"must be {HebrewReview.AgentChecked} (until a native speaker, or an AI-assisted contributor who discloses it, has read the name, #564), or left out once it has been read");
            if (value == "")
            {
                if (sources.Count > 0) throw new ContentException(file, $"{at}.{key}", $"required: {key}_sources is set but the name is empty");
                if (reviewGiven) throw new ContentException(file, $"{at}.{key}", $"required: {key}_review is set but the name is empty");
                return;
            }
            if (!value.Any(ch => ch >= '\u05D0' && ch <= '\u05EA')) throw new ContentException(file, $"{at}.{key}", "must be the Hebrew name, in Hebrew letters");
            if (sources.Count == 0) throw new ContentException(file, $"{at}.{key}_sources", "required: a Hebrew name needs a source (url and checked)");
            for (int i = 0; i < sources.Count; i++)
                if (!sources[i].Url.StartsWith("https://", StringComparison.Ordinal) || sources[i].Checked == default)
                    throw new ContentException(file, FormattableString.Invariant($"{at}.{key}_sources[{i}]"), "needs an https url and a checked date");
        }

        static bool IsContentType(Type t) => t.IsClass && t != typeof(string) && t.Namespace == typeof(Content).Namespace;

        /// <summary>Loads content through <paramref name="readFile"/>, which takes a path relative to the content root
        /// ("people.yaml", "events/x.yaml") and returns the file's text, or null when it is missing. This is the
        /// entry point for platforms without a file system (a WebGL build reads StreamingAssets through a URL).
        /// <paramref name="eventFiles"/> are the event files, relative to the content root; they load in ordinal order.</summary>
        public static Content Load(Func<string, string?> readFile, IEnumerable<string> eventFiles) =>
            Load(readFile, eventFiles, _ => null, Enumerable.Empty<string>());

        /// <summary>Loads content as the overload above does, with the translations <paramref name="translationFiles"/> lists
        /// ("ro/ui.yaml", as TranslationLoader.Collect gives them), which <paramref name="readTranslation"/> reads relative to
        /// the translations folder (#1618 step 2). Each language is checked against the content and kept in
        /// <see cref="Content.Translations"/>, outside the hash.</summary>
        public static Content Load(Func<string, string?> readFile, IEnumerable<string> eventFiles,
            Func<string, string?> readTranslation, IEnumerable<string> translationFiles)
        {
            if (readFile == null) throw new ArgumentNullException(nameof(readFile));
            if (eventFiles == null) throw new ArgumentNullException(nameof(eventFiles));
            if (readTranslation == null) throw new ArgumentNullException(nameof(readTranslation));
            if (translationFiles == null) throw new ArgumentNullException(nameof(translationFiles));
            var read = new List<(string rel, string text)>();
            var inner = readFile;
            static string? NoMark(string? text) =>
                text != null && text.Length > 0 && text[0] == '\uFEFF' ? text.Substring(1) : text;   // a byte-order mark is not content
            readFile = rel =>
            {
                var text = NoMark(inner(rel));
                if (text != null) read.Add((rel, text));
                return text;
            };
            // The translation checks read content files outside the hash (a translation is display text, and may name a
            // file the sim never reads), and a read failure keeps its file rather than passing for a missing file.
            string? Unhashed(string rel)
            {
                try { return NoMark(inner(rel)); }
                catch (IOException e) { throw new ContentException(rel, "(file)", e.Message); }
                catch (UnauthorizedAccessException e) { throw new ContentException(rel, "(file)", e.Message); }
            }
            var c = new Content();
            c.Offices = Read<OfficesFile>(readFile, "offices.yaml").Offices;
            c.Parties = Read<PartiesFile>(readFile, "parties.yaml").Parties;
            c.People = Read<PeopleFile>(readFile, "people.yaml").People;
            c.Legislatures = Read<LegislaturesFile>(readFile, "legislatures.yaml").Legislatures;
            c.Governments = Read<GovernmentsFile>(readFile, "governments.yaml").Governments;
            c.Eras = Read<ErasFile>(readFile, "eras.yaml").Eras;
            var m = Read<ModelFile>(readFile, "model.yaml");
            c.Indicators = m.Indicators; c.Policies = m.Policies; c.Effects = m.Effects;
            c.Situations = m.Situations; c.VoterGroups = m.VoterGroups; c.Actors = m.Actors; c.Money = m.Money;
            string rulesText = "";
            c.Rules = Read<Rules>(p => { var t = readFile(p); rulesText = t ?? ""; return t; }, "rules.yaml");
            c.EraRules = ReadEraRules(rulesText, readFile, c.Eras);
            // Catalogue-only: old content sets need no file; an authored file is strictly validated and hashed.
            c.Gdd03Balance = ReadOptional<Gdd03BalanceCatalogue>(readFile, Gdd03BalanceCatalogue.FileName);
            c.Gdd03Balance?.Validate();
            var aliyah = Read<AliyahFile>(readFile, "aliyah.yaml");
            c.Aliyah = aliyah.Series; c.Regions = aliyah.Regions;
            c.PopulationAnchors = Read<PopulationFile>(readFile, "population.yaml").Anchors;
            c.Hexes = Read<MapFile>(readFile, HexesFile).Hexes;
            c.SettlementHexes = Read<SettlementHexesFile>(readFile, SettlementHexesFileName).Settlements;
            c.MapLocations = Read<MapLocationsFile>(readFile, MapLocationsFileName).Locations;
            var settlements = ReadSettlements(readFile);
            var settlementIds = settlements.Select(x => x.id).ToList();
            foreach (var (id, name, _) in settlements) c.SettlementNames[id] = name;   // a duplicate id fails in ValidateMap
            c.ArabTowns = new HashSet<string>(settlements.Where(x => x.type == ArabTown).Select(x => x.id), StringComparer.Ordinal);
            c.SettlementTargets = Read<SettlementTargetsFile>(readFile, SettlementTargetsFileName).Targets;
            ValidateSettlementTargets(c, settlements.Where(x => x.type == ArabTown).Select(x => x.id));
            // Event files (content/events/*.yaml), one GameEvent each. Keys, for content authors:
            //   id, title, text            text may name office holders only through {office_id} placeholders, which
            //                              must have a holder on every day of the window
            //   title_he, text_he, text_he_review   the Hebrew title and text (#1064); with them every option has a text_he
            //   anchor: hard | soft        hard needs a historical option; in Historical mode it resolves to it
            //   tags: [...]                holocaust, terror, massacre, war-casualties, displacement are sensitive (no gain)
            //   office                     the minister the event is delegated to
            //   from, to                   the window [from, to); it fires on the first turn that overlaps it
            //   conditions: [{ indicator, min, max }]   indicator bounds that must hold when it fires
            //   requires: [{ event, option } | { event, diverged: true }, ...]   fires only once every entry holds: that
            //                              event was resolved (chosen or delegated) with that option, or with any option but
            //                              its historical one (R-ALT-001, R-ALT-002); the ids must exist, an event cannot
            //                              require itself and requirements cannot form a cycle (EventRules)
            //   options: [{ id, text, historical, recommended, effects: [{ target, delta }], set_rung, set_policy,
            //              grant_units: [{ type, n, at }], city_effects: [{ city, field, delta }],
            //              unlock_projects: [<projects.yaml id of a locked kind>],
            //              unit_orders: [{ unit, order, q, r }] (R-ENEMY-005; order go_to or attack, R-ENEMY-008) }]
            //   sources: [{ url, checked }], status
            //   objective                  the objective (objectives.yaml) whose completion card this is: it fires only once
            //                              that objective is recorded, and has exactly one option
            //   site                       a swamp site (sites.yaml) whose works the event is about: in the GDD loop it
            //                              fires only while that site is being worked; the legacy loop ignores it
            //   prisoners                  a front (Prisoners.Fronts) whose prisoners the card returns: it fires only while
            //                              that front holds some either way, and has exactly one option (R-POW-004)
            //   deported                   a settlement target whose Deport the card follows: it fires only once the
            //                              player's Deport has depopulated that place, carries the displacement tag and
            //                              has exactly one option (R-EVT-007)
            //   front_quiet                the front (Prisoners.Fronts) of an armistice_<front> card: under gdd-0.3 it may also
            //                              come early, and again after a refusal, once that front is quiet (R-WAR-008)
            //   early_text, early_text_he  on a front_quiet card only: its text, and its Hebrew, when it is shown before its
            //                              `from` (R-WAR-008, #1709); a what-if, so it needs a reviewed_by (R-ALT-011)
            //   armistice_front            a front (Prisoners.Fronts) whose signed armistice ends the card: a pending
            //                              operation lapses once it is signed, and a card with it never first fires after
            //                              it (R-ENEMY-007); on an operation card or a following card only
            //   follows                    true: under the GDD loop the card fires on the turn after its `requires` are met
            //                              even when its window has closed (R-ENEMY-007); needs a `requires`
            foreach (var rel in eventFiles.OrderBy(p => p, StringComparer.Ordinal))
            {
                var e = Read<GameEvent>(readFile, rel);
                e.File = rel;
                c.Events.Add(e);
            }
            // Objectives (GDD v0.1, Phase 1 PR 6). Read in both loops, since their cards are events every loop loads; a content
            // set without objectives has no file.
            // In the file's order, not sorted: it is the order objectives record and their cards fire in (R-OBJ-007, Q-CARD-2).
            c.Objectives = ReadOptional<ObjectivesFile>(readFile, ObjectivesFileName)?.Objectives ?? new List<Objective>();
            var allEvents = c.Events.ToList();   // before a ruleset leaves some out: their translations still name real events
            // Leave malformed legacy era records to the original validation path (Ruleset needs Systems).
            if (c.Eras.Count > 0 && c.Eras[0].Systems != null && c.Ruleset == SaveGame.Gdd03Ruleset)
            {
                ValidateEras(c);   // establish the game-wide identity before consulting its availability manifest
                ApplyGdd03EventExclusions(readFile, c);
            }
            Validate(c, settlementIds);
            if (c.Ruleset == SaveGame.Gdd03Ruleset && c.Gdd03Balance == null)
                throw new ContentException(Gdd03BalanceCatalogue.FileName, "(file)", "required for the gdd-0.3 ruleset");
            if (c.Ruleset == SaveGame.Gdd03Ruleset) c.Gdd03Balance!.ValidateNumbers();
            // R-POP-001: validate the identity-specific scale without altering old content reads/hash inputs.
            if (c.UsesPopulationLedger) _ = c.PopulationPeoplePerUnit;
            ApplyMapOverrides(readFile, c, settlementIds);   // after the map's own checks, before the GDD records that read it
            if (c.IsGdd)
            {
                // GDD v0.1 city data (Phase 1 PR 3), read once eras.yaml is known to be valid. Only the GDD loop reads it, so
                // the legacy content needs neither file.
                c.Cities = Read<CitiesFile>(readFile, "cities.yaml").Cities;
                c.UnitTypes = Read<UnitTypesFile>(readFile, "unit_types.yaml").Types;
                c.Sites = Read<SitesFile>(readFile, "sites.yaml").Sites;   // sourced facts (Phase 1 PR 5)
                // Design values (Phase 3 PR 4). R-ARMS-004: a row limited to other rulesets is not this game's kind.
                var kinds = Read<ProjectsFile>(readFile, "projects.yaml").Projects;
                c.ProjectKinds = kinds.Where(k => k.Rulesets.Count == 0 || k.Rulesets.Contains(c.Ruleset)).ToList();
                c.ProjectKindsOfOtherRulesets = kinds.Except(c.ProjectKinds).ToList();
                c.Corridors = Read<CorridorsFile>(readFile, "corridors.yaml").Corridors;   // sourced, hexes derived (Phase 4 PR 2)
                var formationXp = c.Ruleset == SaveGame.Gdd03Ruleset ? ApplyGdd03Start(readFile, c) : null;
                ValidateGdd(c, settlementIds, settlements.Where(x => x.type is "city" or "town").Select(x => x.id).ToList());
                Gdd03Military.Validate(c); // after effective map overrides and role validation, only exact gdd-0.3
                // The sourced starting forces (Phase 5 PR 4, R-UNIT-006), once the types and people_per_unit are known valid.
                c.StartingForces = StartingForces.Read(readFile, c);
                if (formationXp != null) ApplyGdd03FormationCombatXp(formationXp, c);
            }
            // R-CITY-006 and R-ENEMY-007: authored geography is immutable lookup data in both GDD identities. Only exact
            // gdd-0.3 initializes regional population/control state. After sites (a site id may be a member) and the effective
            // map overrides; locality hexes are read only with regions, and are required then (#2298).
            if (c.IsGdd)
            {
                var regions = ReadOptional<PlayerRegionsFile>(readFile, PlayerRegionCatalogue.FileName);
                if (regions != null)
                    c.PlayerRegions = PlayerRegionCatalogue.Validate(c, regions.PlayerRegions,
                        LocalityHexes(c, Read<LocalityHexesFile>(readFile, PlayerRegionCatalogue.LocalityHexesFileName)));
            }
            EventRules.ValidateStructured(c);   // R-EFX-006: after the GDD records it names are read
            c.BuildWindows();
            c.Hash = HashOf(read);
            c.Translations = TranslationLoader.Load(allEvents, Unhashed, readTranslation, translationFiles);
            return c;
        }

        // R-CAMP-003: exact-gdd-0.3 start bindings add facilities to the shared city catalogue without changing gdd-0.1.
        // The optional file keeps synthetic gdd-0.3 fixtures independent of the shipped map and city ids.
        static List<StartFormationCombatXp>? ApplyGdd03Start(Func<string, string?> readFile, Content c)
        {
            const string file = "gdd03-start.yaml";
            var start = ReadOptional<Gdd03StartFile>(readFile, file);
            if (start == null) return null;
            if (start.Ruleset != SaveGame.Gdd03Ruleset)
                throw new ContentException(file, "ruleset", "must be gdd-0.3");
            if (start.MilitaryCamps == null)
                throw new ContentException(file, "military_camps", "required: an explicit list");

            var cities = new HashSet<string>(StringComparer.Ordinal);
            var locations = new HashSet<string>(StringComparer.Ordinal);
            for (int i = 0; i < start.MilitaryCamps.Count; i++)
            {
                var row = start.MilitaryCamps[i];
                var at = FormattableString.Invariant($"military_camps[{i}]");
                var city = c.Cities.FirstOrDefault(x => x.Id == row.City);
                if (city == null) throw new ContentException(file, at + ".city", "must name an existing city");
                if (!cities.Add(row.City)) throw new ContentException(file, at + ".city", "duplicate city");
                var location = c.MapLocations.FirstOrDefault(x => x.Id == row.Location);
                if (location == null) throw new ContentException(file, at + ".location", "must name an existing map location");
                if (location.Kind != "military_camp")
                    throw new ContentException(file, at + ".location", "must name a military_camp map location");
                if (!locations.Add(row.Location)) throw new ContentException(file, at + ".location", "duplicate location");
                if (!city.Facilities.Contains("military_camp")) city.Facilities.Add("military_camp");
            }

            var actual = c.Cities.Count(x => x.Facilities.Contains("military_camp"));
            var expected = Gdd03Military.Scalar(c, "start.military_camps");
            if (actual != expected)
                throw new ContentException(file, "military_camps",
                    FormattableString.Invariant($"effective military-camp city count {actual} must equal start.military_camps {expected}"));
            return start.FormationCombatXp;
        }

        /// <summary>#1689 rows 7 and 8 (owner, 7 November 2026, comment 6704389240: "1 each, Negev 0 (Recommended)"): each own
        /// opening formation's combat XP in the Historical ledger fixture, once each, from 0 to military.combat_xp_full. Read
        /// after the starting forces. An absent list leaves the value unset; the ledger fixture then refuses (no fallback).
        /// Ledger fixture only (maintainer call, eyalgolan-30's coordinator, 7 November 2026): NewGame's units keep 0.
        /// #1725 PR 7, producer 08: each own dated brigade (R-UNIT-009) is named too, since it arrives as soldier records
        /// (owner, 8 November 2026, for the 7th Brigade: "1, like the others").</summary>
        static void ApplyGdd03FormationCombatXp(List<StartFormationCombatXp> rows, Content c)
        {
            const string file = "gdd03-start.yaml";
            var full = Gdd03Military.Scalar(c, "military.combat_xp_full");
            var own = new HashSet<string>(HistoricalPopulation.OpeningFormationRows(c)
                .Concat(HistoricalPopulation.DatedFormations(c).Select(f => f.Row)), StringComparer.Ordinal);
            var xp = new SortedDictionary<string, int>(StringComparer.Ordinal);
            for (int i = 0; i < rows.Count; i++)
            {
                var row = rows[i];
                var at = FormattableString.Invariant($"formation_combat_xp[{i}]");
                if (row == null || !own.Contains(row.Row))
                    throw new ContentException(file, at + ".row", "must name an own opening or dated formation of map/units_1948.yaml");
                if (xp.ContainsKey(row.Row)) throw new ContentException(file, at + ".row", "duplicate formation");
                if (!(row.CombatXp is int value) || value < 0 || value > full)
                    throw new ContentException(file, at + ".combat_xp", FormattableString.Invariant($"required: an integer from 0 to military.combat_xp_full {full}"));
                xp.Add(row.Row, value);
            }
            var missing = own.Where(r => !xp.ContainsKey(r)).OrderBy(r => r, StringComparer.Ordinal).ToList();
            if (missing.Count > 0) throw new ContentException(file, "formation_combat_xp", "missing own formation " + string.Join(", ", missing));
            c.Gdd03FormationCombatXp = xp;
        }

        // R-EFX-001: this file is deliberately never read by legacy/gdd-0.1, including for hashing.
        // Parse all event sources first: exclusion is availability, not permission to hide malformed YAML.
        static void ApplyGdd03EventExclusions(Func<string, string?> readFile, Content c)
        {
            const string file = "gdd03-events.yaml";
            var manifest = Read<Gdd03EventsFile>(readFile, file);
            if (manifest.Ruleset != SaveGame.Gdd03Ruleset)
                throw new ContentException(file, "ruleset", "must be gdd-0.3");
            if (manifest.Exclusions == null)
                throw new ContentException(file, "exclusions", "required: an explicit list (possibly empty)");
            var sources = new HashSet<string>(StringComparer.Ordinal);
            foreach (var e in c.Events)
            {
                if (!Offices.OfficeId.IsMatch(e.Id)) throw new ContentException(e.File, $"events[{e.Id}].id", IdRule);
                if (!sources.Add(e.Id)) throw new ContentException(e.File, $"events[{e.Id}].id", "duplicate event id");
            }
            var excluded = new HashSet<string>(StringComparer.Ordinal);
            for (int i = 0; i < manifest.Exclusions.Count; i++)
            {
                var row = manifest.Exclusions[i];
                var at = FormattableString.Invariant($"exclusions[{i}]");
                if (row == null || string.IsNullOrWhiteSpace(row.Id) || !sources.Contains(row.Id))
                    throw new ContentException(file, at + ".id", "must name an existing event");
                if (!excluded.Add(row.Id)) throw new ContentException(file, at + ".id", "duplicate exclusion");
                if (string.IsNullOrWhiteSpace(row.Reason)) throw new ContentException(file, at + ".reason", "required");
            }
            // Fail explicitly rather than leaving a mandatory edge pointing into a filtered catalogue.
            foreach (var e in c.Events.Where(e => !excluded.Contains(e.Id)))
            {
                void Reference(string field, string id)
                {
                    if (excluded.Contains(id)) throw new ContentException(e.File, $"events[{e.Id}].{field}", $"event '{id}' is excluded under gdd-0.3");
                }
                for (int i = 0; i < e.Requires.Count; i++)
                    Reference(FormattableString.Invariant($"requires[{i}].event"), e.Requires[i].Event);
                for (int i = 0; i < e.Variants.Count; i++)
                    for (int j = 0; j < e.Variants[i].When.Count; j++)
                        Reference(FormattableString.Invariant($"variants[{i}].when[{j}].event"), e.Variants[i].When[j].Event);
                foreach (var o in e.Options) Reference($"options[{o.Id}].rejoin", o.Rejoin);
            }
            foreach (var o in c.Objectives)
                if (excluded.Contains(o.Card)) throw new ContentException(ObjectivesFileName, $"objectives[{o.Id}].card", $"event '{o.Card}' is excluded under gdd-0.3");
            // Stable removal retains the loader's original ordinal source order. Shared YAML stays available to review tools.
            c.Events.RemoveAll(e => excluded.Contains(e.Id));
        }

        /// <summary>The map editor's overrides (#1009), applied last, once the generated map inputs have been read and
        /// checked: terrain and location moves here, so every caller of the sim sees them; control in the map, the only
        /// reader of the control file. The file is optional (no file, no overrides) and is in the content hash.</summary>
        static void ApplyMapOverrides(Func<string, string?> readFile, Content c, List<string> settlementIds)
        {
            string? text;
            try { text = readFile(MapOverrides.FileName); }
            catch (IOException e) { throw new ContentException(MapOverrides.FileName, "(file)", e.Message); }
            catch (UnauthorizedAccessException e) { throw new ContentException(MapOverrides.FileName, "(file)", e.Message); }
            var overrides = MapOverrides.Parse(text);
            overrides.ValidateMap(c.Hexes, settlementIds.Concat(c.MapLocations.Select(l => l.Id)));
            overrides.ApplyTo(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. The translations are those beside it
        /// (TranslationLoader.Beside: translations/ next to a folder named content), when there are any.</summary>
        public static Content Load(string contentRoot) => Load(contentRoot, TranslationLoader.Beside(contentRoot));

        /// <summary>Loads content from a directory with the translations in <paramref name="translationsRoot"/> (none when it
        /// is null or missing).</summary>
        public static Content Load(string contentRoot, string? translationsRoot)
        {
            var eventsDir = Path.Combine(contentRoot, "events");
            var eventFiles = Directory.Exists(eventsDir)
                ? Directory.GetFiles(eventsDir, "*.yaml").Select(f => "events/" + Path.GetFileName(f)).ToList()
                : new List<string>();
            var content = Load(rel =>
            {
                var path = Path.Combine(contentRoot, rel);
                return File.Exists(path) ? File.ReadAllText(path) : null;
            }, eventFiles, rel =>
            {
                var path = Path.Combine(translationsRoot!, rel);   // only called for a file Collect found there
                return File.Exists(path) ? File.ReadAllText(path) : null;
            }, TranslationLoader.Collect(translationsRoot));
            // #2598: a checkout has the English UI table beside its content, so the editor, the CLI, the tests and ContentSync's
            // load of the source before every player build hold each ui.yaml to it. A player has none beside its copy.
            if (content.Translations.Any(t => t.Lang != Translations.Hebrew && t.Ui.Count > 0)
                && TranslationLoader.EnglishUi(contentRoot) is string english)
                TranslationLoader.CheckUiAgainstEnglish(content.Translations, english);
            // Only this overload can list the directory. The readFile overload (WebGL) cannot, so a misnamed file is caught
            // here and by RealContentTests before anything ships.
            var rulesDir = Path.Combine(contentRoot, "rules");
            if (Directory.Exists(rulesDir))
                foreach (var f in Directory.GetFiles(rulesDir, "*.yaml").OrderBy(f => f, StringComparer.Ordinal))
                    if (!content.EraRules.ContainsKey(Path.GetFileNameWithoutExtension(f)))
                        throw new ContentException("rules/" + Path.GetFileName(f), "(file)", "the file name must be the id of an era in eras.yaml");
            return content;
        }

        internal const string IdRule = "must be lowercase letters, digits and underscores, starting with a letter";

        /// <summary>Every id has the office-id shape (so it is safe in placeholders, CLI input and save files) and is unique in its list.</summary>
        static void Unique(string file, string list, IEnumerable<string> ids)
        {
            var seen = new HashSet<string>();
            foreach (var id in ids)
            {
                if (!Offices.OfficeId.IsMatch(id)) throw new ContentException(file, $"{list}[{id}].id", IdRule);
                if (!seen.Add(id)) throw new ContentException(file, $"{list}[{id}].id", "duplicate id");
            }
        }

        static readonly HashSet<string> Statuses = new HashSet<string> { "draft", "fact-checked", "historian-reviewed", "sensitivity-reviewed" };

        /// <summary>A display name: required, and not blank.</summary>
        internal static void Named(string file, string field, string name)
        {
            if (string.IsNullOrWhiteSpace(name)) throw new ContentException(file, field, "required (the name shown to the player)");
        }

        /// <summary>Player-facing prose required by a content schema.</summary>
        internal static void RequiredText(string file, string field, string value)
        {
            if (string.IsNullOrWhiteSpace(value)) throw new ContentException(file, field, "required (text shown to the player)");
        }

        /// <summary>A schema-required source list: at least one HTTPS URL with its checked date.</summary>
        internal static void RequiredSources(string file, string field, List<Source> sources)
        {
            if (sources.Count == 0) throw new ContentException(file, field, "needs at least one source");
            for (int i = 0; i < sources.Count; i++)
            {
                var source = sources[i];
                if (source == null || source.Url == null || !source.Url.StartsWith("https://", StringComparison.Ordinal) || source.Checked == default)
                    throw new ContentException(file, FormattableString.Invariant($"{field}[{i}]"), "needs an https url and a checked date");
            }
        }

        /// <summary>A row's sign-off (#375): reviewed_by and reviewed_on together, a GitHub handle, a day as YYYY-MM-DD (read as
        /// text, the same rule as tools/review_record.py and the map's readers). <paramref name="at"/> is the row's path, as in "people[ben_gurion]".</summary>
        internal static void Review(string file, string at, string by, bool byGiven, string on, bool onGiven)
        {
            var p = ReviewRecord.Problem(byGiven, by, onGiven, on);
            if (p != null) throw new ContentException(file, $"{at}.{p.Value.field}", p.Value.message);
        }

        internal static void Status(string file, string field, string status)
        {
            if (!Statuses.Contains(status))
                throw new ContentException(file, field, $"unknown status '{status}' (must be draft, fact-checked, historian-reviewed or sensitivity-reviewed)");
        }

        static bool IsFinite(double v) => !double.IsNaN(v) && !double.IsInfinity(v);

        internal static void Finite(string file, string field, double v)
        {
            if (!IsFinite(v)) throw new ContentException(file, field, "must be a finite number");
        }

        internal static void Unit(string file, string field, double v)
        {
            if (!(v >= 0 && v <= 1)) throw new ContentException(file, field, "must be a number from 0 to 1");
        }

        static void Count(string file, string field, double v)
        {
            if (!(v >= 0 && IsFinite(v))) throw new ContentException(file, field, "must be a finite number >= 0");
        }

        /// <summary>from is required (a missing date deserialises to DateTime default); to, when given, must be after from.</summary>
        internal static void Period(string file, string path, DateTime from, DateTime? to)
        {
            if (from == default) throw new ContentException(file, path + ".from", "required");
            if (to.HasValue && to.Value <= from) throw new ContentException(file, path + ".to", FormattableString.Invariant($"must be after from ({from:yyyy-MM-dd})"));
        }

        /// <summary>Only one legislature sits, and one government holds office, on any date: "which body sat on this
        /// date" must never be ambiguous. Periods are [from, to); sorted by from, each must end on or before the next
        /// one starts (an open-ended period can only be the last).</summary>
        static void NoOverlap(string file, string list, IEnumerable<(string id, DateTime from, DateTime? to)> periods)
        {
            var sorted = periods.OrderBy(p => p.from).ThenBy(p => p.id, StringComparer.Ordinal).ToList();
            for (int i = 1; i < sorted.Count; i++)
            {
                var (prev, next) = (sorted[i - 1], sorted[i]);
                if (!prev.to.HasValue || prev.to.Value > next.from)
                    throw new ContentException(file, $"{list}[{next.id}].from", FormattableString.Invariant(
                        $"overlaps {prev.id} ({prev.from:yyyy-MM-dd} to {(prev.to.HasValue ? prev.to.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) : "open")})"));
            }
        }

        /// <summary>Checks one complete rules set: rules.yaml itself, or an era's rules after its override is merged in.</summary>
        static void ValidateRules(Content c, Rules r, string file, HashSet<string> indicators, HashSet<string> offices, HashSet<string> historicalOffices)
        {
            if (r.Start == default) throw new ContentException(file, "start", "required");
            if (c.UsesAttention)
            {
                if (!(r.AttentionPerTurn >= 0 && !double.IsInfinity(r.AttentionPerTurn))) throw new ContentException(file, "attention_per_turn", "must be a finite non-negative number");
                if (!(r.RungAttentionStep >= 0 && !double.IsInfinity(r.RungAttentionStep))) throw new ContentException(file, "rung_attention_step", "must be a finite non-negative number");
                foreach (var kv in r.AttentionCost)
                    if (!(kv.Value >= 0 && !double.IsInfinity(kv.Value))) throw new ContentException(file, $"attention_cost.{kv.Key}", "must be a finite non-negative number");
                foreach (var k in r.AttentionCost.Keys)
                    if (!AttentionSystem.IsCommandKind(k)) throw new ContentException(file, $"attention_cost.{k}", "unknown command kind");
                foreach (var k in AttentionSystem.CommandKinds)
                    if ((c.IsGdd || !AttentionSystem.IsGddKind(k)) && !r.AttentionCost.ContainsKey(k))   // a GDD kind is priced only where it can run
                        throw new ContentException(file, $"attention_cost.{k}", "missing cost");
            }
            if (r.RungMinMobilization.Count != 5) throw new ContentException(file, "rung_min_mobilization", "needs exactly 5 values (rungs 1-5)");
            for (int i = 0; i < 5; i++)
            {
                var field = FormattableString.Invariant($"rung_min_mobilization[{i}]");
                Unit(file, field, r.RungMinMobilization[i]);
                if (i > 0 && r.RungMinMobilization[i] < r.RungMinMobilization[i - 1])
                    throw new ContentException(file, field, "must not be below the previous rung's floor");
            }
            if (r.TurnLengths.Count != 5) throw new ContentException(file, "turn_lengths", "needs exactly 5 values (rungs 1-5)");
            for (int i = 0; i < 5; i++)
                if (!SimTime.LengthNames.Contains(r.TurnLengths[i]))
                    throw new ContentException(file, FormattableString.Invariant($"turn_lengths[{i}]"), "must be quarter, month or week");
            if (r.StartRung < 1 || r.StartRung > 5) throw new ContentException(file, "start_rung", "must be 1-5");
            if (r.CeasefireWeeks <= 0) throw new ContentException(file, "ceasefire_weeks", "must be > 0");
            foreach (var (key, v) in new[] { ("treasury_start", r.TreasuryStart), ("fx_start", r.FxStart), ("tax_per_capita_per_year", r.TaxPerCapitaPerYear),
                ("spending_per_capita_per_year", r.SpendingPerCapitaPerYear), ("exports_per_year", r.ExportsPerYear), ("imports_per_capita_per_year", r.ImportsPerCapitaPerYear),
                ("mobilization_cost_per_year", r.MobilizationCostPerYear), ("natural_increase_per_year", r.NaturalIncreasePerYear),
                ("capital_inflow_per_year", r.CapitalInflowPerYear), ("fx_crisis_food_per_year", r.FxCrisisFoodPerYear) })
                Finite(file, key, v);
            Unit(file, "appoint_stability_cost_other_party", r.AppointStabilityCostOtherParty);
            Unit(file, "appoint_stability_cost_same_party", r.AppointStabilityCostSameParty);
            if (r.MapActionMaxDistance < 0) throw new ContentException(file, "map_action_max_distance", "must be >= 0");
            if (r.MapActionsPerTurn < 1) throw new ContentException(file, "map_actions_per_turn", "must be >= 1");
            foreach (var kv in r.MapActions)
            {
                if (!MapActions.Actions.Contains(kv.Key)) throw new ContentException(file, $"map_actions.{kv.Key}", "unknown map action (transit_camp or housing)");
                if (!(kv.Value.Cost >= 0 && IsFinite(kv.Value.Cost))) throw new ContentException(file, $"map_actions.{kv.Key}.cost", "must be a finite number >= 0");
                Named(file, $"map_actions.{kv.Key}.name", kv.Value.Name);
                if (kv.Value.From.HasValue && kv.Value.To.HasValue && kv.Value.To.Value <= kv.Value.From.Value)
                    throw new ContentException(file, $"map_actions.{kv.Key}.to", FormattableString.Invariant($"must be after from ({kv.Value.From:yyyy-MM-dd})"));
                foreach (var (key, v) in new[] { ("housing", kv.Value.Housing), ("morale", kv.Value.Morale) })
                    if (!(v >= -1 && v <= 1)) throw new ContentException(file, $"map_actions.{kv.Key}.{key}", "must be a number from -1 to 1");
            }
            if (r.MapActions.Count > 0 && r.MapActionsFrom == default) throw new ContentException(file, "map_actions_from", "required when map_actions are defined");
            if (r.MapActions.Count > 0 && (!indicators.Contains("housing") || !indicators.Contains("morale")))
                throw new ContentException(file, "map_actions", "needs housing and morale indicators in model.yaml");
            if (r.FxCrisisFoodPerYear > 0) throw new ContentException(file, "fx_crisis_food_per_year", "must be <= 0 (a crisis cuts food imports)");
            if (r.FxCrisisFoodPerYear < 0 && !indicators.Contains("food_supply")) throw new ContentException(file, "fx_crisis_food_per_year", "needs a food_supply indicator in model.yaml");
            foreach (var kv in r.InitialPopulation) Count(file, $"initial_population.{kv.Key}", kv.Value);
            // Budget lines (#108). A line is keyed by its own id. With no budget_owners entry the office of that id owns it for
            // the whole era; with an entry, a dated list says which office owns it when. Within one era only: a line that
            // changes across an era boundary is the carry rules' job (chapters spec section 4, #59).
            var era = c.EraAt(r.Start);
            var eraEnd = era?.To ?? DateTime.MaxValue;
            foreach (var kv in r.BudgetOwners)
                if (!r.BudgetStart.ContainsKey(kv.Key)) throw new ContentException(file, $"budget_owners.{kv.Key}", "unknown budget line: list it in budget_start");
            var spans = new List<(string line, string office, DateTime from, DateTime to)>();
            foreach (var kv in r.BudgetStart)
            {
                Unit(file, $"budget_start.{kv.Key}", kv.Value);
                if (!r.BudgetOwners.TryGetValue(kv.Key, out var terms))
                {
                    if (!offices.Contains(kv.Key)) throw new ContentException(file, $"budget_start.{kv.Key}", "unknown office (or give the line an owner in budget_owners)");
                    if (historicalOffices.Contains(kv.Key)) throw new ContentException(file, $"budget_start.{kv.Key}", "historical-only titles cannot have a budget line");
                    if (c.Offices.Any(o => o.Id == kv.Key && o.SeveralHolders)) throw new ContentException(file, $"budget_start.{kv.Key}", "an office with several holders cannot own a budget line");
                    // A budget line must not silently stop mattering when its office is abolished: give it dated owners (#108).
                    var until = c.Offices.First(o => o.Id == kv.Key).Until;
                    if (until.HasValue)
                        throw new ContentException(file, $"budget_start.{kv.Key}", FormattableString.Invariant($"office '{kv.Key}' is abolished on {until:yyyy-MM-dd}: give its budget line to the office that took over (budget_owners)"));
                    spans.Add((kv.Key, kv.Key, r.Start, eraEnd));
                    continue;
                }
                if (!Offices.OfficeId.IsMatch(kv.Key)) throw new ContentException(file, $"budget_start.{kv.Key}", "a budget line id is lowercase letters, digits and underscores");
                var path = $"budget_owners.{kv.Key}";
                if (terms.Count == 0) throw new ContentException(file, path, "needs at least one owner");
                for (int i = 0; i < terms.Count; i++)
                {
                    var t = terms[i]; var tp = FormattableString.Invariant($"{path}[{i}]");
                    if (t.From == default) throw new ContentException(file, tp + ".from", "required");
                    if (t.From < r.Start || t.From >= eraEnd)
                        throw new ContentException(file, tp + ".from", FormattableString.Invariant($"must be inside the era ({r.Start:yyyy-MM-dd} to {eraEnd:yyyy-MM-dd}); a line that changes across eras is the carry rules' job"));
                    if (i == 0 && t.From != r.Start)
                        throw new ContentException(file, tp + ".from", FormattableString.Invariant($"the first owner must start on {r.Start:yyyy-MM-dd}, the first day of the era (no gap)"));
                    if (i > 0 && t.From <= terms[i - 1].From)
                        throw new ContentException(file, tp + ".from", FormattableString.Invariant($"must be after the previous owner's date ({terms[i - 1].From:yyyy-MM-dd})"));
                    if (t.Office == "" || !offices.Contains(t.Office)) throw new ContentException(file, tp + ".office", "unknown office");
                    if (historicalOffices.Contains(t.Office)) throw new ContentException(file, tp + ".office", "historical-only titles cannot have a budget line");
                    // Like policies and effects (#277): the line's factor scales one minister's competence, so it needs one holder.
                    if (c.Offices.Any(o => o.Id == t.Office && o.SeveralHolders)) throw new ContentException(file, tp + ".office", "an office with several holders cannot own a budget line");
                    var end = i + 1 < terms.Count ? terms[i + 1].From : eraEnd;
                    var office = c.Offices.First(o => o.Id == t.Office);
                    if (!office.ExistsOn(t.From))
                        throw new ContentException(file, tp + ".office", FormattableString.Invariant($"office '{t.Office}' does not exist on {t.From:yyyy-MM-dd}"));
                    if (office.Until.HasValue && office.Until.Value < end)
                        throw new ContentException(file, tp + ".office", FormattableString.Invariant($"office '{t.Office}' is abolished on {office.Until:yyyy-MM-dd}, before this owner's stretch ends ({end:yyyy-MM-dd}): add the office that took over"));
                    spans.Add((kv.Key, t.Office, t.From, end));
                }
            }
            // One office owns at most one line on any day, so BudgetFactor(office) has one answer.
            foreach (var a in spans)
                foreach (var b in spans)
                    if (string.CompareOrdinal(a.line, b.line) < 0 && a.office == b.office && a.from < b.to && b.from < a.to)
                        throw new ContentException(file, $"budget_start.{b.line}", $"office '{a.office}' would own both '{a.line}' and '{b.line}' on the same day");
            // The same rule EconomySystem.Allocate applies to every later allocation.
            if (r.BudgetStart.Count > 0 && Math.Abs(r.BudgetStart.Values.Sum() - 1.0) > 1e-6) throw new ContentException(file, "budget_start", "shares must sum to 1");
        }

        // Indicators the code reads by name: food_supply (EconomySystem, FX crisis), housing and morale (MapActions), security
        // and intl_standing (Unity HudModel). A window on one would make those reads miss, so the loader refuses it.
        static readonly string[] CodeNamedIndicators = { "morale", "food_supply", "housing", "security", "intl_standing" };

        /// <summary>Chapters design 3.2: a window must run forward, and nothing may reach a record that is not active for the
        /// whole window of whatever uses it (effect sources and targets, situations, voter-group weights, policy and effect offices).</summary>

        static void ValidateWindows(Content c)
        {
            void Order(string where, DateTime? from, DateTime? to)
            {
                if (from.HasValue && to.HasValue && from.Value >= to.Value) throw new ContentException("model.yaml", where, "from must be before to");
            }
            foreach (var x in c.Indicators)
                if ((x.From.HasValue || x.To.HasValue) && CodeNamedIndicators.Contains(x.Id))
                    throw new ContentException("model.yaml", $"indicators[{x.Id}]", $"'{x.Id}' is read by name in the code, so it cannot have a from/to window");
            foreach (var x in c.Indicators) Order($"indicators[{x.Id}]", x.From, x.To);
            foreach (var x in c.Policies) Order($"policies[{x.Id}]", x.From, x.To);
            foreach (var x in c.Effects) Order($"effects[{x.Id}]", x.From, x.To);
            foreach (var x in c.Situations) Order($"situations[{x.Id}]", x.From, x.To);
            foreach (var x in c.VoterGroups) Order($"voter_groups[{x.Id}]", x.From, x.To);
            foreach (var x in c.Actors) Order($"actors[{x.Id}]", x.From, x.To);

            void Reach(string where, DateTime? from, DateTime? to, string kind, string id, DateTime? rFrom, DateTime? rTo)
            {
                if (!Window.Covers(rFrom, rTo, from, to))
                    throw new ContentException("model.yaml", where, $"{kind} '{id}' is not active for the whole window of this record (give both the same from/to, or a wider one on '{id}')");
            }
            // The reached record's window, or null when the id is a record kind with none: (null, null) means "always".
            (DateTime?, DateTime?) Win(string id)
            {
                var ind = c.Indicators.FirstOrDefault(x => x.Id == id);
                if (ind != null) return (ind.From, ind.To);
                var pol = c.Policies.FirstOrDefault(x => x.Id == id);
                return pol != null ? (pol.From, pol.To) : ((DateTime?)null, (DateTime?)null);
            }
            foreach (var e in c.Effects)
            {
                var s = Win(e.Source); var t = Win(e.Target);
                Reach($"effects[{e.Id}].source", e.From, e.To, "source", e.Source, s.Item1, s.Item2);
                Reach($"effects[{e.Id}].target", e.From, e.To, "target", e.Target, t.Item1, t.Item2);
            }
            foreach (var s in c.Situations)
            {
                var w = Win(s.Indicator);
                Reach($"situations[{s.Id}].indicator", s.From, s.To, "indicator", s.Indicator, w.Item1, w.Item2);
            }
            foreach (var g in c.VoterGroups)
                foreach (var k in g.Weights.Keys)
                {
                    var w = Win(k);
                    Reach($"voter_groups[{g.Id}].weights.{k}", g.From, g.To, "indicator", k, w.Item1, w.Item2);
                }
            // A record with a window of its own must have its office for that whole window. Records with no window keep the
            // existing rule (a policy may name an office that is created later: it has no holder until then).
            void OfficeFor(string where, string office, DateTime? from, DateTime? to)
            {
                if (office == "" || (!from.HasValue && !to.HasValue)) return;
                var o = c.Offices.FirstOrDefault(x => x.Id == office);
                if (o != null && !Window.Covers(o.From, o.Until, from, to))
                    throw new ContentException("model.yaml", where, $"office '{office}' does not exist for the whole window of this record");
            }
            foreach (var p in c.Policies) OfficeFor($"policies[{p.Id}].office", p.Office, p.From, p.To);
            foreach (var e in c.Effects) OfficeFor($"effects[{e.Id}].office", e.Office, e.From, e.To);
        }

        static void Validate(Content c, List<string> settlementIds)
        {
            var offices = new HashSet<string>(c.Offices.Select(o => o.Id));
            var historicalOffices = new HashSet<string>(c.Offices.Where(o => o.HistoricalOnly).Select(o => o.Id));
            var parties = new HashSet<string>(c.Parties.Select(p => p.Id));
            var indicators = new HashSet<string>(c.Indicators.Select(i => i.Id));
            var sources = new HashSet<string>(c.Policies.Select(p => p.Id).Concat(indicators));
            // The cities' employed share (R-CITY-005). Accepted in both loops, so the real content still loads with the loop
            // switch taken out (Unity's SimBridgeGddTests.Legacy); with no cities it reads 0 (EffectsSystem.Source).
            sources.Add(Cities.EmployedShareSource);
            Unique("offices.yaml", "offices", c.Offices.Select(o => o.Id));
            Unique("parties.yaml", "parties", c.Parties.Select(p => p.Id));
            Unique("people.yaml", "people", c.People.Select(p => p.Id));
            foreach (var o in c.Offices) Named("offices.yaml", $"offices[{o.Id}].title", o.Title);
            foreach (var p in c.Parties) Named("parties.yaml", $"parties[{p.Id}].name", p.Name);
            foreach (var p in c.People) Named("people.yaml", $"people[{p.Id}].name", p.Name);
            Unique("legislatures.yaml", "legislatures", c.Legislatures.Select(l => l.Id));
            Unique("governments.yaml", "governments", c.Governments.Select(g => g.Id));
            Unique("eras.yaml", "eras", c.Eras.Select(e => e.Id));
            ValidateEras(c);
            Unique("model.yaml", "indicators", c.Indicators.Select(i => i.Id));
            Unique("model.yaml", "policies", c.Policies.Select(p => p.Id));
            Unique("model.yaml", "effects", c.Effects.Select(e => e.Id));
            Unique("model.yaml", "situations", c.Situations.Select(s => s.Id));
            Unique("model.yaml", "voter_groups", c.VoterGroups.Select(v => v.Id));
            Unique("model.yaml", "actors", c.Actors.Select(a => a.Id));
            Unique("model.yaml", "money", c.Money.Select(a => a.Id));
            Unique("aliyah.yaml", "regions", c.Regions.Select(g => g.Id));
            // Display names (spec: player-facing text): Cause messages show these, never the ids.
            foreach (var i in c.Indicators) Named("model.yaml", $"indicators[{i.Id}].name", i.Name);
            foreach (var p in c.Policies) Named("model.yaml", $"policies[{p.Id}].name", p.Name);
            foreach (var e in c.Effects) Named("model.yaml", $"effects[{e.Id}].name", e.Name);
            foreach (var s in c.Situations) Named("model.yaml", $"situations[{s.Id}].name", s.Name);
            foreach (var g in c.Regions) Named("aliyah.yaml", $"regions[{g.Id}].name", g.Name);
            // Hebrew display names (#558): each value carries its own sources, and sources need a value.
            foreach (var o in c.Offices)
            {
                HebrewName("offices.yaml", $"offices[{o.Id}]", "title_he", o.TitleHe, o.TitleHeSources, o.TitleHeReview, o.TitleHeReviewGiven);
                HebrewName("offices.yaml", $"offices[{o.Id}]", "title_he_f", o.TitleHeF, o.TitleHeFSources, o.TitleHeFReview, o.TitleHeFReviewGiven);
                if (o.TitleHeF != "" && o.TitleHe == "") throw new ContentException("offices.yaml", $"offices[{o.Id}].title_he", "required: a feminine title_he_f needs the title_he beside it");
                // The player can order a woman into any office, so a Hebrew title without its feminine form would show her the
                // masculine one (owner on #861, 17 October 2026).
                if (o.TitleHe != "" && o.TitleHeF == "") throw new ContentException("offices.yaml", $"offices[{o.Id}].title_he_f", $"required: office {o.Id} has a title_he, so it needs its feminine title_he_f beside it");
                if ((o.TitleHeFrom.HasValue || o.TitleHeUntil.HasValue) && o.TitleHe == "") throw new ContentException("offices.yaml", $"offices[{o.Id}].title_he", "required: title_he_from/title_he_until bound a title_he");
                if (o.TitleHeFrom.HasValue && o.TitleHeUntil.HasValue && o.TitleHeUntil.Value <= o.TitleHeFrom.Value)
                    throw new ContentException("offices.yaml", $"offices[{o.Id}].title_he_until", FormattableString.Invariant($"must be after title_he_from ({o.TitleHeFrom:yyyy-MM-dd})"));
            }
            foreach (var p in c.Parties) HebrewName("parties.yaml", $"parties[{p.Id}]", "name_he", p.NameHe, p.NameHeSources, p.NameHeReview, p.NameHeReviewGiven);
            foreach (var l in c.Legislatures) HebrewName("legislatures.yaml", $"legislatures[{l.Id}]", "body_he", l.BodyHe, l.BodyHeSources, l.BodyHeReview, l.BodyHeReviewGiven);
            foreach (var g in c.Governments) HebrewName("governments.yaml", $"governments[{g.Id}]", "name_he", g.NameHe, g.NameHeSources, g.NameHeReview, g.NameHeReviewGiven);
            // People keep their name_he sources in biography_sources (checked below), so only the review flag is checked here (#862).
            foreach (var p in c.People)
            {
                if (p.NameHeReviewGiven && p.NameHeReview != HebrewReview.AgentChecked)
                    throw new ContentException("people.yaml", $"people[{p.Id}].name_he_review", $"must be {HebrewReview.AgentChecked} (until a native speaker, or an AI-assisted contributor who discloses it, has read the name, #564), or left out once it has been read");
                if (p.NameHeReviewGiven && p.NameHe == "") throw new ContentException("people.yaml", $"people[{p.Id}].name_he", "required: name_he_review is set but the name is empty");
            }
            foreach (var a in c.Money)
            {
                if (Array.IndexOf(PlayerText.MoneyIds, a.Id) < 0)
                    throw new ContentException("model.yaml", $"money[{a.Id}].id", $"must be one of {string.Join(", ", PlayerText.MoneyIds)}");
                Named("model.yaml", $"money[{a.Id}].name", a.Name);
                if (string.IsNullOrWhiteSpace(a.Prefix)) throw new ContentException("model.yaml", $"money[{a.Id}].prefix", "required (the currency the player sees, e.g. 'IL ' or '$')");
            }
            var missingMoney = PlayerText.MoneyIds.FirstOrDefault(id => c.Money.All(a => a.Id != id));
            if (missingMoney != null) throw new ContentException("model.yaml", "money", $"missing {missingMoney}");
            foreach (var p in c.Policies)
                if (indicators.Contains(p.Id)) throw new ContentException("model.yaml", $"policies[{p.Id}].id", "same id as an indicator (effect sources would be ambiguous)");
            // Money, indicators and policies share one namespace in Cause targets and PlayerText.Target (fix round 2, N7).
            foreach (var i in c.Indicators)
                if (Array.IndexOf(PlayerText.MoneyIds, i.Id) >= 0) throw new ContentException("model.yaml", $"indicators[{i.Id}].id", "same id as money (treasury, debt, fx_reserves)");
            foreach (var p in c.Policies)
                if (Array.IndexOf(PlayerText.MoneyIds, p.Id) >= 0) throw new ContentException("model.yaml", $"policies[{p.Id}].id", "same id as money (treasury, debt, fx_reserves)");

            foreach (var p in c.People) { Status("people.yaml", $"people[{p.Id}].status", p.Status); Review("people.yaml", $"people[{p.Id}]", p.ReviewedBy, p.ReviewedByGiven, p.ReviewedOn, p.ReviewedOnGiven); }
            foreach (var l in c.Legislatures) { Status("legislatures.yaml", $"legislatures[{l.Id}].status", l.Status); Review("legislatures.yaml", $"legislatures[{l.Id}]", l.ReviewedBy, l.ReviewedByGiven, l.ReviewedOn, l.ReviewedOnGiven); }
            foreach (var g in c.Governments) { Status("governments.yaml", $"governments[{g.Id}].status", g.Status); Review("governments.yaml", $"governments[{g.Id}]", g.ReviewedBy, g.ReviewedByGiven, g.ReviewedOn, g.ReviewedOnGiven); }
            for (int i = 0; i < c.Aliyah.Count; i++) { Status("aliyah.yaml", FormattableString.Invariant($"series[{i}].status"), c.Aliyah[i].Status); Review("aliyah.yaml", FormattableString.Invariant($"series[{i}]"), c.Aliyah[i].ReviewedBy, c.Aliyah[i].ReviewedByGiven, c.Aliyah[i].ReviewedOn, c.Aliyah[i].ReviewedOnGiven); }
            for (int i = 0; i < c.PopulationAnchors.Count; i++) { Status("population.yaml", FormattableString.Invariant($"anchors[{i}].status"), c.PopulationAnchors[i].Status); Review("population.yaml", FormattableString.Invariant($"anchors[{i}]"), c.PopulationAnchors[i].ReviewedBy, c.PopulationAnchors[i].ReviewedByGiven, c.PopulationAnchors[i].ReviewedOn, c.PopulationAnchors[i].ReviewedOnGiven); }

            foreach (var p in c.People)
            {
                if (p.Portrait != null)
                {
                    if (!p.Portrait.FileGiven) throw new ContentException("people.yaml", $"people[{p.Id}].portrait.file", "required");
                    if (!p.Portrait.LicenseGiven) throw new ContentException("people.yaml", $"people[{p.Id}].portrait.license", "required");
                    if (!p.Portrait.SourceGiven) throw new ContentException("people.yaml", $"people[{p.Id}].portrait.source", "required");
                    if (!(p.Portrait.FocusY >= 0 && p.Portrait.FocusY <= 1))
                        throw new ContentException("people.yaml", $"people[{p.Id}].portrait.focus_y", "required: the face's height as a share of the picture, from 0 (top) to 1 (bottom)");
                }
                if (!p.Living.HasValue) throw new ContentException("people.yaml", $"people[{p.Id}].living", "required (true or false)");
                if (p.Competence < 0 || p.Competence > 10) throw new ContentException("people.yaml", $"people[{p.Id}].competence", "must be 0-10");
                if (p.Loyalty < 0 || p.Loyalty > 10) throw new ContentException("people.yaml", $"people[{p.Id}].loyalty", "must be 0-10");
                if (p.Party != "" && !parties.Contains(p.Party)) throw new ContentException("people.yaml", $"people[{p.Id}].party", $"unknown party '{p.Party}'");
                if (p.Born.HasValue && p.Died.HasValue && p.Born.Value >= p.Died.Value)
                    throw new ContentException("people.yaml", $"people[{p.Id}].born", FormattableString.Invariant($"must be before {p.Died:yyyy-MM-dd}, the date of death"));
                var firstTerm = p.Offices.Count > 0 ? p.Offices.Min(t => t.From) : (DateTime?)null;
                if (p.Born.HasValue && firstTerm.HasValue && p.Born.Value > firstTerm.Value)
                    throw new ContentException("people.yaml", $"people[{p.Id}].born", FormattableString.Invariant($"must be on or before {firstTerm:yyyy-MM-dd}, when the first office term starts"));
                // A map skips CheckNulls' list and entry checks, so a misspelt key or an empty source would load silently.
                foreach (var kv in p.BiographySources)
                {
                    var field = $"people[{p.Id}].biography_sources.{kv.Key}";
                    if (kv.Key != "name_he" && kv.Key != "title_he_form" && kv.Key != "born" && kv.Key != "died")
                        throw new ContentException("people.yaml", field, "unknown field (must be name_he, title_he_form, born or died)");
                    if (kv.Value == null) throw new ContentException("people.yaml", field, "must be a list");
                    RequiredSources("people.yaml", field, kv.Value);
                }
                TitleHeForm(c, p);
                foreach (var t in p.Offices)
                {
                    RequiredSources("people.yaml", $"people[{p.Id}].offices.{t.Office}.sources", t.Sources);
                    if (string.IsNullOrEmpty(t.Office)) throw new ContentException("people.yaml", $"people[{p.Id}].offices", "office term without an office");
                    if (!offices.Contains(t.Office)) throw new ContentException("people.yaml", $"people[{p.Id}].offices.{t.Office}", "unknown office");
                    if (t.From == default) throw new ContentException("people.yaml", $"people[{p.Id}].offices.{t.Office}.from", "required");
                    if (t.Party != "" && !parties.Contains(t.Party)) throw new ContentException("people.yaml", $"people[{p.Id}].offices.{t.Office}.party", $"unknown party '{t.Party}'");
                    if (t.To.HasValue && t.To.Value <= t.From) throw new ContentException("people.yaml", $"people[{p.Id}].offices.{t.Office}", FormattableString.Invariant($"term ends ({t.To:yyyy-MM-dd}) before it starts ({t.From:yyyy-MM-dd})"));
                }
            }
            foreach (var o in c.Offices.Where(o => o.Successor != ""))
            {
                var at = $"offices[{o.Id}].successor";
                var next = c.Offices.FirstOrDefault(x => x.Id == o.Successor);
                if (next == null) throw new ContentException("offices.yaml", at, $"unknown office '{o.Successor}'");
                if (next == o) throw new ContentException("offices.yaml", at, "an office cannot succeed itself");
                if (!o.Until.HasValue) throw new ContentException("offices.yaml", at, "needs until: only an abolished office has a successor");
                // The successor takes over the old office's budget lines and policies (chapters spec 4.2, #59), so it must be able
                // to own whatever the old office could.
                if (next.SeveralHolders && !o.SeveralHolders)
                    throw new ContentException("offices.yaml", at, $"office '{next.Id}' has several holders, so it cannot take over budget lines and policies");
                if (next.HistoricalOnly && !o.HistoricalOnly)
                    throw new ContentException("offices.yaml", at, $"office '{next.Id}' is a historical title, so it cannot take over budget lines and policies");
                if (next.From.HasValue && next.From.Value > o.Until.Value)
                    throw new ContentException("offices.yaml", at, FormattableString.Invariant($"office '{next.Id}' is established on {next.From:yyyy-MM-dd}, after {o.Id} is abolished ({o.Until:yyyy-MM-dd})"));
                if (next.Until.HasValue && next.Until.Value <= o.Until.Value)
                    throw new ContentException("offices.yaml", at, FormattableString.Invariant($"office '{next.Id}' is abolished on {next.Until:yyyy-MM-dd}, before it can take over on {o.Until:yyyy-MM-dd}"));
            }
            foreach (var o in c.Offices.Where(o => o.From.HasValue))
            {
                if (o.Until.HasValue && o.Until.Value <= o.From!.Value)
                    throw new ContentException("offices.yaml", $"offices[{o.Id}].until", FormattableString.Invariant($"must be after from ({o.From:yyyy-MM-dd})"));
                foreach (var p in c.People)
                    foreach (var t in p.Offices.Where(t => t.Office == o.Id && t.From < o.From!.Value))
                        throw new ContentException("people.yaml", $"people[{p.Id}].offices.{o.Id}.from", FormattableString.Invariant($"must be on or after {o.From:yyyy-MM-dd}, when the office was established"));
            }
            foreach (var o in c.Offices.Where(o => o.Until.HasValue))
                foreach (var p in c.People)
                    foreach (var t in p.Offices.Where(t => t.Office == o.Id))
                        if (!t.To.HasValue || t.To.Value > o.Until!.Value)
                            throw new ContentException("people.yaml", $"people[{p.Id}].offices.{o.Id}.to", FormattableString.Invariant($"must be on or before {o.Until:yyyy-MM-dd}, when the office was abolished"));
            // An open-ended term runs past the authored governments, so it only conflicts with a death before the latest
            // government began (#167). With no governments, every open-ended term conflicts, as before.
            var latestGovernmentStart = c.Governments.Count > 0 ? c.Governments.Max(g => g.From) : DateTime.MaxValue;
            foreach (var p in c.People.Where(p => p.Died.HasValue))
                foreach (var t in p.Offices)
                {
                    if (t.From >= p.Died!.Value)
                        throw new ContentException("people.yaml", $"people[{p.Id}].offices.{t.Office}.from", FormattableString.Invariant($"must be before {p.Died:yyyy-MM-dd}, the date of death"));
                    if (t.To.HasValue ? t.To.Value > p.Died!.Value : p.Died!.Value < latestGovernmentStart)
                        throw new ContentException("people.yaml", $"people[{p.Id}].offices.{t.Office}.to", FormattableString.Invariant($"must be on or before {p.Died:yyyy-MM-dd}, the date of death"));
                }
            foreach (var p in c.People)
                for (int i = 0; i < p.Offices.Count; i++)
                    for (int j = i + 1; j < p.Offices.Count; j++)
                    {
                        var (a, b) = (p.Offices[i], p.Offices[j]);
                        if (a.Party == "" || b.Party == "" || a.Party == b.Party) continue;
                        if (a.From < (b.To ?? DateTime.MaxValue) && b.From < (a.To ?? DateTime.MaxValue))
                            throw new ContentException("people.yaml", $"people[{p.Id}].offices", "overlapping terms disagree on party");
                    }
            var terms = c.People.SelectMany(p => p.Offices.Select(t => (person: p.Id, term: t))).ToList();
            for (int i = 0; i < terms.Count; i++)
                for (int j = i + 1; j < terms.Count; j++)
                {
                    var (a, b) = (terms[i], terms[j]);
                    if (a.term.Office != b.term.Office || a.person == b.person) continue;
                    if (c.Offices.Any(o => o.Id == a.term.Office && o.SeveralHolders)) continue;
                    if (a.term.From < (b.term.To ?? DateTime.MaxValue) && b.term.From < (a.term.To ?? DateTime.MaxValue))
                        throw new ContentException("people.yaml", $"offices.{a.term.Office}", $"held by both {a.person} and {b.person} on overlapping dates");
                }
            foreach (var l in c.Legislatures)
            {
                Period("legislatures.yaml", $"legislatures[{l.Id}]", l.From, l.To);
                if (l.Size <= 0) throw new ContentException("legislatures.yaml", $"legislatures[{l.Id}].size", "must be > 0");
                foreach (var kv in l.Seats)
                {
                    if (!parties.Contains(kv.Key)) throw new ContentException("legislatures.yaml", $"legislatures[{l.Id}].seats.{kv.Key}", "unknown party");
                    if (kv.Value < 0) throw new ContentException("legislatures.yaml", $"legislatures[{l.Id}].seats.{kv.Key}", "must be >= 0");
                }
                if (l.Seats.Values.Sum() != l.Size) throw new ContentException("legislatures.yaml", $"legislatures[{l.Id}].size", FormattableString.Invariant($"seats sum to {l.Seats.Values.Sum()}, size is {l.Size}"));
            }
            foreach (var g in c.Governments)
            {
                Period("governments.yaml", $"governments[{g.Id}]", g.From, g.To);
                foreach (var p in g.Coalition)
                    if (!parties.Contains(p)) throw new ContentException("governments.yaml", $"governments[{g.Id}].coalition.{p}", "unknown party");
                var inOffice = new List<string>(g.Coalition);
                var previous = g.From;
                for (int i = 0; i < g.CoalitionChanges.Count; i++)
                {
                    var ch = g.CoalitionChanges[i];
                    var at = $"governments[{g.Id}].coalition_changes[{i}]";
                    if (ch.Date == default) throw new ContentException("governments.yaml", at + ".date", "required");
                    if (ch.Date <= g.From || (g.To.HasValue && ch.Date >= g.To.Value))
                        throw new ContentException("governments.yaml", at + ".date", FormattableString.Invariant($"must be inside the term, after {g.From:yyyy-MM-dd}") + (g.To.HasValue ? FormattableString.Invariant($" and before {g.To.Value:yyyy-MM-dd}") : ""));
                    if (i > 0 && ch.Date <= previous) throw new ContentException("governments.yaml", at + ".date", FormattableString.Invariant($"must be after the previous change ({previous:yyyy-MM-dd})"));
                    previous = ch.Date;
                    if (ch.Joins.Count == 0 && ch.Leaves.Count == 0) throw new ContentException("governments.yaml", at, "needs joins or leaves");
                    if (ch.Sources.Count == 0) throw new ContentException("governments.yaml", at + ".sources", "required: a coalition change needs a source");
                    foreach (var p in ch.Leaves)
                    {
                        if (!parties.Contains(p)) throw new ContentException("governments.yaml", $"{at}.leaves.{p}", "unknown party");
                        if (!inOffice.Remove(p)) throw new ContentException("governments.yaml", $"{at}.leaves.{p}", "not in the coalition on that day");
                    }
                    foreach (var p in ch.Joins)
                    {
                        if (!parties.Contains(p)) throw new ContentException("governments.yaml", $"{at}.joins.{p}", "unknown party");
                        if (ch.Leaves.Contains(p)) throw new ContentException("governments.yaml", $"{at}.joins.{p}", "cannot join and leave on the same day");
                        if (inOffice.Contains(p)) throw new ContentException("governments.yaml", $"{at}.joins.{p}", "already in the coalition on that day");
                        inOffice.Add(p);
                    }
                }
            }
            NoOverlap("legislatures.yaml", "legislatures", c.Legislatures.Select(l => (l.Id, l.From, l.To)));
            NoOverlap("governments.yaml", "governments", c.Governments.Select(g => (g.Id, g.From, g.To)));
            foreach (var i in c.Indicators)
            {
                Finite("model.yaml", $"indicators[{i.Id}].base", i.Base);
                Unit("model.yaml", $"indicators[{i.Id}].base", i.Base);
            }
            foreach (var p in c.Policies)
            {
                Finite("model.yaml", $"policies[{p.Id}].default", p.Default);
                Unit("model.yaml", $"policies[{p.Id}].default", p.Default);
            }
            foreach (var p in c.Policies)
            {
                if (!offices.Contains(p.Office)) throw new ContentException("model.yaml", $"policies[{p.Id}].office", $"unknown office '{p.Office}'");
                if (historicalOffices.Contains(p.Office)) throw new ContentException("model.yaml", $"policies[{p.Id}].office", "historical-only titles cannot own policies");
                if (c.Offices.Any(o => o.Id == p.Office && o.SeveralHolders)) throw new ContentException("model.yaml", $"policies[{p.Id}].office", "an office with several holders cannot own policies");
            }
            foreach (var e in c.Effects)
            {
                if (!sources.Contains(e.Source)) throw new ContentException("model.yaml", $"effects[{e.Id}].source", $"unknown policy or indicator '{e.Source}'");
                if (!indicators.Contains(e.Target)) throw new ContentException("model.yaml", $"effects[{e.Id}].target", $"unknown indicator '{e.Target}'");
                Finite("model.yaml", $"effects[{e.Id}].k", e.K);
                if (e.Inertia < 1) throw new ContentException("model.yaml", $"effects[{e.Id}].inertia", "must be >= 1");
                if (e.Office != "" && !offices.Contains(e.Office)) throw new ContentException("model.yaml", $"effects[{e.Id}].office", $"unknown office '{e.Office}'");
                if (historicalOffices.Contains(e.Office)) throw new ContentException("model.yaml", $"effects[{e.Id}].office", "historical-only titles cannot own effects");
                if (c.Offices.Any(o => o.Id == e.Office && o.SeveralHolders)) throw new ContentException("model.yaml", $"effects[{e.Id}].office", "an office with several holders cannot own effects");
            }
            foreach (var s in c.Situations)
            {
                if (!indicators.Contains(s.Indicator)) throw new ContentException("model.yaml", $"situations[{s.Id}].indicator", $"unknown indicator '{s.Indicator}'");
                bool below = s.OnBelow.HasValue && s.OffAbove.HasValue, above = s.OnAbove.HasValue && s.OffBelow.HasValue;
                if (below == above) throw new ContentException("model.yaml", $"situations[{s.Id}]", "needs exactly one pair: on_below+off_above or on_above+off_below");
                foreach (var (key, v) in new[] { ("on_below", s.OnBelow), ("off_above", s.OffAbove), ("on_above", s.OnAbove), ("off_below", s.OffBelow) })
                    if (v.HasValue) Unit("model.yaml", $"situations[{s.Id}].{key}", v.Value);
            }
            foreach (var v in c.VoterGroups)
                foreach (var kv in v.Weights)
                {
                    if (!indicators.Contains(kv.Key)) throw new ContentException("model.yaml", $"voter_groups[{v.Id}].weights.{kv.Key}", "unknown indicator");
                    Finite("model.yaml", $"voter_groups[{v.Id}].weights.{kv.Key}", kv.Value);
                }
            foreach (var a in c.Actors) Unit("model.yaml", $"actors[{a.Id}].standing", a.Standing);
            ValidateRules(c, c.Rules, "rules.yaml", indicators, offices, historicalOffices);
            foreach (var kv in c.EraRules)
                ValidateRules(c, kv.Value, "rules/" + kv.Key + ".yaml", indicators, offices, historicalOffices);
            foreach (var g in c.Regions.Where(g => g.From.HasValue && g.To.HasValue && g.To.Value <= g.From.Value))
                throw new ContentException("aliyah.yaml", $"regions[{g.Id}].to", FormattableString.Invariant($"must be after from ({g.From:yyyy-MM-dd})"));
            for (int i = 0; i < c.Aliyah.Count; i++)
            {
                var a = c.Aliyah[i]; var path = FormattableString.Invariant($"series[{i}]");
                if (a.From == default) throw new ContentException("aliyah.yaml", path + ".from", "required");
                if (a.To < a.From) throw new ContentException("aliyah.yaml", path + ".to", "required, on or after from (both dates are inclusive)");
                foreach (var kv in a.Origins)
                {
                    if (c.Regions.All(g => g.Id != kv.Key)) throw new ContentException("aliyah.yaml", $"{path}.origins.{kv.Key}", $"unknown region '{kv.Key}' (add it to regions with a name)");
                    var region = c.Regions.First(g => g.Id == kv.Key);
                    // A period's dates are inclusive, a region's window is [from, to): the period covers [a.From, a.To + 1 day).
                    if (!Window.Covers(region.From, region.To, a.From, a.To.AddDays(1)))
                        throw new ContentException("aliyah.yaml", $"{path}.origins.{kv.Key}", $"region '{kv.Key}' does not exist for the whole period (its window is {(region.From.HasValue ? region.From.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) : "the start")} to {(region.To.HasValue ? region.To.Value.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) : "open")})");
                    Count("aliyah.yaml", $"{path}.origins.{kv.Key}", kv.Value);
                }
            }
            for (int i = 0; i < c.PopulationAnchors.Count; i++)
            {
                var a = c.PopulationAnchors[i]; var path = FormattableString.Invariant($"anchors[{i}]");
                if (a.Date == default) throw new ContentException("population.yaml", path + ".date", "required");
                Count("population.yaml", path + ".jews", a.Jews);
            }
            ValidateMapLocations(c, settlementIds);
            ValidateMap(c, settlementIds);
            ValidateWindows(c);
            EventRules.Validate(c, offices, indicators);
        }

        /// <summary>One or more eras, each with a name and a non-empty range; the first starts on rules.yaml start and
        /// each starts where the one before ended, so every date in range is in exactly one era.</summary>
        static void ValidateEras(Content c)
        {
            if (c.Eras.Count == 0) throw new ContentException("eras.yaml", "eras", "at least one era is required");
            for (int i = 0; i < c.Eras.Count; i++)
            {
                var e = c.Eras[i];
                var at = $"eras[{e.Id}]";
                Named("eras.yaml", at + ".name", e.Name);
                if (e.To == default) throw new ContentException("eras.yaml", at + ".to", "required (the first day after the era)");
                Period("eras.yaml", at, e.From, e.To);
                if (e.Systems == null) throw new ContentException("eras.yaml", at + ".systems", "must be a map of switches (leave it out for the defaults)");
                if (e.Systems.Legislature != EraSystems.State && e.Systems.Legislature != EraSystems.Assembly)
                    throw new ContentException("eras.yaml", at + ".systems.legislature", "must be state or assembly");
                foreach (var a in e.Systems.MapActions)
                    if (!MapActions.Actions.Contains(a)) throw new ContentException("eras.yaml", at + ".systems.map_actions", $"unknown map action '{a}' (transit_camp or housing)");
                if (e.Systems.MapActions.Distinct().Count() != e.Systems.MapActions.Count)
                    throw new ContentException("eras.yaml", at + ".systems.map_actions", "lists an action twice");
                if (e.Systems.Loop != EraSystems.Legacy && e.Systems.Loop != EraSystems.Gdd)
                    throw new ContentException("eras.yaml", at + ".systems.loop", "must be legacy or gdd");
                if (e.Systems.Loop != c.Eras[0].Systems.Loop)
                    throw new ContentException("eras.yaml", at + ".systems.loop", "every era runs the same loop (a save names one ruleset)");
                var identity = e.Systems.RulesetGiven ? e.Systems.Ruleset
                    : e.Systems.Loop == EraSystems.Gdd ? SaveGame.GddRuleset : SaveGame.LegacyRuleset;
                if (identity != SaveGame.LegacyRuleset && identity != SaveGame.GddRuleset && identity != SaveGame.Gdd03Ruleset)
                    throw new ContentException("eras.yaml", at + ".systems.ruleset", "must be legacy, gdd-0.1 or gdd-0.3");
                if ((identity == SaveGame.LegacyRuleset) != (e.Systems.Loop == EraSystems.Legacy))
                    throw new ContentException("eras.yaml", at + ".systems.ruleset", "legacy requires the legacy loop; gdd-0.1 and gdd-0.3 require the gdd loop");
                if (identity != c.Ruleset)
                    throw new ContentException("eras.yaml", at + ".systems.ruleset", "every era names the same ruleset (explicit or inferred)");
                if (i == 0)
                {
                    if (c.Rules.Start != default && e.From != c.Rules.Start)   // a missing start is rules.yaml's own error
                        throw new ContentException("eras.yaml", at + ".from", FormattableString.Invariant($"must equal start in rules.yaml ({c.Rules.Start:yyyy-MM-dd})"));
                    continue;
                }
                var prev = c.Eras[i - 1];
                if (e.From < prev.To)
                    throw new ContentException("eras.yaml", at + ".from", FormattableString.Invariant($"overlaps {prev.Id} (ends {prev.To:yyyy-MM-dd})"));
                if (e.From > prev.To)
                    throw new ContentException("eras.yaml", at + ".from", FormattableString.Invariant($"leaves a gap after {prev.Id}: must equal its end ({prev.To:yyyy-MM-dd})"));
            }
        }

        /// <summary>Facilities a city may have (cities.yaml facilities): the GDD's training places (D-D5).</summary>
        static readonly string[] Facilities = { "military_camp", "hakhshara" };

        /// <summary>Where a unit type may train (unit_types.yaml facility): a start facility, or a city's completed industry
        /// project (<see cref="Training.Industry"/>; R-CRAFT-001), which no city starts with.</summary>
        static readonly string[] TrainingFacilities = Facilities.Concat(new[] { Training.Industry }).ToArray();

        /// <summary>A military type's sides (unit_types.yaml side): units_1948.yaml's side ids (Q-START-4, owner, 15 October 2026).</summary>
        static readonly string[] Sides = { "israel", "egypt", "jordan", "syria", "iraq", "lebanon", "ala", "local_arab_forces" };

        /// <summary>A military type's classes (unit_types.yaml class; GDD Phase 5 plan, PR 2).</summary>
        static readonly string[] Classes = { "infantry", "artillery", "armour" };

        static readonly string[] CityStatuses = { "sourced", "derived", "wikipedia-only", "design" };
        static readonly System.Text.RegularExpressions.Regex Month = new System.Text.RegularExpressions.Regex(@"^\d{4}-\d{2}\z");

        /// <summary>R-CITY-006: a city value is present and has a known status; a sourced, derived or wikipedia-only value also
        /// has sources, each with a url and a checked date, and the day (YYYY-MM-DD) or month (YYYY-MM) it describes.</summary>
        static CityValue CityValueOf(string file, string at, CityValue? v)
        {
            if (v == null) throw new ContentException(file, at, "required");
            if (v.Status == "") throw new ContentException(file, at + ".status", "required");
            if (!CityStatuses.Contains(v.Status))
                throw new ContentException(file, at + ".status", $"unknown status '{v.Status}' (sourced, derived, wikipedia-only or design)");
            for (int i = 0; i < v.Sources.Count; i++)
                if (v.Sources[i] == null || string.IsNullOrWhiteSpace(v.Sources[i].Url) || v.Sources[i].Checked == default)
                    throw new ContentException(file, FormattableString.Invariant($"{at}.sources[{i}]"), "needs a url and checked date");
            if (v.Date != "" && !ReviewRecord.IsDay(v.Date)
                && !(Month.IsMatch(v.Date) && DateTime.TryParseExact(v.Date, "yyyy-MM", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out _)))
                throw new ContentException(file, at + ".date", "must be YYYY-MM-DD or YYYY-MM");
            if (v.Status == "design") return v;   // a design value may name what its method rests on, and needs no date
            if (v.Sources.Count == 0) throw new ContentException(file, at + ".sources", $"required: a {v.Status} value needs a source");
            if (v.Date == "") throw new ContentException(file, at + ".date", "required: the day or month the value describes");
            return v;
        }

        static void Whole(string file, string at, CityValue v)
        {
            if (v.Value < 0 || v.Value != decimal.Truncate(v.Value) || v.Value > int.MaxValue)
                throw new ContentException(file, at + ".value", "must be a whole number >= 0");
        }

        /// <summary>The GDD v0.1 city data and rules (Phase 1 PR 3), checked only when systems.loop is gdd.</summary>
        static void ValidateGdd(Content c, List<string> settlementIds, List<string> cityAndTownIds)
        {
            const string cf = "cities.yaml", uf = "unit_types.yaml";
            Unique(cf, "cities", c.Cities.Select(x => x.Id));
            var known = new HashSet<string>(settlementIds);
            foreach (var x in c.Cities)
            {
                var at = $"cities[{x.Id}]";
                if (!known.Contains(x.Id)) throw new ContentException(cf, at + ".id", $"is not in {SettlementsFileName}");
                // R-CITY-006: every value is required (never read as 0) and says what it is.
                Whole(cf, at + ".people", CityValueOf(cf, at + ".people", x.People));
                var share = CityValueOf(cf, at + ".employed_share", x.EmployedShare);
                if (share.Value < 0 || share.Value > 1) throw new ContentException(cf, at + ".employed_share.value", "must be a number from 0 to 1");
                Whole(cf, at + ".housing_capacity", CityValueOf(cf, at + ".housing_capacity", x.Housing));
                Whole(cf, at + ".job_slots", CityValueOf(cf, at + ".job_slots", x.Jobs));
                foreach (var f in x.Facilities)
                    if (!Facilities.Contains(f)) throw new ContentException(cf, at + ".facilities", $"unknown facility '{f}' (military_camp or hakhshara)");
                // R-PROJ-005: a resource is a fact about the city, so it is sourced like a sourced city value.
                foreach (var r in x.Resources)
                {
                    var rat = $"{at}.resources[{r.Id}]";
                    if (string.IsNullOrWhiteSpace(r.Id)) throw new ContentException(cf, rat + ".id", "is required");
                    if (r.Sources.Count == 0) throw new ContentException(cf, rat + ".sources", "required: a resource needs a source");
                    for (int i = 0; i < r.Sources.Count; i++)
                        if (r.Sources[i] == null || string.IsNullOrWhiteSpace(r.Sources[i].Url) || r.Sources[i].Checked == default)
                            throw new ContentException(cf, FormattableString.Invariant($"{rat}.sources[{i}]"), "needs a url and checked date");
                }
            }
            Unique(uf, "types", c.UnitTypes.Select(x => x.Id));
            foreach (var x in c.UnitTypes)
            {
                var at = $"types[{x.Id}]";
                if (x.Kind != "population" && x.Kind != "unit") throw new ContentException(uf, at + ".kind", "must be population or unit");
                if (x.Id == "recruit" && x.Side != "israel") throw new ContentException(uf, at + ".side", "a recruit must be an Israeli military unit (R-UNIT-003)");
                // R-UNIT-003 (#2601): a graduating cohort keeps its type (Training.cs), so the recruit itself must be infantry.
                if (x.Id == "recruit" && x.Class != "infantry") throw new ContentException(uf, at + ".class", "a recruit must be infantry (R-UNIT-003)");
                // R-UNIT-001: a type with a side or a class is military, and needs both; the sides are units_1948.yaml's.
                if (x.Side != "" || x.Class != "")
                {
                    if (x.Kind != "unit") throw new ContentException(uf, at + ".kind", "a military type is a unit");
                    if (x.Side == "") throw new ContentException(uf, at + ".side", "required for a military type");
                    if (x.Class == "") throw new ContentException(uf, at + ".class", "required for a military type");
                    if (!Sides.Contains(x.Side)) throw new ContentException(uf, at + ".side", $"unknown side '{x.Side}' ({string.Join(", ", Sides)})");
                    if (!Classes.Contains(x.Class)) throw new ContentException(uf, at + ".class", $"unknown class '{x.Class}' (infantry, artillery or armour)");
                }
                // R-MOVE-001 (Q-MOVE-1): a military type has its movement points; a population count is not on the map.
                if (x.Kind == "population" && x.MovementPoints != 0) throw new ContentException(uf, at + ".movement_points", "only a unit moves");
                if (x.Side != "" && x.MovementPoints < 1) throw new ContentException(uf, at + ".movement_points", "required for a military type, at least 1");
                if (x.MovementPoints < 0) throw new ContentException(uf, at + ".movement_points", "must be >= 0");
                // R-COMBAT-007, R-COMBAT-008 (Q-ARTY-1, Q-ARTY-2): only a military type fights, so only it has a combat
                // factor; range and Arms per firing are artillery's support role and are read for nothing else.
                if (x.CombatPercent != null && x.Side == "") throw new ContentException(uf, at + ".combat_percent", "only a military type has a combat factor");
                if (x.CombatPercent < 1) throw new ContentException(uf, at + ".combat_percent", "must be at least 1");
                if (x.Class == Combat.ArtilleryClass)
                {
                    if (!(x.Range >= 1)) throw new ContentException(uf, at + ".range", "required for an artillery type, at least 1");
                    // R-COMBAT-007: under gdd-0.3 artillery fire spends no Arms (#1706), so arms_per_fire is not required; range stays required.
                    if (Combat.SpendsArms(c) && !(x.ArmsPerFire >= 1)) throw new ContentException(uf, at + ".arms_per_fire", "required for an artillery type, at least 1");
                }
                else
                {
                    if (x.Range != null) throw new ContentException(uf, at + ".range", "only an artillery type has a range");
                    if (x.ArmsPerFire != null) throw new ContentException(uf, at + ".arms_per_fire", "only an artillery type fires");
                }
                if (x.Facility == "")
                {
                    // Training (R-TRAIN-001) needs a place to train; values without one would be read by nothing.
                    if (x.TrainingTurns != 0) throw new ContentException(uf, at + ".training_turns", "only a type with a facility trains");
                    if (x.TrainingCost != 0) throw new ContentException(uf, at + ".training_cost", "only a type with a facility trains");
                    if (x.TrainingArms != null) throw new ContentException(uf, at + ".training_arms", "only a type with a facility trains");
                    continue;
                }
                if (!TrainingFacilities.Contains(x.Facility)) throw new ContentException(uf, at + ".facility", $"unknown facility '{x.Facility}' (military_camp, hakhshara or industry)");
                // A trained count lands in City.Recruits or City.Craftsmen (R-TRAIN-003, R-CRAFT-001); other trained counts
                // wait for their decisions.
                if (x.Kind == "population" && x.Id != "recruit" && x.Id != Training.Craftsman)
                    throw new ContentException(uf, at + ".kind", "only recruit and craftsman are trained counts");
                // Q-CRAFT-1 (owner, 15 October 2026): a craftsman trains in a city with a completed industry project.
                if (x.Id == Training.Craftsman && x.Facility != Training.Industry)
                    throw new ContentException(uf, at + ".facility", "a craftsman trains at industry (Q-CRAFT-1)");
                // R-UNIT-008 (Q-ARTY-3, #2601): Training.Start uses whatever facility is configured, so the loader pins the camp.
                if ((x.Class == Combat.ArtilleryClass || x.Class == "armour") && x.Facility != "military_camp")
                    throw new ContentException(uf, at + ".facility", "an artillery or armour type trains at a military camp (R-UNIT-008)");
                // R-UNIT-008 (Q-ARTY-3): a trained military type pays Arms a group; the recruit's is rules.yaml's
                // arms_per_recruit_group (R-ARMS-003), so a second value on it would be read by nothing.
                if (x.Side != "" && x.Id != "recruit")
                {
                    if (!(x.TrainingArms >= 1)) throw new ContentException(uf, at + ".training_arms", "required for a trained military type, at least 1");
                }
                else if (x.TrainingArms != null) throw new ContentException(uf, at + ".training_arms", "only a trained military type other than the recruit takes its own Arms");
                if (x.TrainingTurns < 1) throw new ContentException(uf, at + ".training_turns", "must be >= 1");
                if (!(x.TrainingCost >= 0 && IsFinite(x.TrainingCost))) throw new ContentException(uf, at + ".training_cost", "must be a finite number >= 0");
            }
            // R-UNIT-004: promotion must not create a unit whose military type is missing or belongs to another side.
            if (c.UnitTypes.Any(t => t.Id == "recruit") && !c.UnitTypes.Any(t => t.Id == "veteran_soldier" && t.Kind == "unit" && t.Side == "israel" && t.Class == "infantry"))
                throw new ContentException(uf, "types[veteran_soldier]", "required as an Israeli infantry unit for recruit promotion");
            // R-CITY-003: the arrivals are spread over the cities, so there must be one to take them.
            if (c.Cities.Count == 0) throw new ContentException(cf, "cities", "the GDD loop needs at least one city to take the arrivals");
            // R-CITY-006 (#2732): the cities are exactly the settlement file's city and town rows, in that file's order.
            foreach (var x in c.Cities)
                if (!cityAndTownIds.Contains(x.Id))
                    throw new ContentException(cf, $"cities[{x.Id}].id", $"is not a city or town row of {SettlementsFileName}");
            for (int i = 0; i < cityAndTownIds.Count; i++)
            {
                if (i >= c.Cities.Count)
                    throw new ContentException(cf, "cities", $"is missing {cityAndTownIds[i]}, a city or town row of {SettlementsFileName}");
                if (c.Cities[i].Id != cityAndTownIds[i])
                    throw new ContentException(cf, FormattableString.Invariant($"cities[{i}].id"),
                        $"is {c.Cities[i].Id}; {SettlementsFileName}'s city and town rows give {cityAndTownIds[i]} here");
            }
            foreach (var (file, r) in new[] { ("rules.yaml", c.Rules) }.Concat(c.EraRules.OrderBy(kv => kv.Key, StringComparer.Ordinal).Select(kv => ("rules/" + kv.Key + ".yaml", kv.Value))))
            {
                var m = r.Mvp ?? throw new ContentException(file, "mvp", "required when eras.yaml systems.loop is gdd");
                if (m.PeoplePerUnit < 1) throw new ContentException(file, "mvp.people_per_unit", "must be >= 1");
                // Arrivals are counted from the game's start in units of one size (R-CITY-003): another size in a later era
                // would lose or double-count units at its boundary.
                if (m.PeoplePerUnit != c.Rules.Mvp!.PeoplePerUnit)
                    throw new ContentException(file, "mvp.people_per_unit", "must be the same in every era (arrivals are counted in one unit size)");
                if (!(m.IncomePerJobPerYear >= 0 && IsFinite(m.IncomePerJobPerYear))) throw new ContentException(file, "mvp.income_per_job_per_year", "must be a finite number >= 0");
                // R-CRAFT-002 (GDD "Population and units": a craftsman "Generates more money than an ordinary civilian"): a missing key reads 0 and is refused.
                if (!(m.CraftsmanIncomeMultiple > 1 && IsFinite(m.CraftsmanIncomeMultiple)))
                    throw new ContentException(file, "mvp.craftsman_income_multiple", "must be a finite number > 1");
                // R-MONEY-002: explicit values keep an omitted kind from silently becoming free upkeep.
                foreach (var (key, v) in new[] {
                    ("city_upkeep_per_year", m.CityUpkeepPerYear), ("housing_upkeep_per_year", m.HousingUpkeepPerYear),
                    ("industry_upkeep_per_year", m.IndustryUpkeepPerYear), ("transit_camp_upkeep_per_year", m.TransitCampUpkeepPerYear),
                    ("military_camp_upkeep_per_year", m.MilitaryCampUpkeepPerYear), ("hakhshara_upkeep_per_year", m.HakhsharaUpkeepPerYear) })
                {
                    if (v == null) throw new ContentException(file, "mvp." + key, "required when eras.yaml systems.loop is gdd");
                    if (!(v >= 0 && IsFinite(v.Value))) throw new ContentException(file, "mvp." + key, "must be a finite number >= 0");
                }
                // R-CITY-003: the cities count arrivals from one day; another day in a later era would lose or double-count units.
                if (m.CityArrivalsFrom == default) throw new ContentException(file, "mvp.city_arrivals_from", "required when eras.yaml systems.loop is gdd");
                foreach (var kv in m.MinisterSystems)
                    if (c.Offices.All(o => o.Id != kv.Value))
                        throw new ContentException(file, $"mvp.minister_systems.{kv.Key}", $"unknown office '{kv.Value}'");
                if (m.CityArrivalsFrom != c.Rules.Mvp!.CityArrivalsFrom) throw new ContentException(file, "mvp.city_arrivals_from", "must be the same in every era (the cities count arrivals from one day)");
                if (m.BuildYishuvTurns < 1) throw new ContentException(file, "mvp.build_yishuv_turns", "must be >= 1");
                if (!(m.BuildYishuvCost >= 0 && IsFinite(m.BuildYishuvCost))) throw new ContentException(file, "mvp.build_yishuv_cost", "must be a finite number >= 0");
                // R-CAMP-001: required, so a missing key is not read as 0 (a camp built at once, or for nothing).
                if (m.BuildCampTurns == null) throw new ContentException(file, "mvp.build_camp_turns", "required when eras.yaml systems.loop is gdd");
                if (m.BuildCampTurns < 1) throw new ContentException(file, "mvp.build_camp_turns", "must be >= 1");
                if (m.BuildCampCost == null) throw new ContentException(file, "mvp.build_camp_cost", "required when eras.yaml systems.loop is gdd");
                if (!(m.BuildCampCost >= 0 && IsFinite(m.BuildCampCost.Value))) throw new ContentException(file, "mvp.build_camp_cost", "must be a finite number >= 0");
                if (m.PlowFieldsTurns < 1) throw new ContentException(file, "mvp.plow_fields_turns", "must be >= 1");
                if (m.PlowFieldsCost == null) throw new ContentException(file, "mvp.plow_fields_cost", "required when eras.yaml systems.loop is gdd");
                if (!(m.PlowFieldsCost >= 0 && IsFinite(m.PlowFieldsCost.Value))) throw new ContentException(file, "mvp.plow_fields_cost", "must be a finite number >= 0");
                // R-SWAMP-001: required, so a missing key is not read as 0 (a swamp drained at once, or for nothing).
                if (m.DrySwampTurns == null) throw new ContentException(file, "mvp.dry_swamp_turns", "required when eras.yaml systems.loop is gdd");
                if (m.DrySwampTurns < 1) throw new ContentException(file, "mvp.dry_swamp_turns", "must be >= 1");
                if (m.DrySwampCost == null) throw new ContentException(file, "mvp.dry_swamp_cost", "required when eras.yaml systems.loop is gdd");
                if (!(m.DrySwampCost >= 0 && IsFinite(m.DrySwampCost.Value))) throw new ContentException(file, "mvp.dry_swamp_cost", "must be a finite number >= 0");
                if (m.FieldFoodPerTurn == null) throw new ContentException(file, "mvp.field_food_per_turn", "required when eras.yaml systems.loop is gdd");
                if (m.FieldFoodPerTurn < 0) throw new ContentException(file, "mvp.field_food_per_turn", "must be >= 0");
                if (m.FieldFoodPerTurn > Pools.MaxFieldFoodPerTurn) throw new ContentException(file, "mvp.field_food_per_turn", FormattableString.Invariant($"must be <= {Pools.MaxFieldFoodPerTurn}"));
                if (m.RoadSegmentTurns < 1) throw new ContentException(file, "mvp.road_segment_turns", "must be >= 1");
                if (!(m.RoadSegmentCost >= 0 && IsFinite(m.RoadSegmentCost))) throw new ContentException(file, "mvp.road_segment_cost", "must be a finite number >= 0");
                if (m.RailSegmentTurns < 1) throw new ContentException(file, "mvp.rail_segment_turns", "must be >= 1");
                if (!(m.RailSegmentCost >= 0 && IsFinite(m.RailSegmentCost))) throw new ContentException(file, "mvp.rail_segment_cost", "must be a finite number >= 0");
                // R-FOOD-001 to R-FOOD-003: required, so a missing key is never read as 0 (a stock term of 0, or no stock).
                if (m.KFood == null) throw new ContentException(file, "mvp.k_food", "required when eras.yaml systems.loop is gdd");
                if (!(m.KFood >= 0 && m.KFood <= 1)) throw new ContentException(file, "mvp.k_food", "must be between 0 and 1");
                if (m.CoverMonths == null) throw new ContentException(file, "mvp.cover_months", "required when eras.yaml systems.loop is gdd");
                if (m.CoverMonths < 1) throw new ContentException(file, "mvp.cover_months", "must be >= 1");
                if (m.CoverMonths > Pools.MaxCoverMonths) throw new ContentException(file, "mvp.cover_months", FormattableString.Invariant($"must be <= {Pools.MaxCoverMonths}"));
                // R-ARMS-001 to R-ARMS-003: required, so a missing key is never read as 0 (no stock, free Arms, or training without them).
                if (m.ArmsStart == null) throw new ContentException(file, "mvp.arms_start", "required when eras.yaml systems.loop is gdd");
                if (m.ArmsStart < 0) throw new ContentException(file, "mvp.arms_start", "must be >= 0");
                if (m.ArmsPrice == null) throw new ContentException(file, "mvp.arms_price", "required when eras.yaml systems.loop is gdd");
                if (!(m.ArmsPrice >= 0 && IsFinite(m.ArmsPrice.Value))) throw new ContentException(file, "mvp.arms_price", "must be a finite number >= 0");
                if (m.ArmsPerRecruitGroup == null) throw new ContentException(file, "mvp.arms_per_recruit_group", "required when eras.yaml systems.loop is gdd");
                if (m.ArmsPerRecruitGroup < 0) throw new ContentException(file, "mvp.arms_per_recruit_group", "must be >= 0");
                // R-MONEY-004: required, so a missing key never makes the lever free, unlimited or worthless.
                if (m.DollarsPerTurn == null) throw new ContentException(file, "mvp.dollars_per_turn", "required when eras.yaml systems.loop is gdd");
                if (m.DollarsPerTurn < 0) throw new ContentException(file, "mvp.dollars_per_turn", "must be >= 0");
                if (m.DollarsTotal == null) throw new ContentException(file, "mvp.dollars_total", "required when eras.yaml systems.loop is gdd");
                if (m.DollarsTotal < 0) throw new ContentException(file, "mvp.dollars_total", "must be >= 0");
                if (m.IlPerDollar.Count == 0) throw new ContentException(file, "mvp.il_per_dollar", "required when eras.yaml systems.loop is gdd (at least one dated rate)");
                for (int i = 0; i < m.IlPerDollar.Count; i++)
                {
                    var x = m.IlPerDollar[i]; var at = FormattableString.Invariant($"mvp.il_per_dollar[{i}]");
                    if (!(x.Rate >= 0 && IsFinite(x.Rate))) throw new ContentException(file, at + ".rate", "must be a finite number >= 0");
                    if (i == 0 && x.From > r.Start) throw new ContentException(file, at + ".from", "the first rate must start on or before the start, so every turn has one");
                    if (i > 0 && x.From <= m.IlPerDollar[i - 1].From) throw new ContentException(file, at + ".from", "must be after the previous rate's day");
                }
                // R-UNIT-010, R-UNIT-004: omitted values must not silently make upkeep free or promotion immediate.
                if (m.MilitaryUpkeepPerTurn == null) throw new ContentException(file, "mvp.military_upkeep_per_turn", "required when eras.yaml systems.loop is gdd");
                if (!(m.MilitaryUpkeepPerTurn >= 0 && IsFinite(m.MilitaryUpkeepPerTurn.Value))) throw new ContentException(file, "mvp.military_upkeep_per_turn", "must be a finite number >= 0");
                if (m.VeteranSoldierService == null) throw new ContentException(file, "mvp.veteran_soldier_service", "required when eras.yaml systems.loop is gdd");
                if (m.VeteranSoldierService < 1) throw new ContentException(file, "mvp.veteran_soldier_service", "must be >= 1");
                // R-VET-001, R-VET-002: required, so a missing key is not read as 0 (a veteran after no work, or one that builds nothing).
                foreach (var (key, v) in new[] { ("veteran_halutz_service", m.VeteranHalutzService), ("veteran_progress", m.VeteranProgress) })
                {
                    if (v == null) throw new ContentException(file, "mvp." + key, "required when eras.yaml systems.loop is gdd");
                    if (v < 1) throw new ContentException(file, "mvp." + key, "must be >= 1");
                }
                // R-HOUSE-001, R-HOUSE-002: required, so a missing key is never read as a condition of 0 or no loss.
                if (m.HousingStartCondition == null) throw new ContentException(file, "mvp.housing_start_condition", "required when eras.yaml systems.loop is gdd");
                Unit(file, "mvp.housing_start_condition", m.HousingStartCondition.Value);
                if (m.OverflowConditionLoss == null) throw new ContentException(file, "mvp.overflow_condition_loss", "required when eras.yaml systems.loop is gdd");
                Unit(file, "mvp.overflow_condition_loss", m.OverflowConditionLoss.Value);
                // R-END-001, R-END-002: required, so a missing key is never read as 0 (a defeat with no debt, or on the first turn).
                if (m.DefeatTurns == null) throw new ContentException(file, "mvp.defeat_turns", "required when eras.yaml systems.loop is gdd");
                if (m.DefeatTurns < 1) throw new ContentException(file, "mvp.defeat_turns", "must be >= 1");
                if (m.DebtCeiling == null) throw new ContentException(file, "mvp.debt_ceiling", "required when eras.yaml systems.loop is gdd");
                if (!(m.DebtCeiling >= 0 && IsFinite(m.DebtCeiling.Value))) throw new ContentException(file, "mvp.debt_ceiling", "must be a finite number >= 0");
                // R-ORDER-002, R-ORDER-003 (#746): required, so a missing key is never read as 0 (a unit with no defence).
                if (m.FortifyDefencePercent == null) throw new ContentException(file, "mvp.fortify_defence_percent", "required when eras.yaml systems.loop is gdd");
                if (m.FortifyDefencePercent < 1) throw new ContentException(file, "mvp.fortify_defence_percent", "must be >= 1");
                if (m.HoldDefencePercent == null) throw new ContentException(file, "mvp.hold_defence_percent", "required when eras.yaml systems.loop is gdd");
                if (m.HoldDefencePercent < 1) throw new ContentException(file, "mvp.hold_defence_percent", "must be >= 1");
                // R-EVT-003 (#107): required, so a missing key is never read as 0 (no floor, or a disloyal minister who does nothing).
                if (m.DelegationLoyaltyFloor == null) throw new ContentException(file, "mvp.delegation_loyalty_floor", "required when eras.yaml systems.loop is gdd");
                if (m.DelegationLoyaltyFloor < 0 || m.DelegationLoyaltyFloor > 10) throw new ContentException(file, "mvp.delegation_loyalty_floor", "must be 0-10");
                // R-ENEMY-007 (owner, 7 November 2026: "6 turns (Recommended)"): required, so no wait is read as 0.
                if (m.OperationWaitTurns == null) throw new ContentException(file, "mvp.operation_wait_turns", "required when eras.yaml systems.loop is gdd");
                if (m.OperationWaitTurns < 1) throw new ContentException(file, "mvp.operation_wait_turns", "must be >= 1");
                if (m.OperationLapseSecurity == null) throw new ContentException(file, "mvp.operation_lapse_security", "required when eras.yaml systems.loop is gdd");
                if (!(m.OperationLapseSecurity <= 0 && IsFinite(m.OperationLapseSecurity.Value))) throw new ContentException(file, "mvp.operation_lapse_security", "must be a finite number <= 0");
                if (m.OperationTruceBreakStanding == null) throw new ContentException(file, "mvp.operation_truce_break_standing", "required when eras.yaml systems.loop is gdd");
                if (!(m.OperationTruceBreakStanding <= 0 && IsFinite(m.OperationTruceBreakStanding.Value))) throw new ContentException(file, "mvp.operation_truce_break_standing", "must be a finite number <= 0");
                if (m.DisloyalEffectShare == null) throw new ContentException(file, "mvp.disloyal_effect_share", "required when eras.yaml systems.loop is gdd");
                Unit(file, "mvp.disloyal_effect_share", m.DisloyalEffectShare.Value);
                // R-MOVE-001 (Q-MOVE-1): a cost for every land biome of the map, so no hex is read as free, and none for a water
                // biome, so lake and sea stay impassable.
                foreach (var b in c.Hexes.Where(h => h.Land).Select(h => h.Biome).Distinct().OrderBy(b => b, StringComparer.Ordinal))
                    if (!m.MoveCost.ContainsKey(b)) throw new ContentException(file, "mvp.move_cost", $"no cost for land biome '{b}' ({HexesFile})");
                foreach (var kv in m.MoveCost)
                {
                    if (c.Hexes.Any(h => !h.Land && h.Biome == kv.Key)) throw new ContentException(file, "mvp.move_cost." + kv.Key, $"is water in {HexesFile}: lake and sea are impassable");
                    if (kv.Value < 1) throw new ContentException(file, "mvp.move_cost." + kv.Key, "must be >= 1");
                }
                // R-MOVE-003 (Q-MOVE-3): required, so a missing key is never read as no room at all.
                if (m.StackLimit == null) throw new ContentException(file, "mvp.stack_limit", "required when eras.yaml systems.loop is gdd");
                if (m.StackLimit < 1) throw new ContentException(file, "mvp.stack_limit", "must be >= 1");
                // R-COMBAT-002 to R-COMBAT-004 (Q-COMBAT-1 to Q-COMBAT-4): required, so a missing key is never read as a free
                // attack, a defender with no strength or an engagement with no outcome.
                // R-COMBAT-004: under gdd-0.3 an attack spends no Arms (#1706), so arms_per_attack is not required or checked there.
                if (Combat.SpendsArms(c) && m.ArmsPerAttack == null) throw new ContentException(file, "mvp.arms_per_attack", "required when eras.yaml systems.loop is gdd");
                if (Combat.SpendsArms(c) && m.ArmsPerAttack < 0) throw new ContentException(file, "mvp.arms_per_attack", "must be >= 0");
                foreach (var b in c.Hexes.Where(h => h.Land).Select(h => h.Biome).Distinct().OrderBy(b => b, StringComparer.Ordinal))
                    if (!m.CombatTerrainPercent.ContainsKey(b)) throw new ContentException(file, "mvp.combat_terrain_percent", $"no percent for land biome '{b}' ({HexesFile})");
                foreach (var kv in m.CombatTerrainPercent)
                    if (kv.Value < 1) throw new ContentException(file, "mvp.combat_terrain_percent." + kv.Key, "must be >= 1");
                if (m.CombatTable.Count == 0) throw new ContentException(file, "mvp.combat_table", "required when eras.yaml systems.loop is gdd");
                var faces = m.CombatTable[0].AttackerLoss.Count;
                for (int i = 0; i < m.CombatTable.Count; i++)
                {
                    var row = m.CombatTable[i];
                    var at = FormattableString.Invariant($"mvp.combat_table[{i}]");
                    if (i == 0 ? row.MinRatioPercent != 0 : row.MinRatioPercent <= m.CombatTable[i - 1].MinRatioPercent)
                        throw new ContentException(file, at + ".min_ratio_percent", i == 0 ? "the first row must start at 0" : "must be above the row before");
                    if (faces < 1 || row.AttackerLoss.Count != faces || row.DefenderLoss.Count != faces || row.DefenderRetreats.Count != faces)
                        throw new ContentException(file, at, "attacker_loss, defender_loss and defender_retreats need one entry per face, the same number in every row");
                    if (row.AttackerLoss.Concat(row.DefenderLoss).Any(x => x < 0)) throw new ContentException(file, at, "a loss must be >= 0");
                    if (row.DefenderRetreats.Any(x => x != 0 && x != 1)) throw new ContentException(file, at + ".defender_retreats", "must be 0 or 1");
                }
                // R-ENEMY-003 (Q-ENEMY-2): required, so a missing key is never read as an enemy that attacks at any odds.
                if (m.EnemyAttackRatioPercent == null) throw new ContentException(file, "mvp.enemy_attack_ratio_percent", "required when eras.yaml systems.loop is gdd");
                if (m.EnemyAttackRatioPercent < 1) throw new ContentException(file, "mvp.enemy_attack_ratio_percent", "must be >= 1");
                // R-MOVE-007 (Q-MOVE-2): required, so a missing key is never read as a free step along a corridor.
                foreach (var (key, v) in new[] { ("road_move_cost", m.RoadMoveCost), ("rail_move_cost", m.RailMoveCost) })
                {
                    if (v == null) throw new ContentException(file, "mvp." + key, "required when eras.yaml systems.loop is gdd");
                    if (v < 1) throw new ContentException(file, "mvp." + key, "must be >= 1");
                }
                // R-MOVE-005 (Q-CIV-1)
                foreach (var id in m.EnemyHeldLocalities)
                    if (c.SettlementHexes.All(h => h.Id != id)) throw new ContentException(file, "mvp.enemy_held_localities", $"unknown settlement '{id}' ({SettlementHexesFileName})");
                if (c.Indicators.All(i => i.Id != Pools.FoodIndicator))
                    throw new ContentException(file, "mvp.k_food", "the Food stock feeds the food_supply indicator, which model.yaml must define");
                // One game has one last day (R-LOOP-004): an era cannot move it.
                if (m.End != c.Rules.Mvp!.End) throw new ContentException(file, "mvp.end", "must be the same in every era (the game has one end)");
                // R-POW-002, R-POW-004, R-POW-005 (Q-POW-2, Q-POW-4, Q-POW-5): required, so a missing key is never read as
                // prisoners who eat nothing, a shortfall that costs nothing or a return that scores nothing.
                foreach (var (key, v) in new[] { ("food_per_prisoner_unit", m.FoodPerPrisonerUnit), ("points_per_prisoner_unit_returned", m.PointsPerPrisonerUnitReturned) })
                {
                    if (v == null) throw new ContentException(file, "mvp." + key, "required when eras.yaml systems.loop is gdd");
                    if (v < 0) throw new ContentException(file, "mvp." + key, "must be >= 0");
                }
                // R-CTRL-011, R-CTRL-012 (Q-OCC-1 (a), Q-OCC-3 (a)): required, so a missing key is never read as an occupation
                // that never ends or costs nothing.
                if (m.OccupationTurns == null) throw new ContentException(file, "mvp.occupation_turns", "required when eras.yaml systems.loop is gdd");
                if (m.OccupationTurns < 1) throw new ContentException(file, "mvp.occupation_turns", "must be >= 1");
                foreach (var (key, v) in new[] { ("prisoner_shortfall_cohesion", m.PrisonerShortfallCohesion), ("held_soldier_cost_per_turn", m.HeldSoldierCostPerTurn), ("occupation_upkeep_per_turn", m.OccupationUpkeepPerTurn),
                    // R-CTRL-018 (Q-DEP-5 (c)): required, so a missing key is never read as a Deport that costs nothing
                    ("deport_cohesion_cost", m.DeportCohesionCost), ("deport_support_cost", m.DeportSupportCost),
                    ("deport_support_drag_per_turn", m.DeportSupportDragPerTurn), ("deport_support_ceiling_drop", m.DeportSupportCeilingDrop),
                    ("deport_money_cost", m.DeportMoneyCost) })
                {
                    if (v == null) throw new ContentException(file, "mvp." + key, "required when eras.yaml systems.loop is gdd");
                    if (!(v >= 0 && IsFinite(v.Value))) throw new ContentException(file, "mvp." + key, "must be a finite number >= 0");
                }
                // R-OBJ-002. Required, so a missing key is not read as 0. Zero is allowed (a balance choice); a negative value
                // would take points away for finishing.
                foreach (var (key, v) in new[] { ("objective_points", m.ObjectivePoints), ("objective_bonus_per_month", m.ObjectiveBonusPerMonth), ("objective_bonus_cap", m.ObjectiveBonusCap) })
                {
                    if (v == null) throw new ContentException(file, "mvp." + key, "required when eras.yaml systems.loop is gdd");
                    if (v < 0) throw new ContentException(file, "mvp." + key, "must be >= 0");
                }
            }
            // R-CITY-007: the units the sim starts from, in the one unit size of every era (checked above).
            foreach (var x in c.Cities)
            {
                var ppu = c.Rules.Mvp!.PeoplePerUnit;
                x.Civilians = Cities.StartUnits(x.People!.Value, ppu);
                x.Employed = Cities.NearestUnit(x.People.Value * x.EmployedShare!.Value, ppu);
                x.HousingCapacity = (int)x.Housing!.Value;
                x.JobSlots = (int)x.Jobs!.Value;
                if (x.Employed > x.JobSlots)
                    throw new ContentException(cf, $"cities[{x.Id}].job_slots.value", FormattableString.Invariant($"is fewer than the {x.Employed} employed units of people times employed_share"));
            }
            // Strictly before the last era's end: an end on it is the era's own end, and the game would be over as era_ended.
            if (c.Rules.Mvp!.End is DateTime end && (end <= c.Rules.Start || end >= c.Eras[c.Eras.Count - 1].To))
                throw new ContentException("rules.yaml", "mvp.end", FormattableString.Invariant($"must be after start ({c.Rules.Start:yyyy-MM-dd}) and before the last era's end ({c.Eras[c.Eras.Count - 1].To:yyyy-MM-dd})"));
            ValidateSites(c);
            ValidateObjectiveConditions(c);
            ValidateEventSites(c);
            ValidateEventPrisoners(c);
            ValidateEventFrontQuiet(c);
            ValidateEventArmisticeFront(c);
            ValidateEventDeported(c);
            ValidateProjects(c);
            ValidateCorridors(c);
        }

        /// <summary>An exchange card (R-POW-004): a known front, and one option, which Delegate resolves without a draw.</summary>
        static void ValidateEventPrisoners(Content c)
        {
            foreach (var e in c.Events.Where(e => e.Prisoners != ""))
            {
                if (!Prisoners.Fronts.Contains(e.Prisoners))
                    throw new ContentException(e.File, $"events[{e.Id}].prisoners", $"unknown front '{e.Prisoners}' (one of {string.Join(", ", Prisoners.Fronts)})");
                if (e.Options.Count != 1)
                    throw new ContentException(e.File, $"events[{e.Id}].options", "an exchange card has exactly one option");
            }
        }

        /// <summary>An armistice card's front (R-WAR-008): a known front, on that front's own card, since Armistice.Resolved
        /// reads the refused front from the id (R-WAR-006).</summary>
        static void ValidateEventFrontQuiet(Content c)
        {
            foreach (var e in c.Events.Where(e => e.FrontQuiet != ""))
            {
                if (!Prisoners.Fronts.Contains(e.FrontQuiet))
                    throw new ContentException(e.File, $"events[{e.Id}].front_quiet", $"unknown front '{e.FrontQuiet}' (one of {string.Join(", ", Prisoners.Fronts)})");
                if (e.Id != "armistice_" + e.FrontQuiet)
                    throw new ContentException(e.File, $"events[{e.Id}].front_quiet", $"'{e.FrontQuiet}' goes only on its own card, armistice_{e.FrontQuiet}");
            }
        }

        /// <summary>R-ENEMY-007: an operation card's armistice front is a known front, on a card with an operation option
        /// (one with requires_unit_regions), so that front's signed armistice can end it.</summary>
        static void ValidateEventArmisticeFront(Content c)
        {
            foreach (var e in c.Events.Where(e => e.ArmisticeFront != ""))
            {
                if (!Prisoners.Fronts.Contains(e.ArmisticeFront))
                    throw new ContentException(e.File, $"events[{e.Id}].armistice_front", $"unknown front '{e.ArmisticeFront}' (one of {string.Join(", ", Prisoners.Fronts)})");
                if (!e.Follows && !e.Options.Any(o => o.RequiresUnitRegions.Count != 0))
                    throw new ContentException(e.File, $"events[{e.Id}].armistice_front", "only an operation card (an option with requires_unit_regions) or a following card has an armistice front");
            }
            foreach (var e in c.Events.Where(e => e.Follows && e.Requires.Count == 0))
                throw new ContentException(e.File, $"events[{e.Id}].follows", "a following card follows its requires: it needs one");
        }

        /// <summary>A Deport follow-up card (R-EVT-007; GDD Phase 6 PR 9, #801): a settlement target whose residents stayed,
        /// since Deport is refused where they fled (R-CTRL-018) and the card could never fire; the displacement tag, so the
        /// release gate holds it until the owner's review (R-GATE-001); one option, which Delegate resolves without a draw; no `to`,
        /// whose closed window would miss a later Deport; no `prisoners`; a soft anchor (it takes no soft slot either way); a window
        /// open from the game's start; nothing else it waits for; and one card per place, so it fires on its Deport's turn, once.</summary>
        static void ValidateEventDeported(Content c)
        {
            var cardOf = new Dictionary<string, string>(StringComparer.Ordinal);
            foreach (var e in c.Events.Where(e => e.Deported != "").OrderBy(e => e.Id, StringComparer.Ordinal))
            {
                var target = c.SettlementTargets.FirstOrDefault(t => t.Id == e.Deported)
                    ?? throw new ContentException(e.File, $"events[{e.Id}].deported", $"unknown settlement target '{e.Deported}' (settlement_targets.yaml)");
                if (target.Residents == Fled)
                    throw new ContentException(e.File, $"events[{e.Id}].deported", $"the residents of '{e.Deported}' fled when it was captured, so it is never deported (R-CTRL-018)");
                if (!e.Tags.Contains("displacement", StringComparer.OrdinalIgnoreCase))
                    throw new ContentException(e.File, $"events[{e.Id}].tags", "a Deport card carries the displacement tag (R-GATE-001)");
                if (e.Options.Count != 1)
                    throw new ContentException(e.File, $"events[{e.Id}].options", "a Deport card has exactly one option");
                if (e.To != null)
                    throw new ContentException(e.File, $"events[{e.Id}].to", "a Deport card has no to: a closed window would miss a later Deport");
                if (e.Prisoners != "")
                    throw new ContentException(e.File, $"events[{e.Id}].prisoners", "a Deport card is not an exchange card");
                if (e.Anchor != "soft")
                    throw new ContentException(e.File, $"events[{e.Id}].anchor", "a Deport card is soft: it is not on the record");
                if (e.From > c.Rules.Start)
                    throw new ContentException(e.File, $"events[{e.Id}].from", FormattableString.Invariant($"a Deport card opens at the game's start ({c.Rules.Start:yyyy-MM-dd}), so a Deport on any turn fires it"));
                foreach (var (key, set) in new[] { ("conditions", e.Conditions.Count > 0), ("requires", e.Requires.Count > 0), ("site", e.Site != ""),
                             ("objective", e.Objective != ""), ("kind", e.Kind != EventKinds.Historical), ("variants", e.Variants.Count > 0),
                             ("front_quiet", e.FrontQuiet != ""), ("armistice_front", e.ArmisticeFront != ""), ("follows", e.Follows) })
                    if (set) throw new ContentException(e.File, $"events[{e.Id}].{key}", "a Deport card waits for nothing but its Deport");
                if (cardOf.TryGetValue(e.Deported, out var first))
                    throw new ContentException(e.File, $"events[{e.Id}].deported", $"'{e.Deported}' already has a card, '{first}': one Deport raises one card");
                cardOf[e.Deported] = e.Id;
            }
        }

        /// <summary>An event's site (R-SWAMP-002): a designated swamp site, whose works the event is about. Only the GDD loop
        /// reads sites.yaml, so only it can check this; the legacy loop ignores the key.</summary>
        static void ValidateEventSites(Content c)
        {
            foreach (var e in c.Events.Where(e => e.Site != ""))
            {
                var site = c.Sites.FirstOrDefault(x => x.Id == e.Site)
                    ?? throw new ContentException(e.File, $"events[{e.Id}].site", $"unknown site '{e.Site}' (sites.yaml)");
                if (!site.Kinds.Contains(Projects.SwampKind))
                    throw new ContentException(e.File, $"events[{e.Id}].site", $"site '{e.Site}' is not a swamp site (sites.yaml kinds)");
            }
        }

        /// <summary>The city project kinds (projects.yaml, R-PROJ-001): unique ids, a name, a cost and turns, and what each adds.
        /// The values are design values (Q-PROJ-1); the checks keep a typo from building a project that never finishes, costs
        /// less than nothing or moves a condition out of its 0 to 1 scale in one step.</summary>
        static void ValidateProjects(Content c)
        {
            const string pf = "projects.yaml";
            var all = c.ProjectKinds.Concat(c.ProjectKindsOfOtherRulesets).ToList();   // every row, whatever the ruleset
            Unique(pf, "projects", all.Select(x => x.Id));
            foreach (var x in all)
            {
                var at = $"projects[{x.Id}]";
                if (string.IsNullOrWhiteSpace(x.Name)) throw new ContentException(pf, at + ".name", "is required");
                if (!(x.Cost >= 0 && !double.IsInfinity(x.Cost))) throw new ContentException(pf, at + ".cost", "must be a finite non-negative number");
                if (x.Turns < 1) throw new ContentException(pf, at + ".turns", "must be at least 1");
                if (x.Capacity < 0) throw new ContentException(pf, at + ".capacity", "must not be negative");
                if (x.JobSlots < 0) throw new ContentException(pf, at + ".job_slots", "must not be negative");
                if (!(x.Condition >= -1 && x.Condition <= 1)) throw new ContentException(pf, at + ".condition", "must be a number from -1 to 1");
                // #1122 (owner ruling 3): a draft Hebrew name is marked agent-checked until a native speaker, or an
                // AI-assisted contributor who discloses it, has read it (#564; owner, 4 November 2026:
                // "AI-assisted can clear it").
                if (x.NameHeReviewGiven && x.NameHeReview != HebrewReview.AgentChecked)
                    throw new ContentException(pf, at + ".name_he_review", $"must be {HebrewReview.AgentChecked} (until a native speaker, or an AI-assisted contributor who discloses it, has read the name, #564), or left out once it has been read");
                if (x.NameHeReviewGiven && string.IsNullOrWhiteSpace(x.NameHe)) throw new ContentException(pf, at + ".name_he", "required: name_he_review is set but the name is empty");
                // R-PROJ-005: a kind whose resource no city has could never be built.
                if (!string.IsNullOrEmpty(x.Requires) && !c.Cities.Any(k => k.Resources.Any(r => r.Id == x.Requires)))
                    throw new ContentException(pf, at + ".requires", $"no city in cities.yaml has the resource '{x.Requires}'");
                ValidateWorkshopKind(c, x, pf, at);
                ValidateRepairKind(c, x, pf, at);
            }
        }

        /// <summary>R-HOUSE-006: the housing_repair row exists under gdd-0.3 only and adds no capacity or job slots, and under
        /// gdd-0.3 it has the balance catalogue's housing_repair price and effect: its cost, its work as turns (maintainer call
        /// (not an owner ruling): 1 work is one turn, as arms_workshop's work 3 is its 3 turns) and its condition_pp as a change
        /// of the 0 to 1 condition (owner, 1 November 2026: "Fixed price 0.5 Money + 1 work").</summary>
        static void ValidateRepairKind(Content c, ProjectKind x, string pf, string at)
        {
            if (x.Id != Projects.HousingRepair) return;
            if (!(x.Rulesets.Count == 1 && x.Rulesets[0] == SaveGame.Gdd03Ruleset))
                throw new ContentException(pf, at + ".rulesets", $"a housing repair exists under {SaveGame.Gdd03Ruleset} only: rulesets: [{SaveGame.Gdd03Ruleset}]");
            if (x.Capacity != 0) throw new ContentException(pf, at + ".capacity", "must be 0: a housing repair adds no capacity");
            if (x.JobSlots != 0) throw new ContentException(pf, at + ".job_slots", "must be 0: a housing repair adds no job slots");
            if (c.Ruleset != SaveGame.Gdd03Ruleset) return;
            const string key = "housing_repair";
            if (!c.Gdd03Balance!.Values.TryGetValue(key, out var row) || row?.Parts == null)
                throw new ContentException(pf, at, $"the gdd-0.3 balance catalogue has no {key} row");
            decimal Part(string part) => row.Parts.TryGetValue(part, out var v) && v?.Values?.Count == 1 ? v.Values[0]
                : throw new ContentException(pf, at, $"the gdd-0.3 balance catalogue's {key} has no single {part} value");
            void Match(string field, decimal actual, decimal expected, string part)
            {
                if (actual != expected)
                    throw new ContentException(pf, at + "." + field, FormattableString.Invariant($"must be {expected}, the gdd-0.3 balance catalogue's {key} {part}"));
            }
            Match("cost", (decimal)x.Cost, Part("cost"), "cost");
            // Maintainer call (not an owner ruling): work is matched as turns, 1 work = 1 turn (the arms_workshop precedent).
            Match("turns", x.Turns, Part("work"), "work");
            Match("condition", (decimal)x.Condition, Part("condition_pp") / 100m, "condition_pp / 100");
        }

        /// <summary>R-ARMS-004: a kind's `rulesets` names GDD rulesets only, and `worker_slots` is 0 or 1. A kind with a worker
        /// slot is an arms workshop: it adds no housing, condition or job slots (its worker holds no job), exists under
        /// gdd-0.3 only, and under gdd-0.3 the arms_workshop row has the balance catalogue's worker slots.</summary>
        static void ValidateWorkshopKind(Content c, ProjectKind x, string pf, string at)
        {
            foreach (var r in x.Rulesets)
                if (r != SaveGame.GddRuleset && r != SaveGame.Gdd03Ruleset)
                    throw new ContentException(pf, at + ".rulesets", $"unknown ruleset '{r}' ({SaveGame.GddRuleset} or {SaveGame.Gdd03Ruleset})");
            if (x.WorkerSlots < 0 || x.WorkerSlots > 1) throw new ContentException(pf, at + ".worker_slots", "must be 0 or 1");
            if (x.WorkerSlots > 0)
            {
                if (x.JobSlots != 0) throw new ContentException(pf, at + ".job_slots", "must be 0 with worker_slots: a workshop worker holds no job");
                if (x.Capacity != 0) throw new ContentException(pf, at + ".capacity", "must be 0 with worker_slots");
                if (x.Condition != 0) throw new ContentException(pf, at + ".condition", "must be 0 with worker_slots");
                if (!(x.Rulesets.Count == 1 && x.Rulesets[0] == SaveGame.Gdd03Ruleset))
                    throw new ContentException(pf, at + ".rulesets", $"a kind with worker_slots exists under {SaveGame.Gdd03Ruleset} only: rulesets: [{SaveGame.Gdd03Ruleset}]");
            }
            if (c.Ruleset == SaveGame.Gdd03Ruleset && x.Id == Workshops.ArmsWorkshop)
            {
                var slots = Gdd03ProjectCatalogue.Read(c).Projects.Single(p => p.Key == Workshops.ArmsWorkshop).Capacity!.Amount;
                if (x.WorkerSlots != slots)
                    throw new ContentException(pf, at + ".worker_slots", FormattableString.Invariant($"must be {slots}, the gdd-0.3 balance catalogue's arms_workshop worker slots"));
            }
        }

        /// <summary>The corridors (corridors.yaml, Phase 4 PR 2): a known kind, names, a route id, and segments whose hexes are
        /// land hexes of the map, each one step from the last, the first of a segment one step from (or on) the last of the one
        /// before (Review focus 2: no corridor with a gap). That the route exists in map/routes_1948.yaml and the hexes are its
        /// traced line's is checked by tools/tests/test_corridor_hexes.py: the sim does not read the map-only route files.</summary>
        static void ValidateCorridors(Content c)
        {
            const string cf = "corridors.yaml";
            Unique(cf, "corridors", c.Corridors.Select(x => x.Id));
            foreach (var x in c.Corridors)
            {
                var at = $"corridors[{x.Id}]";
                if (x.Kind != Corridors.Road && x.Kind != Corridors.Rail) throw new ContentException(cf, at + ".kind", $"unknown kind '{x.Kind}' (road, rail)");
                Named(cf, at + ".name", x.Name);
                Named(cf, at + ".name_he", x.NameHe);
                if (string.IsNullOrWhiteSpace(x.Route)) throw new ContentException(cf, at + ".route", "required: the map route the corridor follows");
                if (x.Segments.Count == 0) throw new ContentException(cf, at + ".segments", "needs at least one segment");
                List<int>? prev = null;
                for (int i = 0; i < x.Segments.Count; i++)
                {
                    var sat = FormattableString.Invariant($"{at}.segments[{i + 1}].hexes");
                    var hexes = x.Segments[i].Hexes;
                    if (hexes.Count == 0) throw new ContentException(cf, sat, "needs at least one hex");
                    foreach (var h in hexes)
                    {
                        if (h == null || h.Count != 2) throw new ContentException(cf, sat, "must be [q, r] pairs");
                        var hex = c.HexAt(h[0], h[1]);
                        if (hex == null || !hex.Land)
                            throw new ContentException(cf, sat, FormattableString.Invariant($"hex q={h[0]} r={h[1]} is not a land hex in {HexesFile}"));
                        if (prev != null && MapActions.Distance(prev[0], prev[1], h[0], h[1]) > 1)
                            throw new ContentException(cf, sat, FormattableString.Invariant($"hex q={h[0]} r={h[1]} is not next to q={prev[0]} r={prev[1]}"));
                        prev = h;
                    }
                }
                if (x.Sources.Count == 0) throw new ContentException(cf, at + ".sources", "required: a corridor is a historical fact");
                for (int i = 0; i < x.Sources.Count; i++)
                    if (x.Sources[i] == null || string.IsNullOrWhiteSpace(x.Sources[i].Url) || x.Sources[i].Checked == default)
                        throw new ContentException(cf, FormattableString.Invariant($"{at}.sources[{i}]"), "needs a url and checked date");
                Status(cf, at + ".status", x.Status);
                Review(cf, at, x.ReviewedBy, x.ReviewedByGiven, x.ReviewedOn, x.ReviewedOnGiven);
            }
        }

        /// <summary>An objective's GDD condition: a standalone site objective keeps the site's founding date (R-OBJ-001),
        /// while an infrastructure part names an existing corridor or one or more buildable yishuv sites (R-OBJ-005).
        /// EventRules checks the loop-independent shape and sources.</summary>
        static void ValidateObjectiveConditions(Content c)
        {
            foreach (var o in c.Objectives)
            {
                var at = $"objectives[{o.Id}]";
                if (o.PartOf != "" && (o.ReferenceDate < c.Rules.Start || o.ReferenceDate >= c.End))
                    throw new ContentException(ObjectivesFileName, at + ".reference_date",
                        FormattableString.Invariant($"must be inside the MVP ({c.Rules.Start:yyyy-MM-dd} to {c.End:yyyy-MM-dd})"));
                // R-OBJ-003: the card fires at the end of the turn its objective is completed in, so nothing but the objective may
                // hold it back: its window runs from the game's start to its end, and it has no requires or conditions. An event
                // may not span an era boundary (EventRules), so with several eras the card's own era bounds it instead.
                // EventRules has already checked the card exists; only the GDD loop fires it, so only it checks this.
                var card = c.Events.First(e => e.Id == o.Card);
                string CardField(string key) => $"events[{card.Id}].{key}";
                var era = c.EraAt(card.From);
                var opens = era?.From ?? c.Rules.Start;
                var closes = era != null && era.To < c.End ? era.To : c.End;
                if (card.From > opens)
                    throw new ContentException(card.File, CardField("from"), FormattableString.Invariant($"an objective's card opens at the game's start, or its era's ({opens:yyyy-MM-dd}), so it fires the turn its objective is completed"));
                if (card.To is DateTime to && to < closes)
                    throw new ContentException(card.File, CardField("to"), FormattableString.Invariant($"an objective's card stays open to the game's end, or its era's ({closes:yyyy-MM-dd}), so it fires the turn its objective is completed"));
                foreach (var (key, set) in new[] { ("requires", card.Requires.Count > 0), ("conditions", card.Conditions.Count > 0) })
                    if (set) throw new ContentException(card.File, CardField(key), "an objective's card waits for nothing but its objective");
                if (o.CompletesWhen!.Absorbed != null) continue;   // R-OBJ-004 has no site; the GDD loop always has cities
                if (o.CompletesWhen.CorridorComplete != "")
                {
                    var corridor = o.CompletesWhen.CorridorComplete;
                    if (c.Corridors.All(x => x.Id != corridor))
                        throw new ContentException(ObjectivesFileName, at + ".completes_when.corridor_complete", $"unknown corridor '{corridor}' (corridors.yaml)");
                    continue;
                }
                if (o.CompletesWhen.SitesBuilt.Count > 0)
                {
                    var ids = new HashSet<string>(StringComparer.Ordinal);
                    for (int i = 0; i < o.CompletesWhen.SitesBuilt.Count; i++)
                    {
                        var siteId = o.CompletesWhen.SitesBuilt[i];
                        var field = FormattableString.Invariant($"{at}.completes_when.sites_built[{i}]");
                        if (!ids.Add(siteId)) throw new ContentException(ObjectivesFileName, field, $"duplicate site '{siteId}'");
                        var listed = c.Sites.FirstOrDefault(x => x.Id == siteId)
                            ?? throw new ContentException(ObjectivesFileName, field, $"unknown site '{siteId}' (sites.yaml)");
                        if (!listed.Kinds.Contains(Projects.YishuvKind))
                            throw new ContentException(ObjectivesFileName, field, $"site '{siteId}' cannot be built as a yishuv");
                    }
                    continue;
                }
                var id = o.CompletesWhen.SiteBuilt;   // EventRules requires one kind
                var site = c.Sites.FirstOrDefault(x => x.Id == id)
                    ?? throw new ContentException(ObjectivesFileName, at + ".completes_when.site_built", $"unknown site '{id}' (sites.yaml)");
                if (!site.Kinds.Contains(Projects.YishuvKind))
                    throw new ContentException(ObjectivesFileName, at + ".completes_when.site_built", $"site '{id}' cannot be built as a yishuv");
                if (o.ReferenceDate != site.Founded)
                    throw new ContentException(ObjectivesFileName, at + ".reference_date",
                        FormattableString.Invariant($"must be {site.Founded:yyyy-MM-dd}, the founding date of site '{id}' in sites.yaml"));
            }
        }

        /// <summary>What a designated site may be built as (sites.yaml kinds; R-SITE-004, the GDD's pioneer actions and D-D5's two
        /// facilities). A camp site is a military_camp or a hakhshara (Q-CAMP-3).</summary>
        static readonly string[] SiteKinds = { Projects.YishuvKind, "field", "swamp", "military_camp", "hakhshara" };
        static readonly string[] CampKinds = { "military_camp", "hakhshara" };

        /// <summary>The designated sites (sites.yaml, Phase 1 PR 5): sourced facts on a land hex that holds no 1948 settlement
        /// and no settlement target, founded inside the MVP's years (D-B1). The armistice line hexes are not checked: that file
        /// is display only, and a site may sit on a line hex (#378, question 2).</summary>
        static void ValidateSites(Content c)
        {
            const string sf = "sites.yaml";
            Unique(sf, "sites", c.Sites.Select(x => x.Id));
            var from = new DateTime(1948, 5, 15);
            var to = new DateTime(1952, 1, 1);
            var yishuvAt = new Dictionary<(int, int), string>();
            foreach (var x in c.Sites)
            {
                var at = $"sites[{x.Id}]";
                Named(sf, at + ".name", x.Name);
                Named(sf, at + ".name_he", x.NameHe);
                var hex = c.HexAt(x.Q, x.R);
                if (hex == null || !hex.Land)
                    throw new ContentException(sf, at + ".q", FormattableString.Invariant($"hex q={x.Q} r={x.R} is not a land hex in {HexesFile}"));
                var settled = c.SettlementHexes.FirstOrDefault(h => h.Q == x.Q && h.R == x.R);
                if (settled != null)
                    throw new ContentException(sf, at + ".q", FormattableString.Invariant($"hex q={x.Q} r={x.R} holds the 1948 settlement {settled.Id} ({SettlementHexesFileName})"));
                // R-CTRL-020 (#2804): a depopulated place closes its target's hex, which for Ramla (TargetOnANeighbour) is not a
                // settlement's hex, and pioneer work never asks DepopulatedAt; so no site may stand on a target's hex either.
                var target = c.SettlementTargets.FirstOrDefault(t => t.Q == x.Q && t.R == x.R);
                if (target != null)
                    throw new ContentException(sf, at + ".q", FormattableString.Invariant($"hex q={x.Q} r={x.R} is the settlement target {target.Id} ({SettlementTargetsFileName})"));
                if (x.Kinds.Count == 0) throw new ContentException(sf, at + ".kinds", "required: one or more of " + string.Join(", ", SiteKinds));
                foreach (var k in x.Kinds)
                    if (!SiteKinds.Contains(k)) throw new ContentException(sf, at + ".kinds", $"unknown kind '{k}' ({string.Join(", ", SiteKinds)})");
                // R-FIELD-001: a field site's built record is its plowed state, so a built yishuv on it would yield Food. Only that
                // pair is refused; other kinds may share a field site.
                if (x.Kinds.Contains(Projects.FieldKind) && x.Kinds.Contains(Projects.YishuvKind))
                    throw new ContentException(sf, at + ".kinds", "a field site cannot also be a yishuv site (its built record is its plowed state)");
                // R-SWAMP-001 (Q-SWAMP-1): the same for a swamp, which drained gives a field site in its hex, to be plowed.
                if (x.Kinds.Contains(Projects.FieldKind) && x.Kinds.Contains(Projects.SwampKind))
                    throw new ContentException(sf, at + ".kinds", "a field site cannot also be a swamp site (its built record is its plowed state)");
                // R-SWAMP-001: nor a yishuv or camp site, whose build would write the same record and so drain the swamp.
                if (x.Kinds.Contains(Projects.SwampKind))
                    foreach (var k in CampKinds.Prepend(Projects.YishuvKind))
                        if (x.Kinds.Contains(k))
                            throw new ContentException(sf, at + ".kinds", $"a swamp site cannot also be a {k} site (its built record is its drained state)");
                // R-SITE-004 (#2599): nor may a yishuv site be a camp site: they would share one built record, so building the yishuv
                // would give the city the camp's facility (Training.HasFacility) without the camp action.
                if (x.Kinds.Contains(Projects.YishuvKind))
                    foreach (var k in CampKinds)
                        if (x.Kinds.Contains(k))
                            throw new ContentException(sf, at + ".kinds", $"a yishuv site cannot also be a {k} site (its built record is its built camp)");
                if (x.Kinds.Contains(Projects.YishuvKind))
                {
                    // R-SITE-005 (Q-SITE-3): one yishuv per hex, so SettlementPlacer keeps one kit per hex; other kinds may share it.
                    if (yishuvAt.TryGetValue((x.Q, x.R), out var first))
                        throw new ContentException(sf, at + ".q", FormattableString.Invariant($"hex q={x.Q} r={x.R} already holds the yishuv site {first}"));
                    yishuvAt[(x.Q, x.R)] = x.Id;
                    if (x.Founded < from || x.Founded >= to)
                        throw new ContentException(sf, at + ".founded", "required, between 15 May 1948 and 31 December 1951 (the MVP's years, D-B1)");
                }
                else if (x.Founded != default)
                    throw new ContentException(sf, at + ".founded", "only a yishuv site has a founding date");
                // Q-CAMP-1: a camp belongs to one city, which a built camp gives the facility to.
                if (x.Kinds.Any(k => CampKinds.Contains(k)))
                {
                    if (string.IsNullOrWhiteSpace(x.City)) throw new ContentException(sf, at + ".city", "required for a camp site (military_camp, hakhshara)");
                    if (!c.Cities.Any(y => y.Id == x.City)) throw new ContentException(sf, at + ".city", $"unknown city '{x.City}' (cities.yaml)");
                }
                else if (x.City != "")
                    throw new ContentException(sf, at + ".city", "only a camp site has a city");
                if (x.Sources.Count == 0) throw new ContentException(sf, at + ".sources", "required: a designated site is a historical fact");
                for (int i = 0; i < x.Sources.Count; i++)
                    if (x.Sources[i] == null || string.IsNullOrWhiteSpace(x.Sources[i].Url) || x.Sources[i].Checked == default)
                        throw new ContentException(sf, FormattableString.Invariant($"{at}.sources[{i}]"), "needs a url and checked date");
                Status(sf, at + ".status", x.Status);
                Review(sf, at, x.ReviewedBy, x.ReviewedByGiven, x.ReviewedOn, x.ReviewedOnGiven);
            }
        }

        static readonly string[] MapLocationKinds = { "city", "kibbutz", "fort", "pass", "bridge", "reception_camp", "outpost", "military_camp" };   // military_camp: #1719
        static readonly string[] MapLocationPriorities = { "must_have", "optional" };
        static readonly string[] StartingControls = { "israeli", "arab_forces", "contested" };

        /// <summary>GDD v0.2 named map locations: sourced metadata on a land hex. A location's explicit role flags keep this
        /// roster from creating a managed city, designated site or settlement-control target by implication.</summary>
        static void ValidateMapLocations(Content c, List<string> settlementIds)
        {
            const string lf = MapLocationsFileName;
            Unique(lf, "locations", c.MapLocations.Select(x => x.Id));
            var settlements = new HashSet<string>(settlementIds);
            foreach (var x in c.MapLocations)
            {
                var at = $"locations[{x.Id}]";
                Named(lf, at + ".name", x.Name);
                Named(lf, at + ".name_he", x.NameHe);   // the map labels it in both languages (#1008)
                if (x.NameHeReviewGiven && x.NameHeReview != "agent-checked")
                    throw new ContentException(lf, at + ".name_he_review", $"'{x.NameHeReview}' is not agent-checked (delete the line once a native speaker, or an AI-assisted contributor who discloses it, has reviewed the name, #564)");
                if (x.NameHeSources.Count == 0) throw new ContentException(lf, at + ".name_he_sources", "required: a Hebrew name needs a source");
                for (int i = 0; i < x.NameHeSources.Count; i++)
                    if (x.NameHeSources[i] == null || !x.NameHeSources[i].Url.StartsWith("https://", StringComparison.Ordinal) || x.NameHeSources[i].Checked == default)
                        throw new ContentException(lf, FormattableString.Invariant($"{at}.name_he_sources[{i}]"), "needs a url and checked date");
                if (!MapLocationKinds.Contains(x.Kind))
                    throw new ContentException(lf, at + ".kind", $"unknown kind '{x.Kind}' ({string.Join(", ", MapLocationKinds)})");
                if (!MapLocationPriorities.Contains(x.Priority))
                    throw new ContentException(lf, at + ".priority", $"unknown priority '{x.Priority}' ({string.Join(", ", MapLocationPriorities)})");
                // #1007, owner 21 October 2026: an outpost is optional map metadata with no implied gameplay role.
                if (x.Kind == "outpost")
                {
                    if (x.Priority != "optional") throw new ContentException(lf, at + ".priority", "an outpost must be optional");
                    if (x.ManagedCity) throw new ContentException(lf, at + ".managed_city", "an outpost has no managed city");
                    if (x.DesignatedSite) throw new ContentException(lf, at + ".designated_site", "an outpost is not a founding site");
                    if (x.SettlementControlTarget) throw new ContentException(lf, at + ".settlement_control_target", "an outpost is not a capture target");
                    if (x.StartingControl != "") throw new ContentException(lf, at + ".starting_control", "an outpost has no starting control");
                }
                Finite(lf, at + ".lon", x.Lon);
                Finite(lf, at + ".lat", x.Lat);
                if (x.Lon < -180 || x.Lon > 180) throw new ContentException(lf, at + ".lon", "must be from -180 to 180");
                if (x.Lat < -90 || x.Lat > 90) throw new ContentException(lf, at + ".lat", "must be from -90 to 90");
                var hex = c.HexAt(x.Q, x.R);
                if (hex == null || !hex.Land)
                    throw new ContentException(lf, at + ".q", FormattableString.Invariant($"hex q={x.Q} r={x.R} is not a land hex in {HexesFile}"));
                if (!x.Marker) throw new ContentException(lf, at + ".marker", "must be true: this file is the map-location roster");
                if (x.ManagedCity && !settlements.Contains(x.Id))
                    throw new ContentException(lf, at + ".managed_city", $"needs the same id in {SettlementsFileName}");
                if (x.StartingControl == "" && x.ControlDate != default)
                    throw new ContentException(lf, at + ".starting_control", "required with control_date");
                if (x.StartingControl != "")
                {
                    if (!StartingControls.Contains(x.StartingControl))
                        throw new ContentException(lf, at + ".starting_control", $"unknown control '{x.StartingControl}' ({string.Join(", ", StartingControls)})");
                    if (x.ControlDate == default) throw new ContentException(lf, at + ".control_date", "required with starting_control");
                }
                if (x.ControlChange != null)
                {
                    var change = x.ControlChange;
                    var cat = at + ".control_change";
                    if (x.ControlDate == default) throw new ContentException(lf, cat + ".date", "requires control_date");
                    if (change.Date <= x.ControlDate) throw new ContentException(lf, cat + ".date", "must be after control_date");
                    if (!StartingControls.Contains(change.Control))
                        throw new ContentException(lf, cat + ".control", $"unknown control '{change.Control}' ({string.Join(", ", StartingControls)})");
                    if (change.Sources == null || change.Sources.Count == 0)
                        throw new ContentException(lf, cat + ".sources", "required: a control change is a historical fact");
                    for (int i = 0; i < change.Sources.Count; i++)
                        if (change.Sources[i] == null || !change.Sources[i].Url.StartsWith("https://", StringComparison.Ordinal) || change.Sources[i].Checked == default)
                            throw new ContentException(lf, FormattableString.Invariant($"{cat}.sources[{i}]"), "needs an https url and a checked date");
                }
                if (x.Sources.Count == 0) throw new ContentException(lf, at + ".sources", "required: a map location is a historical fact");
                for (int i = 0; i < x.Sources.Count; i++)
                    if (x.Sources[i] == null || !x.Sources[i].Url.StartsWith("https://", StringComparison.Ordinal) || x.Sources[i].Checked == default)
                        throw new ContentException(lf, FormattableString.Invariant($"{at}.sources[{i}]"), "needs a url and checked date");
                Status(lf, at + ".status", x.Status);
            }
        }

        static void ValidateMap(Content c, List<string> settlementIds)
        {
            if (c.Hexes.Count == 0) throw new ContentException(HexesFile, "hexes", "no hexes");
            var seen = new HashSet<(int, int)>();
            foreach (var h in c.Hexes)
            {
                var at = FormattableString.Invariant($"hexes[q={h.Q},r={h.R}]");
                if (!seen.Add((h.Q, h.R))) throw new ContentException(HexesFile, at, "duplicate hex");
                if (h.Biome == "") throw new ContentException(HexesFile, at + ".biome", "required");
            }
            Unique(SettlementHexesFileName, "settlements", c.SettlementHexes.Select(s => s.Id));
            Unique(SettlementsFileName, "settlements", settlementIds);
            var known = new HashSet<string>(settlementIds);
            var placed = new HashSet<string>(c.SettlementHexes.Select(s => s.Id));
            foreach (var s in c.SettlementHexes)
                if (!known.Contains(s.Id))
                    throw new ContentException(SettlementHexesFileName, $"settlements[{s.Id}]", $"is not in {SettlementsFileName}");
            foreach (var id in settlementIds)
                if (!placed.Contains(id))
                    throw new ContentException(SettlementsFileName, $"settlements[{id}]", $"has no hex in {SettlementHexesFileName}");
            foreach (var s in c.SettlementHexes)
            {
                var hex = c.HexAt(s.Q, s.R);
                if (hex == null || !hex.Land)
                    throw new ContentException(SettlementHexesFileName, $"settlements[{s.Id}]", FormattableString.Invariant($"hex q={s.Q} r={s.R} is not a land hex in {HexesFile}"));
            }
        }

        /// <summary>Targets whose capture hex is a neighbour of their settlement's hex, not that hex (owner on #1796, 26 October
        /// 2026, "Contested + move target"): at 4.4 km (#1183) Ramla shares (-4, 24) with Rehovot, so a unit on Rehovot's hex
        /// would capture Ramla. Its target is the neighbour nearest Ramla's point, cited in settlement_targets.yaml.
        /// The ruling names the hex, so the loader pins it (#2804): another neighbour is a load error too.</summary>
        internal static readonly Dictionary<string, (int Q, int R)> TargetOnANeighbour = new Dictionary<string, (int Q, int R)>(StringComparer.Ordinal) { ["ramla"] = (-3, 24) };

        /// <summary>R-CTRL-001 (Q-TGT-1 (a)): every target is an arab_town row of settlements_1948.yaml on a land hex that is
        /// its own hex in settlement_hexes.yaml (capture reads the target's hex, movement the settlement's), or for a
        /// <see cref="TargetOnANeighbour"/> row a neighbour of it, with a sourced operation and a review status.</summary>
        static void ValidateSettlementTargets(Content c, IEnumerable<string> arabTownIds)
        {
            Unique(SettlementTargetsFileName, "targets", c.SettlementTargets.Select(x => x.Id));
            var known = new HashSet<string>(arabTownIds, StringComparer.Ordinal);
            foreach (var x in c.SettlementTargets)
            {
                var at = $"targets[{x.Id}]";
                if (!known.Contains(x.Id))
                    throw new ContentException(SettlementTargetsFileName, at + ".id", $"is not an {ArabTown} row of {SettlementsFileName}");
                var hex = c.HexAt(x.Q, x.R);
                if (hex == null || !hex.Land)
                    throw new ContentException(SettlementTargetsFileName, at + ".q", FormattableString.Invariant($"hex q={x.Q} r={x.R} is not a land hex in {HexesFile}"));
                if (TargetOnANeighbour.TryGetValue(x.Id, out var ruled))
                {
                    if ((x.Q, x.R) != ruled)
                        throw new ContentException(SettlementTargetsFileName, at + ".q", FormattableString.Invariant($"hex q={x.Q} r={x.R} is not q={ruled.Q} r={ruled.R}, the hex R-CTRL-001 names for {x.Id} (the neighbour nearest its point; owner on #1796)"));
                    if (!c.SettlementHexes.Any(h => h.Id == x.Id && Movement.Neighbours.Any(d => h.Q + d.Q == x.Q && h.R + d.R == x.R)))
                        throw new ContentException(SettlementTargetsFileName, at + ".q", FormattableString.Invariant($"hex q={x.Q} r={x.R} is not next to {x.Id}'s hex in {SettlementHexesFileName}"));
                }
                else if (c.SettlementHexes.Any(h => h.Id == x.Id && (h.Q != x.Q || h.R != x.R)))
                    throw new ContentException(SettlementTargetsFileName, at + ".q", FormattableString.Invariant($"hex q={x.Q} r={x.R} is not {x.Id}'s hex in {SettlementHexesFileName}"));
                if (string.IsNullOrWhiteSpace(x.Operation)) throw new ContentException(SettlementTargetsFileName, at + ".operation", "required");
                if (x.Sources.Count == 0) throw new ContentException(SettlementTargetsFileName, at + ".sources", "needs at least one source");
                for (int i = 0; i < x.Sources.Count; i++)
                {
                    var source = x.Sources[i];
                    if (!Uri.TryCreate(source.Url, UriKind.Absolute, out var uri) || uri.Scheme != "https" || source.Checked == default)
                        throw new ContentException(SettlementTargetsFileName, at + $".sources[{i}]", "needs an https url and a checked date");
                }
                ValidateResidents(x, at);
                Status(SettlementTargetsFileName, at + ".status", x.Status);
            }
        }

        /// <summary>R-CTRL-016 (Q-ANNEX-1; OWNER QUESTION 1 (a) on #799): a target's residents are fled or stayed, with at least
        /// one source; only a stayed row has an annexation block, whose people are a sourced whole number and whose employed
        /// share is from 0 to 1, each checked as a cities.yaml value.</summary>
        static void ValidateResidents(SettlementTarget x, string at)
        {
            const string f = SettlementTargetsFileName;
            if (x.Residents != Fled && x.Residents != Stayed)
                throw new ContentException(f, at + ".residents", $"must be {Fled} or {Stayed}, not '{x.Residents}'");
            if (x.ResidentsSources.Count == 0) throw new ContentException(f, at + ".residents_sources", "needs at least one source");
            for (int i = 0; i < x.ResidentsSources.Count; i++)
            {
                var source = x.ResidentsSources[i];
                if (source == null || !Uri.TryCreate(source.Url, UriKind.Absolute, out var uri) || uri.Scheme != "https" || source.Checked == default)
                    throw new ContentException(f, at + $".residents_sources[{i}]", "needs an https url and a checked date");
            }
            if (x.Residents == Fled)
            {
                if (x.Annexation != null) throw new ContentException(f, at + ".annexation", "a fled place adds nothing on annexation, so it has no annexation block");
                return;
            }
            if (x.Annexation == null) throw new ContentException(f, at + ".annexation", "required for a stayed place");
            var people = CityValueOf(f, at + ".annexation.people", x.Annexation.People);
            Whole(f, at + ".annexation.people", people);
            if (people.Status != "sourced") throw new ContentException(f, at + ".annexation.people.status", "must be sourced: a resident count is a fact the owner approves");
            var share = CityValueOf(f, at + ".annexation.employed_share", x.Annexation.EmployedShare);
            if (share.Value < 0 || share.Value > 1) throw new ContentException(f, at + ".annexation.employed_share.value", "must be a number from 0 to 1");
        }
    }
}