@morshoto/framekit 0.1.10 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,295 @@
1
+ import { createHash } from "node:crypto";
2
+ import { validateTimelineIr } from "./editing-session.js";
3
+ /**
4
+ * Three-way merge for the provider-neutral timeline. BASE is never written;
5
+ * OURS is the agent's desired state and THEIRS is the latest provider state.
6
+ */
7
+ export function reconcileTimelineIr(input) {
8
+ const { base, ours, theirs } = input;
9
+ const providerRevisionChanged = !sameRevision(base.revision, theirs.revision);
10
+ const common = {
11
+ providerRevisionChanged,
12
+ baseRevision: structuredClone(base.revision),
13
+ oursRevision: structuredClone(ours.revision),
14
+ theirsRevision: structuredClone(theirs.revision),
15
+ };
16
+ for (const [source, timeline] of [["base", base], ["ours", ours], ["theirs", theirs]]) {
17
+ try {
18
+ validateTimelineIr(timeline);
19
+ }
20
+ catch (error) {
21
+ return { status: "conflicted", ...common, conflicts: [validationConflict(source, timeline, error)] };
22
+ }
23
+ }
24
+ const conflicts = [];
25
+ if (base.project.id !== ours.project.id || base.project.id !== theirs.project.id
26
+ || base.sequence.id !== ours.sequence.id || base.sequence.id !== theirs.sequence.id) {
27
+ conflicts.push({
28
+ kind: "ambiguous-identity",
29
+ entity: "sequence",
30
+ id: base.sequence.id,
31
+ path: "project/sequence",
32
+ baseValue: `${base.project.id}/${base.sequence.id}`,
33
+ oursValue: `${ours.project.id}/${ours.sequence.id}`,
34
+ theirsValue: `${theirs.project.id}/${theirs.sequence.id}`,
35
+ message: "BASE, OURS, and THEIRS do not address the same project and sequence",
36
+ });
37
+ return { status: "conflicted", ...common, conflicts };
38
+ }
39
+ const project = mergeRecord("project", "project", "project", base.project, ours.project, theirs.project, conflicts);
40
+ const baseSequence = sequenceMetadata(base);
41
+ const oursSequence = sequenceMetadata(ours);
42
+ const theirsSequence = sequenceMetadata(theirs);
43
+ const sequence = mergeRecord("sequence", base.sequence.id, "sequence", baseSequence, oursSequence, theirsSequence, conflicts);
44
+ const resources = mergeCollection("resource", "resources", base.resources, ours.resources, theirs.resources, conflicts);
45
+ const occurrences = mergeCollection("occurrence", "sequence.occurrences", base.sequence.occurrences, ours.sequence.occurrences, theirs.sequence.occurrences, conflicts);
46
+ const storyElements = mergeCollection("story-element", "sequence.storyElements", base.sequence.storyElements, ours.sequence.storyElements, theirs.sequence.storyElements, conflicts);
47
+ const markers = mergeCollection("marker", "sequence.markers", base.sequence.markers, ours.sequence.markers, theirs.sequence.markers, conflicts);
48
+ const captions = mergeCollection("caption", "sequence.captions", base.sequence.captions, ours.sequence.captions, theirs.sequence.captions, conflicts);
49
+ if (conflicts.length > 0 || !project || !sequence)
50
+ return { status: "conflicted", ...common, conflicts };
51
+ const merged = {
52
+ schemaVersion: 1,
53
+ project: project,
54
+ sequence: {
55
+ ...sequence,
56
+ occurrences: occurrences,
57
+ storyElements: storyElements,
58
+ markers: markers,
59
+ captions: captions,
60
+ },
61
+ resources: resources,
62
+ revision: structuredClone(theirs.revision),
63
+ };
64
+ try {
65
+ validateTimelineIr(merged);
66
+ }
67
+ catch (error) {
68
+ return { status: "conflicted", ...common, conflicts: [validationConflict("merged", merged, error)] };
69
+ }
70
+ return { status: "rebased", ...common, merged, conflicts: [] };
71
+ }
72
+ function sequenceMetadata(timeline) {
73
+ const { occurrences: _occurrences, storyElements: _storyElements, markers: _markers, captions: _captions, ...metadata } = timeline.sequence;
74
+ return metadata;
75
+ }
76
+ function mergeCollection(entity, path, base, ours, theirs, conflicts) {
77
+ const baseMap = uniqueEntityMap(entity, base, conflicts);
78
+ const oursMap = uniqueEntityMap(entity, ours, conflicts);
79
+ const theirsMap = uniqueEntityMap(entity, theirs, conflicts);
80
+ if (!baseMap || !oursMap || !theirsMap)
81
+ return undefined;
82
+ const ids = [...new Set([
83
+ ...base.map(({ id }) => id),
84
+ ...[...oursMap.keys()].filter((id) => !baseMap.has(id)),
85
+ ...[...theirsMap.keys()].filter((id) => !baseMap.has(id)),
86
+ ])];
87
+ const additions = ids.filter((id) => !baseMap.has(id)).sort((left, right) => left.localeCompare(right));
88
+ const orderedIds = [...base.map(({ id }) => id), ...additions];
89
+ const merged = [];
90
+ for (const id of orderedIds) {
91
+ const value = mergeEntity(entity, `${path}[${id}]`, id, baseMap.get(id), oursMap.get(id), theirsMap.get(id), conflicts);
92
+ if (value)
93
+ merged.push(value);
94
+ }
95
+ return merged;
96
+ }
97
+ function mergeEntity(entity, path, id, base, ours, theirs, conflicts) {
98
+ if (!base) {
99
+ if (!ours)
100
+ return structuredClone(theirs);
101
+ if (!theirs)
102
+ return structuredClone(ours);
103
+ if (deepEqual(ours, theirs))
104
+ return structuredClone(ours);
105
+ conflicts.push({ kind: "insert-conflict", entity, id, path, oursValue: ours, theirsValue: theirs, message: `both sides inserted different values for ${entity} ${id}` });
106
+ return undefined;
107
+ }
108
+ if (!ours && !theirs)
109
+ return undefined;
110
+ if (!ours) {
111
+ if (deepEqual(theirs, base))
112
+ return undefined;
113
+ conflicts.push({ kind: "delete-modify-conflict", entity, id, path, baseValue: base, theirsValue: theirs, message: `agent deleted ${entity} ${id} while provider modified it` });
114
+ return undefined;
115
+ }
116
+ if (!theirs) {
117
+ if (deepEqual(ours, base))
118
+ return undefined;
119
+ conflicts.push({ kind: "delete-modify-conflict", entity, id, path, baseValue: base, oursValue: ours, message: `provider deleted ${entity} ${id} while agent modified it` });
120
+ return undefined;
121
+ }
122
+ return mergeRecord(entity, id, path, base, ours, theirs, conflicts);
123
+ }
124
+ function mergeRecord(entity, id, path, base, ours, theirs, conflicts) {
125
+ const merged = {};
126
+ for (const key of [...new Set([...Object.keys(base), ...Object.keys(ours), ...Object.keys(theirs)])].sort()) {
127
+ const value = mergeValue(entity, id, `${path}.${key}`, base[key], ours[key], theirs[key], conflicts);
128
+ if (value !== undefined)
129
+ merged[key] = value;
130
+ }
131
+ return conflicts.some((conflict) => conflict.id === id && conflict.path.startsWith(path)) ? undefined : merged;
132
+ }
133
+ function mergeValue(entity, id, path, base, ours, theirs, conflicts) {
134
+ if (deepEqual(ours, base))
135
+ return structuredClone(theirs);
136
+ if (deepEqual(theirs, base))
137
+ return structuredClone(ours);
138
+ if (deepEqual(ours, theirs))
139
+ return structuredClone(ours);
140
+ if (isRecord(base) && isRecord(ours) && isRecord(theirs))
141
+ return mergeRecord(entity, id, path, base, ours, theirs, conflicts);
142
+ conflicts.push({ kind: "property-conflict", entity, id, path, baseValue: base, oursValue: ours, theirsValue: theirs, message: `both sides changed ${path}` });
143
+ return undefined;
144
+ }
145
+ function uniqueEntityMap(entity, values, conflicts) {
146
+ const result = new Map();
147
+ for (const value of values) {
148
+ if (result.has(value.id)) {
149
+ conflicts.push({ kind: "ambiguous-identity", entity, id: value.id, path: entity, message: `duplicate ${entity} identity ${value.id}` });
150
+ return undefined;
151
+ }
152
+ result.set(value.id, value);
153
+ }
154
+ return result;
155
+ }
156
+ function sameRevision(left, right) {
157
+ return left.id === right.id && left.sequence === right.sequence;
158
+ }
159
+ function validationConflict(source, timeline, error) {
160
+ const message = error instanceof Error ? error.message : String(error);
161
+ const detail = message.replace(/^TIMELINE_IR_INVALID:\s*/, "");
162
+ const duplicate = detail.match(/^duplicate (resource|occurrence|story element|marker|caption) id (.+)$/i);
163
+ if (duplicate) {
164
+ const entity = entityForLabel(duplicate[1]);
165
+ return {
166
+ kind: "ambiguous-identity",
167
+ entity,
168
+ id: duplicate[2],
169
+ path: collectionPath(entity),
170
+ message: `${source} timeline validation failed: ${detail}`,
171
+ };
172
+ }
173
+ const location = validationLocation(detail, timeline);
174
+ return {
175
+ kind: "invalid-state",
176
+ ...location,
177
+ message: `${source} timeline validation failed: ${detail}`,
178
+ };
179
+ }
180
+ function validationLocation(detail, timeline) {
181
+ const topLevelField = detail.match(/^(project|sequence)\.(.+)$/);
182
+ if (topLevelField) {
183
+ const entity = entityForLabel(topLevelField[1]);
184
+ return { entity, id: timelineEntityId(timeline, entity), path: topLevelField[0] };
185
+ }
186
+ if (detail === "project is required")
187
+ return { entity: "project", id: "unknown", path: "project" };
188
+ if (detail === "sequence is required")
189
+ return { entity: "sequence", id: "unknown", path: "sequence" };
190
+ const entityField = parseEntityField(detail);
191
+ if (entityField) {
192
+ const entity = entityForLabel(entityField.label);
193
+ return { entity, id: entityField.id, path: `${collectionPath(entity)}[${entityField.id}].${entityField.field}` };
194
+ }
195
+ const unsupportedMediaKind = detail.match(/^resource (.+) has unsupported mediaKind$/);
196
+ if (unsupportedMediaKind)
197
+ return { entity: "resource", id: unsupportedMediaKind[1], path: `resources[${unsupportedMediaKind[1]}].mediaKind` };
198
+ const occurrenceReference = parseOccurrenceReference(detail);
199
+ if (occurrenceReference) {
200
+ const field = occurrenceReference.kind === "resource" ? "mediaId" : "attachedTo";
201
+ return { entity: "occurrence", id: occurrenceReference.id, path: `sequence.occurrences[${occurrenceReference.id}].${field}` };
202
+ }
203
+ const storyReference = detail.match(/^story element (.+) references unknown occurrence$/);
204
+ if (storyReference)
205
+ return { entity: "story-element", id: storyReference[1], path: `sequence.storyElements[${storyReference[1]}].occurrenceId` };
206
+ const collection = detail.match(/^(resources|occurrences|storyElements|markers|captions) must be an array$/);
207
+ if (collection) {
208
+ const entity = entityForCollection(collection[1]);
209
+ return { entity, id: "unknown", path: collection[1] };
210
+ }
211
+ if (detail.startsWith("revision."))
212
+ return { entity: "sequence", id: timelineEntityId(timeline, "sequence"), path: detail };
213
+ return { entity: "sequence", id: timelineEntityId(timeline, "sequence"), path: "timeline" };
214
+ }
215
+ function parseEntityField(detail) {
216
+ for (const label of ["resource", "occurrence", "story element", "marker", "caption"]) {
217
+ const prefix = `${label} `;
218
+ if (!detail.startsWith(prefix))
219
+ continue;
220
+ const remainder = detail.slice(prefix.length);
221
+ const separator = remainder.lastIndexOf(".");
222
+ if (separator <= 0 || separator === remainder.length - 1)
223
+ continue;
224
+ const fieldEnd = remainder.indexOf(" ", separator + 1);
225
+ const field = remainder.slice(separator + 1, fieldEnd === -1 ? remainder.length : fieldEnd);
226
+ if (!field)
227
+ continue;
228
+ return { label, id: remainder.slice(0, separator), field };
229
+ }
230
+ return undefined;
231
+ }
232
+ function parseOccurrenceReference(detail) {
233
+ const prefix = "occurrence ";
234
+ const marker = " references unknown ";
235
+ if (!detail.startsWith(prefix))
236
+ return undefined;
237
+ const remainder = detail.slice(prefix.length);
238
+ const separator = remainder.lastIndexOf(marker);
239
+ if (separator <= 0)
240
+ return undefined;
241
+ const target = remainder.slice(separator + marker.length);
242
+ const targetEnd = target.indexOf(" ");
243
+ const kind = target.slice(0, targetEnd === -1 ? target.length : targetEnd);
244
+ if (kind !== "resource" && kind !== "attachment")
245
+ return undefined;
246
+ return { id: remainder.slice(0, separator), kind };
247
+ }
248
+ function entityForLabel(label) {
249
+ return label === "story element" ? "story-element" : label;
250
+ }
251
+ function entityForCollection(collection) {
252
+ switch (collection) {
253
+ case "resources": return "resource";
254
+ case "occurrences": return "occurrence";
255
+ case "storyElements": return "story-element";
256
+ case "markers": return "marker";
257
+ case "captions": return "caption";
258
+ default: return "sequence";
259
+ }
260
+ }
261
+ function collectionPath(entity) {
262
+ switch (entity) {
263
+ case "resource": return "resources";
264
+ case "occurrence": return "sequence.occurrences";
265
+ case "story-element": return "sequence.storyElements";
266
+ case "marker": return "sequence.markers";
267
+ case "caption": return "sequence.captions";
268
+ case "project": return "project";
269
+ case "sequence": return "sequence";
270
+ }
271
+ }
272
+ function timelineEntityId(timeline, entity) {
273
+ if (entity === "project")
274
+ return typeof timeline?.project?.id === "string" ? timeline.project.id : "unknown";
275
+ return typeof timeline?.sequence?.id === "string" ? timeline.sequence.id : "unknown";
276
+ }
277
+ function deepEqual(left, right) {
278
+ return stableJson(left) === stableJson(right);
279
+ }
280
+ function stableJson(value) {
281
+ if (value === null || typeof value !== "object")
282
+ return JSON.stringify(value);
283
+ if (Array.isArray(value))
284
+ return `[${value.map(stableJson).join(",")}]`;
285
+ const entries = Object.entries(value).filter(([, child]) => child !== undefined).sort(([left], [right]) => left.localeCompare(right));
286
+ return `{${entries.map(([key, child]) => `${JSON.stringify(key)}:${stableJson(child)}`).join(",")}}`;
287
+ }
288
+ export function timelineIrContentDigest(timeline) {
289
+ const content = structuredClone(timeline);
290
+ delete content.revision;
291
+ return createHash("sha256").update(stableJson(content)).digest("hex");
292
+ }
293
+ function isRecord(value) {
294
+ return value !== null && typeof value === "object" && !Array.isArray(value);
295
+ }