Files
Chronos/src/Chronos.Data/Projects/ProjectMerge.cs
T
Alby96andClaude Opus 5.5 eac4a36a7b fix(projects): one photo merges as one, newer settings are never merged
A workspace copied before the home hashed or converted a photo named it
differently from the versions the home made since, so a pull merged the
same photo as two: frame edits were silently undone and Keep mine placed
the library's value. Before replaying, the workspace media now learn the
home's hashes (same frame id, size and capture time) and conversion
aliases, so every side names each photo alike. Rebind also gives a
renamed entry the occurrence a placement looks for, so positions on
burst photos keep applying once hashed, and folds entries of one photo
(in Rebind and in the merge's keyed form) instead of keeping one.

Settings of a newer Chronos are no longer merged member by member with
this one's: ProjectMerge refuses when both sides changed. A workspace
pull keeps its local versions and working state untouched and records a
conflict of format that only Save both settles (into a new project of
this format); with nothing local it takes the newer head read-only.
Main's catch-up leaves a newer head and settings written meanwhile as
they are.

When Main's catch-up merge overrides values another writer stored, that
writer's settings are kept as an External version before the Merge one,
so nothing is lost from the history.

Unknown members inside Auto values, camera keyframes and curve points,
and on pending entries once placed, are kept like ProjectSettings' Extra.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 10:05:27 +01:00

275 lines
15 KiB
C#

using System.Globalization;
using System.Text.Json;
using System.Text.Json.Nodes;
using Chronos.Core.Project;
using Chronos.Data.Sync;
namespace Chronos.Data.Projects;
/// <summary>The result of a three-way merge of projects: the merged settings and the members both sides changed to different values.</summary>
/// <param name="Conflicts">Each settled for the side asked (<c>takeTheirs</c>), else for ours; empty when the merge needed nobody.</param>
public sealed record ProjectMergeResult(ProjectSettings Merged, IReadOnlyList<SettingsDifference> Conflicts)
{
public bool HasConflicts => Conflicts.Count > 0;
}
/// <summary>
/// Commits not stored at their home yet, replayed on top of the version stored there meanwhile (owner review 2, R8): one
/// project per commit, in order, and the conflicts of the last one (the net change of all of them against theirs).
/// </summary>
public sealed record ProjectReplay(IReadOnlyList<ProjectSettings> Commits, IReadOnlyList<SettingsDifference> Conflicts)
{
public bool HasConflicts => Conflicts.Count > 0;
}
/// <summary>
/// A merge both sides of which changed met settings of a newer Chronos (<see cref="ProjectSettings.IsNewerFormat"/>): this
/// Chronos never merges them, as their known members may mean something else there (owner review 2, R8). Nothing was merged.
/// </summary>
public sealed class NewerSettingsException(string message) : InvalidOperationException(message);
/// <summary>
/// Three-way merge of projects: the editor's edit (<c>ours</c>) and a change stored meanwhile by someone else
/// (<c>theirs</c>: an analysis filling Auto values, another client through the server, another workspace through a
/// project's home), both made from <c>basis</c>. Values are compared member by member down the JSON tree; a member only
/// one side changed takes that side's value, a member both changed takes the editor's (the user is looking at it) unless
/// its path is among those asked to take theirs. <see cref="Conflicts"/> lists those members for a source that asks the
/// user instead (a server sequence, BRIEF §14.5; a workspace project, owner review 2, R8). Pending frames (frame
/// positions parked by photo, the portable form of <see cref="ProjectContent"/>) merge photo by photo and flag by flag, so
/// two people excluding different photos never conflict; two heroes chosen on both sides do (path <see cref="HeroPath"/>).
/// Entries of one photo in one project (saved under two names, alike since) merge as one, keeping the positions of both.
/// Members this Chronos does not know merge like the others and are kept. Settings of a newer Chronos are never merged:
/// a side that did not change takes the other's as they are, anything else is refused (<see cref="NewerSettingsException"/>).
/// </summary>
public static class ProjectMerge
{
/// <summary>The path of the conflict of two heroes chosen among pending frames on both sides.</summary>
public const string HeroPath = "hero";
/// <summary>
/// The path of the settings format (<see cref="ProjectSettings.Version"/>): a difference there is settings of a newer
/// Chronos that this one cannot merge with its own (a workspace's conflict of format).
/// </summary>
public const string FormatPath = "version";
private const string PendingPath = "pendingFrames";
/// <exception cref="NewerSettingsException">Both sides changed, and one of the three is of a newer format.</exception>
public static ProjectSettings Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) =>
MergeWithConflicts(basis, ours, theirs).Merged;
/// <summary>
/// The merge of <paramref name="ours"/> and <paramref name="theirs"/> made from <paramref name="basis"/>, and its
/// conflicts. A conflict whose path is in <paramref name="takeTheirs"/> takes theirs (the user chose "take server"
/// there), every other one ours.
/// </summary>
/// <exception cref="NewerSettingsException">Both sides changed, and one of the three is of a newer format.</exception>
public static ProjectMergeResult MergeWithConflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs, IReadOnlySet<string>? takeTheirs = null)
{
ArgumentNullException.ThrowIfNull(basis);
ArgumentNullException.ThrowIfNull(ours);
ArgumentNullException.ThrowIfNull(theirs);
var conflicts = new List<SettingsDifference>();
var choice = takeTheirs ?? EmptySet;
var (b, o, t) = (Keyed(basis), Keyed(ours), Keyed(theirs));
if (basis.IsNewerFormat || ours.IsNewerFormat || theirs.IsNewerFormat)
{
// Their known members may mean something else there: only a side that did not change gives way.
if (JsonNode.DeepEquals(o, b) || JsonNode.DeepEquals(t, o)) return new ProjectMergeResult(Read(theirs.ToJson()), []);
if (JsonNode.DeepEquals(t, b)) return new ProjectMergeResult(Read(ours.ToJson()), []);
throw new NewerSettingsException(string.Create(CultureInfo.InvariantCulture,
$"Settings of format {Math.Max(basis.Version, Math.Max(ours.Version, theirs.Version))} are not merged by this Chronos (format {ProjectSettings.CurrentVersion})."));
}
var merged = MergeNode(b, o, t, string.Empty, conflicts, choice) as JsonObject ?? new JsonObject();
OneHero(merged, o, t, conflicts, choice);
return new ProjectMergeResult(FromKeyed(merged), conflicts);
}
/// <summary>
/// The members both sides changed to different values, in document order: the path below the project
/// ("exposure.deflickerWindow.manual"; "pendingFrames.&lt;photo&gt;.excluded" for a pending frame), the editor's value and
/// theirs as JSON (null when absent).
/// </summary>
public static IReadOnlyList<SettingsDifference> Conflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) =>
MergeWithConflicts(basis, ours, theirs).Conflicts;
/// <summary>
/// Replays commits made from <paramref name="basis"/> (<paramref name="mine"/>, oldest first, each including the ones
/// before it) on top of <paramref name="theirs"/>: each becomes theirs with that commit's changes since the basis, so the
/// history stays linear and the last one holds the net change. Conflicts are those of the last commit; their paths in
/// <paramref name="takeTheirs"/> take theirs in every commit.
/// </summary>
/// <exception cref="NewerSettingsException">A commit and theirs both changed, and one of them (or the basis) is of a newer format.</exception>
public static ProjectReplay Replay(ProjectSettings basis, IReadOnlyList<ProjectSettings> mine, ProjectSettings theirs, IReadOnlySet<string>? takeTheirs = null)
{
ArgumentNullException.ThrowIfNull(mine);
var commits = new List<ProjectSettings>(mine.Count);
IReadOnlyList<SettingsDifference> conflicts = [];
foreach (var commit in mine)
{
var result = MergeWithConflicts(basis, commit, theirs, takeTheirs);
commits.Add(result.Merged);
conflicts = result.Conflicts;
}
return new ProjectReplay(commits, conflicts);
}
/// <summary>True when both projects store the same values.</summary>
public static bool SameValues(ProjectSettings a, ProjectSettings b) => a.ToJson() == b.ToJson();
private static readonly IReadOnlySet<string> EmptySet = new HashSet<string>();
private static JsonNode? MergeNode(JsonNode? basis, JsonNode? ours, JsonNode? theirs, string path, List<SettingsDifference> conflicts,
IReadOnlySet<string> takeTheirs)
{
if (JsonNode.DeepEquals(ours, basis)) return theirs?.DeepClone();
if (JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return ours?.DeepClone();
if (path == PendingPath && ours is JsonObject or null && theirs is JsonObject or null)
return MergePending(basis as JsonObject, ours as JsonObject, theirs as JsonObject, conflicts, takeTheirs);
if (ours is JsonObject mine && theirs is JsonObject other)
{
var common = basis as JsonObject;
var merged = new JsonObject();
foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key)))
{
var child = path.Length == 0 ? name : path + "." + name;
var value = MergeNode(common?[name], mine[name], other[name], child, conflicts, takeTheirs);
if (value is not null || (takeTheirs.Contains(child) ? other.ContainsKey(name) : mine.ContainsKey(name))) merged[name] = value;
}
return merged;
}
var at = path.Length == 0 ? "settings" : path;
conflicts.Add(new SettingsDifference(at, ours?.ToJsonString(), theirs?.ToJsonString()));
return takeTheirs.Contains(at) ? theirs?.DeepClone() : ours?.DeepClone();
}
/// <summary>
/// Pending frames keyed by photo, merged entry by entry: an entry one side lacks counts as the photo with no position on
/// it, so excluding one photo here and another there both stay, and a flag both changed alike is no conflict.
/// </summary>
private static JsonObject MergePending(JsonObject? basis, JsonObject? ours, JsonObject? theirs, List<SettingsDifference> conflicts,
IReadOnlySet<string> takeTheirs)
{
var merged = new JsonObject();
var keys = (ours?.Select(p => p.Key) ?? []).Union(theirs?.Select(p => p.Key) ?? []).Union(basis?.Select(p => p.Key) ?? []).ToList();
foreach (var key in keys)
{
var template = ours?[key] ?? theirs?[key] ?? basis?[key];
var value = MergeNode(basis?[key] ?? Unplaced(template), ours?[key] ?? Unplaced(template), theirs?[key] ?? Unplaced(template),
PendingPath + "." + key, conflicts, takeTheirs);
if (value is not null) merged[key] = value;
}
return merged;
}
/// <summary>
/// Two heroes after a merge (each side chose one among photos that wait): one conflict, settled for ours or, when asked,
/// theirs; the other entry no longer holds the hero.
/// </summary>
private static void OneHero(JsonObject merged, JsonObject ours, JsonObject theirs, List<SettingsDifference> conflicts, IReadOnlySet<string> takeTheirs)
{
if (merged[PendingPath] is not JsonObject pending) return;
var heroes = pending.Where(p => p.Value is JsonObject entry && Flag(entry, "hero")).Select(p => p.Key).ToList();
if (heroes.Count < 2) return;
var mine = HeroOf(ours);
var other = HeroOf(theirs);
var keep = takeTheirs.Contains(HeroPath) ? other ?? heroes[0] : mine ?? heroes[0];
foreach (var key in heroes.Where(k => k != keep)) pending[key]!["hero"] = false;
conflicts.Add(new SettingsDifference(HeroPath, mine is null ? null : (ours[PendingPath] as JsonObject)?[mine]?.ToJsonString(),
other is null ? null : (theirs[PendingPath] as JsonObject)?[other]?.ToJsonString()));
}
private static string? HeroOf(JsonObject project) =>
project[PendingPath] is JsonObject pending ? pending.FirstOrDefault(p => p.Value is JsonObject entry && Flag(entry, "hero")).Key : null;
/// <summary>
/// The project as JSON with its pending frames as an object keyed by photo (<see cref="KeyOf"/>); entries of one photo
/// (saved under two names, alike since) are one, with the positions of both (<see cref="ProjectContent.Fold"/>).
/// </summary>
private static JsonObject Keyed(ProjectSettings settings)
{
var project = JsonNode.Parse(settings.ToJson())!.AsObject();
if (project[PendingPath] is JsonArray pending)
{
var keyed = new JsonObject();
foreach (var entry in pending)
{
var key = KeyOf(entry);
if (keyed[key] is JsonObject known && entry is JsonObject other) ProjectContent.Fold(known, other);
else keyed[key] = entry?.DeepClone();
}
project[PendingPath] = keyed;
}
return project;
}
/// <summary>A keyed project back as settings: pending frames as a list again, without those that no longer hold a position.</summary>
private static ProjectSettings FromKeyed(JsonObject project)
{
if (project[PendingPath] is JsonObject keyed)
{
var list = new JsonArray();
foreach (var (_, entry) in keyed)
{
if (entry is JsonObject e && !Waits(e)) continue;
list.Add(entry?.DeepClone());
}
if (list.Count == 0) project.Remove(PendingPath);
else project[PendingPath] = list;
}
return ProjectSettings.FromJson(project.ToJsonString(), allowNewer: true);
}
/// <summary>
/// The key of a pending entry: its photo and which copy of it (<see cref="ProjectContent.PhotoKey"/>: "sha:…#0", or
/// "photo:size@ticks#0" for a photo not hashed), or its JSON for an entry naming no photo.
/// </summary>
private static string KeyOf(JsonNode? entry) => ProjectContent.PhotoKey(entry) ?? "raw:" + (entry?.ToJsonString() ?? "null");
/// <summary>The entry of the photo of <paramref name="template"/> holding no position; null for an entry naming no photo.</summary>
private static JsonNode? Unplaced(JsonNode? template)
{
if (template is not JsonObject entry || KeyOf(entry).StartsWith("raw:", StringComparison.Ordinal)) return null;
var empty = new JsonObject();
foreach (var name in new[] { "sha256", "size", "capturedAt", "occurrence" })
{
if (entry[name] is { } value) empty[name] = value.DeepClone();
}
empty["excluded"] = false;
empty["hero"] = false;
empty["keyframes"] = new JsonArray();
return empty;
}
private static bool Flag(JsonObject entry, string name) => entry[name] is JsonValue value && value.TryGetValue<bool>(out var set) && set;
/// <summary>A pending entry still holds a position (its unknown members count too: they are not this Chronos's to drop).</summary>
private static bool Waits(JsonObject entry) =>
Flag(entry, "excluded") || Flag(entry, "hero") || entry["keyframes"] is JsonArray { Count: > 0 }
|| entry.Any(p => p.Key is not ("sha256" or "size" or "capturedAt" or "occurrence" or "excluded" or "hero" or "keyframes"));
/// <summary>One outside change (<paramref name="basis"/> → <paramref name="theirs"/>) applied to any number of projects made from the basis.</summary>
public sealed class Rebase(ProjectSettings basis, ProjectSettings theirs)
{
public ProjectSettings Apply(ProjectSettings ours)
{
ArgumentNullException.ThrowIfNull(ours);
return Merge(basis, ours, theirs);
}
}
/// <summary>A project's JSON text as settings, a newer Chronos's too (read-only there).</summary>
/// <exception cref="InvalidDataException">The text is not a project.</exception>
internal static ProjectSettings Read(string json)
{
try
{
return ProjectSettings.FromJson(json, allowNewer: true);
}
catch (JsonException ex)
{
throw new InvalidDataException(ex.Message, ex);
}
}
}