feat(projects): workspace projects with linear versions, the local archive as their home

Owner review 2, phase 5a (R8): editing moves out of the library into a workspace on a fast disk, and a
sequence gets several projects, each with a linear version history pushed and pulled like git.

- Core: ProjectSettings keeps members a newer Chronos wrote (Extra) and reads a newer settings format
  read-only; ProjectContent is the portable form of a version (every frame position parked by photo,
  canonical text, SHA-256 content hash); ProjectBundle format 2 adds the workspace section, and a file
  without it is still written as format 1. JobKind.WorkspaceCopy = 20 (19 kept for Convert).
- Data: migration 0009 (projects, project_versions, the render's project columns); ProjectService on
  ArchiveService.Projects keeps projects as sidecars first (.chronos/projects/<id>/), then the index,
  under the sequence lease: create, rename, delete into the projects' trash, history, push with
  fast-forward, idempotent repeat, divergence and hash checks. Main is made from the sequence's settings
  and mirrored both ways, so every older code path keeps working; outside writes become "external"
  versions, a mirror a crash cut short is completed or merged. Full scans and rebuilds take the projects
  back from their sidecars.
- ProjectMerge moves from the App to Data/Projects, merges pending frames photo by photo and replays
  unpushed commits on a moved head.
- Workspaces: WorkspaceStore, WorkspaceSync (checkout, save, commit, push, pull with replay and merge,
  conflicts settled by keep mine / take server / save both, restore, status) and the WorkspaceCopy job
  (proxies copied hash-verified and resumable; originals refused until phase 5c).
- Renders of a project version place its positions on the frames and record the project and version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c4c1802884e403db8759ed0501f770a67a047f20)
This commit is contained in:
Alby96 committed 2026-10-27 22:51:32 +01:00
1 parent e3cbe30b29
commit 03d32f18d3
51 files changed
+4917 -108

No files matched your search

+253
View File
@@ -0,0 +1,253 @@
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>
/// 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"/>).
/// Members this Chronos does not know merge like the others and are kept.
/// </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";
private const string PendingPath = "pendingFrames";
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>
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));
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>
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"/>).</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) keyed[KeyOf(entry)] = 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 ("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)
{
if (entry is JsonObject e)
{
var occurrence = e["occurrence"] is JsonValue o && o.TryGetValue<int>(out var n) ? n : 0;
if (e["sha256"] is JsonValue s && s.TryGetValue<string>(out var sha) && sha.Length > 0)
return string.Create(CultureInfo.InvariantCulture, $"sha:{sha.ToLowerInvariant()}#{occurrence}");
var size = e["size"] is JsonValue z && z.TryGetValue<long>(out var bytes) ? bytes : 0;
if (e["capturedAt"] is JsonValue c && c.TryGetValue<DateTime>(out var at))
return string.Create(CultureInfo.InvariantCulture, $"photo:{size}@{at.Ticks}#{occurrence}");
}
return "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);
}
}
}