diff --git a/RPGModder.Core/Merge/AddedIdIndex.cs b/RPGModder.Core/Merge/AddedIdIndex.cs
new file mode 100644
index 0000000..7c52c94
--- /dev/null
+++ b/RPGModder.Core/Merge/AddedIdIndex.cs
@@ -0,0 +1,55 @@
+using Newtonsoft.Json.Linq;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The ids a change set adds, by kind and scope (GR-R2, GR-R3). An op the builder writes for a record vanilla does
+/// not have is the only kind of added id: a map event is an AddRecord on event:n of a vanilla map; a
+/// map is a whole new MapNNN.json , its MapInfos record, or both. Step 1 lists these two kinds only.
+///
+internal static class AddedIdIndex
+{
+ public static IReadOnlyList Of(ModChangeSet changeSet)
+ {
+ var events = new List();
+ var maps = new SortedDictionary();
+ foreach (ChangeOp op in changeSet.Ops)
+ {
+ if (op.Kind != ChangeKind.AddRecord || op.Path.Length != 0 || op.Value is null)
+ {
+ continue;
+ }
+
+ if (op.Key.IsWholeFile && RpgDataSchema.TryGetMapId(op.Key.File, out int mapId))
+ {
+ maps[mapId] = (op.Value, maps.GetValueOrDefault(mapId).Info);
+ }
+ else if (op.Key.File == RpgDataSchema.MapInfosKey && RecordKey.TryGetIndex(op.Key.Record, out int infoId) && infoId > 0)
+ {
+ maps[infoId] = (maps.GetValueOrDefault(infoId).File, op.Value);
+ }
+ else if (RpgDataSchema.IsMapFile(op.Key.File) && RecordKey.TryGetEvent(op.Key.Record, out int eventId) && eventId > 0)
+ {
+ events.Add(new AddedId(IdKind.MapEvent, op.Key.File, eventId, op.Value));
+ }
+ }
+
+ var result = new List(events);
+ foreach ((int id, (JToken? file, JToken? info)) in maps)
+ {
+ // Both halves are the content, cloned so no op gains a parent; two mods that add one map with one tree entry are one map (GR-R3).
+ result.Add(new AddedId(IdKind.Map, "", id, new JArray(file?.DeepClone() ?? JValue.CreateNull(), info?.DeepClone() ?? JValue.CreateNull())));
+ }
+
+ return result;
+ }
+
+ /// True when the change set still adds 's old id; otherwise the entry is inactive (GR-R12).
+ public static bool IsActive(IdRemap remap, IReadOnlyList added)
+ {
+ return added.Any(item => item.Kind == remap.Kind && item.Scope == remap.Scope && item.Id == remap.FromId);
+ }
+}
+
+/// One added id and the content that decides whether two mods add the same thing.
+internal sealed record AddedId(IdKind Kind, string Scope, int Id, JToken Content);
diff --git a/RPGModder.Core/Merge/BaseFile.cs b/RPGModder.Core/Merge/BaseFile.cs
new file mode 100644
index 0000000..955aedd
--- /dev/null
+++ b/RPGModder.Core/Merge/BaseFile.cs
@@ -0,0 +1,10 @@
+namespace RPGModder.Core.Merge;
+
+///
+/// A vanilla file, or the live config save (GR-M10). Text is set when
+/// is not ; Sha256 is lower-case hex.
+///
+public sealed record BaseFile(
+ string Path,
+ string? Text,
+ string Sha256);
diff --git a/RPGModder.Core/Merge/BaseFileSet.cs b/RPGModder.Core/Merge/BaseFileSet.cs
new file mode 100644
index 0000000..52a0d64
--- /dev/null
+++ b/RPGModder.Core/Merge/BaseFileSet.cs
@@ -0,0 +1,37 @@
+namespace RPGModder.Core.Merge;
+
+///
+/// The base files of one plan, looked up by key. A path with no entry means vanilla does not have the file (GR-M9).
+///
+public sealed class BaseFileSet
+{
+ private readonly Dictionary _byKey;
+
+ private BaseFileSet(Dictionary byKey)
+ {
+ _byKey = byKey;
+ }
+
+ /// Two entries with one key are a caller bug, because the plan would depend on which one wins.
+ public static BaseFileSet From(IEnumerable files)
+ {
+ ArgumentNullException.ThrowIfNull(files);
+
+ var byKey = new Dictionary(StringComparer.Ordinal);
+ foreach (BaseFile file in files)
+ {
+ string key = MergePath.ToKey(file.Path);
+ if (!byKey.TryAdd(key, file))
+ {
+ throw new ArgumentException($"Two base files share the key {key}.", nameof(files));
+ }
+ }
+
+ return new BaseFileSet(byKey);
+ }
+
+ public BaseFile? Find(string path)
+ {
+ return _byKey.GetValueOrDefault(MergePath.ToKey(path));
+ }
+}
diff --git a/RPGModder.Core/Merge/ChangeKind.cs b/RPGModder.Core/Merge/ChangeKind.cs
new file mode 100644
index 0000000..c44670e
--- /dev/null
+++ b/RPGModder.Core/Merge/ChangeKind.cs
@@ -0,0 +1,12 @@
+namespace RPGModder.Core.Merge;
+
+public enum ChangeKind
+{
+ SetLeaf,
+ RemoveLeaf,
+ AddRecord,
+ RemoveRecord,
+ EditSequence,
+ EditCommands,
+ ReplaceFile
+}
diff --git a/RPGModder.Core/Merge/ChangeOp.cs b/RPGModder.Core/Merge/ChangeOp.cs
new file mode 100644
index 0000000..74cdd4d
--- /dev/null
+++ b/RPGModder.Core/Merge/ChangeOp.cs
@@ -0,0 +1,15 @@
+using Newtonsoft.Json.Linq;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// One change a mod makes against vanilla (GR-M1). Value is null for the remove kinds; a leaf
+/// set to JSON null holds a of type null instead.
+///
+public sealed record ChangeOp(
+ string ModId,
+ RecordKey Key,
+ string Path,
+ ChangeKind Kind,
+ JToken? Value,
+ string? SourceFile);
diff --git a/RPGModder.Core/Merge/ChangeSetBuilder.cs b/RPGModder.Core/Merge/ChangeSetBuilder.cs
new file mode 100644
index 0000000..0dc9544
--- /dev/null
+++ b/RPGModder.Core/Merge/ChangeSetBuilder.cs
@@ -0,0 +1,522 @@
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using RPGModder.Core.Models;
+using RPGModder.Core.Operations;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// Turns one mod into ops against vanilla (guide 3.1, first step). A whole-file mod and a json_patches mod
+/// go through the same walker, so they give the same kind of ops (GR-M4). Bad mod content is a diagnostic,
+/// never an exception and never a fallback (GR-C5, GR-M8).
+///
+public static class ChangeSetBuilder
+{
+ public static ModChangeSet Build(ModSource mod, BaseFileSet baseFiles)
+ {
+ ArgumentNullException.ThrowIfNull(mod);
+ ArgumentNullException.ThrowIfNull(baseFiles);
+
+ var ops = new List();
+ var diagnostics = new List();
+
+ foreach (TargetEdits target in CollectTargets(mod))
+ {
+ switch (RpgDataSchema.KindOf(target.Key))
+ {
+ case MergeFileKind.Data:
+ BuildDataFile(mod.ModId, target, baseFiles, ops, diagnostics);
+ break;
+ case MergeFileKind.PluginList:
+ BuildPluginList(mod, target, baseFiles, ops, diagnostics);
+ break;
+ case MergeFileKind.ConfigSave:
+ BuildConfigSave(mod.ModId, target, baseFiles, ops, diagnostics);
+ break;
+ case MergeFileKind.Opaque:
+ BuildOpaqueFile(mod.ModId, target, baseFiles, ops, diagnostics);
+ break;
+ default:
+ throw new UnreachableException($"KindOf returned a kind the builder does not know for {target.Key}.");
+ }
+ }
+
+ ops.Sort(CompareOps);
+ return new ModChangeSet(mod.ModId, mod.Priority, ops, diagnostics);
+ }
+
+ internal static int CompareOps(ChangeOp left, ChangeOp right)
+ {
+ int result = string.CompareOrdinal(left.Key.File, right.Key.File);
+ if (result == 0)
+ {
+ result = string.CompareOrdinal(left.Key.Record, right.Key.Record);
+ }
+
+ if (result == 0)
+ {
+ result = string.CompareOrdinal(left.Path, right.Path);
+ }
+
+ return result;
+ }
+
+ private static void BuildDataFile(
+ string modId,
+ TargetEdits target,
+ BaseFileSet baseFiles,
+ List ops,
+ List diagnostics)
+ {
+ BaseFile? baseFile = baseFiles.Find(target.Key);
+ if (baseFile is null)
+ {
+ BuildNewDataFile(modId, target, ops, diagnostics);
+ return;
+ }
+
+ if (!TryReadBase(baseFile, out JToken? vanilla, out OperationDiagnostic? baseProblem))
+ {
+ diagnostics.Add(baseProblem);
+ return;
+ }
+
+ // Vanilla is cloned only for a patch-only mod; a mod that ships the file is read instead.
+ JToken? modded;
+ if (target.File is null)
+ {
+ modded = vanilla.DeepClone();
+ }
+ else if (!TryReadModData(modId, target, target.File, out modded, diagnostics))
+ {
+ return;
+ }
+
+ if (!TryApplyPatches(modId, target, modded, diagnostics))
+ {
+ return;
+ }
+
+ if (RpgDataSchema.ShapeOf(target.Key, vanilla) == RootShape.Map &&
+ RpgDataSchema.IsEventList(vanilla[RpgDataSchema.EventsProperty]) &&
+ modded is JObject map &&
+ map[RpgDataSchema.EventsProperty] is not JArray)
+ {
+ // Vanilla's events are records other mods edit one by one; a mod without an events list would
+ // replace them all with no collision, so it is refused like a root of the wrong shape.
+ diagnostics.Add(Error(
+ DiagnosticCodes.MergeRootShapeMismatch,
+ $"Mod {modId} gives {target.Key} an events value that is not a list.",
+ modId));
+ return;
+ }
+
+ ops.AddRange(DataDiff.Compare(modId, target.Key, target.File?.Source, vanilla, modded));
+ }
+
+ ///
+ /// GR-M9: a data file vanilla lacks is one AddRecord on * , never merged from an empty base. Its
+ /// source stays on the op so the writer copies the mod's bytes, unless a patch changed the content.
+ ///
+ private static void BuildNewDataFile(string modId, TargetEdits target, List ops, List diagnostics)
+ {
+ if (target.File is null)
+ {
+ diagnostics.Add(Error(
+ DiagnosticCodes.MergePatchTargetMissing,
+ $"Mod {modId} patches {target.Key}, which the game does not have.",
+ modId));
+ return;
+ }
+
+ if (!TryReadModData(modId, target, target.File, out JToken? content, diagnostics) ||
+ !TryApplyPatches(modId, target, content, diagnostics))
+ {
+ return;
+ }
+
+ string? source = target.Patches.Count == 0 ? target.File.Source : null;
+ ops.Add(new ChangeOp(modId, new RecordKey(target.Key, RecordKey.WholeFile), "", ChangeKind.AddRecord, content, source));
+ }
+
+ ///
+ /// Bytes are compared by hash only (guide 3.3): a file equal to vanilla is no change, anything else replaces
+ /// the whole file. A patch cannot apply to bytes.
+ ///
+ private static void BuildOpaqueFile(
+ string modId,
+ TargetEdits target,
+ BaseFileSet baseFiles,
+ List ops,
+ List diagnostics)
+ {
+ if (!RejectPatches(modId, target, diagnostics) || target.File is null)
+ {
+ return;
+ }
+
+ string hash = target.File.Sha256.ToLowerInvariant();
+ if (string.Equals(baseFiles.Find(target.Key)?.Sha256, hash, StringComparison.OrdinalIgnoreCase))
+ {
+ return;
+ }
+
+ ops.Add(new ChangeOp(
+ modId,
+ new RecordKey(target.Key, RecordKey.WholeFile),
+ "",
+ ChangeKind.ReplaceFile,
+ new JValue(hash),
+ target.File.Source));
+ }
+
+ ///
+ /// The mod's list is its own plugins.js , or vanilla's when it ships none, with its
+ /// plugins_registry applied on top (seam 11.1). No vanilla plugins.js is an empty list.
+ ///
+ private static void BuildPluginList(
+ ModSource mod,
+ TargetEdits target,
+ BaseFileSet baseFiles,
+ List ops,
+ List diagnostics)
+ {
+ string modId = mod.ModId;
+ if (!RejectPatches(modId, target, diagnostics))
+ {
+ return;
+ }
+
+ PluginListText? vanilla = PluginListText.Empty();
+ BaseFile? baseFile = baseFiles.Find(target.Key);
+ if (baseFile is not null && !PluginListText.TryParse(baseFile.Text, out vanilla, out string? baseError))
+ {
+ diagnostics.Add(Error(DiagnosticCodes.MergeBaseParseFailed, $"The game file {target.Key} cannot be read: {baseError}.", target.Key));
+ return;
+ }
+
+ JArray list;
+ if (target.File is null)
+ {
+ list = (JArray)vanilla.Entries.DeepClone();
+ }
+ else if (PluginListText.TryParse(target.File.Text, out PluginListText? own, out string? modError))
+ {
+ list = own.Entries;
+ }
+ else
+ {
+ diagnostics.Add(Error(
+ DiagnosticCodes.MergeParseFailed,
+ $"Mod {modId} file {target.File.Source} for {target.Key} cannot be read: {modError}.",
+ modId));
+ return;
+ }
+
+ var named = new List(mod.Plugins.Count);
+ for (int index = 0; index < mod.Plugins.Count; index++)
+ {
+ PluginEntry? plugin = mod.Plugins[index];
+ if (string.IsNullOrEmpty(plugin?.Name))
+ {
+ // A nameless entry has no record to merge, and a silent whole-list fallback would hide the fault.
+ diagnostics.Add(Error(
+ DiagnosticCodes.MergeParseFailed,
+ $"Mod {modId} plugins_registry entry {index} has no name.",
+ modId));
+ continue;
+ }
+
+ named.Add(plugin);
+ }
+
+ PluginListDiff.ApplyRegistry(list, named);
+ ops.AddRange(PluginListDiff.Compare(modId, target.File?.Source, vanilla.Entries, list));
+ }
+
+ ///
+ /// GR-M10: the base is the live file (or {} ), and each top-level key the mod sets to another value is
+ /// one op. A key the mod lacks is the player's and is never removed.
+ ///
+ private static void BuildConfigSave(
+ string modId,
+ TargetEdits target,
+ BaseFileSet baseFiles,
+ List ops,
+ List diagnostics)
+ {
+ if (!RpgDataSchema.IsDecodedConfigSave(target.Key))
+ {
+ diagnostics.Add(Error(
+ DiagnosticCodes.MergeConfigSaveUnsupported,
+ $"Mod {modId} changes {target.Key}, a config save form this version cannot read yet.",
+ modId));
+ return;
+ }
+
+ if (!TryReadConfigBase(baseFiles.Find(target.Key), target.Key, out JObject? live, out OperationDiagnostic? baseProblem))
+ {
+ diagnostics.Add(baseProblem);
+ return;
+ }
+
+ JObject? modded = (JObject)live.DeepClone();
+ if (target.File is not null && !ConfigSaveText.TryDecode(target.Key, target.File.Text, out modded, out string? modError))
+ {
+ diagnostics.Add(Error(
+ DiagnosticCodes.MergeParseFailed,
+ $"Mod {modId} file {target.File.Source} for {target.Key} cannot be read: {modError}.",
+ modId));
+ return;
+ }
+
+ foreach (ModPatch patch in target.Patches)
+ {
+ ApplyPatch(modded, patch.MergeData);
+ }
+
+ foreach (JProperty property in modded.Properties())
+ {
+ JToken? current = live.Property(property.Name, StringComparison.Ordinal)?.Value;
+ if (current is null || !JToken.DeepEquals(current, property.Value))
+ {
+ ops.Add(new ChangeOp(
+ modId,
+ new RecordKey(target.Key, RecordKey.WholeFile),
+ MergePath.Child("", property.Name),
+ ChangeKind.SetLeaf,
+ property.Value.DeepClone(),
+ target.File?.Source));
+ }
+ }
+ }
+
+ /// The live config save, or an empty object when the player has none yet (GR-M10).
+ internal static bool TryReadConfigBase(
+ BaseFile? baseFile,
+ string key,
+ [NotNullWhen(true)] out JObject? live,
+ [NotNullWhen(false)] out OperationDiagnostic? problem)
+ {
+ problem = null;
+ if (baseFile is null)
+ {
+ live = new JObject();
+ return true;
+ }
+
+ if (ConfigSaveText.TryDecode(key, baseFile.Text, out live, out string? error))
+ {
+ return true;
+ }
+
+ problem = Error(DiagnosticCodes.MergeBaseParseFailed, $"The config save {key} cannot be read: {error}.", key);
+ return false;
+ }
+
+ private static bool TryReadModData(
+ string modId,
+ TargetEdits target,
+ ModFile file,
+ [NotNullWhen(true)] out JToken? content,
+ List diagnostics)
+ {
+ if (!TryParse(file.Text, out content, out string? modError))
+ {
+ diagnostics.Add(Error(
+ DiagnosticCodes.MergeParseFailed,
+ $"Mod {modId} file {file.Source} for {target.Key} is not valid JSON ({modError}).",
+ modId));
+ return false;
+ }
+
+ if (RpgDataSchema.ExpectedRootOf(target.Key) is JTokenType expected && content.Type != expected)
+ {
+ diagnostics.Add(Error(
+ DiagnosticCodes.MergeRootShapeMismatch,
+ $"Mod {modId} file {file.Source} for {target.Key} has {Describe(content.Type)} at its root, but the game reads {Describe(expected)}.",
+ modId));
+ content = null;
+ return false;
+ }
+
+ return true;
+ }
+
+ private static bool TryApplyPatches(string modId, TargetEdits target, JToken content, List diagnostics)
+ {
+ foreach (ModPatch patch in target.Patches)
+ {
+ if (content is not JObject root)
+ {
+ diagnostics.Add(Error(
+ DiagnosticCodes.MergePatchShapeMismatch,
+ $"Mod {modId} patches {target.Key} with an object, but the file's root is not an object.",
+ modId));
+ return false;
+ }
+
+ ApplyPatch(root, patch.MergeData);
+ }
+
+ return true;
+ }
+
+ /// json_patches apply to JSON data and to config saves; on a plugin list or bytes they are a shape mismatch.
+ private static bool RejectPatches(string modId, TargetEdits target, List diagnostics)
+ {
+ if (target.Patches.Count == 0)
+ {
+ return true;
+ }
+
+ diagnostics.Add(Error(
+ DiagnosticCodes.MergePatchShapeMismatch,
+ $"Mod {modId} patches {target.Key} with an object, but that file is not a JSON data file.",
+ modId));
+ return false;
+ }
+
+ ///
+ /// Groups a mod's edits by file key, in key order. When file_ops names one target twice the later entry
+ /// wins, as the copy order does; patches apply after the file, in manifest order. A mod that registers plugins
+ /// changes the plugin list even when it ships no plugins.js .
+ ///
+ private static IEnumerable CollectTargets(ModSource mod)
+ {
+ var targets = new SortedDictionary(StringComparer.Ordinal);
+ foreach (ModFile file in mod.Files)
+ {
+ TargetEdits target = GetTarget(targets, file.Target);
+ target.File = file;
+ }
+
+ foreach (ModPatch patch in mod.Patches)
+ {
+ GetTarget(targets, patch.Target).Patches.Add(patch);
+ }
+
+ if (mod.Plugins.Count > 0)
+ {
+ GetTarget(targets, RpgDataSchema.PluginListKey);
+ }
+
+ return targets.Values;
+ }
+
+ private static TargetEdits GetTarget(SortedDictionary targets, string path)
+ {
+ string key = MergePath.ToKey(path);
+ if (!targets.TryGetValue(key, out TargetEdits? target))
+ {
+ target = new TargetEdits(key);
+ targets.Add(key, target);
+ }
+
+ return target;
+ }
+
+ /// The json_patches rule of 1.x: objects merge property by property, anything else replaces.
+ private static void ApplyPatch(JObject target, JObject patch)
+ {
+ foreach (JProperty property in patch.Properties())
+ {
+ JProperty? existing = target.Property(property.Name, StringComparison.Ordinal);
+ if (existing is null)
+ {
+ target.Add(property.Name, property.Value.DeepClone());
+ }
+ else if (existing.Value is JObject existingObject && property.Value is JObject patchObject)
+ {
+ ApplyPatch(existingObject, patchObject);
+ }
+ else
+ {
+ existing.Value = property.Value.DeepClone();
+ }
+ }
+ }
+
+ ///
+ /// Reads a game file the way every step reads it, so the same fault always gives the same diagnostic and
+ /// can fold the copies (seam section 11). The subject is the file key.
+ ///
+ internal static bool TryReadBase(
+ BaseFile baseFile,
+ [NotNullWhen(true)] out JToken? root,
+ [NotNullWhen(false)] out OperationDiagnostic? problem)
+ {
+ string key = MergePath.ToKey(baseFile.Path);
+ problem = null;
+ if (!TryParse(baseFile.Text, out root, out string? error))
+ {
+ problem = Error(DiagnosticCodes.MergeBaseParseFailed, $"The game file {key} is not valid JSON ({error}).", key);
+ return false;
+ }
+
+ if (RpgDataSchema.ExpectedRootOf(key) is JTokenType expected && root.Type != expected)
+ {
+ problem = Error(
+ DiagnosticCodes.MergeRootShapeMismatch,
+ $"The game file {key} has {Describe(root.Type)} at its root, but the game reads {Describe(expected)}.",
+ key);
+ root = null;
+ return false;
+ }
+
+ return true;
+ }
+
+ private static string Describe(JTokenType type)
+ {
+ return type switch
+ {
+ JTokenType.Object => "an object",
+ JTokenType.Array => "an array",
+ _ => "a value of type " + type.ToString().ToLowerInvariant()
+ };
+ }
+
+ private static bool TryParse(string? text, [NotNullWhen(true)] out JToken? token, out string? error)
+ {
+ token = null;
+ if (text is null)
+ {
+ error = "no text";
+ return false;
+ }
+
+ try
+ {
+ token = MergeJson.Parse(text);
+ error = null;
+ return true;
+ }
+ catch (JsonReaderException exception)
+ {
+ error = $"line {exception.LineNumber}, position {exception.LinePosition}";
+ return false;
+ }
+ }
+
+ private static OperationDiagnostic Error(string code, string message, string subject)
+ {
+ return new OperationDiagnostic(code, message, DiagnosticSeverity.Error, subject);
+ }
+
+ private sealed class TargetEdits
+ {
+ public TargetEdits(string key)
+ {
+ Key = key;
+ }
+
+ public string Key { get; }
+
+ public ModFile? File { get; set; }
+
+ public List Patches { get; } = new();
+ }
+}
diff --git a/RPGModder.Core/Merge/Collision.cs b/RPGModder.Core/Merge/Collision.cs
new file mode 100644
index 0000000..1ddd96d
--- /dev/null
+++ b/RPGModder.Core/Merge/Collision.cs
@@ -0,0 +1,15 @@
+namespace RPGModder.Core.Merge;
+
+///
+/// Two or more mods that cannot both have their way. Id hashes the place and the mods but no value
+/// (GR-X1), so a stored choice survives a mod update; Fingerprint hashes the values (GR-X2).
+///
+public sealed record Collision(
+ string Id,
+ CollisionKind Kind,
+ RecordKey Key,
+ string Path,
+ IReadOnlyList ModIds,
+ bool Blocking,
+ IReadOnlyList Allowed,
+ string Fingerprint);
diff --git a/RPGModder.Core/Merge/CollisionKind.cs b/RPGModder.Core/Merge/CollisionKind.cs
new file mode 100644
index 0000000..2461116
--- /dev/null
+++ b/RPGModder.Core/Merge/CollisionKind.cs
@@ -0,0 +1,17 @@
+namespace RPGModder.Core.Merge;
+
+public enum CollisionKind
+{
+ ValueClash,
+ DeleteVersusEdit,
+ IdClash,
+ SequenceClash,
+ LogicClash,
+ PageClash,
+ FileClash,
+ PluginOrderClash,
+ OrderAmbiguous,
+ BaseMismatch,
+ SwitchBandConflict,
+ StateIdOverlap
+}
diff --git a/RPGModder.Core/Merge/CollisionOutcome.cs b/RPGModder.Core/Merge/CollisionOutcome.cs
new file mode 100644
index 0000000..6947ec5
--- /dev/null
+++ b/RPGModder.Core/Merge/CollisionOutcome.cs
@@ -0,0 +1,7 @@
+namespace RPGModder.Core.Merge;
+
+public sealed record CollisionOutcome(
+ string CollisionId,
+ ResolutionSource Source,
+ ResolutionKind? Kind,
+ string? ModId);
diff --git a/RPGModder.Core/Merge/Composer.cs b/RPGModder.Core/Merge/Composer.cs
new file mode 100644
index 0000000..4039bcd
--- /dev/null
+++ b/RPGModder.Core/Merge/Composer.cs
@@ -0,0 +1,668 @@
+using Newtonsoft.Json.Linq;
+using RPGModder.Core.Models;
+using RPGModder.Core.Operations;
+using System.Diagnostics;
+using System.Globalization;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// Composes the change sets of every enabled mod into one plan (guide 3.4) and applies the stored choices
+/// (guide 3.5). The result does not depend on the order of the inputs (GR-C4); priority is read only by the two
+/// plugin order defaults, which name profile order. Nothing is merged by text, pattern or load order (GR-C11).
+///
+public static class Composer
+{
+ ///
+ /// The plan, when lane A ran : an IdClash one of its offers settles lists
+ /// and carries rules.remap_unchecked (GR-R11), and its diagnostics join
+ /// the plan's.
+ ///
+ public static MergePlan Compose(
+ IReadOnlyList changeSets,
+ IReadOnlyList resolutions,
+ BaseFileSet baseFiles,
+ RemapPlan? remapPlan = null)
+ {
+ ArgumentNullException.ThrowIfNull(changeSets);
+ ArgumentNullException.ThrowIfNull(resolutions);
+ ArgumentNullException.ThrowIfNull(baseFiles);
+
+ List ordered = changeSets.OrderBy(set => set.ModId, StringComparer.Ordinal).ToList();
+ for (int index = 1; index < ordered.Count; index++)
+ {
+ if (ordered[index].ModId == ordered[index - 1].ModId)
+ {
+ throw new ArgumentException($"Two change sets share the mod id {ordered[index].ModId}.", nameof(changeSets));
+ }
+ }
+
+ var diagnostics = new List();
+ foreach (ModChangeSet set in ordered)
+ {
+ diagnostics.AddRange(set.Diagnostics);
+ }
+
+ diagnostics.AddRange(remapPlan?.Diagnostics ?? []);
+
+ // The writer stamps versionId into System.json (C-7), so a broken one must stop the plan here, not there.
+ BaseFile? system = baseFiles.Find(RpgDataSchema.SystemFileKey);
+ if (system is not null && !ChangeSetBuilder.TryReadBase(system, out _, out OperationDiagnostic? systemProblem))
+ {
+ diagnostics.Add(systemProblem);
+ }
+
+ var priorities = ordered.ToDictionary(set => set.ModId, set => set.Priority, StringComparer.Ordinal);
+
+ // One lookup for the whole plan: a large map repaint can give tens of thousands of collisions and choices.
+ ILookup choices = resolutions.ToLookup(item => item.CollisionId, StringComparer.Ordinal);
+ var ops = new List();
+ var collisions = new List<(Collision Collision, CollisionOutcome Outcome)>();
+ IReadOnlyList offers = remapPlan?.Offers ?? [];
+ foreach (List cluster in Cluster(Group(ordered)))
+ {
+ ComposeCluster(cluster, choices, priorities, offers, ops, collisions, diagnostics);
+ }
+
+ ComposePluginOrder(ops, choices, priorities, collisions, diagnostics);
+
+ ops.Sort((left, right) => ChangeSetBuilder.CompareOps(left.Op, right.Op));
+ collisions.Sort((left, right) => string.CompareOrdinal(left.Collision.Id, right.Collision.Id));
+
+ List allDiagnostics = diagnostics
+ .Distinct()
+ .OrderBy(item => item.Code, StringComparer.Ordinal)
+ .ThenBy(item => item.Subject ?? "", StringComparer.Ordinal)
+ .ThenBy(item => item.Message, StringComparer.Ordinal)
+ .ThenBy(item => item.Severity)
+ .ToList();
+
+ List outcomes = collisions.Select(item => item.Outcome).ToList();
+ bool deployable = allDiagnostics.All(item => item.Severity != DiagnosticSeverity.Error) &&
+ collisions.All(item => !item.Collision.Blocking || item.Outcome.Source != ResolutionSource.Unresolved);
+
+ return new MergePlan(
+ ops,
+ collisions.Select(item => item.Collision).ToList(),
+ outcomes,
+ allDiagnostics,
+ deployable,
+ Hash(ops, outcomes));
+ }
+
+ /// GR-C1: ops on one key and path, with equal ops folded into one variant.
+ private static List Group(List ordered)
+ {
+ var groups = new Dictionary<(string File, string Record, string Path), OpGroup>();
+ foreach (ModChangeSet set in ordered)
+ {
+ foreach (ChangeOp op in set.Ops)
+ {
+ var key = (op.Key.File, op.Key.Record, op.Path);
+ if (!groups.TryGetValue(key, out OpGroup? group))
+ {
+ group = new OpGroup(op.Key, op.Path);
+ groups.Add(key, group);
+ }
+
+ group.Add(op, set.ModId);
+ }
+ }
+
+ return groups.Values.ToList();
+ }
+
+ ///
+ /// GR-C2: a group joins the outermost group whose place contains it: a whole-file value, else the shortest
+ /// ancestor path in the same record. The head comes first in each cluster, the rest follow in place order.
+ ///
+ private static List> Cluster(IReadOnlyList groups)
+ {
+ var byPlace = new Dictionary<(string File, string Record, string Path), OpGroup>();
+ foreach (OpGroup group in groups)
+ {
+ byPlace.Add((group.Key.File, group.Key.Record, group.Path), group);
+ }
+
+ var clusters = new List>();
+ var clusterOfHead = new Dictionary>();
+ IEnumerable inPlaceOrder = groups
+ .OrderBy(group => group.Key.File, StringComparer.Ordinal)
+ .ThenBy(group => group.Key.Record, StringComparer.Ordinal)
+ .ThenBy(group => group.Path, StringComparer.Ordinal);
+ foreach (OpGroup group in inPlaceOrder)
+ {
+ OpGroup head = HeadOf(group, byPlace);
+ if (!clusterOfHead.TryGetValue(head, out List? cluster))
+ {
+ cluster = [head];
+ clusterOfHead.Add(head, cluster);
+ clusters.Add(cluster);
+ }
+
+ if (!ReferenceEquals(group, head))
+ {
+ cluster.Add(group);
+ }
+ }
+
+ return clusters;
+ }
+
+ private static OpGroup HeadOf(OpGroup group, Dictionary<(string File, string Record, string Path), OpGroup> byPlace)
+ {
+ if (byPlace.TryGetValue((group.Key.File, RecordKey.WholeFile, ""), out OpGroup? wholeFile))
+ {
+ return wholeFile;
+ }
+
+ foreach (string ancestor in MergePath.Ancestors(group.Path))
+ {
+ if (byPlace.TryGetValue((group.Key.File, group.Key.Record, ancestor), out OpGroup? found))
+ {
+ return found;
+ }
+ }
+
+ return group;
+ }
+
+ private static void ComposeCluster(
+ List cluster,
+ ILookup choices,
+ Dictionary priorities,
+ IReadOnlyList offers,
+ List ops,
+ List<(Collision, CollisionOutcome)> collisions,
+ List diagnostics)
+ {
+ List mods = cluster
+ .SelectMany(group => group.Variants)
+ .SelectMany(variant => variant.ModIds)
+ .Distinct()
+ .OrderBy(id => id, StringComparer.Ordinal)
+ .ToList();
+
+ bool clash = cluster.Count == 1 ? cluster[0].Variants.Count > 1 : mods.Count > 1;
+ if (!clash)
+ {
+ foreach (OpGroup group in cluster)
+ {
+ ops.AddRange(group.Variants.Select(variant => variant.ToMergedOp()));
+ }
+
+ return;
+ }
+
+ Collision collision = OfferRemaps(MakeCollision(cluster, mods), offers, diagnostics);
+ CollisionOutcome outcome = Decide(collision, choices, diagnostics);
+ collisions.Add((collision, outcome));
+
+ ResolutionKind? kind = outcome.Source == ResolutionSource.Unresolved ? null : outcome.Kind;
+ switch (kind)
+ {
+ case null:
+ case ResolutionKind.PickVanilla:
+ // Unresolved: the plan is not deployable and the clashing ops are described by the collision.
+ break;
+ case ResolutionKind.PickMod when cluster.Count > 1 && !IsHeadMod(cluster[0], outcome.ModId!):
+ // Choosing a change inside the head keeps every inner change: only the head is dropped, and the
+ // inner ops are composed again, so a clash among them becomes a collision of its own (seam 11).
+ foreach (List inner in Cluster(cluster.Skip(1).ToList()))
+ {
+ ComposeCluster(inner, choices, priorities, offers, ops, collisions, diagnostics);
+ }
+
+ break;
+ case ResolutionKind.KeepBothInProfileOrder when collision.Kind == CollisionKind.PluginOrderClash:
+ // The anchors apply in profile order, so the last one wins (seam 11.1). An OrderAmbiguous
+ // collision is composed after the clusters, by ComposePluginOrder.
+ ops.Add(LatestInProfileOrder(cluster[0], priorities).ToMergedOp());
+ break;
+ case ResolutionKind.PickMod:
+ foreach (OpGroup group in cluster)
+ {
+ ops.AddRange(group.Variants
+ .Where(variant => variant.ModIds.Contains(outcome.ModId!, StringComparer.Ordinal))
+ .Select(variant => variant.ToMergedOp()));
+ }
+
+ break;
+ default:
+ // Decide accepts only kinds in Allowed, and no cluster kind of 2a allows another choice.
+ throw new UnreachableException($"Resolution {kind} is not applied to {collision.Kind}.");
+ }
+ }
+
+ /// The variant of the mod latest in profile order; equal priorities fall back to the mod id that sorts last.
+ private static Variant LatestInProfileOrder(OpGroup group, Dictionary priorities)
+ {
+ return group.Variants
+ .OrderByDescending(variant => variant.ModIds.Max(id => priorities[id]))
+ .ThenByDescending(variant => variant.ModIds.Max(StringComparer.Ordinal), StringComparer.Ordinal)
+ .First();
+ }
+
+ ///
+ /// GR-C10: entries from more than one mod behind one anchor are an OrderAmbiguous collision (seam 11.1),
+ /// settled here, after every cluster, because the anchors are only final once each PluginOrderClash is.
+ /// The chosen order is written back as a chain, so each @after names the entry placed right before it.
+ /// A null anchor sends a new entry to the end and a moved entry to the front, so each forms its own group:
+ /// @after on * for the end, @first on * for the front.
+ ///
+ private static void ComposePluginOrder(
+ List ops,
+ ILookup choices,
+ Dictionary priorities,
+ List<(Collision, CollisionOutcome)> collisions,
+ List diagnostics)
+ {
+ var added = new HashSet(StringComparer.Ordinal);
+ foreach (MergedOp merged in ops)
+ {
+ ChangeOp op = merged.Op;
+ if (op.Key.File == RpgDataSchema.PluginListKey && op.Kind == ChangeKind.AddRecord && !op.Key.IsWholeFile)
+ {
+ added.Add(op.Key.Record);
+ }
+ }
+
+ var byAnchor = new SortedDictionary<(string Record, string Path), List>(Comparer<(string Record, string Path)>.Create(
+ (left, right) =>
+ {
+ int byRecord = string.CompareOrdinal(left.Record, right.Record);
+ return byRecord != 0 ? byRecord : string.CompareOrdinal(left.Path, right.Path);
+ }));
+ var afterOps = new List();
+ for (int index = 0; index < ops.Count; index++)
+ {
+ ChangeOp op = ops[index].Op;
+ if (op.Key.File != RpgDataSchema.PluginListKey || op.Path != MergePath.AfterLeaf)
+ {
+ continue;
+ }
+
+ afterOps.Add(index);
+
+ string? anchor = op.Value?.Type == JTokenType.String ? op.Value.Value() : null;
+ (string Record, string Path) place = anchor is not null
+ ? (RecordKey.ForPlugin(anchor), MergePath.AfterLeaf)
+ : (RecordKey.WholeFile, added.Contains(op.Key.Record) ? MergePath.AfterLeaf : MergePath.FirstLeaf);
+ if (!byAnchor.TryGetValue(place, out List? entries))
+ {
+ entries = new List();
+ byAnchor.Add(place, entries);
+ }
+
+ entries.Add(index);
+ }
+
+ foreach (((string anchorRecord, string path), List entries) in byAnchor)
+ {
+ List mods = entries
+ .SelectMany(index => ops[index].ModIds)
+ .Distinct()
+ .OrderBy(id => id, StringComparer.Ordinal)
+ .ToList();
+ if (entries.Count < 2 || mods.Count < 2)
+ {
+ continue;
+ }
+
+ var key = new RecordKey(RpgDataSchema.PluginListKey, anchorRecord);
+ string id = CollisionId(CollisionKind.OrderAmbiguous, key, path, mods);
+ var collision = new Collision(
+ id,
+ CollisionKind.OrderAmbiguous,
+ key,
+ path,
+ mods,
+ IsBlocking(CollisionKind.OrderAmbiguous),
+ AllowedFor(CollisionKind.OrderAmbiguous),
+ OrderFingerprint(ops, entries));
+ CollisionOutcome outcome = Decide(collision, choices, diagnostics);
+ collisions.Add((collision, outcome));
+
+ string? first = outcome.Kind == ResolutionKind.PickMod ? outcome.ModId : null;
+ List placed = entries
+ .OrderBy(index => first is not null && ops[index].ModIds.Contains(first, StringComparer.Ordinal) ? 0 : 1)
+ .ThenBy(index => ops[index].ModIds.Min(mod => priorities[mod]))
+ .ThenBy(index => ops[index].Op.Key.Record, StringComparer.Ordinal)
+ .ToList();
+
+ for (int position = 1; position < placed.Count; position++)
+ {
+ MergedOp merged = ops[placed[position]];
+ string before = RunTail(ops, afterOps, ops[placed[position - 1]]);
+ ops[placed[position]] = merged with { Op = merged.Op with { Value = new JValue(before) } };
+ }
+ }
+ }
+
+ ///
+ /// The last entry of the run that starts at : each next entry is anchored on the one
+ /// before and comes from the same mods, so a mod's own run of plugins is never split by another mod's.
+ ///
+ private static string RunTail(List ops, List afterOps, MergedOp start)
+ {
+ RecordKey.TryGetPlugin(start.Op.Key.Record, out string tail);
+ var seen = new HashSet(StringComparer.Ordinal) { tail };
+ while (true)
+ {
+ MergedOp? next = afterOps.Select(index => ops[index]).FirstOrDefault(merged =>
+ merged.Op.Value?.Type == JTokenType.String &&
+ merged.Op.Value.Value() == tail &&
+ merged.ModIds.SequenceEqual(start.ModIds, StringComparer.Ordinal));
+ if (next is null || !RecordKey.TryGetPlugin(next.Op.Key.Record, out string name) || !seen.Add(name))
+ {
+ return tail;
+ }
+
+ tail = name;
+ }
+ }
+
+ /// GR-X2 for an order collision: the entries behind the anchor and their mods, by record.
+ private static string OrderFingerprint(List ops, List entries)
+ {
+ var items = new JArray();
+ foreach (MergedOp merged in entries.Select(index => ops[index]).OrderBy(item => item.Op.Key.Record, StringComparer.Ordinal))
+ {
+ items.Add(new JArray(merged.Op.Key.Record, new JArray(merged.ModIds.ToArray())));
+ }
+
+ return MergeJson.Sha256Hex(MergeJson.Write(items));
+ }
+
+ ///
+ /// GR-R11: an IdClash an offer settles lists Remap , stays blocking and has no default, and each
+ /// offer carries the warning once, though a map offer settles two collisions (its file and its tree record).
+ /// Lane A carries a chosen Remap out by recording the offer (seam 4.3).
+ ///
+ private static Collision OfferRemaps(Collision collision, IReadOnlyList offers, List diagnostics)
+ {
+ List settling = offers.Where(offer => RemapPlaces.Settles(offer, collision)).ToList();
+ if (settling.Count == 0)
+ {
+ return collision;
+ }
+
+ foreach (IdRemap offer in settling)
+ {
+ diagnostics.Add(new OperationDiagnostic(
+ DiagnosticCodes.RulesRemapUnchecked,
+ string.Create(
+ CultureInfo.InvariantCulture,
+ $"Mod {offer.ModId}: {offer.Kind} {offer.FromId}{(offer.Kind == IdKind.MapEvent ? " in " + offer.Scope : "")} can move to {offer.ToId} to settle its id clash, but a plugin file the mod ships contains that number."),
+ DiagnosticSeverity.Warning,
+ offer.ModId));
+ }
+
+ // Declaration order, so Remap sits between the choices the collision already allows.
+ return collision with { Allowed = collision.Allowed.Append(ResolutionKind.Remap).Distinct().Order().ToList() };
+ }
+
+ private static bool IsHeadMod(OpGroup head, string modId)
+ {
+ return head.Variants.Any(variant => variant.ModIds.Contains(modId, StringComparer.Ordinal));
+ }
+
+ private static Collision MakeCollision(List cluster, List mods)
+ {
+ OpGroup head = cluster[0];
+ List all = cluster.SelectMany(group => group.Variants).Select(variant => variant.Op).ToList();
+
+ CollisionKind kind;
+ if (all.All(op => op.Kind == ChangeKind.ReplaceFile))
+ {
+ kind = CollisionKind.FileClash;
+ }
+ else if (all.Any(op => op.Kind == ChangeKind.RemoveRecord))
+ {
+ kind = CollisionKind.DeleteVersusEdit;
+ }
+ else if (all.All(op => op.Kind == ChangeKind.AddRecord))
+ {
+ kind = CollisionKind.IdClash;
+ }
+ else if (cluster.Count == 1 && head.Path == MergePath.AfterLeaf)
+ {
+ kind = CollisionKind.PluginOrderClash;
+ }
+ else if (RpgDataSchema.IsPageSetting(head.Key, head.Path))
+ {
+ kind = CollisionKind.PageClash;
+ }
+ else if (cluster.Count == 1 && all.All(op => op.Kind == ChangeKind.EditSequence))
+ {
+ kind = CollisionKind.SequenceClash;
+ }
+ else if (cluster.Count == 1 && all.All(op => op.Kind == ChangeKind.EditCommands))
+ {
+ kind = CollisionKind.LogicClash;
+ }
+ else
+ {
+ kind = CollisionKind.ValueClash;
+ }
+
+ // A mod with two variants of one place clashes with itself: a recorded remap moved an id onto one the mod now
+ // adds as well. Picking that mod would keep both ops, so it is not a choice (seam 11.2).
+ IReadOnlyList allowed = AllowedFor(kind);
+ if (cluster.Any(group => group.Variants.SelectMany(variant => variant.ModIds).GroupBy(modId => modId, StringComparer.Ordinal).Any(ids => ids.Count() > 1)))
+ {
+ allowed = allowed.Where(item => item != ResolutionKind.PickMod).ToList();
+ }
+
+ string id = CollisionId(kind, head.Key, head.Path, mods);
+ return new Collision(id, kind, head.Key, head.Path, mods, IsBlocking(kind), allowed, Fingerprint(cluster));
+ }
+
+ ///
+ /// GR-X1: the first 16 hex characters of SHA-256 over the kind, file, record, path and sorted mod ids, one per
+ /// line. No value takes part, so a mod update keeps the player's choice.
+ ///
+ internal static string CollisionId(CollisionKind kind, RecordKey key, string path, IReadOnlyList sortedModIds)
+ {
+ var lines = new List { kind.ToString(), key.File, key.Record, path };
+ lines.AddRange(sortedModIds);
+ return MergeJson.Sha256Hex(string.Join('\n', lines))[..16];
+ }
+
+ /// GR-X2: a hash of every colliding value, by place and by mod.
+ private static string Fingerprint(List cluster)
+ {
+ var entries = new JArray();
+ foreach (OpGroup group in cluster.OrderBy(item => item.Key.Record, StringComparer.Ordinal).ThenBy(item => item.Path, StringComparer.Ordinal))
+ {
+ foreach (Variant variant in group.Variants)
+ {
+ entries.Add(new JArray(
+ group.Key.Record,
+ group.Path,
+ variant.Op.Kind.ToString(),
+ variant.Op.Value is null ? new JArray() : new JArray(variant.Op.Value.DeepClone()),
+ new JArray(variant.ModIds.ToArray())));
+ }
+ }
+
+ return MergeJson.Sha256Hex(MergeJson.Write(entries));
+ }
+
+ private static CollisionOutcome Decide(Collision collision, ILookup choices, List diagnostics)
+ {
+ Resolution? stored = choices[collision.Id]
+ .Where(item => IsApplicable(item, collision))
+ .OrderBy(item => item.Kind)
+ .ThenBy(item => item.ModId ?? "", StringComparer.Ordinal)
+ .ThenBy(item => item.Fingerprint ?? "", StringComparer.Ordinal)
+ .FirstOrDefault();
+
+ if (stored is not null)
+ {
+ string? modId = stored.Kind == ResolutionKind.PickMod ? stored.ModId : null;
+
+ // A choice stored without a fingerprint cannot be checked against the content, so it is taken as made.
+ if (stored.Fingerprint is null || stored.Fingerprint == collision.Fingerprint)
+ {
+ return new CollisionOutcome(collision.Id, ResolutionSource.Profile, stored.Kind, modId);
+ }
+
+ diagnostics.Add(new OperationDiagnostic(
+ DiagnosticCodes.RulesResolutionReused,
+ $"A stored choice for collision {collision.Id} was applied to content that changed since it was made.",
+ DiagnosticSeverity.Info,
+ collision.Id));
+ return new CollisionOutcome(collision.Id, ResolutionSource.ProfileReused, stored.Kind, modId);
+ }
+
+ ResolutionKind? fallback = DefaultFor(collision.Kind);
+ return fallback is null
+ ? new CollisionOutcome(collision.Id, ResolutionSource.Unresolved, null, null)
+ : new CollisionOutcome(collision.Id, ResolutionSource.Default, fallback, null);
+ }
+
+ ///
+ /// A stored choice applies when its kind is allowed for the collision and Compose carries it out (seam 4.3),
+ /// and a PickMod names one of the collision's mods. Anything else leaves the collision unresolved, so the
+ /// player chooses again.
+ ///
+ private static bool IsApplicable(Resolution resolution, Collision collision)
+ {
+ if (resolution.Kind is ResolutionKind.DisableMod or ResolutionKind.Remap ||
+ !collision.Allowed.Contains(resolution.Kind))
+ {
+ return false;
+ }
+
+ return resolution.Kind != ResolutionKind.PickMod ||
+ (resolution.ModId is not null && collision.ModIds.Contains(resolution.ModId, StringComparer.Ordinal));
+ }
+
+ /// The "Blocks deploy until resolved" column of guide 3.5, for slice 2a.
+ private static bool IsBlocking(CollisionKind kind)
+ {
+ return kind switch
+ {
+ CollisionKind.ValueClash or CollisionKind.DeleteVersusEdit or CollisionKind.IdClash or CollisionKind.SequenceClash
+ or CollisionKind.LogicClash or CollisionKind.PageClash or CollisionKind.FileClash
+ or CollisionKind.BaseMismatch => true,
+ CollisionKind.PluginOrderClash or CollisionKind.OrderAmbiguous
+ or CollisionKind.SwitchBandConflict or CollisionKind.StateIdOverlap => false,
+ _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "A collision kind guide 3.5 does not list.")
+ };
+ }
+
+ ///
+ /// The "Allowed resolutions" column of guide 3.5 for slice 2a, in declaration order. Remap is added by
+ /// (2r) and Gate comes with 2c; a SwitchBandConflict is settled by moving the band, never by a choice.
+ ///
+ private static IReadOnlyList AllowedFor(CollisionKind kind)
+ {
+ return kind switch
+ {
+ CollisionKind.ValueClash or CollisionKind.DeleteVersusEdit or CollisionKind.SequenceClash
+ or CollisionKind.LogicClash or CollisionKind.PageClash => [ResolutionKind.PickMod, ResolutionKind.PickVanilla],
+ CollisionKind.IdClash => [ResolutionKind.PickMod, ResolutionKind.DisableMod],
+ CollisionKind.FileClash => [ResolutionKind.PickMod],
+ CollisionKind.PluginOrderClash or CollisionKind.OrderAmbiguous => [ResolutionKind.PickMod, ResolutionKind.KeepBothInProfileOrder],
+ CollisionKind.BaseMismatch => [ResolutionKind.Accept, ResolutionKind.DisableMod],
+ CollisionKind.SwitchBandConflict => [],
+ CollisionKind.StateIdOverlap => [ResolutionKind.Accept],
+ _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "A collision kind guide 3.5 does not list.")
+ };
+ }
+
+ ///
+ /// The "Default" column of guide 3.5 for slice 2a. Only the order kinds and StateIdOverlap have one; a
+ /// BaseMismatch waits for the player to accept that mod (owner decision, 2026-11-12).
+ ///
+ private static ResolutionKind? DefaultFor(CollisionKind kind)
+ {
+ return kind switch
+ {
+ CollisionKind.PluginOrderClash or CollisionKind.OrderAmbiguous => ResolutionKind.KeepBothInProfileOrder,
+ CollisionKind.StateIdOverlap => ResolutionKind.Accept,
+ _ => null
+ };
+ }
+
+ /// Lane B's half of GR-C9 and TST-5: SHA-256 over a canonical form of the ops and the outcomes.
+ private static string Hash(List ops, List outcomes)
+ {
+ var opEntries = new JArray();
+ foreach (MergedOp merged in ops)
+ {
+ ChangeOp op = merged.Op;
+ opEntries.Add(new JArray(
+ op.Key.File,
+ op.Key.Record,
+ op.Path,
+ op.Kind.ToString(),
+ op.Value is null ? new JArray() : new JArray(op.Value.DeepClone()),
+ Text(op.SourceFile),
+ new JArray(merged.ModIds.ToArray())));
+ }
+
+ var outcomeEntries = new JArray();
+ foreach (CollisionOutcome outcome in outcomes)
+ {
+ outcomeEntries.Add(new JArray(
+ outcome.CollisionId,
+ outcome.Source.ToString(),
+ Text(outcome.Kind?.ToString()),
+ Text(outcome.ModId)));
+ }
+
+ var root = new JArray(RpgDataSchema.SchemaVersion.ToString(CultureInfo.InvariantCulture), opEntries, outcomeEntries);
+ return MergeJson.Sha256Hex(MergeJson.Write(root));
+ }
+
+ private static JValue Text(string? value)
+ {
+ return value is null ? JValue.CreateNull() : new JValue(value);
+ }
+
+ private sealed class OpGroup
+ {
+ public OpGroup(RecordKey key, string path)
+ {
+ Key = key;
+ Path = path;
+ }
+
+ public RecordKey Key { get; }
+
+ public string Path { get; }
+
+ public List Variants { get; } = new();
+
+ /// Ops arrive in mod id order, so each variant's op is the one of the mod whose id sorts first.
+ public void Add(ChangeOp op, string modId)
+ {
+ foreach (Variant variant in Variants)
+ {
+ if (variant.Op.Kind == op.Kind && ValuesEqual(variant.Op.Value, op.Value))
+ {
+ variant.ModIds.Add(modId);
+ return;
+ }
+ }
+
+ Variants.Add(new Variant(op, [modId]));
+ }
+
+ private static bool ValuesEqual(JToken? left, JToken? right)
+ {
+ return left is null ? right is null : right is not null && JToken.DeepEquals(left, right);
+ }
+ }
+
+ private sealed record Variant(ChangeOp Op, List ModIds)
+ {
+ public MergedOp ToMergedOp()
+ {
+ return new MergedOp(Op, ModIds.ToList());
+ }
+ }
+}
diff --git a/RPGModder.Core/Merge/ConfigSaveText.cs b/RPGModder.Core/Merge/ConfigSaveText.cs
new file mode 100644
index 0000000..5345209
--- /dev/null
+++ b/RPGModder.Core/Merge/ConfigSaveText.cs
@@ -0,0 +1,121 @@
+using LZStringCSharp;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using System.Diagnostics.CodeAnalysis;
+using System.IO.Compression;
+using System.Text;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The config saves 2a decodes (GR-M10), each holding one JSON object in the form the game's
+/// StorageManager writes:
+///
+/// - MV
config.rpgsave : LZ-String base64 of the JSON text.
+/// - MZ
config.rmmzsave : the zlib deflate of the UTF-8 JSON, each byte one character (pako's binary
+/// string), and that text stored as UTF-8. Checked against the MZ editor's new-project scripts.
+///
+/// Input that does not decode is refused, never guessed, so the text is checked before and after each step.
+///
+internal static class ConfigSaveText
+{
+ private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
+
+ /// A key accepts; it picks the form.
+ public static bool TryDecode(string fileKey, string? text, [NotNullWhen(true)] out JObject? config, [NotNullWhen(false)] out string? error)
+ {
+ config = null;
+ string? json = RpgDataSchema.IsMzConfigSave(fileKey) ? InflateMz(text, out error) : DecompressMv(text, out error);
+ if (json is null)
+ {
+ error ??= "it does not decode";
+ return false;
+ }
+
+ try
+ {
+ config = MergeJson.Parse(json) as JObject;
+ }
+ catch (JsonReaderException exception)
+ {
+ error = $"it decodes to text that is not valid JSON (line {exception.LineNumber}, position {exception.LinePosition})";
+ return false;
+ }
+
+ error = config is null ? "it decodes to JSON that is not an object" : null;
+ return config is not null;
+ }
+
+ public static string Encode(string fileKey, JObject config)
+ {
+ string json = MergeJson.Write(config);
+ if (!RpgDataSchema.IsMzConfigSave(fileKey))
+ {
+ return LZString.CompressToBase64(json);
+ }
+
+ using var buffer = new MemoryStream();
+ using (var zlib = new ZLibStream(buffer, CompressionLevel.Fastest, leaveOpen: true))
+ {
+ zlib.Write(StrictUtf8.GetBytes(json));
+ }
+
+ // Latin-1 maps byte n to character n, the binary string pako's deflate returns.
+ return Encoding.Latin1.GetString(buffer.ToArray());
+ }
+
+ private static string? DecompressMv(string? text, out string? error)
+ {
+ error = null;
+ string encoded = text?.Trim() ?? "";
+ if (encoded.Length == 0 || !encoded.All(IsBase64Char))
+ {
+ error = "it is not LZ-String base64";
+ return null;
+ }
+
+ try
+ {
+ string? json = LZString.DecompressFromBase64(encoded);
+ return string.IsNullOrEmpty(json) ? null : json;
+ }
+ catch (Exception exception) when (exception is IndexOutOfRangeException or KeyNotFoundException)
+ {
+ // The library's own faults on a truncated or foreign text; both mean "does not decode".
+ return null;
+ }
+ }
+
+ private static string? InflateMz(string? text, out string? error)
+ {
+ error = null;
+ if (string.IsNullOrEmpty(text) || text.Any(current => current > byte.MaxValue))
+ {
+ error = "it is not a zlib byte string";
+ return null;
+ }
+
+ try
+ {
+ using var input = new MemoryStream(Encoding.Latin1.GetBytes(text));
+ using var zlib = new ZLibStream(input, CompressionMode.Decompress);
+ using var output = new MemoryStream();
+ zlib.CopyTo(output);
+ return output.Length == 0 ? null : StrictUtf8.GetString(output.ToArray());
+ }
+ catch (InvalidDataException)
+ {
+ return null;
+ }
+ catch (DecoderFallbackException)
+ {
+ error = "it decodes to bytes that are not UTF-8";
+ return null;
+ }
+ }
+
+ private static bool IsBase64Char(char current)
+ {
+ return char.IsAsciiLetterOrDigit(current) || current is '+' or '/' or '=';
+ }
+}
diff --git a/RPGModder.Core/Merge/DataDiff.cs b/RPGModder.Core/Merge/DataDiff.cs
new file mode 100644
index 0000000..e117481
--- /dev/null
+++ b/RPGModder.Core/Merge/DataDiff.cs
@@ -0,0 +1,240 @@
+using Newtonsoft.Json.Linq;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The schema-driven walker: compares one mod's version of a data file with vanilla and returns the ops
+/// (GR-M1, guide 3.3). Every decision about a file or a path comes from .
+///
+internal sealed class DataDiff
+{
+ private readonly string _modId;
+ private readonly string _fileKey;
+ private readonly string? _sourceFile;
+ private readonly List _ops = new();
+
+ private DataDiff(string modId, string fileKey, string? sourceFile)
+ {
+ _modId = modId;
+ _fileKey = fileKey;
+ _sourceFile = sourceFile;
+ }
+
+ public static IReadOnlyList Compare(string modId, string fileKey, string? sourceFile, JToken vanilla, JToken modded)
+ {
+ var diff = new DataDiff(modId, fileKey, sourceFile);
+ diff.CompareRoot(vanilla, modded);
+ return diff._ops;
+ }
+
+ /// The leaves of one record that lives outside a data file: a $plugins entry.
+ public static IReadOnlyList CompareRecord(string modId, string fileKey, string? sourceFile, string record, JObject vanilla, JObject modded)
+ {
+ var diff = new DataDiff(modId, fileKey, sourceFile);
+ diff.CompareObject(record, "", vanilla, modded);
+ return diff._ops;
+ }
+
+ private void CompareRoot(JToken vanilla, JToken modded)
+ {
+ if (JToken.DeepEquals(vanilla, modded))
+ {
+ return;
+ }
+
+ if (vanilla.Type != modded.Type)
+ {
+ // A root of another type has no record to line up with vanilla: one value for the whole file.
+ Add(RecordKey.WholeFile, "", ChangeKind.SetLeaf, modded);
+ return;
+ }
+
+ switch (RpgDataSchema.ShapeOf(_fileKey, vanilla))
+ {
+ case RootShape.Records:
+ CompareRecords((JArray)vanilla, (JArray)modded, RecordKey.ForIndex);
+ break;
+ case RootShape.Map:
+ CompareMap((JObject)vanilla, (JObject)modded);
+ break;
+ case RootShape.Object:
+ CompareObject(RecordKey.WholeFile, "", (JObject)vanilla, (JObject)modded);
+ break;
+ default:
+ Add(RecordKey.WholeFile, "", ChangeKind.SetLeaf, modded);
+ break;
+ }
+ }
+
+ ///
+ /// A map is an object whose events are records of their own (guide 3.3). When vanilla's events are not
+ /// a record list, events is one more map-level value. The builder refuses a mod whose events are not a
+ /// list while vanilla's are; the second test below only keeps a direct call safe.
+ ///
+ private void CompareMap(JObject vanilla, JObject modded)
+ {
+ JToken? vanillaEvents = vanilla[RpgDataSchema.EventsProperty];
+ if (!RpgDataSchema.IsEventList(vanillaEvents) || modded[RpgDataSchema.EventsProperty] is not JArray moddedEvents)
+ {
+ CompareObject(RecordKey.WholeFile, "", vanilla, modded);
+ return;
+ }
+
+ CompareObject(RecordKey.WholeFile, "", vanilla, modded, RpgDataSchema.EventsProperty);
+ CompareRecords((JArray)vanillaEvents!, moddedEvents, RecordKey.ForEvent);
+ }
+
+ private void CompareRecords(JArray vanilla, JArray modded, Func recordOf)
+ {
+ int count = Math.Max(vanilla.Count, modded.Count);
+ for (int index = 0; index < count; index++)
+ {
+ JToken? before = RecordAt(vanilla, index);
+ JToken? after = RecordAt(modded, index);
+ string record = recordOf(index);
+
+ if (before is null && after is null)
+ {
+ continue;
+ }
+
+ if (before is null)
+ {
+ Add(record, "", ChangeKind.AddRecord, after);
+ }
+ else if (after is null)
+ {
+ Add(record, "", ChangeKind.RemoveRecord, null);
+ }
+ else if (before is JObject beforeRecord && after is JObject afterRecord)
+ {
+ CompareObject(record, "", beforeRecord, afterRecord);
+ }
+ else if (!JToken.DeepEquals(before, after))
+ {
+ // A record that is not an object has no leaves: it is one value.
+ Add(record, "", ChangeKind.SetLeaf, after);
+ }
+ }
+ }
+
+ /// names a property compared elsewhere, as a map's events .
+ private void CompareObject(string record, string path, JObject vanilla, JObject modded, string? skipped = null)
+ {
+ foreach (JProperty property in modded.Properties())
+ {
+ if (property.Name == skipped || RpgDataSchema.IsVolatile(_fileKey, path, property.Name))
+ {
+ continue;
+ }
+
+ string child = MergePath.Child(path, property.Name);
+ JProperty? original = vanilla.Property(property.Name, StringComparison.Ordinal);
+ if (original is null)
+ {
+ Add(record, child, ChangeKind.SetLeaf, property.Value);
+ }
+ else
+ {
+ CompareValue(record, child, original.Value, property.Value);
+ }
+ }
+
+ foreach (JProperty property in vanilla.Properties())
+ {
+ if (property.Name == skipped ||
+ RpgDataSchema.IsVolatile(_fileKey, path, property.Name) ||
+ modded.Property(property.Name, StringComparison.Ordinal) is not null)
+ {
+ continue;
+ }
+
+ Add(record, MergePath.Child(path, property.Name), ChangeKind.RemoveLeaf, null);
+ }
+ }
+
+ private void CompareValue(string record, string path, JToken vanilla, JToken modded)
+ {
+ if (JToken.DeepEquals(vanilla, modded))
+ {
+ return;
+ }
+
+ if (vanilla is JObject vanillaObject && modded is JObject moddedObject && !RpgDataSchema.IsAtomicObject(_fileKey, path))
+ {
+ CompareObject(record, path, vanillaObject, moddedObject);
+ return;
+ }
+
+ if (vanilla is JArray vanillaArray && modded is JArray moddedArray)
+ {
+ CompareArray(record, path, vanillaArray, moddedArray);
+ return;
+ }
+
+ Add(record, path, ChangeKind.SetLeaf, modded);
+ }
+
+ private void CompareArray(string record, string path, JArray vanilla, JArray modded)
+ {
+ switch (RpgDataSchema.PolicyOf(_fileKey, path))
+ {
+ case ArrayPolicy.Sequence:
+ Add(record, path, ChangeKind.EditSequence, modded);
+ break;
+ case ArrayPolicy.Commands:
+ Add(record, path, ChangeKind.EditCommands, modded);
+ break;
+ case ArrayPolicy.Positional when vanilla.Count == modded.Count:
+ for (int index = 0; index < vanilla.Count; index++)
+ {
+ CompareValue(record, MergePath.Index(path, index), vanilla[index], modded[index]);
+ }
+
+ break;
+ case ArrayPolicy.Keyed:
+ CompareKeyed(record, path, vanilla, modded);
+ break;
+ default:
+ // Atomic, and a Positional array whose length changed (one value until GR-K4 in 2b).
+ Add(record, path, ChangeKind.SetLeaf, modded);
+ break;
+ }
+ }
+
+ private void CompareKeyed(string record, string path, JArray vanilla, JArray modded)
+ {
+ int count = Math.Max(vanilla.Count, modded.Count);
+ for (int index = 0; index < count; index++)
+ {
+ string child = MergePath.Index(path, index);
+ if (index >= modded.Count)
+ {
+ Add(record, child, ChangeKind.RemoveLeaf, null);
+ }
+ else if (index >= vanilla.Count)
+ {
+ Add(record, child, ChangeKind.SetLeaf, modded[index]);
+ }
+ else
+ {
+ CompareValue(record, child, vanilla[index], modded[index]);
+ }
+ }
+ }
+
+ private void Add(string record, string path, ChangeKind kind, JToken? value)
+ {
+ _ops.Add(new ChangeOp(_modId, new RecordKey(_fileKey, record), path, kind, value?.DeepClone(), _sourceFile));
+ }
+
+ private static JToken? RecordAt(JArray array, int index)
+ {
+ if (index >= array.Count || array[index].Type == JTokenType.Null)
+ {
+ return null;
+ }
+
+ return array[index];
+ }
+}
diff --git a/RPGModder.Core/Merge/IdKind.cs b/RPGModder.Core/Merge/IdKind.cs
new file mode 100644
index 0000000..e77da9d
--- /dev/null
+++ b/RPGModder.Core/Merge/IdKind.cs
@@ -0,0 +1,22 @@
+namespace RPGModder.Core.Merge;
+
+/// The kinds of id a mod can add and a remap can move (guide 3.11). Step 1 moves MapEvent and Map .
+public enum IdKind
+{
+ MapEvent,
+ Map,
+ Item,
+ Weapon,
+ Armor,
+ Skill,
+ State,
+ Enemy,
+ Troop,
+ CommonEvent,
+ Actor,
+ Class,
+ Animation,
+ Tileset,
+ Switch,
+ Variable
+}
diff --git a/RPGModder.Core/Merge/IdRemap.cs b/RPGModder.Core/Merge/IdRemap.cs
new file mode 100644
index 0000000..b75187b
--- /dev/null
+++ b/RPGModder.Core/Merge/IdRemap.cs
@@ -0,0 +1,12 @@
+namespace RPGModder.Core.Merge;
+
+///
+/// One mod's added id moved to another (guide 3.11). Scope is the map file key for
+/// (data/map012.json ) and empty for every other kind. The profile keeps these append-only (GR-R12).
+///
+public sealed record IdRemap(
+ string ModId,
+ IdKind Kind,
+ string Scope,
+ int FromId,
+ int ToId);
diff --git a/RPGModder.Core/Merge/IdRemapPlanner.cs b/RPGModder.Core/Merge/IdRemapPlanner.cs
new file mode 100644
index 0000000..8faae1b
--- /dev/null
+++ b/RPGModder.Core/Merge/IdRemapPlanner.cs
@@ -0,0 +1,366 @@
+using Newtonsoft.Json.Linq;
+using RPGModder.Core.Models;
+using RPGModder.Core.Operations;
+using RPGModder.Core.Services;
+using System.Globalization;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// Decides which added ids move before composition (guide 3.11, GR-R3 to GR-R12). Step 1 plans the
+/// and kinds. The result does not depend on the order of any
+/// input.
+///
+public static class IdRemapPlanner
+{
+ /// Every installed mod, enabled or not, once each.
+ /// The profile's Remaps , every entry, active or not.
+ /// The profile's DeployedMods (GR-R4).
+ ///
+ /// Vanilla's files, for the ids vanilla uses (GR-R5): the map file of every map that gets an event, and, when a
+ /// mod adds a map, data/MapInfos.json and every vanilla map file, listed in the tree or not. A clash whose
+ /// base file is missing cannot move, and a map id whose file vanilla has is never a target and never moves.
+ ///
+ ///
+ /// The game's engine, which sets the highest map id a move may give (GR-R6): 2000 for MZ, 999 for MV and for an
+ /// unknown engine (null ).
+ ///
+ public static RemapPlan Plan(
+ IReadOnlyList installed,
+ IReadOnlyList recorded,
+ IReadOnlyCollection deployedMods,
+ BaseFileSet baseFiles,
+ RpgMakerEngine? engine)
+ {
+ ArgumentNullException.ThrowIfNull(installed);
+ ArgumentNullException.ThrowIfNull(recorded);
+ ArgumentNullException.ThrowIfNull(deployedMods);
+ ArgumentNullException.ThrowIfNull(baseFiles);
+
+ List mods = installed.OrderBy(mod => mod.ChangeSet.ModId, StringComparer.Ordinal).ToList();
+ for (int index = 1; index < mods.Count; index++)
+ {
+ if (mods[index].ChangeSet.ModId == mods[index - 1].ChangeSet.ModId)
+ {
+ throw new ArgumentException($"Two installed mods share the mod id {mods[index].ChangeSet.ModId}.", nameof(installed));
+ }
+ }
+
+ var added = mods.ToDictionary(mod => mod.ChangeSet.ModId, mod => AddedIdIndex.Of(mod.ChangeSet), StringComparer.Ordinal);
+ var deployed = new HashSet(deployedMods, StringComparer.Ordinal);
+ var diagnostics = new List();
+ Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int> pins = Pins(mods, added, recorded, baseFiles, diagnostics);
+
+ var claims = new List();
+ foreach (RemapMod mod in mods.Where(item => item.Enabled))
+ {
+ string modId = mod.ChangeSet.ModId;
+ foreach (AddedId id in added[modId])
+ {
+ bool pinned = pins.TryGetValue((modId, id.Kind, id.Scope, id.Id), out int toId);
+ claims.Add(new Claim(mod, id, pinned ? toId : id.Id, pinned, deployed.Contains(modId)));
+ }
+ }
+
+ var targets = new Targets(added.Values.SelectMany(list => list).ToList(), recorded, baseFiles, engine);
+ var references = new Dictionary(StringComparer.Ordinal);
+ var moves = new List();
+ var offers = new List();
+ IEnumerable> groups = claims
+ .GroupBy(claim => (Kind: claim.Added.Kind, Scope: claim.Added.Scope, Id: claim.Effective))
+ .OrderBy(group => group.Key.Kind)
+ .ThenBy(group => group.Key.Scope, StringComparer.Ordinal)
+ .ThenBy(group => group.Key.Id);
+ foreach (IGrouping<(IdKind Kind, string Scope, int Id), Claim> group in groups)
+ {
+ List parties = Partition(group);
+ if (parties.Count < 2)
+ {
+ continue;
+ }
+
+ (IdKind kind, string scope, _) = group.Key;
+ foreach (Party party in parties)
+ {
+ party.Classify(kind, claim => ReferencesOf(claim.Mod, references), claim => IsVanillaMapFile(kind, claim.Added.Id, baseFiles));
+ }
+
+ // GR-R4 and GR-R10: the parties that cannot move stay; when every party can, the first in order stays.
+ List staying = parties.Where(party => !party.CanMove).ToList();
+ if (staying.Count == 0)
+ {
+ staying.Add(parties[0]);
+ }
+ else if (staying.All(party => party.IsUnchecked))
+ {
+ // GR-R4 before GR-R11 (the owner, 2026-11-12): a party in DeployedMods does not move to make room
+ // for parties only a plugin file holds. It stays too, and the player is offered their move.
+ staying.AddRange(parties.Except(staying).Where(party => party.Rank == 1));
+ }
+
+ foreach (Party party in parties.Except(staying).ToList())
+ {
+ int? target = targets.Take(kind, scope);
+ if (target is null)
+ {
+ // GR-R6: past the editor's limit, or vanilla's ids are unknown; the clash stays a choice.
+ staying.Add(party);
+ continue;
+ }
+
+ moves.AddRange(party.Claims.Select(claim => new IdRemap(claim.Mod.ChangeSet.ModId, kind, scope, claim.Added.Id, target.Value)));
+ }
+
+ if (staying.Count < 2)
+ {
+ continue;
+ }
+
+ // GR-R11: a party held only by a number in a shipped plugin file is offered a move of its own.
+ foreach (Party party in staying.Where(item => item.IsUnchecked))
+ {
+ int? target = targets.Take(kind, scope);
+ if (target is not null)
+ {
+ offers.AddRange(party.Claims.Select(claim => new IdRemap(claim.Mod.ChangeSet.ModId, kind, scope, claim.Added.Id, target.Value)));
+ }
+ }
+ }
+
+ List remaps = pins
+ .Select(pin => new IdRemap(pin.Key.ModId, pin.Key.Kind, pin.Key.Scope, pin.Key.FromId, pin.Value))
+ .Concat(moves)
+ .ToList();
+ return new RemapPlan(Sorted(remaps), Sorted(moves), Sorted(offers), diagnostics);
+ }
+
+ ///
+ /// GR-R12: a recorded entry stands while its mod is enabled and still adds the old id. Two entries for one old
+ /// id cannot both stand; the one with the lowest target does, so the input order never decides. An entry whose
+ /// target vanilla now uses (a game update filled a hole) stands no more: the old id is planned again, and when no
+ /// other entry stands for it the plan carries rules.remap_target_taken (the owner, 2026-11-12).
+ ///
+ private static Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int> Pins(
+ List mods,
+ Dictionary> added,
+ IReadOnlyList recorded,
+ BaseFileSet baseFiles,
+ List diagnostics)
+ {
+ var taken = new List();
+ var enabled = new HashSet(mods.Where(mod => mod.Enabled).Select(mod => mod.ChangeSet.ModId), StringComparer.Ordinal);
+ var pins = new Dictionary<(string ModId, IdKind Kind, string Scope, int FromId), int>();
+ var targets = new HashSet<(string ModId, IdKind Kind, string Scope, int ToId)>();
+ foreach (IdRemap remap in Sorted(recorded))
+ {
+ (string ModId, IdKind Kind, string Scope, int FromId) from = (remap.ModId, remap.Kind, remap.Scope, remap.FromId);
+ if (remap.Kind is not (IdKind.MapEvent or IdKind.Map) || remap.ToId <= 0 || !enabled.Contains(remap.ModId) ||
+ !AddedIdIndex.IsActive(remap, added[remap.ModId]) || pins.ContainsKey(from) ||
+ !targets.Add((remap.ModId, remap.Kind, remap.Scope, remap.ToId)))
+ {
+ // Only a standing entry holds its target, so a losing duplicate leaves the next entry free.
+ continue;
+ }
+
+ if (VanillaUses(remap.Kind, remap.Scope, remap.ToId, baseFiles))
+ {
+ taken.Add(remap);
+ continue;
+ }
+
+ pins.Add(from, remap.ToId);
+ }
+
+ foreach (IdRemap remap in taken.Where(item => !pins.ContainsKey((item.ModId, item.Kind, item.Scope, item.FromId)))
+ .DistinctBy(item => (item.ModId, item.Kind, item.Scope, item.FromId)))
+ {
+ string where = remap.Kind == IdKind.MapEvent ? " in " + remap.Scope : "";
+ diagnostics.Add(new OperationDiagnostic(
+ DiagnosticCodes.RulesRemapTargetTaken,
+ string.Create(
+ CultureInfo.InvariantCulture,
+ $"Mod {remap.ModId}: {remap.Kind} {remap.FromId}{where} was recorded as moved to {remap.ToId}, which vanilla now uses, so the entry no longer applies and the id is planned again."),
+ DiagnosticSeverity.Warning,
+ remap.ModId));
+ }
+
+ return pins;
+ }
+
+ /// True when vanilla has a record at : a map file or tree record, or a map's event.
+ private static bool VanillaUses(IdKind kind, string scope, int id, BaseFileSet baseFiles)
+ {
+ if (kind == IdKind.Map && baseFiles.Find(RpgDataSchema.MapKey(id)) is not null)
+ {
+ return true;
+ }
+
+ return VanillaList(kind, scope, baseFiles) is JArray list && id < list.Count && list[id].Type != JTokenType.Null;
+ }
+
+ /// Vanilla's list for a kind and scope, holes included: the map tree for maps, a map's events for events.
+ private static JArray? VanillaList(IdKind kind, string scope, BaseFileSet baseFiles)
+ {
+ string file = kind == IdKind.Map ? RpgDataSchema.MapInfosKey : scope;
+ BaseFile? baseFile = baseFiles.Find(file);
+ if (baseFile is null || !ChangeSetBuilder.TryReadBase(baseFile, out JToken? root, out _))
+ {
+ return null;
+ }
+
+ return (kind == IdKind.Map ? root : (root as JObject)?[RpgDataSchema.EventsProperty]) as JArray;
+ }
+
+ /// GR-R3: claims with equal content are one party, because their ops fold into one.
+ private static List Partition(IEnumerable claims)
+ {
+ var parties = new List();
+ foreach (Claim claim in claims)
+ {
+ Party? party = parties.FirstOrDefault(item => JToken.DeepEquals(item.Claims[0].Added.Content, claim.Added.Content));
+ if (party is null)
+ {
+ parties.Add(new Party(claim));
+ }
+ else
+ {
+ party.Claims.Add(claim);
+ }
+ }
+
+ return parties
+ .OrderBy(party => party.Rank)
+ .ThenBy(party => party.Claims.Min(claim => claim.Mod.ChangeSet.Priority))
+ .ThenBy(party => party.Claims.Select(claim => claim.Mod.ChangeSet.ModId).Order(StringComparer.Ordinal).First(), StringComparer.Ordinal)
+ .ToList();
+ }
+
+ ///
+ /// A map vanilla ships a file for, though its tree lacks the record: a mod that adds only the record edits that
+ /// file in place, and a remap cannot rename vanilla's file.
+ ///
+ private static bool IsVanillaMapFile(IdKind kind, int id, BaseFileSet baseFiles)
+ {
+ return kind == IdKind.Map && baseFiles.Find(RpgDataSchema.MapKey(id)) is not null;
+ }
+
+ private static ModReferences ReferencesOf(RemapMod mod, Dictionary cache)
+ {
+ if (!cache.TryGetValue(mod.ChangeSet.ModId, out ModReferences? found))
+ {
+ found = ReferenceMap.Scan(mod.ChangeSet, mod.PluginScripts);
+ cache.Add(mod.ChangeSet.ModId, found);
+ }
+
+ return found;
+ }
+
+ private static List Sorted(IEnumerable remaps)
+ {
+ return remaps
+ .OrderBy(remap => remap.ModId, StringComparer.Ordinal)
+ .ThenBy(remap => remap.Kind)
+ .ThenBy(remap => remap.Scope, StringComparer.Ordinal)
+ .ThenBy(remap => remap.FromId)
+ .ThenBy(remap => remap.ToId)
+ .ToList();
+ }
+
+ /// One enabled mod's added id, at the id it has after its recorded entry.
+ private sealed record Claim(RemapMod Mod, AddedId Added, int Effective, bool Pinned, bool Deployed);
+
+ /// The mods of one clash that add equal content, so they keep or move together.
+ private sealed class Party
+ {
+ public Party(Claim first)
+ {
+ Claims = [first];
+ }
+
+ public List Claims { get; }
+
+ /// GR-R4: a recorded entry, then a mod in DeployedMods , then the rest.
+ public int Rank => Claims.Any(claim => claim.Pinned) ? 0 : Claims.Any(claim => claim.Deployed) ? 1 : 2;
+
+ public bool CanMove { get; private set; }
+
+ public bool IsUnchecked { get; private set; }
+
+ ///
+ /// A party moves only when no member is pinned, no member's id is fixed in vanilla's files and no member's
+ /// change set names the id where a remap cannot follow it (GR-R9). A number found only in a shipped plugin
+ /// file makes the move an offer (GR-R11).
+ ///
+ public void Classify(IdKind kind, Func referencesOf, Func isFixed)
+ {
+ bool pinned = Claims.Any(claim => claim.Pinned);
+ bool blocked = !pinned && Claims.Any(claim => isFixed(claim) || referencesOf(claim).Blocks(kind, claim.Added.Id));
+ IsUnchecked = !pinned && !blocked && Claims.Any(claim => referencesOf(claim).IsUnchecked(claim.Added.Id));
+ CanMove = !pinned && !blocked && !IsUnchecked;
+ }
+ }
+
+ /// GR-R5: the next free id per kind and scope, above vanilla, every installed mod and every entry.
+ private sealed class Targets
+ {
+ private readonly List _added;
+ private readonly IReadOnlyList _recorded;
+ private readonly BaseFileSet _baseFiles;
+ private readonly RpgMakerEngine? _engine;
+ private readonly Dictionary<(IdKind Kind, string Scope), int?> _next = new();
+
+ public Targets(List added, IReadOnlyList recorded, BaseFileSet baseFiles, RpgMakerEngine? engine)
+ {
+ _added = added;
+ _recorded = recorded;
+ _baseFiles = baseFiles;
+ _engine = engine;
+ }
+
+ public int? Take(IdKind kind, string scope)
+ {
+ if (!_next.TryGetValue((kind, scope), out int? next))
+ {
+ next = First(kind, scope);
+ }
+
+ // A vanilla map file outside the tree still owns its id.
+ while (next is not null && kind == IdKind.Map && _baseFiles.Find(RpgDataSchema.MapKey(next.Value)) is not null)
+ {
+ next++;
+ }
+
+ int? limit = RpgDataSchema.RemapLimit(kind, _engine);
+ if (next is null || limit is null || next > limit)
+ {
+ _next[(kind, scope)] = next;
+ return null;
+ }
+
+ _next[(kind, scope)] = next + 1;
+ return next;
+ }
+
+ private int? First(IdKind kind, string scope)
+ {
+ JArray? vanilla = VanillaList(kind, scope, _baseFiles);
+ if (vanilla is null)
+ {
+ return null;
+ }
+
+ int used = Math.Max(0, vanilla.Count - 1);
+ foreach (AddedId id in _added.Where(item => item.Kind == kind && item.Scope == scope))
+ {
+ used = Math.Max(used, id.Id);
+ }
+
+ foreach (IdRemap remap in _recorded.Where(item => item.Kind == kind && item.Scope == scope))
+ {
+ used = Math.Max(used, Math.Max(remap.FromId, remap.ToId));
+ }
+
+ return used + 1;
+ }
+ }
+}
diff --git a/RPGModder.Core/Merge/IdRemapper.cs b/RPGModder.Core/Merge/IdRemapper.cs
new file mode 100644
index 0000000..9e1dcc0
--- /dev/null
+++ b/RPGModder.Core/Merge/IdRemapper.cs
@@ -0,0 +1,91 @@
+using RPGModder.Core.Models;
+using RPGModder.Core.Operations;
+using System.Globalization;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The only code that changes an id (GR-K3, GR-R1). It runs after and before
+/// , one mod at a time, and returns a new change set.
+///
+public static class IdRemapper
+{
+ ///
+ /// Applies the entries of that name this mod and an id it still adds; the others are
+ /// inactive and change nothing (GR-R12). All moves of one mod apply in one pass, so an id moved onto another
+ /// moved id is not moved twice. Each applied entry adds rules.remap_applied (GR-R13). Step 1 applies the
+ /// and kinds and ignores the others.
+ ///
+ public static ModChangeSet Apply(ModChangeSet changeSet, IReadOnlyList remaps)
+ {
+ ArgumentNullException.ThrowIfNull(changeSet);
+ ArgumentNullException.ThrowIfNull(remaps);
+
+ if (!remaps.Any(remap => remap.ModId == changeSet.ModId))
+ {
+ return changeSet;
+ }
+
+ IReadOnlyList added = AddedIdIndex.Of(changeSet);
+ List active = remaps
+ .Where(remap => remap.ModId == changeSet.ModId && remap.Kind is IdKind.MapEvent or IdKind.Map && AddedIdIndex.IsActive(remap, added))
+ .Distinct()
+ .OrderBy(remap => remap.Kind)
+ .ThenBy(remap => remap.Scope, StringComparer.Ordinal)
+ .ThenBy(remap => remap.FromId)
+ .ToList();
+
+ var table = new RemapTable();
+ foreach (IdRemap remap in active)
+ {
+ Dictionary moves = remap.Kind == IdKind.Map ? table.Maps : EventMoves(table, remap.Scope);
+ if (remap.ToId <= 0 || moves.ContainsValue(remap.ToId) || !moves.TryAdd(remap.FromId, remap.ToId))
+ {
+ // The planner gives each old id one positive target of its own; anything else is a caller bug.
+ throw new ArgumentException(
+ $"The remaps for mod {changeSet.ModId} do not give {remap.Kind} {remap.FromId} a single target of its own.",
+ nameof(remaps));
+ }
+ }
+
+ if (table.IsEmpty)
+ {
+ return changeSet;
+ }
+
+ // A stable sort: two ops can share a place when a recorded move lands on an id the mod now adds too.
+ List ops = changeSet.Ops
+ .Select(op => ReferenceMap.Rewrite(op, table))
+ .OrderBy(op => op, Comparer.Create(ChangeSetBuilder.CompareOps))
+ .ToList();
+
+ var diagnostics = changeSet.Diagnostics.ToList();
+ diagnostics.AddRange(active.Select(remap => new OperationDiagnostic(
+ DiagnosticCodes.RulesRemapApplied,
+ Describe(remap),
+ DiagnosticSeverity.Info,
+ remap.ModId)));
+
+ return changeSet with { Ops = ops, Diagnostics = diagnostics };
+ }
+
+ /// The mod, kind, old id and new id GR-R13 asks for, with the map file of an event.
+ private static string Describe(IdRemap remap)
+ {
+ string where = remap.Kind == IdKind.MapEvent ? " in " + remap.Scope : "";
+ return string.Create(
+ CultureInfo.InvariantCulture,
+ $"Mod {remap.ModId}: {remap.Kind} {remap.FromId}{where} moved to {remap.ToId}.");
+ }
+
+ private static Dictionary EventMoves(RemapTable table, string scope)
+ {
+ if (!table.Events.TryGetValue(scope, out Dictionary? moves))
+ {
+ moves = new Dictionary();
+ table.Events.Add(scope, moves);
+ }
+
+ return moves;
+ }
+}
diff --git a/RPGModder.Core/Merge/MergeFileKind.cs b/RPGModder.Core/Merge/MergeFileKind.cs
new file mode 100644
index 0000000..5daf748
--- /dev/null
+++ b/RPGModder.Core/Merge/MergeFileKind.cs
@@ -0,0 +1,9 @@
+namespace RPGModder.Core.Merge;
+
+public enum MergeFileKind
+{
+ Data,
+ PluginList,
+ ConfigSave,
+ Opaque
+}
diff --git a/RPGModder.Core/Merge/MergeJson.cs b/RPGModder.Core/Merge/MergeJson.cs
new file mode 100644
index 0000000..a3f7dbc
--- /dev/null
+++ b/RPGModder.Core/Merge/MergeJson.cs
@@ -0,0 +1,92 @@
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using System.Security.Cryptography;
+using System.Text;
+using StrictJsonException = System.Text.Json.JsonException;
+using StrictReader = System.Text.Json.Utf8JsonReader;
+using StrictReaderOptions = System.Text.Json.JsonReaderOptions;
+using StrictTokenType = System.Text.Json.JsonTokenType;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The one reader and the one writer of game data inside the merge (GR-M7, seam 4.1). The reader accepts what the
+/// game's JSON.parse accepts and nothing more, so a file the engine reads is a file the game can load. A
+/// string that looks like a date stays a string.
+///
+internal static class MergeJson
+{
+ private const int MaxDepth = 128;
+ private const char ByteOrderMark = '';
+ private const byte LineFeed = (byte)'\n';
+
+ ///
+ /// Throws , with the line and position, when is not
+ /// exactly one strict JSON value: no comment, single quote, bare name, trailing comma, undefined ,
+ /// NaN , constructor, or number too large for a double.
+ ///
+ public static JToken Parse(string text)
+ {
+ if (text.Length > 0 && text[0] == ByteOrderMark)
+ {
+ text = text[1..];
+ }
+
+ Validate(text);
+
+ using var reader = new JsonTextReader(new StringReader(text))
+ {
+ DateParseHandling = DateParseHandling.None,
+ FloatParseHandling = FloatParseHandling.Double,
+ MaxDepth = MaxDepth
+ };
+
+ return JToken.ReadFrom(reader, new JsonLoadSettings { LineInfoHandling = LineInfoHandling.Ignore });
+ }
+
+ /// Compact text: no indentation, property order as held, so equal trees give equal bytes.
+ public static string Write(JToken token)
+ {
+ return token.ToString(Formatting.None);
+ }
+
+ public static string Sha256Hex(string text)
+ {
+ return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text)));
+ }
+
+ /// Newtonsoft repairs loose input, so a strict reader checks the text first.
+ private static void Validate(string text)
+ {
+ byte[] bytes = Encoding.UTF8.GetBytes(text);
+ var reader = new StrictReader(bytes, new StrictReaderOptions { MaxDepth = MaxDepth });
+ try
+ {
+ while (reader.Read())
+ {
+ if (reader.TokenType == StrictTokenType.Number &&
+ (!reader.TryGetDouble(out double number) || !double.IsFinite(number)))
+ {
+ throw Rejected("A number is too large for the game to read.", bytes, (int)reader.TokenStartIndex);
+ }
+ }
+ }
+ catch (StrictJsonException exception)
+ {
+ throw new JsonReaderException(
+ exception.Message,
+ "",
+ (int)(exception.LineNumber ?? 0) + 1,
+ (int)(exception.BytePositionInLine ?? 0) + 1,
+ exception);
+ }
+ }
+
+ private static JsonReaderException Rejected(string message, byte[] bytes, int byteIndex)
+ {
+ int lineStart = byteIndex == 0 ? 0 : Array.LastIndexOf(bytes, LineFeed, byteIndex - 1) + 1;
+ int line = bytes.AsSpan(0, lineStart).Count(LineFeed) + 1;
+ int position = Encoding.UTF8.GetCharCount(bytes, lineStart, byteIndex - lineStart) + 1;
+ return new JsonReaderException(message, "", line, position, null);
+ }
+}
diff --git a/RPGModder.Core/Merge/MergePath.cs b/RPGModder.Core/Merge/MergePath.cs
new file mode 100644
index 0000000..e9686b4
--- /dev/null
+++ b/RPGModder.Core/Merge/MergePath.cs
@@ -0,0 +1,254 @@
+using System.Globalization;
+using System.Text;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// File keys (GR-M2) and the leaf paths inside a record. A leaf path joins property names with . and
+/// writes indexes as [n] : pages[2].conditions.switch1Id . A property name that is not a plain
+/// identifier is written ['the name'] , so a path never reads two ways. The empty path is the record itself.
+///
+public static class MergePath
+{
+ ///
+ /// The order pseudo-leaf of a plugin record (seam 11.1): not a property of the entry but its place in the list.
+ /// A pseudo-leaf starts with @ , which never writes bare, so it cannot be mistaken
+ /// for a real property (a property named @after is written ['@after'] ).
+ ///
+ internal const string AfterLeaf = "@after";
+
+ ///
+ /// The place of an OrderAmbiguous collision among entries that more than one mod moves to the front of
+ /// the list (seam 11.1). No op carries it: it only names that collision apart from the one for new entries.
+ ///
+ internal const string FirstLeaf = "@first";
+
+ internal static bool IsPseudoLeaf(string path)
+ {
+ return path.Length > 0 && path[0] == '@';
+ }
+
+ /// Back slashes become forward slashes, a leading ./ or / is removed, the result is lower case.
+ public static string ToKey(string path)
+ {
+ ArgumentNullException.ThrowIfNull(path);
+
+ string key = path.Replace('\\', '/');
+ while (true)
+ {
+ if (key.StartsWith("./", StringComparison.Ordinal))
+ {
+ key = key[2..];
+ }
+ else if (key.StartsWith('/'))
+ {
+ key = key[1..];
+ }
+ else
+ {
+ break;
+ }
+ }
+
+ return key.ToLowerInvariant();
+ }
+
+ internal static string Child(string parent, string propertyName)
+ {
+ string segment = IsIdentifier(propertyName)
+ ? propertyName
+ : "['" + propertyName.Replace("\\", "\\\\").Replace("'", "\\'") + "']";
+
+ if (parent.Length == 0)
+ {
+ return segment;
+ }
+
+ return segment[0] == '[' ? parent + segment : parent + "." + segment;
+ }
+
+ internal static string Index(string parent, int index)
+ {
+ return parent + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
+ }
+
+ ///
+ /// Every path that contains , shortest first: the empty path, then each longer prefix,
+ /// without the path itself. A pseudo-leaf has none, so it never joins its record's cluster.
+ ///
+ internal static IEnumerable Ancestors(string path)
+ {
+ if (path.Length == 0 || IsPseudoLeaf(path))
+ {
+ yield break;
+ }
+
+ IReadOnlyList segments = Parse(path);
+ string prefix = "";
+ yield return prefix;
+ for (int index = 0; index < segments.Count - 1; index++)
+ {
+ prefix = Append(prefix, segments[index]);
+ yield return prefix;
+ }
+ }
+
+ /// The path with every index replaced by [*] , the form keys its policies by.
+ internal static string Pattern(string path)
+ {
+ var builder = new StringBuilder();
+ foreach (PathSegment segment in Parse(path))
+ {
+ if (segment.Name is null)
+ {
+ builder.Append("[*]");
+ }
+ else
+ {
+ builder.Append(builder.Length == 0 ? "" : ".").Append(segment.Name);
+ }
+ }
+
+ return builder.ToString();
+ }
+
+ /// Reads a path written by and . Throws for anything else.
+ internal static IReadOnlyList Parse(string path)
+ {
+ var segments = new List();
+ int position = 0;
+ while (position < path.Length)
+ {
+ char current = path[position];
+ if (current == '[' && position + 1 < path.Length && path[position + 1] == '\'')
+ {
+ position = ReadQuotedName(path, position + 2, segments);
+ }
+ else if (current == '[')
+ {
+ position = ReadIndex(path, position + 1, segments);
+ }
+ else
+ {
+ if (segments.Count > 0)
+ {
+ if (current != '.')
+ {
+ throw new FormatException($"Unexpected character in leaf path: {path}");
+ }
+
+ position++;
+ }
+
+ position = ReadIdentifier(path, position, segments);
+ }
+ }
+
+ return segments;
+ }
+
+ internal static string Format(IEnumerable segments)
+ {
+ string path = "";
+ foreach (PathSegment segment in segments)
+ {
+ path = Append(path, segment);
+ }
+
+ return path;
+ }
+
+ private static string Append(string parent, PathSegment segment)
+ {
+ return segment.Name is null ? Index(parent, segment.Index) : Child(parent, segment.Name);
+ }
+
+ private static int ReadQuotedName(string path, int position, List segments)
+ {
+ var name = new StringBuilder();
+ while (position < path.Length)
+ {
+ char current = path[position];
+ if (current == '\\' && position + 1 < path.Length)
+ {
+ name.Append(path[position + 1]);
+ position += 2;
+ }
+ else if (current == '\'' && position + 1 < path.Length && path[position + 1] == ']')
+ {
+ segments.Add(PathSegment.Property(name.ToString()));
+ return position + 2;
+ }
+ else
+ {
+ name.Append(current);
+ position++;
+ }
+ }
+
+ throw new FormatException($"Unterminated name in leaf path: {path}");
+ }
+
+ private static int ReadIndex(string path, int position, List segments)
+ {
+ int end = path.IndexOf(']', position);
+ if (end < 0 ||
+ !int.TryParse(path.AsSpan(position, end - position), NumberStyles.None, CultureInfo.InvariantCulture, out int index))
+ {
+ throw new FormatException($"Bad index in leaf path: {path}");
+ }
+
+ segments.Add(PathSegment.At(index));
+ return end + 1;
+ }
+
+ private static int ReadIdentifier(string path, int position, List segments)
+ {
+ int start = position;
+ while (position < path.Length && path[position] is not ('.' or '['))
+ {
+ position++;
+ }
+
+ string name = path[start..position];
+ if (!IsIdentifier(name))
+ {
+ throw new FormatException($"Bad property name in leaf path: {path}");
+ }
+
+ segments.Add(PathSegment.Property(name));
+ return position;
+ }
+
+ private static bool IsIdentifier(string name)
+ {
+ if (name.Length == 0 || !(char.IsAsciiLetter(name[0]) || name[0] is '_' or '$'))
+ {
+ return false;
+ }
+
+ foreach (char current in name)
+ {
+ if (!(char.IsAsciiLetterOrDigit(current) || current is '_' or '$'))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+}
+
+/// One step of a leaf path: a property name, or an array index when Name is null .
+internal readonly record struct PathSegment(string? Name, int Index)
+{
+ public static PathSegment Property(string name)
+ {
+ return new PathSegment(name, -1);
+ }
+
+ public static PathSegment At(int index)
+ {
+ return new PathSegment(null, index);
+ }
+}
diff --git a/RPGModder.Core/Merge/MergePlan.cs b/RPGModder.Core/Merge/MergePlan.cs
new file mode 100644
index 0000000..49acc92
--- /dev/null
+++ b/RPGModder.Core/Merge/MergePlan.cs
@@ -0,0 +1,15 @@
+using RPGModder.Core.Models;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The result of . Ops is sorted by file, record and path; Collisions
+/// by id; Outcomes follows Collisions . MergeHash covers Ops and Outcomes .
+///
+public sealed record MergePlan(
+ IReadOnlyList Ops,
+ IReadOnlyList Collisions,
+ IReadOnlyList Outcomes,
+ IReadOnlyList Diagnostics,
+ bool IsDeployable,
+ string MergeHash);
diff --git a/RPGModder.Core/Merge/MergedFile.cs b/RPGModder.Core/Merge/MergedFile.cs
new file mode 100644
index 0000000..b46f5f5
--- /dev/null
+++ b/RPGModder.Core/Merge/MergedFile.cs
@@ -0,0 +1,14 @@
+namespace RPGModder.Core.Merge;
+
+///
+/// One file a deploy writes. Text is written as UTF-8 without a byte order mark; ModFile means copy
+/// SourceFile of mod ModId . DiskPath is set only for a name the engine generates (from 2r).
+///
+public sealed record MergedFile(
+ string File,
+ MergedFileSource Source,
+ string? Text,
+ string? ModId,
+ string? SourceFile,
+ IReadOnlyList ModIds,
+ string? DiskPath = null);
diff --git a/RPGModder.Core/Merge/MergedFileSource.cs b/RPGModder.Core/Merge/MergedFileSource.cs
new file mode 100644
index 0000000..f53741a
--- /dev/null
+++ b/RPGModder.Core/Merge/MergedFileSource.cs
@@ -0,0 +1,7 @@
+namespace RPGModder.Core.Merge;
+
+public enum MergedFileSource
+{
+ Text,
+ ModFile
+}
diff --git a/RPGModder.Core/Merge/MergedFileWriter.cs b/RPGModder.Core/Merge/MergedFileWriter.cs
new file mode 100644
index 0000000..fa94258
--- /dev/null
+++ b/RPGModder.Core/Merge/MergedFileWriter.cs
@@ -0,0 +1,479 @@
+using Newtonsoft.Json.Linq;
+using RPGModder.Core.Models;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// Renders a deployable plan into the files a deploy writes. Only touched files are listed; every other file
+/// stays vanilla and is copied by lane A (GR-M6). Every touched data file goes through one serializer (GR-M7);
+/// a whole file a mod supplies unchanged is listed as a copy of the mod's file.
+///
+public static class MergedFileWriter
+{
+ public static IReadOnlyList Write(MergePlan plan, BaseFileSet baseFiles, int? systemVersionId)
+ {
+ ArgumentNullException.ThrowIfNull(plan);
+ ArgumentNullException.ThrowIfNull(baseFiles);
+
+ if (!plan.IsDeployable)
+ {
+ throw new InvalidOperationException("Only a deployable plan can be written.");
+ }
+
+ var files = new SortedDictionary>(StringComparer.Ordinal);
+ foreach (MergedOp merged in plan.Ops)
+ {
+ if (!files.TryGetValue(merged.Op.Key.File, out List? fileOps))
+ {
+ fileOps = new List();
+ files.Add(merged.Op.Key.File, fileOps);
+ }
+
+ fileOps.Add(merged);
+ }
+
+ if (systemVersionId is not null)
+ {
+ if (baseFiles.Find(RpgDataSchema.SystemFileKey) is null)
+ {
+ throw new ArgumentException("A versionId needs data/System.json among the base files.", nameof(baseFiles));
+ }
+
+ files.TryAdd(RpgDataSchema.SystemFileKey, new List());
+ }
+
+ var result = new List();
+ foreach ((string file, List fileOps) in files)
+ {
+ List modIds = fileOps
+ .SelectMany(merged => merged.ModIds)
+ .Distinct()
+ .OrderBy(id => id, StringComparer.Ordinal)
+ .ToList();
+
+ result.Add(RpgDataSchema.KindOf(file) switch
+ {
+ MergeFileKind.Opaque => Copy(file, fileOps, modIds),
+ MergeFileKind.PluginList => new MergedFile(file, MergedFileSource.Text, RenderPluginList(file, fileOps, baseFiles), null, null, modIds),
+ MergeFileKind.ConfigSave => new MergedFile(file, MergedFileSource.Text, RenderConfigSave(file, fileOps, baseFiles), null, null, modIds),
+ _ => WriteDataFile(file, fileOps, baseFiles, systemVersionId, modIds)
+ });
+ }
+
+ return result;
+ }
+
+ private static MergedFile WriteDataFile(string file, List fileOps, BaseFileSet baseFiles, int? systemVersionId, List modIds)
+ {
+ BaseFile? baseFile = baseFiles.Find(file);
+ if (baseFile is null)
+ {
+ // GR-M9: a new file is one AddRecord on *, copied as the mod shipped it unless a patch or a remap changed
+ // it. Written as text, it names its mod so lane A takes the casing of that mod's file (seam 4.2 step 2);
+ // a map gets the casing the game loads instead (step 0), because a remapped one has no mod file name.
+ ChangeOp added = SingleOp(fileOps, ChangeKind.AddRecord);
+ return added.SourceFile is null
+ ? new MergedFile(file, MergedFileSource.Text, MergeJson.Write(Value(added)), added.ModId, null, modIds, RpgDataSchema.DiskPathOf(file))
+ : new MergedFile(file, MergedFileSource.ModFile, null, added.ModId, added.SourceFile, modIds);
+ }
+
+ JToken root = Render(file, baseFile, fileOps);
+ if (file == RpgDataSchema.SystemFileKey && systemVersionId is not null)
+ {
+ SetVersionId(root, systemVersionId.Value);
+ }
+
+ return new MergedFile(file, MergedFileSource.Text, MergeJson.Write(root), null, null, modIds);
+ }
+
+ /// A replaced opaque file is the bytes of the mod whose id sorts first among those that ship them.
+ private static MergedFile Copy(string file, List fileOps, List modIds)
+ {
+ ChangeOp replaced = SingleOp(fileOps, ChangeKind.ReplaceFile);
+ return new MergedFile(
+ file,
+ MergedFileSource.ModFile,
+ null,
+ replaced.ModId,
+ replaced.SourceFile ?? throw new InvalidOperationException($"The ReplaceFile op for {file} names no source file."),
+ modIds);
+ }
+
+ private static ChangeOp SingleOp(List fileOps, ChangeKind kind)
+ {
+ if (fileOps.Count != 1 || fileOps[0].Op.Kind != kind || !fileOps[0].Op.Key.IsWholeFile || fileOps[0].Op.Path.Length != 0)
+ {
+ throw new InvalidOperationException($"{fileOps[0].Op.Key.File} needs exactly one whole-file {kind} op.");
+ }
+
+ return fileOps[0].Op;
+ }
+
+ private static JToken Render(string file, BaseFile baseFile, List fileOps)
+ {
+ JToken root = MergeJson.Parse(baseFile.Text
+ ?? throw new ArgumentException($"The base file {file} has no text.", nameof(baseFile)));
+
+ var removals = new List();
+ foreach (MergedOp merged in fileOps)
+ {
+ ChangeOp op = merged.Op;
+ if (op.Kind is ChangeKind.RemoveLeaf or ChangeKind.RemoveRecord)
+ {
+ removals.Add(op);
+ }
+ else if (op.Key.IsWholeFile && op.Path.Length == 0)
+ {
+ root = Value(op);
+ }
+ else
+ {
+ Set(root, op);
+ }
+ }
+
+ // Removals run last and from the highest index down, so an index still names the element it named in vanilla.
+ removals.Sort(CompareDescending);
+ var removedRecords = new Dictionary>(ReferenceEqualityComparer.Instance);
+ foreach (ChangeOp op in removals)
+ {
+ if (op.Kind == ChangeKind.RemoveRecord)
+ {
+ RemoveRecord(root, op, removedRecords);
+ }
+ else
+ {
+ RemoveLeaf(RecordOf(root, op.Key), op);
+ }
+ }
+
+ // Removed records at the end of their list are cut off, as the editor does: database files and map events.
+ foreach ((JArray records, HashSet removed) in removedRecords)
+ {
+ while (records.Count > 0 && removed.Contains(records.Count - 1))
+ {
+ records.RemoveAt(records.Count - 1);
+ }
+ }
+
+ return root;
+ }
+
+ ///
+ /// Vanilla's list with the ops applied: leaf edits in place, removals, new entries, then every entry with an
+ /// @after placed by . Prefix and suffix are vanilla's (seam 11.1).
+ ///
+ private static string RenderPluginList(string file, List fileOps, BaseFileSet baseFiles)
+ {
+ PluginListText? vanilla = PluginListText.Empty();
+ BaseFile? baseFile = baseFiles.Find(file);
+ if (baseFile is not null && !PluginListText.TryParse(baseFile.Text, out vanilla, out string? error))
+ {
+ throw new ArgumentException($"The base file {file} cannot be read: {error}.", nameof(baseFiles));
+ }
+
+ if (fileOps.FirstOrDefault(merged => merged.Op.Key.IsWholeFile) is { } whole)
+ {
+ // A whole list clusters with every other op of the file, so nothing else survives beside it.
+ return (vanilla with { Entries = Value(whole.Op) as JArray ?? throw Misfit(whole.Op) }).Render();
+ }
+
+ var order = new List();
+ var entries = new Dictionary(StringComparer.Ordinal);
+ foreach (JToken element in vanilla.Entries)
+ {
+ string name = (element is JObject entry ? PluginListDiff.NameOf(entry) : null)
+ ?? throw new InvalidOperationException($"{file} has an entry without a name, so only whole-list ops fit it.");
+ if (!entries.TryAdd(name, (JObject)element.DeepClone()))
+ {
+ throw new InvalidOperationException($"{file} names {name} twice, so only whole-list ops fit it.");
+ }
+
+ order.Add(name);
+ }
+
+ var added = new HashSet(StringComparer.Ordinal);
+ var anchors = new Dictionary(StringComparer.Ordinal);
+ foreach (MergedOp merged in fileOps)
+ {
+ ChangeOp op = merged.Op;
+ if (!RecordKey.TryGetPlugin(op.Key.Record, out string name))
+ {
+ throw Misfit(op);
+ }
+
+ if (op.Kind == ChangeKind.AddRecord)
+ {
+ entries[name] = Value(op) as JObject ?? throw Misfit(op);
+ added.Add(name);
+ }
+ else if (op.Kind == ChangeKind.RemoveRecord)
+ {
+ entries.Remove(name);
+ }
+ else if (op.Path == MergePath.AfterLeaf)
+ {
+ anchors[name] = Value(op).Type == JTokenType.String ? Value(op).Value() : null;
+ }
+ else if (!entries.TryGetValue(name, out JObject? entry))
+ {
+ throw Misfit(op);
+ }
+ else if (op.Kind == ChangeKind.SetLeaf)
+ {
+ IReadOnlyList segments = MergePath.Parse(op.Path);
+ Put(Find(entry, segments, op), segments[^1], Value(op));
+ }
+ else if (op.Kind == ChangeKind.RemoveLeaf)
+ {
+ RemoveLeaf(entry, op);
+ }
+ else
+ {
+ throw Misfit(op);
+ }
+ }
+
+ // An anchor for an entry that is gone (removed by one mod, moved by another) has nothing to place.
+ var present = new HashSet(entries.Keys, StringComparer.Ordinal);
+ Dictionary live = anchors.Where(pair => present.Contains(pair.Key)).ToDictionary(StringComparer.Ordinal);
+ var list = new JArray();
+ foreach (string name in PluginPlacement.Place(order, present, added, live))
+ {
+ list.Add(entries[name]);
+ }
+
+ return (vanilla with { Entries = list }).Render();
+ }
+
+ /// GR-M10: the live save (or {} ) with each top-level value set, encoded as the game reads it.
+ private static string RenderConfigSave(string file, List fileOps, BaseFileSet baseFiles)
+ {
+ if (!ChangeSetBuilder.TryReadConfigBase(baseFiles.Find(file), file, out JObject? live, out OperationDiagnostic? problem))
+ {
+ throw new ArgumentException(problem.Message, nameof(baseFiles));
+ }
+
+ foreach (MergedOp merged in fileOps)
+ {
+ if (merged.Op.Kind != ChangeKind.SetLeaf || !merged.Op.Key.IsWholeFile)
+ {
+ throw Misfit(merged.Op);
+ }
+
+ Set(live, merged.Op);
+ }
+
+ return ConfigSaveText.Encode(file, live);
+ }
+
+ private static void Set(JToken root, ChangeOp op)
+ {
+ IReadOnlyList segments = MergePath.Parse(op.Path);
+ if (segments.Count == 0)
+ {
+ // A whole record: AddRecord, or a record that is not an object.
+ (JArray records, int index) = SlotOf(root, op.Key);
+ Put(records, PathSegment.At(index), Value(op));
+ return;
+ }
+
+ JToken container = Find(RecordOf(root, op.Key), segments, op);
+ Put(container, segments[^1], Value(op));
+ }
+
+ private static void RemoveRecord(JToken root, ChangeOp op, Dictionary> removedRecords)
+ {
+ _ = RecordOf(root, op.Key);
+ (JArray records, int index) = SlotOf(root, op.Key);
+ records[index] = JValue.CreateNull();
+ if (!removedRecords.TryGetValue(records, out HashSet? removed))
+ {
+ removed = new HashSet();
+ removedRecords.Add(records, removed);
+ }
+
+ removed.Add(index);
+ }
+
+ private static void RemoveLeaf(JToken record, ChangeOp op)
+ {
+ IReadOnlyList segments = MergePath.Parse(op.Path);
+ if (segments.Count == 0)
+ {
+ throw Misfit(op);
+ }
+
+ JToken container = Find(record, segments, op);
+ PathSegment last = segments[^1];
+ if (container is JObject parent && last.Name is not null && parent.Remove(last.Name))
+ {
+ return;
+ }
+
+ if (container is JArray array && last.Name is null && last.Index < array.Count)
+ {
+ // Cutting the tail keeps the list short, as the mod left it; a hole in the middle keeps later indexes.
+ if (last.Index == array.Count - 1)
+ {
+ array.RemoveAt(last.Index);
+ }
+ else
+ {
+ array[last.Index] = JValue.CreateNull();
+ }
+
+ return;
+ }
+
+ throw Misfit(op);
+ }
+
+ /// The container of the last segment. Every step must exist: the walker only names places vanilla has.
+ private static JToken Find(JToken record, IReadOnlyList segments, ChangeOp op)
+ {
+ JToken container = record;
+ for (int index = 0; index < segments.Count - 1; index++)
+ {
+ container = Get(container, segments[index]) ?? throw Misfit(op);
+ }
+
+ return container;
+ }
+
+ private static void SetVersionId(JToken root, int versionId)
+ {
+ if (root is not JObject system)
+ {
+ throw new InvalidOperationException("data/System.json has no object root to carry a versionId.");
+ }
+
+ Put(system, PathSegment.Property(RpgDataSchema.VersionIdField), new JValue(versionId));
+ }
+
+ private static JToken RecordOf(JToken root, RecordKey key)
+ {
+ if (key.IsWholeFile)
+ {
+ return root;
+ }
+
+ (JArray records, int index) = SlotOf(root, key);
+ return index < records.Count && records[index].Type != JTokenType.Null
+ ? records[index]
+ : throw new InvalidOperationException($"{key.File} has no record {key.Record}.");
+ }
+
+ /// The list that holds a record and its index there: the root for id: , a map's events for event: .
+ private static (JArray Records, int Index) SlotOf(JToken root, RecordKey key)
+ {
+ if (RecordKey.TryGetIndex(key.Record, out int index))
+ {
+ return (root as JArray ?? throw new InvalidOperationException($"A record op on {key.File} needs a file whose root is an array."), index);
+ }
+
+ if (RecordKey.TryGetEvent(key.Record, out index))
+ {
+ return (root[RpgDataSchema.EventsProperty] as JArray
+ ?? throw new InvalidOperationException($"An event op on {key.File} needs a map with an events list."), index);
+ }
+
+ throw new InvalidOperationException($"{key.Record} is not a record of {key.File}.");
+ }
+
+ private static InvalidOperationException Misfit(ChangeOp op)
+ {
+ return new InvalidOperationException($"The {op.Kind} op at {op.Key.File} {op.Key.Record} {op.Path} does not fit the file.");
+ }
+
+ private static JToken? Get(JToken container, PathSegment segment)
+ {
+ if (segment.Name is not null)
+ {
+ return container is JObject parent ? parent.Property(segment.Name, StringComparison.Ordinal)?.Value : null;
+ }
+
+ return container is JArray array && segment.Index < array.Count ? array[segment.Index] : null;
+ }
+
+ /// An existing property keeps its place; a new one goes at the end (GR-M7). An index past the end pads with null .
+ private static void Put(JToken container, PathSegment segment, JToken value)
+ {
+ if (segment.Name is not null && container is JObject parent)
+ {
+ JProperty? existing = parent.Property(segment.Name, StringComparison.Ordinal);
+ if (existing is null)
+ {
+ parent.Add(segment.Name, value);
+ }
+ else
+ {
+ existing.Value = value;
+ }
+
+ return;
+ }
+
+ if (segment.Name is null && container is JArray array)
+ {
+ while (array.Count <= segment.Index)
+ {
+ array.Add(JValue.CreateNull());
+ }
+
+ array[segment.Index] = value;
+ return;
+ }
+
+ throw new InvalidOperationException("A merged value does not fit the shape of its file.");
+ }
+
+ /// A copy of the op's value. A JSON null is a value; only a missing one (the remove kinds) throws.
+ private static JToken Value(ChangeOp op)
+ {
+ return op.Value?.DeepClone() ?? throw new InvalidOperationException($"A {op.Kind} op carries no value.");
+ }
+
+ private static int CompareDescending(ChangeOp left, ChangeOp right)
+ {
+ int result = CompareRecords(right.Key.Record, left.Key.Record);
+ if (result != 0)
+ {
+ return result;
+ }
+
+ IReadOnlyList leftSegments = MergePath.Parse(left.Path);
+ IReadOnlyList rightSegments = MergePath.Parse(right.Path);
+ for (int index = 0; index < Math.Min(leftSegments.Count, rightSegments.Count); index++)
+ {
+ result = CompareSegments(rightSegments[index], leftSegments[index]);
+ if (result != 0)
+ {
+ return result;
+ }
+ }
+
+ return rightSegments.Count.CompareTo(leftSegments.Count);
+ }
+
+ private static int CompareRecords(string left, string right)
+ {
+ if ((RecordKey.TryGetIndex(left, out int leftIndex) && RecordKey.TryGetIndex(right, out int rightIndex)) ||
+ (RecordKey.TryGetEvent(left, out leftIndex) && RecordKey.TryGetEvent(right, out rightIndex)))
+ {
+ return leftIndex.CompareTo(rightIndex);
+ }
+
+ return string.CompareOrdinal(left, right);
+ }
+
+ private static int CompareSegments(PathSegment left, PathSegment right)
+ {
+ if (left.Name is null && right.Name is null)
+ {
+ return left.Index.CompareTo(right.Index);
+ }
+
+ return string.CompareOrdinal(left.Name ?? "", right.Name ?? "");
+ }
+}
diff --git a/RPGModder.Core/Merge/MergedOp.cs b/RPGModder.Core/Merge/MergedOp.cs
new file mode 100644
index 0000000..70c7288
--- /dev/null
+++ b/RPGModder.Core/Merge/MergedOp.cs
@@ -0,0 +1,9 @@
+namespace RPGModder.Core.Merge;
+
+///
+/// An op that survives composition. Op is the contribution of the mod whose id sorts first;
+/// ModIds lists every mod that contributed an equal op, sorted (GR-C8).
+///
+public sealed record MergedOp(
+ ChangeOp Op,
+ IReadOnlyList ModIds);
diff --git a/RPGModder.Core/Merge/ModChangeSet.cs b/RPGModder.Core/Merge/ModChangeSet.cs
new file mode 100644
index 0000000..925836d
--- /dev/null
+++ b/RPGModder.Core/Merge/ModChangeSet.cs
@@ -0,0 +1,9 @@
+using RPGModder.Core.Models;
+
+namespace RPGModder.Core.Merge;
+
+public sealed record ModChangeSet(
+ string ModId,
+ int Priority,
+ IReadOnlyList Ops,
+ IReadOnlyList Diagnostics);
diff --git a/RPGModder.Core/Merge/ModChangeSetSerializer.cs b/RPGModder.Core/Merge/ModChangeSetSerializer.cs
new file mode 100644
index 0000000..bb2f575
--- /dev/null
+++ b/RPGModder.Core/Merge/ModChangeSetSerializer.cs
@@ -0,0 +1,262 @@
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using RPGModder.Core.Models;
+using System.Diagnostics.CodeAnalysis;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The stable text form of a change set for lane A's cache (GR-M11). The text holds no priority, because the
+/// priority belongs to the profile; takes the current one.
+///
+public static class ModChangeSetSerializer
+{
+ public static string Serialize(ModChangeSet changeSet)
+ {
+ ArgumentNullException.ThrowIfNull(changeSet);
+
+ var ops = new JArray();
+ foreach (ChangeOp op in changeSet.Ops)
+ {
+ var entry = new JObject
+ {
+ ["file"] = op.Key.File,
+ ["record"] = op.Key.Record,
+ ["path"] = op.Path,
+ ["kind"] = op.Kind.ToString()
+ };
+
+ // An absent "value" is a C# null (the remove kinds); a JSON null leaf is written as null.
+ if (op.Value is not null)
+ {
+ entry["value"] = op.Value.DeepClone();
+ }
+
+ if (op.SourceFile is not null)
+ {
+ entry["source"] = op.SourceFile;
+ }
+
+ ops.Add(entry);
+ }
+
+ var diagnostics = new JArray();
+ foreach (OperationDiagnostic diagnostic in changeSet.Diagnostics)
+ {
+ var entry = new JObject
+ {
+ ["code"] = diagnostic.Code,
+ ["message"] = diagnostic.Message,
+ ["severity"] = diagnostic.Severity.ToString()
+ };
+
+ if (diagnostic.Subject is not null)
+ {
+ entry["subject"] = diagnostic.Subject;
+ }
+
+ diagnostics.Add(entry);
+ }
+
+ var root = new JObject
+ {
+ ["schema"] = RpgDataSchema.SchemaVersion,
+ ["mod"] = changeSet.ModId,
+ ["ops"] = ops,
+ ["diagnostics"] = diagnostics
+ };
+
+ return MergeJson.Write(root);
+ }
+
+ ///
+ /// Returns null for malformed text, for text written under another ,
+ /// and for any op could not have written, so a damaged cache is rebuilt, not deployed.
+ ///
+ public static ModChangeSet? Deserialize(string text, int priority)
+ {
+ if (string.IsNullOrEmpty(text))
+ {
+ return null;
+ }
+
+ try
+ {
+ return Read(MergeJson.Parse(text), priority);
+ }
+ catch (JsonException)
+ {
+ // The cache is a speed-up only: unreadable text means "rebuild", which the null return tells lane A.
+ return null;
+ }
+ }
+
+ private static ModChangeSet? Read(JToken token, int priority)
+ {
+ if (token is not JObject root ||
+ root["schema"] is not JValue { Type: JTokenType.Integer, Value: long schema } ||
+ schema != RpgDataSchema.SchemaVersion ||
+ !TryString(root["mod"], out string? modId) ||
+ root["ops"] is not JArray opsArray ||
+ root["diagnostics"] is not JArray diagnosticsArray)
+ {
+ return null;
+ }
+
+ var ops = new List();
+ foreach (JToken item in opsArray)
+ {
+ ChangeOp? op = ReadOp(item, modId);
+ if (op is null)
+ {
+ return null;
+ }
+
+ ops.Add(op);
+ }
+
+ var diagnostics = new List();
+ foreach (JToken item in diagnosticsArray)
+ {
+ if (item is not JObject entry ||
+ !TryString(entry["code"], out string? code) ||
+ !TryString(entry["message"], out string? message) ||
+ !TryEnum(entry["severity"], out DiagnosticSeverity severity) ||
+ !TryOptionalString(entry, "subject", out string? subject))
+ {
+ return null;
+ }
+
+ diagnostics.Add(new OperationDiagnostic(code, message, severity, subject));
+ }
+
+ return new ModChangeSet(modId, priority, ops, diagnostics);
+ }
+
+ private static ChangeOp? ReadOp(JToken item, string modId)
+ {
+ if (item is not JObject entry ||
+ !TryString(entry["file"], out string? file) ||
+ !TryString(entry["record"], out string? record) ||
+ !TryString(entry["path"], out string? path) ||
+ !TryEnum(entry["kind"], out ChangeKind kind) ||
+ !TryOptionalString(entry, "source", out string? source))
+ {
+ return null;
+ }
+
+ JToken? value = entry.TryGetValue("value", StringComparison.Ordinal, out JToken? stored) ? stored.DeepClone() : null;
+ var op = new ChangeOp(modId, new RecordKey(file, record), path, kind, value, source);
+ return IsWellFormed(op) ? op : null;
+ }
+
+ ///
+ /// The shapes the builder writes: a canonical file key and path, a record form the file's family uses, and a
+ /// kind and value that fit both (seam 11.1).
+ ///
+ private static bool IsWellFormed(ChangeOp op)
+ {
+ if (MergePath.ToKey(op.Key.File) != op.Key.File)
+ {
+ return false;
+ }
+
+ MergeFileKind family = RpgDataSchema.KindOf(op.Key.File);
+ bool whole = op.Key.IsWholeFile;
+ bool isPlugin = RecordKey.TryGetPlugin(op.Key.Record, out _);
+ bool isRecord = family switch
+ {
+ MergeFileKind.Data when RpgDataSchema.IsMapFile(op.Key.File) => RecordKey.TryGetEvent(op.Key.Record, out _),
+ MergeFileKind.Data => RecordKey.TryGetIndex(op.Key.Record, out _),
+ MergeFileKind.PluginList => isPlugin,
+ _ => false
+ };
+
+ if (!isRecord && !whole)
+ {
+ return false;
+ }
+
+ if (op.Path == MergePath.AfterLeaf)
+ {
+ // The order pseudo-leaf: only on a plugin entry, naming the entry before it or nothing.
+ return isPlugin && op.Kind == ChangeKind.SetLeaf && op.Value?.Type is JTokenType.String or JTokenType.Null;
+ }
+
+ if (!IsCanonicalPath(op.Path))
+ {
+ return false;
+ }
+
+ bool wholePlace = op.Path.Length == 0;
+ return family switch
+ {
+ MergeFileKind.Opaque =>
+ op.Kind == ChangeKind.ReplaceFile && wholePlace && op.Value?.Type == JTokenType.String && op.SourceFile is not null,
+
+ // One value per top-level key of the config object.
+ MergeFileKind.ConfigSave => op.Kind == ChangeKind.SetLeaf && op.Value is not null && MergePath.Parse(op.Path).Count == 1,
+
+ // The whole list as one value on *, or an entry's own record ops.
+ MergeFileKind.PluginList when whole => op.Kind == ChangeKind.SetLeaf && wholePlace && op.Value is JArray,
+ MergeFileKind.PluginList => op.Kind switch
+ {
+ ChangeKind.AddRecord => wholePlace && op.Value is JObject,
+ ChangeKind.RemoveRecord => wholePlace && op.Value is null,
+ ChangeKind.SetLeaf => !wholePlace && op.Value is not null,
+ ChangeKind.RemoveLeaf => !wholePlace && op.Value is null,
+ _ => false
+ },
+
+ _ => op.Kind switch
+ {
+ // A whole file with no vanilla counterpart is an AddRecord on * (GR-M9).
+ ChangeKind.AddRecord => wholePlace && op.Value is not null,
+ ChangeKind.RemoveRecord => isRecord && wholePlace && op.Value is null,
+ ChangeKind.RemoveLeaf => !wholePlace && op.Value is null,
+ ChangeKind.SetLeaf => op.Value is not null,
+ ChangeKind.EditSequence or ChangeKind.EditCommands => !wholePlace && op.Value is JArray,
+ _ => false
+ }
+ };
+ }
+
+ private static bool IsCanonicalPath(string path)
+ {
+ try
+ {
+ return MergePath.Format(MergePath.Parse(path)) == path;
+ }
+ catch (FormatException)
+ {
+ return false;
+ }
+ }
+
+ private static bool TryString(JToken? token, [NotNullWhen(true)] out string? value)
+ {
+ value = token is JValue { Type: JTokenType.String } text ? text.Value() : null;
+ return value is not null;
+ }
+
+ private static bool TryOptionalString(JObject entry, string name, out string? value)
+ {
+ value = null;
+ if (!entry.TryGetValue(name, StringComparison.Ordinal, out JToken? token) || token.Type == JTokenType.Null)
+ {
+ return true;
+ }
+
+ return TryString(token, out value);
+ }
+
+ /// Only a member's exact name: no number, no comma list of flags, no spaces, no other case.
+ private static bool TryEnum(JToken? token, out TEnum value)
+ where TEnum : struct, Enum
+ {
+ value = default;
+ return TryString(token, out string? text) &&
+ Enum.GetNames().Contains(text, StringComparer.Ordinal) &&
+ Enum.TryParse(text, ignoreCase: false, out value);
+ }
+}
diff --git a/RPGModder.Core/Merge/ModFile.cs b/RPGModder.Core/Merge/ModFile.cs
new file mode 100644
index 0000000..4ce0548
--- /dev/null
+++ b/RPGModder.Core/Merge/ModFile.cs
@@ -0,0 +1,8 @@
+namespace RPGModder.Core.Merge;
+
+/// One file_ops entry. Source is returned untouched so the caller can copy the file.
+public sealed record ModFile(
+ string Target,
+ string Source,
+ string? Text,
+ string Sha256);
diff --git a/RPGModder.Core/Merge/ModPatch.cs b/RPGModder.Core/Merge/ModPatch.cs
new file mode 100644
index 0000000..aa94646
--- /dev/null
+++ b/RPGModder.Core/Merge/ModPatch.cs
@@ -0,0 +1,8 @@
+using Newtonsoft.Json.Linq;
+
+namespace RPGModder.Core.Merge;
+
+/// One json_patches entry.
+public sealed record ModPatch(
+ string Target,
+ JObject MergeData);
diff --git a/RPGModder.Core/Merge/ModReferences.cs b/RPGModder.Core/Merge/ModReferences.cs
new file mode 100644
index 0000000..f432a32
--- /dev/null
+++ b/RPGModder.Core/Merge/ModReferences.cs
@@ -0,0 +1,40 @@
+namespace RPGModder.Core.Merge;
+
+/// What found in one mod: the numbers a remap cannot rewrite.
+internal sealed class ModReferences
+{
+ /// Whole numbers in the change set's free text (GR-R9).
+ public HashSet FreeTextNumbers { get; } = new();
+
+ /// Event ids named by event commands in a common event or a troop, which act on any map (3.11).
+ public HashSet AmbiguousEventIds { get; } = new();
+
+ /// Constants Control Variables assigns; with a transfer by variable, one of them may be a map id.
+ public HashSet VariableConstants { get; } = new();
+
+ /// Whole numbers in the plugin files the mod ships (GR-R11).
+ public HashSet PluginScriptNumbers { get; } = new();
+
+ ///
+ /// True when the mod sends the player or a vehicle to a map named by a variable (201 with p[0] 1, 202 with
+ /// p[1] 1).
+ ///
+ public bool UsesVariableTransfer { get; set; }
+
+ /// True when the change set refers to where a remap cannot follow it (GR-R9).
+ public bool Blocks(IdKind kind, int id)
+ {
+ return FreeTextNumbers.Contains(id) || kind switch
+ {
+ IdKind.MapEvent => AmbiguousEventIds.Contains(id),
+ IdKind.Map => UsesVariableTransfer && VariableConstants.Contains(id),
+ _ => true
+ };
+ }
+
+ /// True when appears in a shipped plugin file, so a move is only offered (GR-R11).
+ public bool IsUnchecked(int id)
+ {
+ return PluginScriptNumbers.Contains(id);
+ }
+}
diff --git a/RPGModder.Core/Merge/ModSource.cs b/RPGModder.Core/Merge/ModSource.cs
new file mode 100644
index 0000000..a9a36d6
--- /dev/null
+++ b/RPGModder.Core/Merge/ModSource.cs
@@ -0,0 +1,11 @@
+using RPGModder.Core.Models;
+
+namespace RPGModder.Core.Merge;
+
+/// One enabled mod. ModId is the folder name (GR-M3).
+public sealed record ModSource(
+ string ModId,
+ int Priority,
+ IReadOnlyList Files,
+ IReadOnlyList Patches,
+ IReadOnlyList Plugins);
diff --git a/RPGModder.Core/Merge/PluginListDiff.cs b/RPGModder.Core/Merge/PluginListDiff.cs
new file mode 100644
index 0000000..6547a61
--- /dev/null
+++ b/RPGModder.Core/Merge/PluginListDiff.cs
@@ -0,0 +1,201 @@
+using Newtonsoft.Json.Linq;
+using RPGModder.Core.Models;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// Compares one mod's $plugins list with vanilla's (guide 3.3, seam 11.1). Entries are records named by
+/// their plugin name; where an entry sits is the @after pseudo-leaf, never its index (GR-C10).
+///
+internal static class PluginListDiff
+{
+ private const string NameProperty = "name";
+
+ public static IReadOnlyList Compare(string modId, string? sourceFile, JArray vanilla, JArray modded)
+ {
+ var ops = new List();
+ if (JToken.DeepEquals(vanilla, modded))
+ {
+ return ops;
+ }
+
+ if (!TryNames(vanilla, out List vanillaNames) || !TryNames(modded, out List moddedNames))
+ {
+ // Repeated or missing names leave no record to line up: the mod's list is one value.
+ ops.Add(Op(modId, RecordKey.WholeFile, "", ChangeKind.SetLeaf, modded, sourceFile));
+ return ops;
+ }
+
+ var vanillaIndex = new Dictionary(StringComparer.Ordinal);
+ for (int index = 0; index < vanillaNames.Count; index++)
+ {
+ vanillaIndex.Add(vanillaNames[index], index);
+ }
+
+ var moddedSet = new HashSet(moddedNames, StringComparer.Ordinal);
+ var common = new HashSet(moddedNames.Where(vanillaIndex.ContainsKey), StringComparer.Ordinal);
+ HashSet kept = LongestCommonOrder(vanillaNames.Where(common.Contains).ToList(), moddedNames.Where(common.Contains).ToList());
+
+ foreach (string name in vanillaNames.Where(name => !moddedSet.Contains(name)))
+ {
+ ops.Add(Op(modId, RecordKey.ForPlugin(name), "", ChangeKind.RemoveRecord, null, sourceFile));
+ }
+
+ for (int index = 0; index < moddedNames.Count; index++)
+ {
+ string name = moddedNames[index];
+ string record = RecordKey.ForPlugin(name);
+ var entry = (JObject)modded[index];
+ JToken after = index == 0 ? JValue.CreateNull() : new JValue(moddedNames[index - 1]);
+
+ if (!vanillaIndex.TryGetValue(name, out int vanillaPosition))
+ {
+ ops.Add(Op(modId, record, "", ChangeKind.AddRecord, entry, sourceFile));
+ ops.Add(Op(modId, record, MergePath.AfterLeaf, ChangeKind.SetLeaf, after, sourceFile));
+ continue;
+ }
+
+ ops.AddRange(DataDiff.CompareRecord(modId, RpgDataSchema.PluginListKey, sourceFile, record, (JObject)vanilla[vanillaPosition], entry));
+
+ // The entries both lists keep, in the longest order both agree on, stay where they are; every other
+ // kept entry moved. A removal or an insertion next to an entry does not move it, and a moved block
+ // carries an anchor on each of its entries, so it is placed whole.
+ if (!kept.Contains(name))
+ {
+ ops.Add(Op(modId, record, MergePath.AfterLeaf, ChangeKind.SetLeaf, after, sourceFile));
+ }
+ }
+
+ return ops;
+ }
+
+ ///
+ /// Applies a mod's plugins_registry after its own plugins.js (seam 11.1): an entry whose name is
+ /// listed replaces it where it is, a new name is appended.
+ ///
+ public static void ApplyRegistry(JArray list, IReadOnlyList registry)
+ {
+ foreach (PluginEntry plugin in registry)
+ {
+ JObject entry = EntryOf(plugin);
+ int existing = -1;
+ for (int index = 0; index < list.Count && existing < 0; index++)
+ {
+ if (list[index] is JObject listed && NameOf(listed) == plugin.Name)
+ {
+ existing = index;
+ }
+ }
+
+ if (existing < 0)
+ {
+ list.Add(entry);
+ }
+ else
+ {
+ list[existing] = entry;
+ }
+ }
+ }
+
+ /// The editor's property order: name, status, description, parameters, then anything else the entry carries.
+ internal static JObject EntryOf(PluginEntry plugin)
+ {
+ var parameters = new JObject();
+ foreach ((string key, string value) in plugin.Parameters ?? new Dictionary())
+ {
+ parameters[key] = value;
+ }
+
+ var entry = new JObject
+ {
+ [NameProperty] = plugin.Name,
+ ["status"] = plugin.Status,
+ ["description"] = plugin.Description,
+ ["parameters"] = parameters
+ };
+
+ foreach ((string key, JToken value) in plugin.ExtensionData ?? new Dictionary())
+ {
+ if (entry.Property(key, StringComparison.Ordinal) is null)
+ {
+ entry.Add(key, value.DeepClone());
+ }
+ }
+
+ return entry;
+ }
+
+ internal static string? NameOf(JObject entry)
+ {
+ return entry.Property(NameProperty, StringComparison.Ordinal)?.Value is JValue { Type: JTokenType.String } name
+ ? name.Value()
+ : null;
+ }
+
+ /// Every entry an object with a non-empty name, and no name twice.
+ private static bool TryNames(JArray list, out List names)
+ {
+ names = new List(list.Count);
+ var seen = new HashSet(StringComparer.Ordinal);
+ foreach (JToken element in list)
+ {
+ string? name = element is JObject entry ? NameOf(entry) : null;
+ if (string.IsNullOrEmpty(name) || !seen.Add(name))
+ {
+ return false;
+ }
+
+ names.Add(name);
+ }
+
+ return true;
+ }
+
+ ///
+ /// The entries of one longest common subsequence of two orders of the same names. On a tie the vanilla entry
+ /// is the one dropped, so a swap of two neighbours moves the one vanilla had first.
+ ///
+ private static HashSet LongestCommonOrder(List vanilla, List modded)
+ {
+ // suffix[i, j] is the length for vanilla[i..] and modded[j..].
+ var suffix = new int[vanilla.Count + 1, modded.Count + 1];
+ for (int i = vanilla.Count - 1; i >= 0; i--)
+ {
+ for (int j = modded.Count - 1; j >= 0; j--)
+ {
+ suffix[i, j] = vanilla[i] == modded[j]
+ ? suffix[i + 1, j + 1] + 1
+ : Math.Max(suffix[i + 1, j], suffix[i, j + 1]);
+ }
+ }
+
+ var kept = new HashSet(StringComparer.Ordinal);
+ int left = 0;
+ int right = 0;
+ while (left < vanilla.Count && right < modded.Count)
+ {
+ if (vanilla[left] == modded[right])
+ {
+ kept.Add(vanilla[left]);
+ left++;
+ right++;
+ }
+ else if (suffix[left + 1, right] >= suffix[left, right + 1])
+ {
+ left++;
+ }
+ else
+ {
+ right++;
+ }
+ }
+
+ return kept;
+ }
+
+ private static ChangeOp Op(string modId, string record, string path, ChangeKind kind, JToken? value, string? sourceFile)
+ {
+ return new ChangeOp(modId, new RecordKey(RpgDataSchema.PluginListKey, record), path, kind, value?.DeepClone(), sourceFile);
+ }
+}
diff --git a/RPGModder.Core/Merge/PluginListText.cs b/RPGModder.Core/Merge/PluginListText.cs
new file mode 100644
index 0000000..ac37567
--- /dev/null
+++ b/RPGModder.Core/Merge/PluginListText.cs
@@ -0,0 +1,191 @@
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using System.Diagnostics.CodeAnalysis;
+using System.Text;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The text form of js/plugins.js (seam 11.1): a prefix that names $plugins and ends with = ,
+/// one strict JSON array, then only white space and an optional ; . The array is read as JSON, never as
+/// script and never line by line (GR-C11); prefix and suffix are kept byte for byte.
+///
+internal sealed record PluginListText(string Prefix, JArray Entries, string Suffix)
+{
+ /// What the editor writes, used when vanilla has no plugins.js at all.
+ internal const string DefaultPrefix = "// Generated by RPG Maker.\n// Do not edit this file directly.\nvar $plugins =\n";
+
+ internal const string DefaultSuffix = ";\n";
+
+ private const string ListName = "$plugins";
+
+ public static PluginListText Empty()
+ {
+ return new PluginListText(DefaultPrefix, new JArray(), DefaultSuffix);
+ }
+
+ public static bool TryParse(string? text, [NotNullWhen(true)] out PluginListText? list, [NotNullWhen(false)] out string? error)
+ {
+ list = null;
+ if (text is null)
+ {
+ error = "no text";
+ return false;
+ }
+
+ if (!TryFindListStart(text, out int start, out error))
+ {
+ return false;
+ }
+
+ int end = FindListEnd(text, start);
+ if (end < 0)
+ {
+ error = "the list is not closed";
+ return false;
+ }
+
+ string suffix = text[(end + 1)..];
+ if (!IsPlainSuffix(suffix))
+ {
+ error = "something other than ; follows the list";
+ return false;
+ }
+
+ try
+ {
+ if (MergeJson.Parse(text[start..(end + 1)]) is JArray entries)
+ {
+ list = new PluginListText(text[..start], entries, suffix);
+ error = null;
+ return true;
+ }
+ }
+ catch (JsonReaderException exception)
+ {
+ error = $"the list is not valid JSON (line {exception.LineNumber}, position {exception.LinePosition})";
+ return false;
+ }
+
+ error = "the list is not a JSON array";
+ return false;
+ }
+
+ ///
+ /// The [ of the first $plugins = [ , so a mention of the name in a comment before it is skipped.
+ /// The error names what follows the first mention when no mention is the declaration.
+ ///
+ private static bool TryFindListStart(string text, out int start, [NotNullWhen(false)] out string? error)
+ {
+ start = -1;
+ error = "it does not name " + ListName;
+ bool first = true;
+ for (int name = text.IndexOf(ListName, StringComparison.Ordinal);
+ name >= 0;
+ name = text.IndexOf(ListName, name + ListName.Length, StringComparison.Ordinal))
+ {
+ int position = SkipWhiteSpace(text, name + ListName.Length);
+ string? problem = null;
+ if (position >= text.Length || text[position] != '=')
+ {
+ problem = ListName + " is not followed by =";
+ }
+ else
+ {
+ position = SkipWhiteSpace(text, position + 1);
+ if (position >= text.Length || text[position] != '[')
+ {
+ problem = ListName + " is not set to a list";
+ }
+ }
+
+ if (problem is null)
+ {
+ start = position;
+ error = null;
+ return true;
+ }
+
+ if (first)
+ {
+ error = problem;
+ first = false;
+ }
+ }
+
+ return false;
+ }
+
+ ///
+ /// [ , a line end, each entry compact, joined by , and a line end, a line end, ] . The line
+ /// end is the prefix's own, so a file the editor saved on Windows stays CRLF.
+ ///
+ public string Render()
+ {
+ if (Entries.Count == 0)
+ {
+ return Prefix + "[]" + Suffix;
+ }
+
+ string lineEnd = Prefix.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
+ var builder = new StringBuilder(Prefix).Append('[').Append(lineEnd);
+ for (int index = 0; index < Entries.Count; index++)
+ {
+ builder.Append(index == 0 ? "" : "," + lineEnd).Append(MergeJson.Write(Entries[index]));
+ }
+
+ return builder.Append(lineEnd).Append(']').Append(Suffix).ToString();
+ }
+
+ private static int SkipWhiteSpace(string text, int position)
+ {
+ while (position < text.Length && char.IsWhiteSpace(text[position]))
+ {
+ position++;
+ }
+
+ return position;
+ }
+
+ /// The index of the ] that closes the list at , skipping brackets inside strings.
+ private static int FindListEnd(string text, int start)
+ {
+ int depth = 0;
+ bool inString = false;
+ for (int position = start; position < text.Length; position++)
+ {
+ char current = text[position];
+ if (inString)
+ {
+ if (current == '\\')
+ {
+ position++;
+ }
+ else if (current == '"')
+ {
+ inString = false;
+ }
+ }
+ else if (current == '"')
+ {
+ inString = true;
+ }
+ else if (current is '[' or '{')
+ {
+ depth++;
+ }
+ else if (current is ']' or '}' && --depth == 0)
+ {
+ return current == ']' ? position : -1;
+ }
+ }
+
+ return -1;
+ }
+
+ private static bool IsPlainSuffix(string suffix)
+ {
+ string rest = suffix.Trim();
+ return rest.Length == 0 || rest == ";";
+ }
+}
diff --git a/RPGModder.Core/Merge/PluginPlacement.cs b/RPGModder.Core/Merge/PluginPlacement.cs
new file mode 100644
index 0000000..f4c895c
--- /dev/null
+++ b/RPGModder.Core/Merge/PluginPlacement.cs
@@ -0,0 +1,104 @@
+namespace RPGModder.Core.Merge;
+
+///
+/// Places the entries of the merged $plugins list by their @after anchors (GR-C10, seam 11.1).
+/// Vanilla entries with no anchor keep their order; nothing is placed by index.
+///
+internal static class PluginPlacement
+{
+ /// Every vanilla name, in vanilla's order, removed ones included (for the fallback).
+ /// Every name of the merged list.
+ /// The names vanilla does not have.
+ /// The @after of each entry that has one; null means "no entry before it".
+ public static List Place(
+ IReadOnlyList vanillaOrder,
+ IReadOnlySet present,
+ IReadOnlySet added,
+ IReadOnlyDictionary anchors)
+ {
+ var placed = vanillaOrder.Where(name => present.Contains(name) && !anchors.ContainsKey(name)).ToList();
+ var pending = new SortedSet(present.Where(name => !placed.Contains(name)), StringComparer.Ordinal);
+ var lastAfter = new Dictionary(StringComparer.Ordinal);
+ int front = 0;
+
+ while (pending.Count > 0)
+ {
+ bool progress = false;
+ foreach (string name in pending.ToList())
+ {
+ string? anchor = anchors.GetValueOrDefault(name);
+ if (anchor is null)
+ {
+ // A new entry with nothing before it goes to the end (GR-C10); a moved one goes first.
+ if (added.Contains(name) || !anchors.ContainsKey(name))
+ {
+ placed.Add(name);
+ }
+ else
+ {
+ placed.Insert(front++, name);
+ }
+ }
+ else if (placed.Contains(anchor))
+ {
+ InsertAfter(placed, lastAfter, anchor, name);
+ }
+ else if (pending.Contains(anchor))
+ {
+ continue;
+ }
+ else if (NearestPlacedBefore(vanillaOrder, placed, anchor) is string fallback)
+ {
+ InsertAfter(placed, lastAfter, fallback, name);
+ }
+ else
+ {
+ placed.Add(name);
+ }
+
+ pending.Remove(name);
+ progress = true;
+ }
+
+ if (!progress)
+ {
+ // A cycle of anchors, and whatever waits on it: the end of the list, by name.
+ placed.AddRange(pending);
+ break;
+ }
+ }
+
+ return placed;
+ }
+
+ /// Right after the anchor, or after the entry last placed there, so entries behind one anchor keep their placing order.
+ private static void InsertAfter(List placed, Dictionary lastAfter, string anchor, string name)
+ {
+ string target = lastAfter.TryGetValue(anchor, out string? last) && placed.Contains(last) ? last : anchor;
+ placed.Insert(placed.IndexOf(target) + 1, name);
+ lastAfter[anchor] = name;
+ }
+
+ /// The anchor's nearest preceding vanilla entry that is in the list; null when the anchor is not a vanilla entry or none precedes it.
+ private static string? NearestPlacedBefore(IReadOnlyList vanillaOrder, List placed, string anchor)
+ {
+ int position = -1;
+ for (int index = 0; index < vanillaOrder.Count && position < 0; index++)
+ {
+ if (vanillaOrder[index] == anchor)
+ {
+ position = index;
+ }
+ }
+
+ for (int index = position - 1; index >= 0; index--)
+ {
+ if (placed.Contains(vanillaOrder[index]))
+ {
+ return vanillaOrder[index];
+ }
+ }
+
+ return null;
+ }
+}
diff --git a/RPGModder.Core/Merge/RecordKey.cs b/RPGModder.Core/Merge/RecordKey.cs
new file mode 100644
index 0000000..7d1172c
--- /dev/null
+++ b/RPGModder.Core/Merge/RecordKey.cs
@@ -0,0 +1,62 @@
+using System.Globalization;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// The identity of one record of one file (GR-M2): File is the key from ,
+/// Record is id:<n> for a database record, event:<n> for a map event,
+/// plugin:<name> for a $plugins entry, or * for whole-file and root-level ops.
+///
+public sealed record RecordKey(string File, string Record)
+{
+ /// The record of a whole-file op, and of every op in a file whose root is not a record list.
+ internal const string WholeFile = "*";
+
+ private const string RecordPrefix = "id:";
+ private const string EventPrefix = "event:";
+ private const string PluginPrefix = "plugin:";
+
+ internal bool IsWholeFile => Record == WholeFile;
+
+ internal static string ForIndex(int index)
+ {
+ return RecordPrefix + index.ToString(CultureInfo.InvariantCulture);
+ }
+
+ internal static string ForEvent(int index)
+ {
+ return EventPrefix + index.ToString(CultureInfo.InvariantCulture);
+ }
+
+ internal static string ForPlugin(string name)
+ {
+ return PluginPrefix + name;
+ }
+
+ /// Reads id:<n> in the one form writes: no sign, no leading zero.
+ internal static bool TryGetIndex(string record, out int index)
+ {
+ return TryGetNumber(record, RecordPrefix, out index);
+ }
+
+ /// Reads event:<n> in the one form writes.
+ internal static bool TryGetEvent(string record, out int index)
+ {
+ return TryGetNumber(record, EventPrefix, out index);
+ }
+
+ /// Reads plugin:<name> ; the name is never empty.
+ internal static bool TryGetPlugin(string record, out string name)
+ {
+ name = record.StartsWith(PluginPrefix, StringComparison.Ordinal) ? record[PluginPrefix.Length..] : "";
+ return name.Length > 0;
+ }
+
+ private static bool TryGetNumber(string record, string prefix, out int index)
+ {
+ index = -1;
+ return record.StartsWith(prefix, StringComparison.Ordinal) &&
+ int.TryParse(record.AsSpan(prefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out index) &&
+ prefix + index.ToString(CultureInfo.InvariantCulture) == record;
+ }
+}
diff --git a/RPGModder.Core/Merge/ReferenceMap.cs b/RPGModder.Core/Merge/ReferenceMap.cs
new file mode 100644
index 0000000..dd03786
--- /dev/null
+++ b/RPGModder.Core/Merge/ReferenceMap.cs
@@ -0,0 +1,429 @@
+using Newtonsoft.Json.Linq;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+
+namespace RPGModder.Core.Merge;
+
+///
+/// Where an id is referenced (guide 3.11, reference table), for the two kinds of step 1. reads a
+/// change set's free text and the references the table cannot rewrite (GR-R9); moves every
+/// reference the table lists. p[n] below is parameters[n] of an event or route command; only values
+/// above 0 are ids. Every position was checked against the MV and MZ core scripts.
+///
+internal static class ReferenceMap
+{
+ // Route command (inside a moveRoute list): Script.
+ private const int RouteScript = 45;
+
+ // Event commands.
+ private const int ConditionalBranch = 111;
+ private const int ControlVariables = 122;
+ private const int TransferPlayer = 201;
+ private const int SetVehicleLocation = 202;
+ private const int SetEventLocation = 203;
+ private const int SetMovementRoute = 205;
+ private const int ShowAnimation = 212;
+ private const int ShowBalloon = 213;
+ private const int GetLocationInfo = 285;
+ private const int Script = 355;
+ private const int PluginCommandMv = 356;
+ private const int PluginCommandMz = 357;
+ private const int ScriptMore = 655;
+
+ // 111 p[0], 122 p[3] and p[4], 201 p[0], 202 p[1], 203 p[1], 285 p[2]: the operand forms the table names.
+ private const int BranchCharacter = 6;
+ private const int BranchScript = 12;
+ private const int OperandConstant = 0;
+ private const int OperandGameData = 3;
+ private const int OperandScript = 4;
+ private const int GameDataCharacter = 5;
+ private const int DesignationDirect = 0;
+ private const int DesignationByVariable = 1;
+ private const int EventLocationExchange = 2;
+ private const int LocationByCharacter = 2;
+
+ private const string NoteProperty = "note";
+ private const string DamageProperty = "damage";
+ private const string FormulaProperty = "formula";
+ private const string ParentIdProperty = "parentId";
+ private const string IdProperty = "id";
+ private const string ParametersProperty = "parameters";
+ private const string CodeProperty = "code";
+
+ /// The System.json places that hold a map id.
+ private static readonly HashSet StartMapPaths = new(StringComparer.Ordinal)
+ {
+ "startMapId",
+ "boat.startMapId",
+ "ship.startMapId",
+ "airship.startMapId"
+ };
+
+ /// What in one mod's change set stops a move (GR-R9) or makes it unchecked (GR-R11).
+ public static ModReferences Scan(ModChangeSet changeSet, IReadOnlyList pluginScripts)
+ {
+ var references = new ModReferences();
+ foreach (ChangeOp op in changeSet.Ops)
+ {
+ if (op.Value is null || MergePath.IsPseudoLeaf(op.Path))
+ {
+ continue;
+ }
+
+ IReadOnlyList segments = MergePath.Parse(op.Path);
+ string? name = segments.Count > 0 ? segments[^1].Name : null;
+ string? parent = segments.Count > 1 ? segments[^2].Name : null;
+ bool isPluginList = op.Key.File == RpgDataSchema.PluginListKey;
+ var context = new ScanContext(references, RpgDataSchema.IsMapFile(op.Key.File), isPluginList);
+
+ // Plugin parameters the mod sets are free text (GR-R9), whether the op names one or the whole entry.
+ bool inParameters = isPluginList && segments.Count > 0 && segments[0].Name == ParametersProperty;
+ Visit(op.Value, name, parent, inParameters, context);
+ }
+
+ foreach (string script in pluginScripts)
+ {
+ AddNumbers(script, references.PluginScriptNumbers);
+ }
+
+ return references;
+ }
+
+ ///
+ /// with every listed reference moved by , or the op itself when
+ /// nothing moved. A whole new file whose content changed loses its source file, so it is written as text.
+ ///
+ public static ChangeOp Rewrite(ChangeOp op, RemapTable table)
+ {
+ RecordKey key = op.Key;
+ JToken? value = op.Value?.DeepClone();
+ if (op.Kind == ChangeKind.AddRecord && op.Path.Length == 0)
+ {
+ if (key.IsWholeFile && RpgDataSchema.TryGetMapId(key.File, out int mapId) && table.Maps.TryGetValue(mapId, out int newMap))
+ {
+ key = new RecordKey(RpgDataSchema.MapKey(newMap), RecordKey.WholeFile);
+ }
+ else if (key.File == RpgDataSchema.MapInfosKey && RecordKey.TryGetIndex(key.Record, out int infoId) &&
+ table.Maps.TryGetValue(infoId, out int newInfo))
+ {
+ key = key with { Record = RecordKey.ForIndex(newInfo) };
+ SetOwnId(value, infoId, newInfo);
+ }
+ else if (table.Events.TryGetValue(key.File, out Dictionary? moved) && RecordKey.TryGetEvent(key.Record, out int eventId) &&
+ moved.TryGetValue(eventId, out int newEvent))
+ {
+ key = key with { Record = RecordKey.ForEvent(newEvent) };
+ SetOwnId(value, eventId, newEvent);
+ }
+ }
+
+ if (value is not null && !MergePath.IsPseudoLeaf(op.Path))
+ {
+ // Event references are scoped to the map file the commands sit in, so the op's own file decides.
+ Dictionary? events = table.Events.GetValueOrDefault(op.Key.File);
+ VisitCommands(value, command => RewriteCommand(command, table.Maps, events));
+ if (op.Key.File == RpgDataSchema.MapInfosKey && !op.Key.IsWholeFile)
+ {
+ // A map's parent, in the moved map's own record or in a vanilla map the mod hangs under it.
+ value = RewriteAt(value, op.Path, path => path == ParentIdProperty, table.Maps);
+ }
+ else if (op.Key.File == RpgDataSchema.SystemFileKey)
+ {
+ value = RewriteAt(value, op.Path, StartMapPaths.Contains, table.Maps);
+ }
+ }
+
+ bool changed = key != op.Key || !JToken.DeepEquals(value, op.Value);
+ if (!changed)
+ {
+ return op;
+ }
+
+ string? source = op.Kind == ChangeKind.AddRecord && op.Key.IsWholeFile ? null : op.SourceFile;
+ return op with { Key = key, Value = value, SourceFile = source };
+ }
+
+ private static void Visit(JToken token, string? name, string? parent, bool inParameters, ScanContext context)
+ {
+ if (inParameters)
+ {
+ AddNumbers(token, context.References.FreeTextNumbers);
+ return;
+ }
+
+ switch (token)
+ {
+ case JObject item:
+ if (TryCommand(item, out int code, out JArray? parameters))
+ {
+ ScanCommand(code, parameters, context);
+ }
+
+ foreach (JProperty property in item.Properties())
+ {
+ bool pluginParameters = context.IsPluginList && property.Name == ParametersProperty;
+ Visit(property.Value, property.Name, name, pluginParameters, context);
+ }
+
+ break;
+ case JArray list:
+ foreach (JToken element in list)
+ {
+ Visit(element, null, name, false, context);
+ }
+
+ break;
+ case JValue { Type: JTokenType.String } text when name == NoteProperty || (name == FormulaProperty && parent == DamageProperty):
+ AddNumbers(text, context.References.FreeTextNumbers);
+ break;
+ }
+ }
+
+ private static void ScanCommand(int code, JArray parameters, ScanContext context)
+ {
+ ModReferences references = context.References;
+ switch (code)
+ {
+ case Script or ScriptMore or PluginCommandMv or RouteScript:
+ AddNumbers(At(parameters, 0), references.FreeTextNumbers);
+ break;
+ case PluginCommandMz:
+ AddNumbers(At(parameters, 3), references.FreeTextNumbers);
+ break;
+ case ConditionalBranch when Is(parameters, 0, BranchScript):
+ AddNumbers(At(parameters, 1), references.FreeTextNumbers);
+ break;
+ case ControlVariables when Is(parameters, 3, OperandScript):
+ AddNumbers(At(parameters, 4), references.FreeTextNumbers);
+ break;
+ case ControlVariables when Is(parameters, 3, OperandConstant):
+ AddId(At(parameters, 4), references.VariableConstants);
+ break;
+ case TransferPlayer when Is(parameters, 0, DesignationByVariable):
+ case SetVehicleLocation when Is(parameters, 1, DesignationByVariable):
+ references.UsesVariableTransfer = true;
+ break;
+ }
+
+ if (context.IsMapFile)
+ {
+ return;
+ }
+
+ // Outside a map the event commands act on whatever map is loaded, so their ids cannot be rewritten (3.11).
+ foreach (int index in EventPositions(code, parameters))
+ {
+ AddId(At(parameters, index), references.AmbiguousEventIds);
+ }
+ }
+
+ private static void RewriteCommand(JObject command, Dictionary maps, Dictionary? events)
+ {
+ if (!TryCommand(command, out int code, out JArray? parameters))
+ {
+ return;
+ }
+
+ if (maps.Count > 0)
+ {
+ if (code == TransferPlayer && Is(parameters, 0, DesignationDirect))
+ {
+ Move(parameters, 1, maps);
+ }
+ else if (code == SetVehicleLocation && Is(parameters, 1, DesignationDirect))
+ {
+ Move(parameters, 2, maps);
+ }
+ }
+
+ if (events is not null)
+ {
+ foreach (int index in EventPositions(code, parameters))
+ {
+ Move(parameters, index, events);
+ }
+ }
+ }
+
+ /// The positions of a command that hold an event id of the current map, from the reference table.
+ private static IEnumerable EventPositions(int code, JArray parameters)
+ {
+ switch (code)
+ {
+ case SetEventLocation:
+ yield return 0;
+ if (Is(parameters, 1, EventLocationExchange))
+ {
+ yield return 2;
+ }
+
+ break;
+ case SetMovementRoute or ShowAnimation or ShowBalloon:
+ yield return 0;
+ break;
+ case ConditionalBranch when Is(parameters, 0, BranchCharacter):
+ yield return 1;
+ break;
+ case ControlVariables when Is(parameters, 3, OperandGameData) && Is(parameters, 4, GameDataCharacter):
+ yield return 5;
+ break;
+ case GetLocationInfo when Is(parameters, 2, LocationByCharacter):
+ yield return 3;
+ break;
+ }
+ }
+
+ /// Every command object in , including route commands inside a move route.
+ private static void VisitCommands(JToken token, Action visit)
+ {
+ switch (token)
+ {
+ case JObject item:
+ visit(item);
+ foreach (JProperty property in item.Properties())
+ {
+ VisitCommands(property.Value, visit);
+ }
+
+ break;
+ case JArray list:
+ foreach (JToken element in list)
+ {
+ VisitCommands(element, visit);
+ }
+
+ break;
+ }
+ }
+
+ ///
+ /// Moves the map ids at the places accepts, walking down
+ /// from its own path (relative to the record, as op paths are).
+ ///
+ private static JToken RewriteAt(JToken token, string path, Func isPlace, Dictionary maps)
+ {
+ if (isPlace(path))
+ {
+ return token is JValue value && TryId(value, out int id) && maps.TryGetValue(id, out int moved) ? new JValue(moved) : token;
+ }
+
+ if (token is not JObject item)
+ {
+ return token;
+ }
+
+ foreach (JProperty property in item.Properties().ToList())
+ {
+ property.Value = RewriteAt(property.Value, MergePath.Child(path, property.Name), isPlace, maps);
+ }
+
+ return item;
+ }
+
+ private static void SetOwnId(JToken? value, int oldId, int newId)
+ {
+ if (value is JObject record && record[IdProperty] is JValue id && TryId(id, out int current) && current == oldId)
+ {
+ record[IdProperty] = newId;
+ }
+ }
+
+ private static void Move(JArray parameters, int index, Dictionary moves)
+ {
+ if (At(parameters, index) is JValue value && TryId(value, out int id) && moves.TryGetValue(id, out int moved))
+ {
+ parameters[index] = moved;
+ }
+ }
+
+ private static bool TryCommand(JObject item, out int code, [NotNullWhen(true)] out JArray? parameters)
+ {
+ parameters = item[ParametersProperty] as JArray;
+ code = 0;
+ return parameters is not null && item[CodeProperty] is JValue { Type: JTokenType.Integer } value && TryInt(value, out code);
+ }
+
+ private static JToken? At(JArray parameters, int index)
+ {
+ return index < parameters.Count ? parameters[index] : null;
+ }
+
+ private static bool Is(JArray parameters, int index, int expected)
+ {
+ return At(parameters, index) is JValue value && TryInt(value, out int actual) && actual == expected;
+ }
+
+ /// An id is a whole number above 0 (reference table).
+ private static bool TryId(JValue value, out int id)
+ {
+ return TryInt(value, out id) && id > 0;
+ }
+
+ private static bool TryInt(JValue value, out int number)
+ {
+ number = 0;
+ if (value.Type != JTokenType.Integer || value.Value is not long whole || whole is < int.MinValue or > int.MaxValue)
+ {
+ return false;
+ }
+
+ number = (int)whole;
+ return true;
+ }
+
+ private static void AddId(JToken? token, HashSet ids)
+ {
+ if (token is JValue value && TryId(value, out int id))
+ {
+ ids.Add(id);
+ }
+ }
+
+ /// Every whole number in : each run of ASCII digits in its text, and each integer.
+ private static void AddNumbers(JToken? token, HashSet numbers)
+ {
+ switch (token)
+ {
+ case JValue { Type: JTokenType.String } text:
+ AddNumbers(text.Value() ?? "", numbers);
+ break;
+ case JValue { Type: JTokenType.Integer, Value: long whole }:
+ numbers.Add(whole);
+ break;
+ case JContainer container:
+ foreach (JToken child in container.Children())
+ {
+ AddNumbers(child is JProperty property ? property.Value : child, numbers);
+ }
+
+ break;
+ }
+ }
+
+ private static void AddNumbers(string text, HashSet numbers)
+ {
+ int index = 0;
+ while (index < text.Length)
+ {
+ if (!char.IsAsciiDigit(text[index]))
+ {
+ index++;
+ continue;
+ }
+
+ int start = index;
+ while (index < text.Length && char.IsAsciiDigit(text[index]))
+ {
+ index++;
+ }
+
+ // A run too long for a long names no id; "003" is 3, so a padded map name counts.
+ if (long.TryParse(text.AsSpan(start, index - start), NumberStyles.None, CultureInfo.InvariantCulture, out long number))
+ {
+ numbers.Add(number);
+ }
+ }
+ }
+
+ private sealed record ScanContext(ModReferences References, bool IsMapFile, bool IsPluginList);
+}
diff --git a/RPGModder.Core/Merge/RemapMod.cs b/RPGModder.Core/Merge/RemapMod.cs
new file mode 100644
index 0000000..74991f6
--- /dev/null
+++ b/RPGModder.Core/Merge/RemapMod.cs
@@ -0,0 +1,11 @@
+namespace RPGModder.Core.Merge;
+
+///
+/// One installed mod as sees it. A disabled mod still reserves its ids (GR-R5).
+/// PluginScripts holds the text of every js/plugins/*.js file the mod ships; a number found only there
+/// makes a remap an explicit choice (GR-R11).
+///
+public sealed record RemapMod(
+ ModChangeSet ChangeSet,
+ bool Enabled,
+ IReadOnlyList PluginScripts);
diff --git a/RPGModder.Core/Merge/RemapPlaces.cs b/RPGModder.Core/Merge/RemapPlaces.cs
new file mode 100644
index 0000000..9a46a41
--- /dev/null
+++ b/RPGModder.Core/Merge/RemapPlaces.cs
@@ -0,0 +1,26 @@
+namespace RPGModder.Core.Merge;
+
+/// The places an added id occupies in a change set, so an offer can be matched to its