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.

Map editor infrastructure: isolated gdd-0.3 authoring envelope, synthetic fixtures only (Refs #1721) (#1883)

Eyal Golanc911cdf8ab0a
diff --git a/changelog.d/1721.md b/changelog.d/1721.md
new file mode 100644
index 000000000..7a208a52f
--- /dev/null
+++ b/changelog.d/1721.md
@@ -0,0 +1 @@
+- Add isolated gdd-0.3 map authoring schema, source document and blocking diagnostics infrastructure (refs #1721). Domain integration and canonical export remain unavailable; legacy map files are unchanged.
diff --git a/content/schema/map-editor-overlay.schema.json b/content/schema/map-editor-overlay.schema.json
new file mode 100644
index 000000000..f87274c50
--- /dev/null
+++ b/content/schema/map-editor-overlay.schema.json
@@ -0,0 +1,209 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "Isolated gdd-0.3 map authoring envelope",
+ "description": "R-MEDIT-001/002/003: legacy format is unchanged. The explicit gdd-0.3 envelope is authoring infrastructure only, not runtime content or a validation receipt. Registry ids require owning validators; canonical export is blocked until those contracts are integrated. Offset units and base manifest remain deferred.",
+ "definitions": {
+ "hex": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "q",
+ "r"
+ ],
+ "properties": {
+ "q": {
+ "type": "integer"
+ },
+ "r": {
+ "type": "integer"
+ }
+ }
+ },
+ "legacy": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "terrain",
+ "control",
+ "locations"
+ ],
+ "properties": {
+ "terrain": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "hex",
+ "value"
+ ],
+ "properties": {
+ "hex": {
+ "$ref": "#/definitions/hex"
+ },
+ "value": {
+ "type": "string",
+ "minLength": 1
+ }
+ }
+ }
+ },
+ "control": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "hex",
+ "period",
+ "value"
+ ],
+ "properties": {
+ "hex": {
+ "$ref": "#/definitions/hex"
+ },
+ "period": {
+ "type": "string",
+ "minLength": 1
+ },
+ "value": {
+ "type": "string",
+ "minLength": 1
+ }
+ }
+ }
+ },
+ "locations": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "id",
+ "hex"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^[a-z][a-z0-9_]*$"
+ },
+ "hex": {
+ "$ref": "#/definitions/hex"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "version",
+ "ruleset",
+ "draft",
+ "base_revision",
+ "base_digest",
+ "overlay",
+ "workable",
+ "regions",
+ "infrastructure"
+ ],
+ "properties": {
+ "version": {
+ "type": "string",
+ "enum": [
+ "map-editor-0.3"
+ ]
+ },
+ "ruleset": {
+ "type": "string",
+ "enum": [
+ "gdd-0.3"
+ ]
+ },
+ "draft": {
+ "type": "boolean"
+ },
+ "base_revision": {
+ "type": "string",
+ "pattern": "^[^\\s\\u0000-\\u001f\\u007f]+(?![\\s\\S])"
+ },
+ "base_digest": {
+ "type": "string",
+ "pattern": "^[0-9a-f]{64}(?![\\s\\S])"
+ },
+ "overlay": {
+ "$ref": "#/definitions/legacy"
+ },
+ "workable": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "hex",
+ "value"
+ ],
+ "properties": {
+ "hex": {
+ "$ref": "#/definitions/hex"
+ },
+ "value": {
+ "type": "boolean"
+ }
+ }
+ }
+ },
+ "regions": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "hex",
+ "region_id"
+ ],
+ "properties": {
+ "hex": {
+ "$ref": "#/definitions/hex"
+ },
+ "region_id": {
+ "type": "string",
+ "pattern": "^[^\\s\\u0000-\\u001f\\u007f]+(?![\\s\\S])"
+ }
+ }
+ }
+ },
+ "infrastructure": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "id",
+ "hex",
+ "kind",
+ "parent_id"
+ ],
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^[^\\s\\u0000-\\u001f\\u007f]+(?![\\s\\S])"
+ },
+ "hex": {
+ "$ref": "#/definitions/hex"
+ },
+ "kind": {
+ "type": "string",
+ "pattern": "^[^\\s\\u0000-\\u001f\\u007f]+(?![\\s\\S])"
+ },
+ "parent_id": {
+ "type": "string",
+ "pattern": "^[^\\s\\u0000-\\u001f\\u007f]+(?![\\s\\S])"
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/docs/rules/mvp.md b/docs/rules/mvp.md
index 9d77cc302..fc0483901 100644
--- a/docs/rules/mvp.md
+++ b/docs/rules/mvp.md
@@ -520,3 +520,11 @@ R-POP-002: A ledger record has exactly one typed status and assignment, validate
R-POP-003: Clone copies all ledger containers; immutable records and frozen bindings may be shared. The canonical writer emits a gdd-0.3-only section ordered by numeric population id, with fixed field order, stable machine tokens, invariant integer formatting and length-prefixed reference strings. It covers every record/assignment/equipment/reference field, binding, creation/loss provenance and allocator even after the last combat loss. Legacy/gdd-0.1 emit no ledger section or allocator marker. R-SAVE-001/002 still govern identity mismatch refusal and replay: no ledger snapshot or new command syntax is added in this foundation, and fixture injection is not replay evidence. Existing unpublished schema-4 draft hashes change; no migration promise is made.
#1706 slices 0/1 (coordinator decision, 26 Oct 2026, Q5): the synthetic combat catalogue foundation is inactive in the actual game. R-COMBAT-001 through R-COMBAT-008 retain their current runtime meanings. See [the catalogue foundation](../gdd03-catalogue.md#1706-slices-01-inactive-combat-catalogue-foundation) for its data contract and sources.
+
+## Map editor infrastructure (gdd-0.3 authoring only)
+
+R-MEDIT-001: The versioned authoring envelope changes override fields only. It carries no names, source/review metadata, population, jobs, capacities or campaign state. Region, field and facility ids in synthetic tests are fixture-only. No production integration or historical data is authorized by this infrastructure slice.
+
+R-MEDIT-002: Only an explicit gdd-0.3 editor context accepts the versioned envelope. Version, ruleset, draft flag, base revision/digest and all edit lists are required; unknown properties, incomplete axial coordinates and duplicate edit identities are refused. Base revision and registry references are single-line tokens without whitespace or control characters. Serialization is invariant and ordered without mutating the candidate. The authoring envelope uses a separate schema; the legacy schema stays byte-identical. Legacy parsing/serialization, content, save/state bytes and goldens remain unchanged. Failed document replacement retains both the current candidate and rejected raw input; serialized source preserves edits and provenance through Undo and domain reload.
+
+R-MEDIT-003: Schema validity is not semantic validation. Missing region/field/facility/corridor/anchor/target/objective adapters and an unapproved base-manifest contract are named blocking diagnostics, even for an empty candidate. Base mismatch reports both identities. This infrastructure cannot canonical-save or export, and has no runtime reader or disk writer. Integrating domain validators, persistence, offsets and the headed editor is separate work.
diff --git a/sim/Statecraft.Sim.Tests/MapOverridesTests.cs b/sim/Statecraft.Sim.Tests/MapOverridesTests.cs
index 3bffd8c3a..a618ec47f 100644
--- a/sim/Statecraft.Sim.Tests/MapOverridesTests.cs
+++ b/sim/Statecraft.Sim.Tests/MapOverridesTests.cs
@@ -147,4 +147,187 @@ public class MapOverridesTests
Assert.Equal(without.Hexes.Select(h => h.Biome), with.Hexes.Select(h => h.Biome));
Assert.Equal(without.SettlementHexes.Select(h => (h.Id, h.Q, h.R)), with.SettlementHexes.Select(h => (h.Id, h.Q, h.R)));
}
+ // R-MEDIT-001, R-MEDIT-002, R-MEDIT-003, R-LOOP-001, R-LOOP-002:
+ // All editor-0.3 examples are SYNTHETIC, fixture-only, never historical authoring data.
+ const string EditorFixture = "version: map-editor-0.3\nruleset: gdd-0.3\ndraft: true\n"
+ + "base_revision: fixture-only\nbase_digest: "
+ + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ + "overlay: { terrain: [], control: [], locations: [] }\n"
+ + "workable: []\nregions: []\ninfrastructure: []\n";
+
+ [Fact]
+ public void EditorEnvelopeRoundTripsWithoutEnteringTheLegacyParser()
+ {
+ var value = MapEditorOverlay.Parse(EditorFixture, SaveGame.Gdd03Ruleset);
+ var text = MapEditorOverlay.Serialize(value);
+ Assert.Equal(text, MapEditorOverlay.Serialize(MapEditorOverlay.Parse(text, SaveGame.Gdd03Ruleset)));
+ Assert.Throws<ContentException>(() => MapOverrides.Parse(text));
+ Assert.Contains("MAPEDIT_RULESET", Assert.Throws<ContentException>(() =>
+ MapEditorOverlay.Parse(text, SaveGame.GddRuleset)).Message);
+ Assert.Contains("MAPEDIT_RULESET", Assert.Throws<ContentException>(() =>
+ MapEditorOverlay.Parse(text, SaveGame.LegacyRuleset)).Message);
+ }
+
+ [Theory]
+ [InlineData("overlay: { terrain: [], control: [], locations: [] }", "overlay: { terrain: [], control: [], locations: [{ id: fixture_only, hex: { q: 1 } }] }", "MAPEDIT_SHAPE")]
+ [InlineData("draft: true", "draft: true\nunknown: 1", "MAPEDIT_SHAPE")]
+ [InlineData("regions: []", "regions: [{ hex: { q: 1, r: 2 }, region_id: fixture_only }, { hex: { q: 1, r: 2 }, region_id: another_fixture_only }]", "MAPEDIT_DUPLICATE")]
+ [InlineData("infrastructure: []", "infrastructure: [{ id: fixture_only, hex: { q: 1, r: 2 }, kind: fixture_only, parent_id: fixture_only }, { id: fixture_only, hex: { q: 2, r: 2 }, kind: fixture_only, parent_id: fixture_only }]", "MAPEDIT_DUPLICATE")]
+ [InlineData("map-editor-0.3", "future", "MAPEDIT_VERSION")]
+ [InlineData("draft: true", "draft: null", "MAPEDIT_SHAPE")]
+ [InlineData("base_revision: fixture-only", "base_revision: ''", "MAPEDIT_BASE")]
+ [InlineData("workable: []", "workable: [{ hex: { q: 1, r: -2 }, value: true }, { hex: { q: 1, r: -2 }, value: false }]", "MAPEDIT_DUPLICATE")]
+ [InlineData("workable: []", "workable: [{ hex: { q: 1 }, value: true }]", "MAPEDIT_SHAPE")]
+ [InlineData("regions: []", "regions: [{ hex: { q: 1, r: 2 }, region_id: '' }]", "MAPEDIT_SHAPE")]
+ [InlineData("infrastructure: []", "infrastructure: [{ id: fixture_only, hex: { q: 1, r: 2 }, kind: fixture_only, parent_id: fixture_only, capacity: 3 }]", "MAPEDIT_SHAPE")]
+ public void EditorShapeRefusalsHaveNamedErrors(string old, string replacement, string code)
+ {
+ var error = Assert.Throws<ContentException>(() =>
+ MapEditorOverlay.Parse(EditorFixture.Replace(old, replacement), SaveGame.Gdd03Ruleset));
+ Assert.Contains(code, error.Message);
+ Assert.Equal(MapOverrides.FileName, error.File);
+ }
+
+ [Fact]
+ public void MissingDependencyContractsAlwaysBlockCanonicalExportEvenForAnEmptyCandidate()
+ {
+ var value = MapEditorOverlay.Parse(EditorFixture.Replace("draft: true", "draft: false"), SaveGame.Gdd03Ruleset);
+ var diagnostics = value.Diagnostics("current-fixture-only", new string('b', 64));
+ Assert.Contains(diagnostics, x => x.Code == "MAPEDIT_BASE_CONFLICT" && x.Message.Contains("fixture-only"));
+ Assert.Contains(diagnostics, x => x.Code == "MAPEDIT_DEPENDENCY_UNAVAILABLE");
+ Assert.Equal(diagnostics.Select(x => x.Field).OrderBy(x => x, System.StringComparer.Ordinal), diagnostics.Select(x => x.Field));
+ Assert.All(diagnostics, x => { Assert.Equal(MapOverrides.FileName, x.File); Assert.NotEmpty(x.Action); });
+ Assert.False(value.CanExport);
+ }
+
+ [Fact]
+ public void EditorNumbersAreInvariantAndCallerOwnedInputIsNotReordered()
+ {
+ var value = MapEditorOverlay.Parse(EditorFixture.Replace("workable: []",
+ "workable: [{ hex: { q: 3, r: 2 }, value: false }, { hex: { q: 1, r: -2 }, value: true }]"), SaveGame.Gdd03Ruleset);
+ var before = System.Globalization.CultureInfo.CurrentCulture;
+ try
+ {
+ System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
+ var text = MapEditorOverlay.Serialize(value);
+ System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("he-IL");
+ Assert.Equal(text, MapEditorOverlay.Serialize(value));
+ Assert.Contains("r: -2", text);
+ Assert.Equal(3, value.Workable[0].Hex.Q);
+ }
+ finally { System.Globalization.CultureInfo.CurrentCulture = before; }
+ }
+
+ // R-MEDIT-002: same-run guard, no literal hash. A legacy overrides fixture parsed by the legacy path and the same
+ // fixture carried through the authoring envelope give identical legacy text.
+ [Fact]
+ public void LegacyOverridesReadTheSameThroughTheLegacyPathAndTheAuthoringEnvelope()
+ {
+ const string legacy = "terrain:\n - { hex: { q: 2, r: 2 }, value: desert }\n - { hex: { q: 1, r: 2 }, value: hills }\n"
+ + "control:\n - { hex: { q: 1, r: 2 }, period: truce1, value: E }\n - { hex: { q: 1, r: 2 }, period: opening, value: '-' }\n"
+ + "locations:\n - { id: town_a, hex: { q: 1, r: 2 } }\n - { id: fort_a, hex: { q: 2, r: 2 } }\n";
+ var viaLegacy = MapOverrides.Serialize(MapOverrides.Parse(legacy));
+ var envelope = MapEditorOverlay.Parse(EditorFixture, SaveGame.Gdd03Ruleset);
+ envelope.Overlay = MapOverrides.Parse(legacy);
+ var back = MapEditorOverlay.Parse(MapEditorOverlay.Serialize(envelope), SaveGame.Gdd03Ruleset);
+ Assert.Equal(viaLegacy, MapOverrides.Serialize(back.Overlay));
+ }
+
+ // R-MEDIT-002, R-LOOP-001/002: capture this test's baseline before authoring operations.
+ // This checks noninterference in one run, not a base-versus-candidate runtime receipt.
+ [Theory]
+ [InlineData(false, "legacy")]
+ [InlineData(true, "gdd-0.1")]
+ public void AuthoringOperationsLeaveCapturedRuntimeBytesUnchanged(bool gdd, string ruleset)
+ {
+ var root = Fixture.Write(gdd ? Fixture.Gdd() : new Dictionary<string, string>());
+ (string Hash, string State, string Save) Capture()
+ {
+ var content = ContentLoader.Load(root);
+ Assert.Equal(ruleset, content.Ruleset);
+ var session = GameSession.New(content, 99, Mode.Historical);
+ session.Step(System.Array.Empty<Command>());
+ session.Step(System.Array.Empty<Command>());
+ return (content.Hash, session.State.Describe(), session.Save.Write());
+ }
+ var baseline = Capture();
+ var value = MapEditorOverlay.Parse(EditorFixture, SaveGame.Gdd03Ruleset);
+ var text = MapEditorOverlay.Serialize(value);
+ Assert.False(MapEditorOverlay.Parse(text, SaveGame.Gdd03Ruleset).CanExport);
+ Assert.NotEmpty(value.Diagnostics("fixture-only", new string('a', 64)));
+ var after = Capture();
+ Assert.Equal(System.Text.Encoding.UTF8.GetBytes(baseline.Hash), System.Text.Encoding.UTF8.GetBytes(after.Hash));
+ Assert.Equal(System.Text.Encoding.UTF8.GetBytes(baseline.State), System.Text.Encoding.UTF8.GetBytes(after.State));
+ Assert.Equal(System.Text.Encoding.UTF8.GetBytes(baseline.Save), System.Text.Encoding.UTF8.GetBytes(after.Save));
+ }
+
+ // R-MEDIT-001/002/003: fixture-only tokens are not approved regional or facility data.
+ [Fact]
+ public void ReferenceRecordsRoundTripButNeverImplyDomainApproval()
+ {
+ var yaml = EditorFixture.Replace("regions: []",
+ "regions: [{ hex: { q: 1, r: -2 }, region_id: fixture_only }]")
+ .Replace("infrastructure: []", "infrastructure: [{ id: fixture_only, hex: { q: 1, r: -2 }, kind: fixture_only, parent_id: fixture_only }]");
+ var value = MapEditorOverlay.Parse(yaml, SaveGame.Gdd03Ruleset);
+ var text = MapEditorOverlay.Serialize(value);
+ var back = MapEditorOverlay.Parse(text, SaveGame.Gdd03Ruleset);
+ Assert.Equal("fixture_only", back.Regions.Single().RegionId);
+ Assert.Equal("fixture_only", back.Infrastructure.Single().ParentId);
+ Assert.False(back.CanExport);
+ Assert.Contains(back.Diagnostics("fixture-only", new string('a', 64)), x => x.Field == "facilities");
+ }
+
+
+ // R-MEDIT-002: all new provenance/registry fields share the schema token contract.
+ [Theory]
+ [InlineData("fixture-only")]
+ [InlineData("fixture'only")]
+ public void SingleLineTokensRoundTripExactly(string token)
+ {
+ var value = MapEditorOverlay.Parse(EditorFixture, SaveGame.Gdd03Ruleset);
+ value.BaseRevision = token;
+ value.Regions.Add(new MapEditorRegion { Hex = new MapEditorHex { Q = 1, R = -2 }, RegionId = token });
+ value.Infrastructure.Add(new MapEditorInfrastructure {
+ Hex = new MapEditorHex { Q = 1, R = -2 }, Id = token, Kind = token, ParentId = token });
+ var text = MapEditorOverlay.Serialize(value);
+ var back = MapEditorOverlay.Parse(text, SaveGame.Gdd03Ruleset);
+ Assert.Equal(token, back.BaseRevision);
+ Assert.Equal(token, back.Regions.Single().RegionId);
+ Assert.Equal(token, back.Infrastructure.Single().Id);
+ Assert.Equal(token, back.Infrastructure.Single().Kind);
+ Assert.Equal(token, back.Infrastructure.Single().ParentId);
+ Assert.Equal(text, MapEditorOverlay.Serialize(back));
+ }
+
+ [Theory]
+ [InlineData("fixture\nrevision")]
+ [InlineData("fixture\rrevision")]
+ [InlineData("fixture\trevision")]
+ [InlineData("fixture\n")]
+ [InlineData("fixture revision")]
+ public void TokenControlsAreRejectedByParsingAndObjectSerialization(string token)
+ {
+ // JSON quoting is a valid YAML double-quoted scalar, preserving escaped controls on input.
+ var quoted = System.Text.Json.JsonSerializer.Serialize(token);
+ foreach (var field in new[] { "base_revision", "region_id", "id", "kind", "parent_id" })
+ {
+ var yaml = field == "base_revision"
+ ? EditorFixture.Replace("base_revision: fixture-only", "base_revision: " + quoted)
+ : field == "region_id"
+ ? EditorFixture.Replace("regions: []", "regions: [{ hex: { q: 1, r: -2 }, region_id: " + quoted + " }]")
+ : EditorFixture.Replace("infrastructure: []",
+ "infrastructure: [{ hex: { q: 1, r: -2 }, id: fixture_only, kind: fixture_only, parent_id: fixture_only }]"
+ .Replace(", " + field + ": fixture_only", ", " + field + ": " + quoted));
+ var code = field == "base_revision" ? "MAPEDIT_BASE" : "MAPEDIT_SHAPE";
+ Assert.Contains(code, Assert.Throws<ContentException>(() => MapEditorOverlay.Parse(yaml, SaveGame.Gdd03Ruleset)).Message);
+ var value = MapEditorOverlay.Parse(EditorFixture, SaveGame.Gdd03Ruleset);
+ if (field == "base_revision") value.BaseRevision = token;
+ else if (field == "region_id") value.Regions.Add(new MapEditorRegion {
+ Hex = new MapEditorHex { Q = 1, R = -2 }, RegionId = token });
+ else value.Infrastructure.Add(new MapEditorInfrastructure {
+ Hex = new MapEditorHex { Q = 1, R = -2 }, Id = field == "id" ? token : "fixture_only",
+ Kind = field == "kind" ? token : "fixture_only", ParentId = field == "parent_id" ? token : "fixture_only" });
+ Assert.Contains(code, Assert.Throws<ContentException>(() => MapEditorOverlay.Serialize(value)).Message);
+ }
+ }
}
diff --git a/sim/Statecraft.Sim.Tests/SchemaTests.cs b/sim/Statecraft.Sim.Tests/SchemaTests.cs
index 6cffd7054..4353e3b0c 100644
--- a/sim/Statecraft.Sim.Tests/SchemaTests.cs
+++ b/sim/Statecraft.Sim.Tests/SchemaTests.cs
@@ -338,4 +338,82 @@ people:
[Fact]
public void AnUnsupportedKeywordIsRefusedNotIgnored() =>
Assert.Throws<InvalidOperationException>(() => Check(JsonDocument.Parse("{\"oneOf\": []}").RootElement, default, JsonValue.Create("x"), "$", new List<string>()));
+
+ // R-MEDIT-001/002/003: synthetic authoring shape, never runtime content.
+ static string SyntheticEditorEnvelope()
+ {
+ var value = new MapEditorOverlay {
+ Version = MapEditorOverlay.VersionId, Ruleset = SaveGame.Gdd03Ruleset, Draft = true,
+ BaseRevision = "fixture'only", BaseDigest = new string('a', 64),
+ Overlay = MapOverrides.Parse("terrain: []\ncontrol: []\nlocations: []\n"),
+ Workable = new List<MapEditorWorkable> { new MapEditorWorkable {
+ Hex = new MapEditorHex { Q = 1, R = -2 }, Value = false } },
+ Regions = new List<MapEditorRegion> { new MapEditorRegion {
+ Hex = new MapEditorHex { Q = 1, R = -2 }, RegionId = "fixture'only" } },
+ Infrastructure = new List<MapEditorInfrastructure> { new MapEditorInfrastructure {
+ Hex = new MapEditorHex { Q = 1, R = -2 }, Id = "fixture'only", Kind = "fixture'only", ParentId = "fixture'only" } }
+ };
+ value.Overlay = MapOverrides.Parse("terrain: [{ hex: { q: 1, r: -2 }, value: hills }]\n"
+ + "control: [{ hex: { q: 1, r: -2 }, period: fixture_only, value: I }]\n"
+ + "locations: [{ id: fixture_only, hex: { q: 1, r: -2 } }]\n");
+ return MapEditorOverlay.Serialize(value);
+ }
+
+ [Fact]
+ public void SyntheticEditorEnvelopePassesItsSeparateSchema()
+ {
+ var text = SyntheticEditorEnvelope();
+ Assert.Equal("# yaml-language-server: $schema=../schema/map-editor-overlay.schema.json", text.Split('\n')[0]);
+ Assert.Empty(Errors("map-editor-overlay.schema.json", text));
+ Assert.NotEmpty(Errors("map-overrides.schema.json", text));
+ Assert.Equal(text, MapEditorOverlay.Serialize(MapEditorOverlay.Parse(text, SaveGame.Gdd03Ruleset)));
+ }
+
+ [Fact]
+ public void EveryAuthoringSchemaKeywordIsSupportedWithoutWideningTheValidator()
+ {
+ void Visit(JsonElement node)
+ {
+ foreach (var property in node.EnumerateObject())
+ {
+ Assert.Contains(property.Name, Supported);
+ if (property.Name == "properties" || property.Name == "definitions")
+ foreach (var child in property.Value.EnumerateObject()) Visit(child.Value);
+ else if ((property.Name == "items" || property.Name == "additionalProperties")
+ && property.Value.ValueKind == JsonValueKind.Object) Visit(property.Value);
+ }
+ }
+ Visit(LoadSchema("map-editor-overlay.schema.json"));
+ }
+
+ [Theory]
+ [InlineData("version: 'map-editor-0.3'", "version: future")]
+ [InlineData("ruleset: 'gdd-0.3'", "ruleset: legacy")]
+ [InlineData("draft: true", "unknown: true")]
+ public void AuthoringSchemaRejectsWrongVersionRulesetAndMissingFields(string old, string replacement) =>
+ Assert.NotEmpty(Errors("map-editor-overlay.schema.json", SyntheticEditorEnvelope().Replace(old, replacement)));
+
+ [Theory]
+ [InlineData("fixture\nrevision")]
+ [InlineData("fixture\rrevision")]
+ [InlineData("fixture\trevision")]
+ [InlineData("fixture\n")]
+ [InlineData("fixture revision")]
+ public void AuthoringSchemaRejectsControlAndWhitespaceTokens(string token)
+ {
+ var schema = LoadSchema("map-editor-overlay.schema.json");
+ foreach (var pointer in new[] { "/properties/base_revision", "/properties/regions/items/properties/region_id",
+ "/properties/infrastructure/items/properties/id", "/properties/infrastructure/items/properties/kind",
+ "/properties/infrastructure/items/properties/parent_id" })
+ {
+ Assert.Equal(MapEditorOverlay.TokenPattern, At(schema, pointer).GetProperty("pattern").GetString());
+ var value = (JsonObject)ParseYaml(SyntheticEditorEnvelope())!;
+ if (pointer == "/properties/base_revision") value["base_revision"] = token;
+ else if (pointer.Contains("/regions/")) value["regions"]![0]!["region_id"] = token;
+ else value["infrastructure"]![0]![pointer.Substring(pointer.LastIndexOf('/') + 1)] = token;
+ var errors = new List<string>();
+ Check(schema, schema, value, "$", errors);
+ Assert.NotEmpty(errors);
+ }
+ }
}
diff --git a/sim/Statecraft.Sim/MapOverrides.cs b/sim/Statecraft.Sim/MapOverrides.cs
index 4ef2b5250..4033a51ec 100644
--- a/sim/Statecraft.Sim/MapOverrides.cs
+++ b/sim/Statecraft.Sim/MapOverrides.cs
@@ -241,4 +241,222 @@ namespace Statecraft.Sim
if (TryLocation(l.Id, out var q, out var r)) { l.Q = q; l.R = r; }
}
}
+ /// <summary>Authoring-only envelope. No loader or runtime caller consumes this format.
+ /// Region, field and facility semantics remain with their owning issues. No evidence or campaign state lives here.</summary>
+ public sealed class MapEditorOverlay
+ {
+ // Strict end assertion also rejects a final LF (unlike the .NET $ anchor).
+ public const string TokenPattern = @"^[^\s\u0000-\u001f\u007f]+(?![\s\S])";
+ public const string VersionId = "map-editor-0.3";
+ public string Version { get; set; } = "";
+ public string Ruleset { get; set; } = "";
+ public bool? Draft { get; set; }
+ public string BaseRevision { get; set; } = "";
+ public string BaseDigest { get; set; } = "";
+ public MapOverrides Overlay { get; set; } = null!;
+ public List<MapEditorWorkable> Workable { get; set; } = null!;
+ public List<MapEditorRegion> Regions { get; set; } = null!;
+ public List<MapEditorInfrastructure> Infrastructure { get; set; } = null!;
+
+ // R-MEDIT-003: no receipt or export until accepted dependency adapters and base-manifest contract exist.
+ [YamlIgnore] public bool CanExport => false;
+
+ static readonly IDeserializer Reader = new DeserializerBuilder()
+ .WithNamingConvention(UnderscoredNamingConvention.Instance).WithDuplicateKeyChecking().Build();
+
+ public static MapEditorOverlay Parse(string source, string selectedRuleset)
+ {
+ if (selectedRuleset != SaveGame.Gdd03Ruleset)
+ throw Error("MAPEDIT_RULESET", "ruleset", "select an explicit gdd-0.3 authoring context");
+ MapEditorOverlay value;
+ try
+ {
+ CheckPayloadCoordinates(source);
+ value = Reader.Deserialize<MapEditorOverlay>(source)
+ ?? throw Error("MAPEDIT_SHAPE", "(file)", "an envelope is required");
+ }
+ catch (YamlException e)
+ {
+ throw Error("MAPEDIT_SHAPE", FormattableString.Invariant($"line {e.Start.Line}"), e.InnerException?.Message ?? e.Message);
+ }
+ Validate(value);
+ return value;
+ }
+
+ static void CheckPayloadCoordinates(string source)
+ {
+ var stream = new YamlDotNet.RepresentationModel.YamlStream();
+ stream.Load(new System.IO.StringReader(source));
+ if (stream.Documents.Count != 1) throw Error("MAPEDIT_SHAPE", "(file)", "one YAML document is required");
+ if (!(stream.Documents[0].RootNode is YamlDotNet.RepresentationModel.YamlMappingNode root)) return;
+ if (!root.Children.TryGetValue(new YamlDotNet.RepresentationModel.YamlScalarNode("overlay"), out var payload)
+ || !(payload is YamlDotNet.RepresentationModel.YamlMappingNode overlay)) return;
+ foreach (var section in overlay.Children)
+ {
+ if (!(section.Value is YamlDotNet.RepresentationModel.YamlSequenceNode rows)) continue;
+ foreach (var row in rows.Children)
+ {
+ if (!(row is YamlDotNet.RepresentationModel.YamlMappingNode mapping)) continue;
+ if (!mapping.Children.TryGetValue(new YamlDotNet.RepresentationModel.YamlScalarNode("hex"), out var hex)
+ || !(hex is YamlDotNet.RepresentationModel.YamlMappingNode coordinates)
+ || !HasInteger(coordinates, "q") || !HasInteger(coordinates, "r"))
+ throw Error("MAPEDIT_SHAPE", "overlay." + section.Key + ".hex", "both axial coordinates are required");
+ }
+ }
+ }
+
+ static bool HasInteger(YamlDotNet.RepresentationModel.YamlMappingNode map, string key) =>
+ map.Children.TryGetValue(new YamlDotNet.RepresentationModel.YamlScalarNode(key), out var node)
+ && node is YamlDotNet.RepresentationModel.YamlScalarNode scalar
+ && int.TryParse(scalar.Value, System.Globalization.NumberStyles.Integer,
+ System.Globalization.CultureInfo.InvariantCulture, out _);
+
+ static void Validate(MapEditorOverlay value)
+ {
+ if (value.Version != VersionId) throw Error("MAPEDIT_VERSION", "version", "unsupported editor envelope version");
+ if (value.Ruleset != SaveGame.Gdd03Ruleset) throw Error("MAPEDIT_RULESET", "ruleset", "expected gdd-0.3");
+ if (value.Draft == null) throw Error("MAPEDIT_SHAPE", "draft", "an explicit boolean is required");
+ if (!IsToken(value.BaseRevision) || value.BaseDigest == null
+ || value.BaseDigest.Length != 64 || value.BaseDigest.Any(c => !(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f')))
+ throw Error("MAPEDIT_BASE", "base", "a single-line revision token and lowercase SHA-256 base-input digest are required");
+ if (value.Overlay == null || value.Workable == null || value.Regions == null || value.Infrastructure == null)
+ throw Error("MAPEDIT_SHAPE", "(file)", "overlay and all edit lists are required");
+ // Reuse legacy duplicate/shape checks without changing their behavior or serialization.
+ try { MapOverrides.Serialize(value.Overlay); }
+ catch (ContentException e) { throw Error("MAPEDIT_SHAPE", "overlay." + e.Field, e.Message); }
+ foreach (var row in value.Overlay.Terrain) Nonempty(row.Value, "overlay.terrain.value");
+ foreach (var row in value.Overlay.Control)
+ { Nonempty(row.Period, "overlay.control.period"); Nonempty(row.Value, "overlay.control.value"); }
+ foreach (var row in value.Overlay.Locations)
+ if (row.Id == null || !System.Text.RegularExpressions.Regex.IsMatch(row.Id, "^[a-z][a-z0-9_]*$"))
+ throw Error("MAPEDIT_SHAPE", "overlay.locations.id", "a stable location id is required");
+ CheckRows(value.Workable, "workable", x => HexKey(x.Hex));
+ foreach (var row in value.Workable)
+ if (row.Value == null) throw Error("MAPEDIT_SHAPE", "workable.value", "an explicit boolean is required");
+ CheckRows(value.Regions, "regions", x => HexKey(x.Hex));
+ foreach (var row in value.Regions) Token(row.RegionId, "regions.region_id");
+ CheckRows(value.Infrastructure, "infrastructure", x => x.Id);
+ foreach (var row in value.Infrastructure)
+ {
+ Token(row.Id, "infrastructure.id"); Token(row.Kind, "infrastructure.kind");
+ Token(row.ParentId, "infrastructure.parent_id");
+ }
+ }
+
+ static ContentException Error(string code, string field, string message) =>
+ new ContentException(MapOverrides.FileName, field, code + ": " + message);
+
+ static void Nonempty(string value, string field)
+ {
+ if (string.IsNullOrEmpty(value)) throw Error("MAPEDIT_SHAPE", field, "a nonempty value is required");
+ }
+
+ static bool IsToken(string value) => value != null
+ && System.Text.RegularExpressions.Regex.IsMatch(value, TokenPattern);
+
+ static void Token(string value, string field)
+ {
+ if (!IsToken(value)) throw Error("MAPEDIT_SHAPE", field, "a single-line owning-registry token without whitespace or controls is required");
+ }
+
+ static string HexKey(MapEditorHex hex) => FormattableString.Invariant($"{hex.Q},{hex.R}");
+
+ static void CheckRows<T>(List<T> rows, string field, Func<T, string> key) where T : MapEditorHexEdit
+ {
+ var seen = new HashSet<string>(StringComparer.Ordinal);
+ for (int i = 0; i < rows.Count; i++)
+ {
+ var at = FormattableString.Invariant($"{field}[{i}]");
+ var row = rows[i];
+ if (row == null || row.Hex == null || row.Hex.Q == null || row.Hex.R == null)
+ throw Error("MAPEDIT_SHAPE", at + ".hex", "an axial hex with both integer coordinates is required");
+ if (!seen.Add(key(row))) throw Error("MAPEDIT_DUPLICATE", at, "a second override of the same identity");
+ }
+ }
+
+ static string Quote(string value) => "'" + value.Replace("'", "''") + "'";
+ static string Hex(MapEditorHex h) => FormattableString.Invariant($"{{ q: {h.Q}, r: {h.R} }}");
+ static void Rows<T>(StringBuilder text, string field, IEnumerable<T> rows, Func<T, string> format)
+ {
+ var list = rows.ToList();
+ if (list.Count == 0) { text.Append(field).Append(": []\n"); return; }
+ text.Append(field).Append(":\n");
+ foreach (var row in list) text.Append(" - ").Append(format(row)).Append('\n');
+ }
+
+ /// <summary>Stable authoring text, not a validation receipt. Never mutates or reorders caller-owned lists.</summary>
+ public static string Serialize(MapEditorOverlay value)
+ {
+ if (value == null) throw new ArgumentNullException(nameof(value));
+ // Validate object callers too; never use a culture-sensitive intermediate serializer.
+ Validate(value);
+ var copy = value;
+ var text = new StringBuilder("# yaml-language-server: $schema=../schema/map-editor-overlay.schema.json\n");
+ text.Append("version: ").Append(Quote(copy.Version)).Append("\nruleset: 'gdd-0.3'\ndraft: ")
+ .Append(copy.Draft == true ? "true" : "false").Append("\nbase_revision: ").Append(Quote(copy.BaseRevision))
+ .Append("\nbase_digest: ").Append(Quote(copy.BaseDigest)).Append("\noverlay:\n");
+ foreach (var line in MapOverrides.Serialize(copy.Overlay).Split('\n').Skip(1))
+ if (line.Length != 0) text.Append(" ").Append(line).Append('\n');
+ Rows(text, "workable", copy.Workable.OrderBy(x => x.Hex.R).ThenBy(x => x.Hex.Q),
+ x => "{ hex: " + Hex(x.Hex) + ", value: " + (x.Value == true ? "true" : "false") + " }");
+ Rows(text, "regions", copy.Regions.OrderBy(x => x.Hex.R).ThenBy(x => x.Hex.Q),
+ x => "{ hex: " + Hex(x.Hex) + ", region_id: " + Quote(x.RegionId) + " }");
+ Rows(text, "infrastructure", copy.Infrastructure.OrderBy(x => x.Id, StringComparer.Ordinal),
+ x => "{ id: " + Quote(x.Id) + ", hex: " + Hex(x.Hex) + ", kind: " + Quote(x.Kind) + ", parent_id: " + Quote(x.ParentId) + " }");
+ return text.ToString();
+ }
+
+ /// <summary>Infrastructure diagnostics only. Caller supplies current base identity; this is not Content.Hash.
+ /// Missing domain adapters are explicit errors, even on an empty candidate. No automatic repair is performed.</summary>
+ public IReadOnlyList<MapEditorDiagnostic> Diagnostics(string currentRevision, string currentDigest)
+ {
+ var result = new List<MapEditorDiagnostic>();
+ if (BaseRevision != currentRevision || BaseDigest != currentDigest)
+ result.Add(new MapEditorDiagnostic("MAPEDIT_BASE_CONFLICT", "base",
+ "overlay base " + BaseRevision + "/" + BaseDigest + "; current base " + currentRevision + "/" + currentDigest,
+ "Compare base inputs and deliberately rebase; retain the current edits."));
+ if (Draft == true)
+ result.Add(new MapEditorDiagnostic("MAPEDIT_DRAFT", "draft", "draft input cannot be canonical content",
+ "Resolve all diagnostics before requesting canonical export."));
+ foreach (var field in new[] { "regions", "fields", "facilities", "corridors", "anchors", "targets", "objectives", "base_manifest" })
+ result.Add(new MapEditorDiagnostic("MAPEDIT_DEPENDENCY_UNAVAILABLE", field, "accepted validation adapter is not installed",
+ "Integrate the owning contract before canonical save or export."));
+ return result.OrderBy(x => x.Field, StringComparer.Ordinal).ThenBy(x => x.Code, StringComparer.Ordinal).ToList().AsReadOnly();
+ }
+ }
+
+ public sealed class MapEditorHex
+ {
+ public int? Q { get; set; }
+ public int? R { get; set; }
+ }
+ public abstract class MapEditorHexEdit
+ {
+ public MapEditorHex Hex { get; set; } = null!;
+ }
+ public sealed class MapEditorWorkable : MapEditorHexEdit
+ {
+ public bool? Value { get; set; }
+ }
+ public sealed class MapEditorRegion : MapEditorHexEdit
+ {
+ public string RegionId { get; set; } = "";
+ }
+ public sealed class MapEditorInfrastructure : MapEditorHexEdit
+ {
+ public string Id { get; set; } = "";
+ public string Kind { get; set; } = "";
+ public string ParentId { get; set; } = "";
+ }
+ public sealed class MapEditorDiagnostic
+ {
+ public string Code { get; }
+ public string File => MapOverrides.FileName;
+ public string Field { get; }
+ public string Message { get; }
+ public string Action { get; }
+ public MapEditorDiagnostic(string code, string field, string message, string action)
+ { Code = code; Field = field; Message = message; Action = action; }
+ }
+
}
diff --git a/unity/Assets/Scripts/Map/MapOverrideEditorDocument.cs b/unity/Assets/Scripts/Map/MapOverrideEditorDocument.cs
index c58804533..859962bd1 100644
--- a/unity/Assets/Scripts/Map/MapOverrideEditorDocument.cs
+++ b/unity/Assets/Scripts/Map/MapOverrideEditorDocument.cs
@@ -249,6 +249,34 @@ namespace Statecraft.Game.Map
control = value.Control.Select(x => new MapEditorControlEdit { q = x.Hex.Q, r = x.Hex.R, period = x.Period, value = x.Value }).ToList();
locations = value.Locations.Select(x => new MapEditorLocationEdit { id = x.Id, q = x.Hex.Q, r = x.Hex.R }).ToList();
}
+
+ // Isolated 0.3 authoring state; no window hookup or disk writer in this infrastructure slice.
+ // Serialize exact source for Undo/domain reload. Caller owns the Undo transaction.
+ [SerializeField] string infrastructureSource = "";
+ [SerializeField] string rejectedInfrastructureSource = "";
+ public string InfrastructureSource => infrastructureSource;
+ public string RejectedInfrastructureSource => rejectedInfrastructureSource;
+
+ public bool TryReplaceInfrastructure(string candidate, string selectedRuleset, out string error)
+ {
+ try
+ {
+ MapEditorOverlay.Parse(candidate, selectedRuleset);
+ infrastructureSource = candidate;
+ rejectedInfrastructureSource = "";
+ error = "";
+ return true;
+ }
+ catch (ContentException exception)
+ {
+ rejectedInfrastructureSource = candidate;
+ error = exception.Message;
+ return false;
+ }
+ }
+
+ // Return a fresh snapshot; callers cannot mutate the serialized document through this model.
+ public MapEditorOverlay InfrastructureCandidate() => MapEditorOverlay.Parse(infrastructureSource, SaveGame.Gdd03Ruleset);
}
}
#endif
diff --git a/unity/Assets/Tests/EditMode/MapOverrideEditorTests.cs b/unity/Assets/Tests/EditMode/MapOverrideEditorTests.cs
index f987416c2..b39bd83e4 100644
--- a/unity/Assets/Tests/EditMode/MapOverrideEditorTests.cs
+++ b/unity/Assets/Tests/EditMode/MapOverrideEditorTests.cs
@@ -229,4 +229,42 @@ public sealed class MapOverrideEditorTests
foreach (var directory in Directory.GetDirectories(source))
CopyDirectory(directory, Path.Combine(destination, Path.GetFileName(directory)));
}
+ // R-MEDIT-002, R-MEDIT-003: SYNTHETIC fixture-only authoring state; no files are written.
+ [Test]
+ public void InfrastructureDocumentKeepsEditsAndRawFailedInputAcrossReloadAndUndo()
+ {
+ const string source = "version: map-editor-0.3\nruleset: gdd-0.3\ndraft: true\n"
+ + "base_revision: fixture-only\nbase_digest: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
+ + "overlay: { terrain: [], control: [], locations: [] }\nworkable: []\nregions: []\ninfrastructure: []\n";
+ var document = ScriptableObject.CreateInstance<MapOverrideEditorDocument>();
+ try
+ {
+ Assert.IsTrue(document.TryReplaceInfrastructure(source, SaveGame.Gdd03Ruleset, out var error), error);
+ var saved = document.InfrastructureSource;
+ Undo.RegisterCompleteObjectUndo(document, "fixture-only edit");
+ Assert.IsTrue(document.TryReplaceInfrastructure(source.Replace("workable: []",
+ "workable: [{ hex: { q: 1, r: -2 }, value: false }]"), SaveGame.Gdd03Ruleset, out error), error);
+ Undo.FlushUndoRecordObjects();
+ var edited = document.InfrastructureSource;
+ Assert.IsFalse(document.TryReplaceInfrastructure("unreadable: [", SaveGame.Gdd03Ruleset, out error));
+ Assert.AreEqual(edited, document.InfrastructureSource);
+ Assert.AreEqual("unreadable: [", document.RejectedInfrastructureSource);
+ var clone = ScriptableObject.CreateInstance<MapOverrideEditorDocument>();
+ try
+ {
+ EditorJsonUtility.FromJsonOverwrite(EditorJsonUtility.ToJson(document), clone);
+ Assert.AreEqual(edited, clone.InfrastructureSource);
+ Assert.AreEqual(document.RejectedInfrastructureSource, clone.RejectedInfrastructureSource);
+ Assert.IsFalse(clone.InfrastructureCandidate().CanExport);
+ Assert.IsNotEmpty(clone.InfrastructureCandidate().Diagnostics("fixture-only", new string('a', 64)));
+ }
+ finally { UnityEngine.Object.DestroyImmediate(clone); }
+ Undo.PerformUndo();
+ Assert.AreEqual(saved, document.InfrastructureSource);
+ Undo.PerformRedo();
+ Assert.AreEqual(edited, document.InfrastructureSource);
+ }
+ finally { UnityEngine.Object.DestroyImmediate(document); }
+ }
+
}