Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Sync/VQMerge.swift3// Description: The client conflict policy of CONTRACT §1.2, as a pure function of (base, local, remote).4import Foundation56/// How the parts of an object that are not element lists are reconciled.7public enum VQMergeGranularity: String, Sendable, Hashable, Codable {8 /// The contract's policy: the last writer's object wins (this device, since it is the one retrying).9 case object10 /// Opt-in refinement: last writer wins **per top-level key** — a key this device did not touch keeps the server's11 /// value. Never loses more than `.object`.12 case field13}1415public struct VQMergeOutcome: Sendable, Equatable {16 /// What to write.17 public var merged: VQJSON18 /// Names of the element lists that were merged element-wise (e.g. `["symbols"]`).19 public var mergedLists: [String]20 /// Top-level keys whose server-side change is discarded by the merge (both sides changed them, or the whole21 /// object was taken from this device): the "text differs" case the UI must show.22 public var overwrittenKeys: [String]23}2425public enum VQMerge {26 /// Element lists merged element-wise, per kind: (key of the list, key of an element's identity; nil = the element itself).27 /// CONTRACT §1.2: watchlist (symbols), portfolio (positions by symbol — and cash by currency), `project.items`, `chart.drawings`.28 public static func elementLists(of kind: VQObjectKind) -> [(list: String, identity: String?)] {29 switch kind {30 case .watchlist: return [("symbols", nil)]31 case .portfolio: return [("positions", "symbol"), ("cash", "currency")]32 case .project: return [("items", "id")]33 case .chart: return [("drawings", "id")]34 default: return []35 }36 }3738 /// - Parameters:39 /// - base: the object this device's edit started from (nil when it created the object).40 /// - local: what this device wants to write.41 /// - remote: what the server holds now.42 public static func merge(kind: VQObjectKind, base: VQJSON?, local: VQJSON, remote: VQJSON, granularity: VQMergeGranularity = .object) -> VQMergeOutcome {43 guard let l = local.objectValue, let r = remote.objectValue else {44 return VQMergeOutcome(merged: local, mergedLists: [], overwrittenKeys: local == remote ? [] : ["*"])45 }46 let b = base?.objectValue47 let lists = elementLists(of: kind)48 let listKeys = Set(lists.map(\.list))49 var out: VQJSONObject = [:]50 var overwritten: [String] = []51 var mergedLists: [String] = []5253 for key in Set(l.keys).union(r.keys).subtracting(listKeys).sorted() {54 let lv = l[key], rv = r[key], bv = b?[key]55 let localChanged = b == nil ? true : lv != bv56 let remoteChanged = b == nil ? true : rv != bv57 let value: VQJSON?58 switch granularity {59 case .object: value = lv60 case .field: value = localChanged ? lv : rv61 }62 if let value { out[key] = value }63 if value != rv, remoteChanged, lv != rv { overwritten.append(key) }64 }6566 for (list, identity) in lists {67 let la = l[list]?.arrayValue, ra = r[list]?.arrayValue68 if la == nil && ra == nil { continue }69 let merged = mergeElements(base: b?[list]?.arrayValue, local: la ?? [], remote: ra ?? [], identity: identity)70 out[list] = .array(merged)71 if (la ?? []) != (ra ?? []) { mergedLists.append(list) }72 }73 return VQMergeOutcome(merged: .object(out), mergedLists: mergedLists, overwrittenKeys: overwritten)74 }7576 /// Union by identity, local edit wins per element:77 /// - an element this device added or changed keeps its local version;78 /// - an element this device removed stays removed;79 /// - an element this device did not touch follows the server (its version, or its removal);80 /// - an element only the server has is kept.81 /// Order: the local order, then the server-only elements in the server's order.82 static func mergeElements(base: [VQJSON]?, local: [VQJSON], remote: [VQJSON], identity: String?) -> [VQJSON] {83 func id(_ v: VQJSON) -> String {84 if let identity, let s = v[identity]?.displayString { return s }85 return v.stringValue ?? v.text()86 }87 var baseByID: [String: VQJSON] = [:]88 for v in base ?? [] { baseByID[id(v)] = v }89 var remoteByID: [String: VQJSON] = [:]90 for v in remote { remoteByID[id(v)] = v }91 var out: [VQJSON] = []92 var seen = Set<String>()93 for v in local {94 let k = id(v)95 guard seen.insert(k).inserted else { continue }96 if let was = baseByID[k], was == v {97 if let now = remoteByID[k] { out.append(now) } // untouched here: follow the server (or its removal)98 } else {99 out.append(v) // added or edited here: local wins100 }101 }102 for v in remote {103 let k = id(v)104 guard !seen.contains(k) else { continue }105 seen.insert(k)106 if baseByID[k] == nil { out.append(v) } // new on the server; (in base and gone locally = removed here)107 }108 return out109 }110}111