@morshoto/framekit 0.1.10 → 0.1.12

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.
Files changed (31) hide show
  1. package/README.md +1 -0
  2. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +68 -5
  3. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +175 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery.js +31 -0
  5. package/dist-package/adapters/final-cut/typescript/src/canonical-verification.js +16 -0
  6. package/dist-package/adapters/final-cut/typescript/src/canonical.js +600 -56
  7. package/dist-package/adapters/final-cut/typescript/src/connection.js +52 -14
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml-console-experiment.js +74 -0
  9. package/dist-package/adapters/final-cut/typescript/src/index.js +9 -0
  10. package/dist-package/adapters/final-cut/typescript/src/live.js +11 -4
  11. package/dist-package/adapters/final-cut/typescript/src/native.js +321 -19
  12. package/dist-package/adapters/final-cut/typescript/src/session.js +19 -1
  13. package/dist-package/adapters/final-cut/typescript/src/shadow-mutation.js +174 -0
  14. package/dist-package/adapters/final-cut/typescript/src/sqlite-experiment.js +472 -0
  15. package/dist-package/adapters/final-cut/typescript/src/sqlite-inspection.js +433 -0
  16. package/dist-package/adapters/final-cut/typescript/src/sqlite-materialization.js +230 -0
  17. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +372 -0
  18. package/dist-package/adapters/final-cut/typescript/src/unattended-editing.js +66 -0
  19. package/dist-package/apps/mcp-server/src/headless-sessions.js +112 -0
  20. package/dist-package/apps/mcp-server/src/main.js +36 -2
  21. package/dist-package/apps/mcp-server/src/materialization-jobs.js +326 -0
  22. package/dist-package/apps/mcp-server/src/routing.js +17 -0
  23. package/dist-package/apps/mcp-server/src/server.js +146 -12
  24. package/dist-package/packages/runtime/src/application/media-analysis-service.js +52 -6
  25. package/dist-package/packages/runtime/src/context/project-catalog.js +46 -1
  26. package/dist-package/packages/runtime/src/index.js +2 -0
  27. package/dist-package/packages/runtime/src/skills/builtin.js +99 -8
  28. package/dist-package/packages/runtime/src/skills/runtime.js +1 -0
  29. package/dist-package/packages/runtime/src/timeline/drift-reconciliation.js +295 -0
  30. package/dist-package/packages/runtime/src/timeline/editing-session.js +490 -0
  31. package/package.json +10 -6
@@ -3,9 +3,26 @@ import { mkdtemp, rm, stat } from "node:fs/promises";
3
3
  import { basename, join } from "node:path";
4
4
  import { tmpdir } from "node:os";
5
5
  import { promisify } from "node:util";
6
- import { canonicalSnapshotDigest, assertTimelineTargetReadAfterWrite, createTimelineTarget, resolveTimelineTarget, reconcileProjectCatalog, validateProjectCatalog, withCapabilityFamilies, CapabilityUnavailableError, } from "../../../../packages/runtime/src/index.js";
6
+ import { canonicalSnapshotDigest, canonicalTimelineMode, assertTimelineTargetReadAfterWrite, createTimelineTarget, resolveTimelineTarget, reconcileProjectCatalog, validateProjectCatalog, withCapabilityFamilies, CapabilityUnavailableError, } from "../../../../packages/runtime/src/index.js";
7
+ import { recoverCanonicalNativeMutation } from "./canonical-recovery.js";
8
+ import { verifyCanonicalReadback } from "./canonical-verification.js";
7
9
  import { FcpxmlDocumentAdapter } from "./fcpxml.js";
8
10
  const execFile = promisify(execFileCallback);
11
+ /** Report the complete guarantees required before claiming canonical live support. */
12
+ export function assessCanonicalLiveReadiness(capabilities) {
13
+ const mode = canonicalTimelineMode(capabilities);
14
+ const editor = capabilities.editor;
15
+ const missing = [
16
+ ...(mode === "canonical-write" ? [] : ["canonical-write"]),
17
+ ...(!editor.projectCatalogRead ? ["projectCatalogRead"] : []),
18
+ ...(!editor.projectSelection ? ["projectSelection"] : []),
19
+ ...(!editor.timelineSnapshotRead ? ["timelineSnapshotRead"] : []),
20
+ ...(!editor.timelineWrite ? ["timelineWrite"] : []),
21
+ ...(!editor.readAfterWrite ? ["readAfterWrite"] : []),
22
+ ...(!editor.rollback ? ["rollback"] : []),
23
+ ];
24
+ return { ready: missing.length === 0, mode, missing };
25
+ }
9
26
  /** Reads the active Final Cut project through its headed Export XML command. */
10
27
  export class FinalCutCanonicalSnapshotSource {
11
28
  executor;
@@ -67,20 +84,42 @@ on findWindow(finalCut, expectedNames, timeoutSeconds, timeoutMessage)
67
84
  end repeat
68
85
  end findWindow
69
86
 
70
- on pressButtonIfPresent(targetWindow, expectedNames)
71
- repeat with candidate in (buttons of targetWindow)
87
+ on findDescendantByRole(container, expectedRole, timeoutSeconds, timeoutMessage)
88
+ set deadline to (current date) + timeoutSeconds
89
+ repeat
72
90
  try
73
- set candidateName to name of candidate as text
74
- repeat with expectedName in expectedNames
75
- if candidateName is (expectedName as text) and enabled of candidate then
76
- perform action "AXPress" of candidate
77
- return true
78
- end if
91
+ repeat with candidate in (entire contents of container)
92
+ try
93
+ if role of candidate is expectedRole then return candidate
94
+ end try
79
95
  end repeat
80
96
  end try
97
+ if (current date) > deadline then error timeoutMessage
98
+ delay 0.1
99
+ end repeat
100
+ end findDescendantByRole
101
+
102
+ on pressDescendantButtonIfPresent(container, expectedNames)
103
+ try
104
+ set candidates to entire contents of container
105
+ on error
106
+ return false
107
+ end try
108
+ repeat with candidate in candidates
109
+ try
110
+ if role of candidate is "AXButton" then
111
+ set candidateName to name of candidate as text
112
+ repeat with expectedName in expectedNames
113
+ if candidateName is (expectedName as text) and enabled of candidate then
114
+ perform action "AXPress" of candidate
115
+ return true
116
+ end if
117
+ end repeat
118
+ end if
119
+ end try
81
120
  end repeat
82
121
  return false
83
- end pressButtonIfPresent
122
+ end pressDescendantButtonIfPresent
84
123
 
85
124
  end using terms from
86
125
 
@@ -112,25 +151,18 @@ tell application "System Events"
112
151
  end try
113
152
  perform action "AXPress" of exportCommand
114
153
  set exportWindow to my findWindow(finalCut, {"Export XML", "XML"}, 15, "FINAL_CUT_CANONICAL_EXPORT_WINDOW_UNAVAILABLE: Export XML window did not appear")
115
- my pressButtonIfPresent(exportWindow, {"Next…", "Next...", "Export"})
154
+ my pressDescendantButtonIfPresent(exportWindow, {"Next…", "Next...", "Export"})
116
155
  delay 0.2
117
156
  set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
118
157
  keystroke "g" using {command down, shift down}
119
- repeat 50 times
120
- try
121
- if exists sheet 1 of saveWindow then exit repeat
122
- end try
123
- delay 0.1
124
- end repeat
125
- if not (exists sheet 1 of saveWindow) then error "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: save path sheet did not appear"
126
- set pathSheet to sheet 1 of saveWindow
127
- if (count of text fields of pathSheet) is 0 then error "FINAL_CUT_CANONICAL_SAVE_PATH_UNAVAILABLE: save path field did not appear"
128
- set value of text field 1 of pathSheet to ${appleScriptString(exportPath)}
158
+ set pathSheet to my findDescendantByRole(saveWindow, "AXSheet", 5, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: save path sheet did not appear")
159
+ set pathField to my findDescendantByRole(pathSheet, "AXTextField", 5, "FINAL_CUT_CANONICAL_SAVE_PATH_UNAVAILABLE: save path field did not appear")
160
+ set value of pathField to ${appleScriptString(exportPath)}
129
161
  key code 36
130
162
  delay 0.2
131
- if exists button "Save" of saveWindow then click button "Save" of saveWindow
163
+ my pressDescendantButtonIfPresent(saveWindow, {"Save"})
132
164
  delay 0.2
133
- if exists button "Replace" of saveWindow then click button "Replace" of saveWindow
165
+ my pressDescendantButtonIfPresent(saveWindow, {"Replace"})
134
166
  return "canonical-export-requested"
135
167
  end tell
136
168
  end tell`;
@@ -225,7 +257,7 @@ export class FinalCutCanonicalNativeProvider {
225
257
  const canonicalSnapshotCapability = snapshotProbe.available
226
258
  ? true
227
259
  : unavailableCanonicalSnapshot(snapshotProbe.reason);
228
- return withCapabilityFamilies({
260
+ const capabilities = withCapabilityFamilies({
229
261
  editor: {
230
262
  projectRead: snapshotProbe.available,
231
263
  timelineSnapshotRead: snapshotProbe.available,
@@ -244,6 +276,13 @@ export class FinalCutCanonicalNativeProvider {
244
276
  projectSelectionMode: "unavailable",
245
277
  backgroundLibraryInspection: Boolean(backgroundCatalog),
246
278
  compositeTransactions: snapshotProbe.available,
279
+ semanticOperations: {
280
+ "rename-clip": snapshotProbe.available,
281
+ "trim-clip": snapshotProbe.available && Boolean(this.native.trimSelectedClipToRange),
282
+ "add-marker": snapshotProbe.available && Boolean(this.native.addMarkerAtTime),
283
+ "ripple-delete": snapshotProbe.available && Boolean(this.native.rippleDeleteRange),
284
+ "set-gain": snapshotProbe.available && Boolean(this.native.setSelectedClipGain),
285
+ },
247
286
  },
248
287
  analyzers: {
249
288
  speechTranscribe: false,
@@ -269,6 +308,21 @@ export class FinalCutCanonicalNativeProvider {
269
308
  : false,
270
309
  },
271
310
  });
311
+ const readiness = assessCanonicalLiveReadiness(capabilities);
312
+ if (readiness.ready)
313
+ return capabilities;
314
+ return withCapabilityFamilies({
315
+ ...capabilities,
316
+ editor: {
317
+ ...capabilities.editor,
318
+ projectRead: false,
319
+ timelineSnapshotRead: false,
320
+ timelineWrite: false,
321
+ readAfterWrite: false,
322
+ rollback: false,
323
+ compositeTransactions: false,
324
+ },
325
+ });
272
326
  }
273
327
  async probeCanonicalSnapshot() {
274
328
  try {
@@ -306,11 +360,8 @@ export class FinalCutCanonicalNativeProvider {
306
360
  const before = await this.readProject();
307
361
  assertSameRevision(expectedRevision, before.revision);
308
362
  const operation = supportedCanonicalOperation(operations);
309
- const clip = before.timeline.clips.find(({ id }) => id === operation.clipId);
310
- if (!clip)
311
- throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
312
- const preview = structuredClone(before);
313
- preview.timeline.clips = preview.timeline.clips.map((candidate) => (candidate.id === operation.clipId ? { ...candidate, name: operation.name } : candidate));
363
+ assertCanonicalOperationAvailable(this.native, operation);
364
+ const preview = projectCanonicalOperation(before, operation);
314
365
  preview.revision = previewRevision(preview, before.revision);
315
366
  return preview;
316
367
  }
@@ -321,22 +372,46 @@ export class FinalCutCanonicalNativeProvider {
321
372
  async apply(operation, expectedRevision) {
322
373
  const before = await this.readProject();
323
374
  assertSameRevision(expectedRevision, before.revision);
324
- if (operation.type !== "rename-clip") {
325
- throw new Error(`CAPABILITY_UNAVAILABLE: final-cut native canonical provider does not support ${operation.type}`);
326
- }
327
- validateCanonicalRename(operation);
328
- const clip = before.timeline.clips.find(({ id }) => id === operation.clipId);
329
- if (!clip)
330
- throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
375
+ const supported = supportedCanonicalOperation([operation]);
376
+ const markerRange = supported.type === "add-marker" ? canonicalMarkerRange(before, supported.marker) : undefined;
377
+ const clipTarget = supported.type === "rename-clip" || supported.type === "trim-clip" || supported.type === "set-gain"
378
+ ? canonicalTargetForOperation(before, supported)
379
+ : undefined;
380
+ const clip = clipTarget?.clip;
381
+ const rippleTarget = supported.type === "ripple-delete" ? canonicalTargetForOperation(before, supported) : undefined;
382
+ const targetClip = clip;
383
+ const trimDuration = supported.type === "trim-clip"
384
+ ? validateCanonicalTrim(supported, clip, before)
385
+ : undefined;
331
386
  const timelineTarget = createTimelineTarget(before, {
332
- occurrenceId: clip.id,
333
- mediaId: clip.mediaId,
387
+ ...(targetClip ? { occurrenceId: targetClip.id, mediaId: targetClip.mediaId } : {}),
388
+ ...(rippleTarget?.range ? { range: rippleTarget.range } : {}),
389
+ ...(markerRange && compareRational(markerRange.duration, zeroRational()) > 0
390
+ ? { range: { start: markerRange.start, end: markerRange.end } }
391
+ : {}),
334
392
  });
335
393
  resolveTimelineTarget(before, timelineTarget);
336
- await this.resolveTarget(clip, before);
337
- const nativeResult = await this.native.renameSelectedClip(operation.name);
394
+ if (targetClip)
395
+ await this.resolveTarget(targetClip, before);
396
+ assertCanonicalOperationAvailable(this.native, supported);
397
+ const nativeResult = supported.type === "rename-clip"
398
+ ? await this.native.renameSelectedClip(supported.name)
399
+ : supported.type === "trim-clip"
400
+ ? await this.native.trimSelectedClipToRange({
401
+ start: structuredClone(clip.startTime),
402
+ end: addRational(clip.startTime, trimDuration),
403
+ })
404
+ : supported.type === "ripple-delete"
405
+ ? await this.native.rippleDeleteRange(rippleTarget.range)
406
+ : supported.type === "set-gain"
407
+ ? await this.native.setSelectedClipGain(supported.gainDb)
408
+ : await this.native.addMarkerAtTime({
409
+ start: markerRange.start,
410
+ duration: markerRange.duration,
411
+ name: supported.marker.name,
412
+ });
338
413
  if (!nativeResult.operationId || !nativeResult.undoAvailable) {
339
- throw new Error("FINAL_CUT_CANONICAL_UNDO_UNAVAILABLE: native rename did not expose Undo");
414
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_UNAVAILABLE: native edit did not expose Undo");
340
415
  }
341
416
  this.pending = {
342
417
  operationId: nativeResult.operationId,
@@ -346,27 +421,63 @@ export class FinalCutCanonicalNativeProvider {
346
421
  };
347
422
  try {
348
423
  const after = await this.readProject();
349
- const afterClip = after.timeline.clips.find(({ id }) => id === operation.clipId);
350
- if (!afterClip || afterClip.name !== operation.name) {
351
- throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: renamed occurrence was not read back from Final Cut");
424
+ if (supported.type === "rename-clip") {
425
+ const readback = verifyCanonicalReadback(before, after, timelineTarget, {
426
+ validateDiff: (diff) => {
427
+ const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
428
+ const changed = diff.modified.filter(({ itemId }) => itemId === supported.clipId);
429
+ if (!afterClip || afterClip.name !== supported.name
430
+ || diff.added.length !== 0
431
+ || diff.removed.length !== 0
432
+ || diff.modified.length !== 1
433
+ || changed.length !== 1
434
+ || diff.markerChanges.length !== 0
435
+ || diff.storyElementChanges.length !== 0
436
+ || diff.captionChanges.length !== 0
437
+ || diff.mediaChanges.length !== 0) {
438
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: renamed occurrence was not read back as a rename-only diff from Final Cut");
439
+ }
440
+ },
441
+ });
442
+ if (readback.beforeDigest !== this.pending.beforeDigest) {
443
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: canonical before digest changed during verification");
444
+ }
445
+ }
446
+ else if (supported.type === "trim-clip") {
447
+ const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
448
+ if (!afterClip || !sameRational(afterClip.startTime, clip.startTime)
449
+ || !sameRational(afterClip.durationTime, trimDuration)) {
450
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: trimmed occurrence range was not read back from Final Cut");
451
+ }
452
+ }
453
+ else if (supported.type === "set-gain") {
454
+ const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
455
+ if (!afterClip || (afterClip.gainDb ?? 0) !== supported.gainDb) {
456
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: gain was not read back from Final Cut");
457
+ }
458
+ }
459
+ else if (supported.type === "ripple-delete") {
460
+ assertRippleDeleteReadback(before, after, rippleTarget.clip, rippleTarget.range);
461
+ }
462
+ else {
463
+ assertMarkerReadback(before, after, supported.marker, markerRange);
352
464
  }
353
465
  if (canonicalSnapshotDigest(after) === this.pending.beforeDigest) {
354
466
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native edit did not change the canonical digest");
355
467
  }
356
- assertTimelineTargetReadAfterWrite(timelineTarget, before, after);
468
+ assertTimelineTargetReadAfterWrite(timelineTarget, before, after, supported.type === "ripple-delete" ? { allowOccurrenceRemoval: true } : undefined);
357
469
  this.pending.afterRevision = after.revision;
358
470
  return after.revision;
359
471
  }
360
472
  catch (error) {
361
473
  try {
362
- const undone = await this.native.undo(nativeResult.operationId);
363
- if (!undone.undone || undone.verification?.verified !== true) {
364
- throw new Error("native Undo did not verify restoration");
365
- }
366
- const restored = await this.readProject();
367
- if (canonicalSnapshotDigest(restored) !== this.pending.beforeDigest) {
368
- throw new Error("restored canonical digest does not match the pre-edit state");
369
- }
474
+ await recoverCanonicalNativeMutation({
475
+ operationId: nativeResult.operationId,
476
+ before,
477
+ target: timelineTarget,
478
+ undo: this.native.undo,
479
+ readSnapshot: () => this.readProject(),
480
+ });
370
481
  }
371
482
  catch (rollbackError) {
372
483
  const original = error instanceof Error ? error.message : String(error);
@@ -493,16 +604,449 @@ export class FinalCutCanonicalNativeProvider {
493
604
  }
494
605
  }
495
606
  function supportedCanonicalOperation(operations) {
496
- if (operations.length !== 1 || operations[0]?.type !== "rename-clip") {
497
- throw new Error("CAPABILITY_UNAVAILABLE: final-cut native canonical provider supports one rename-clip transaction");
607
+ if (operations.length !== 1 || (operations[0]?.type !== "rename-clip" && operations[0]?.type !== "trim-clip" && operations[0]?.type !== "add-marker" && operations[0]?.type !== "ripple-delete" && operations[0]?.type !== "set-gain")) {
608
+ throw new Error("CAPABILITY_UNAVAILABLE: final-cut native canonical provider supports one rename-clip, trim-clip, add-marker, ripple-delete, or set-gain transaction");
609
+ }
610
+ return operations[0].type === "rename-clip"
611
+ ? validateCanonicalRename(operations[0])
612
+ : operations[0].type === "add-marker"
613
+ ? validateCanonicalMarker(operations[0])
614
+ : operations[0].type === "set-gain"
615
+ ? validateCanonicalGain(operations[0])
616
+ : operations[0];
617
+ }
618
+ function canonicalTargetForOperation(snapshot, operation) {
619
+ if (operation.type === "rename-clip" || operation.type === "trim-clip" || operation.type === "set-gain") {
620
+ const clip = snapshot.timeline.clips.find(({ id }) => id === operation.clipId);
621
+ if (!clip)
622
+ throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
623
+ return { clip };
624
+ }
625
+ if (operation.timelineId !== snapshot.timeline.id) {
626
+ throw new Error(`TIMELINE_NOT_FOUND: ${operation.timelineId}`);
627
+ }
628
+ const range = canonicalRippleRange(snapshot, operation.range);
629
+ const candidates = snapshot.timeline.clips.filter((candidate) => {
630
+ const end = addRational(candidate.startTime, candidate.durationTime);
631
+ return compareRational(candidate.startTime, range.end) < 0 && compareRational(end, range.start) > 0;
632
+ });
633
+ if (candidates.length === 0) {
634
+ throw new Error("TARGET_NOT_FOUND: ripple-delete range does not intersect a timeline occurrence");
635
+ }
636
+ if (candidates.length > 1) {
637
+ throw new Error("AMBIGUOUS_TIMELINE_TARGET: ripple-delete range intersects multiple timeline occurrences");
638
+ }
639
+ const clip = candidates[0];
640
+ const clipEnd = addRational(clip.startTime, clip.durationTime);
641
+ if (compareRational(range.start, clip.startTime) < 0 || compareRational(range.end, clipEnd) > 0) {
642
+ throw new Error("INVALID_OPERATION: ripple-delete range must fit inside one timeline occurrence");
643
+ }
644
+ if (compareRational(range.start, clip.startTime) > 0 && compareRational(range.end, clipEnd) < 0) {
645
+ throw new Error("INVALID_OPERATION: ripple-delete middle-of-clip range requires a source-preserving split");
646
+ }
647
+ return { clip, range };
648
+ }
649
+ function projectCanonicalOperation(snapshot, operation) {
650
+ if (operation.type === "rename-clip" || operation.type === "set-gain") {
651
+ const { clip } = canonicalTargetForOperation(snapshot, operation);
652
+ return {
653
+ ...structuredClone(snapshot),
654
+ timeline: {
655
+ ...structuredClone(snapshot.timeline),
656
+ clips: snapshot.timeline.clips.map((candidate) => {
657
+ if (candidate.id !== clip.id)
658
+ return candidate;
659
+ return operation.type === "rename-clip"
660
+ ? { ...candidate, name: operation.name }
661
+ : { ...candidate, gainDb: operation.gainDb };
662
+ }),
663
+ },
664
+ };
665
+ }
666
+ if (operation.type === "trim-clip") {
667
+ const preview = structuredClone(snapshot);
668
+ const { clip } = canonicalTargetForOperation(preview, operation);
669
+ const trimDuration = validateCanonicalTrim(operation, clip, preview);
670
+ const updatedClip = {
671
+ ...clip,
672
+ duration: rationalSeconds(trimDuration),
673
+ durationTime: trimDuration,
674
+ };
675
+ preview.timeline.clips = preview.timeline.clips.map((candidate) => (candidate.id === clip.id ? updatedClip : candidate));
676
+ preview.timeline.storyElements = preview.timeline.storyElements.map((element) => (element.id === clip.id
677
+ ? { ...element, duration: updatedClip.duration, durationTime: updatedClip.durationTime }
678
+ : element));
679
+ const oldTimelineEnd = snapshot.timeline.durationTime
680
+ ? addRational(clip.startTime, clip.durationTime)
681
+ : undefined;
682
+ if (oldTimelineEnd && snapshot.timeline.durationTime && sameRational(oldTimelineEnd, snapshot.timeline.durationTime)) {
683
+ const nextTimelineEnd = addRational(clip.startTime, trimDuration);
684
+ preview.timeline.durationTime = nextTimelineEnd;
685
+ preview.timeline.duration = rationalSeconds(nextTimelineEnd);
686
+ }
687
+ return preview;
688
+ }
689
+ if (operation.type === "ripple-delete") {
690
+ const target = canonicalTargetForOperation(snapshot, operation);
691
+ return projectCanonicalRippleDelete(snapshot, target.range);
498
692
  }
499
- return validateCanonicalRename(operations[0]);
693
+ const range = canonicalMarkerRange(snapshot, operation.marker);
694
+ if (snapshot.timeline.markers.some(({ id }) => id === operation.marker.id)) {
695
+ throw new Error(`MARKER_ALREADY_EXISTS: ${operation.marker.id}`);
696
+ }
697
+ const marker = {
698
+ ...structuredClone(operation.marker),
699
+ start: rationalSeconds(range.start),
700
+ duration: rationalSeconds(range.duration),
701
+ startTime: range.start,
702
+ durationTime: range.duration,
703
+ };
704
+ return {
705
+ ...structuredClone(snapshot),
706
+ timeline: {
707
+ ...structuredClone(snapshot.timeline),
708
+ markers: [...snapshot.timeline.markers, marker],
709
+ },
710
+ };
711
+ }
712
+ function projectCanonicalRippleDelete(snapshot, range) {
713
+ const duration = subtractRational(range.end, range.start);
714
+ const clips = snapshot.timeline.clips.flatMap((clip) => projectClipAfterRippleDelete(clip, range, duration));
715
+ const storyElements = snapshot.timeline.storyElements.flatMap((element) => projectStoryElementAfterRippleDelete(element, range, duration));
716
+ const markers = snapshot.timeline.markers.flatMap((marker) => projectMarkerAfterRippleDelete(marker, range, duration));
717
+ const captions = snapshot.timeline.captions.flatMap((caption) => projectCaptionAfterRippleDelete(caption, range, duration));
718
+ const timelineDuration = subtractRational(snapshot.timeline.durationTime ?? secondsToRational(snapshot.timeline.duration, snapshot.timeline.frameDuration), duration);
719
+ return {
720
+ ...structuredClone(snapshot),
721
+ timeline: {
722
+ ...structuredClone(snapshot.timeline),
723
+ duration: rationalSeconds(timelineDuration),
724
+ durationTime: timelineDuration,
725
+ clips,
726
+ storyElements,
727
+ markers,
728
+ captions,
729
+ },
730
+ };
731
+ }
732
+ function projectClipAfterRippleDelete(clip, range, removedDuration) {
733
+ const clipEnd = addRational(clip.startTime, clip.durationTime);
734
+ if (compareRational(clipEnd, range.start) <= 0)
735
+ return [structuredClone(clip)];
736
+ if (compareRational(clip.startTime, range.end) >= 0) {
737
+ const startTime = subtractRational(clip.startTime, removedDuration);
738
+ return [{ ...structuredClone(clip), start: rationalSeconds(startTime), startTime }];
739
+ }
740
+ if (compareRational(clip.startTime, range.start) < 0) {
741
+ const duration = subtractRational(range.start, clip.startTime);
742
+ return compareRational(duration, zeroRational()) > 0
743
+ ? [{ ...structuredClone(clip), duration: rationalSeconds(duration), durationTime: duration }]
744
+ : [];
745
+ }
746
+ if (compareRational(clipEnd, range.end) > 0) {
747
+ const duration = subtractRational(clipEnd, range.end);
748
+ return [{
749
+ ...structuredClone(clip),
750
+ start: rationalSeconds(range.start),
751
+ startTime: structuredClone(range.start),
752
+ duration: rationalSeconds(duration),
753
+ durationTime: duration,
754
+ }];
755
+ }
756
+ return [];
757
+ }
758
+ function projectStoryElementAfterRippleDelete(element, range, removedDuration) {
759
+ if (!element.startTime || !element.durationTime)
760
+ return [structuredClone(element)];
761
+ const elementEnd = addRational(element.startTime, element.durationTime);
762
+ if (compareRational(elementEnd, range.start) <= 0)
763
+ return [structuredClone(element)];
764
+ if (compareRational(element.startTime, range.end) >= 0) {
765
+ const startTime = subtractRational(element.startTime, removedDuration);
766
+ return [{ ...structuredClone(element), start: rationalSeconds(startTime), startTime }];
767
+ }
768
+ if (compareRational(element.startTime, range.start) < 0) {
769
+ const duration = subtractRational(range.start, element.startTime);
770
+ return compareRational(duration, zeroRational()) > 0
771
+ ? [{ ...structuredClone(element), duration: rationalSeconds(duration), durationTime: duration }]
772
+ : [];
773
+ }
774
+ if (compareRational(elementEnd, range.end) > 0) {
775
+ const duration = subtractRational(elementEnd, range.end);
776
+ return [{
777
+ ...structuredClone(element),
778
+ start: rationalSeconds(range.start),
779
+ startTime: structuredClone(range.start),
780
+ duration: rationalSeconds(duration),
781
+ durationTime: duration,
782
+ }];
783
+ }
784
+ return [];
785
+ }
786
+ function projectMarkerAfterRippleDelete(marker, range, removedDuration) {
787
+ const start = marker.startTime ?? secondsToRational(marker.start, undefined);
788
+ const duration = marker.durationTime ?? secondsToRational(marker.duration, undefined);
789
+ const end = addRational(start, duration);
790
+ if (compareRational(end, range.start) <= 0)
791
+ return [structuredClone(marker)];
792
+ if (compareRational(start, range.end) >= 0) {
793
+ const shifted = subtractRational(start, removedDuration);
794
+ return [{ ...structuredClone(marker), start: rationalSeconds(shifted), startTime: shifted }];
795
+ }
796
+ return [];
797
+ }
798
+ function projectCaptionAfterRippleDelete(caption, range, removedDuration) {
799
+ const start = caption.startTime ?? secondsToRational(caption.start, undefined);
800
+ const duration = caption.durationTime ?? secondsToRational(caption.duration, undefined);
801
+ const end = addRational(start, duration);
802
+ if (compareRational(end, range.start) <= 0)
803
+ return [structuredClone(caption)];
804
+ if (compareRational(start, range.end) >= 0) {
805
+ const shifted = subtractRational(start, removedDuration);
806
+ return [{ ...structuredClone(caption), start: rationalSeconds(shifted), startTime: shifted }];
807
+ }
808
+ return [];
809
+ }
810
+ function canonicalRippleRange(snapshot, range) {
811
+ const frameDuration = snapshot.timeline.frameDuration;
812
+ if (!frameDuration)
813
+ throw new Error("CAPABILITY_UNAVAILABLE: ripple-delete requires sequence frame duration");
814
+ if (!Number.isFinite(range.start) || !Number.isFinite(range.end) || range.end <= range.start) {
815
+ throw new Error("INVALID_OPERATION: ripple-delete range must be finite and increasing");
816
+ }
817
+ const start = range.startTime ?? secondsToRational(range.start, frameDuration);
818
+ const duration = range.durationTime ?? secondsToRational(range.end - range.start, frameDuration);
819
+ if (Math.abs(rationalSeconds(start) - range.start) > 0.000001
820
+ || Math.abs(rationalSeconds(duration) - (range.end - range.start)) > 0.000001) {
821
+ throw new Error("INVALID_OPERATION: ripple-delete rational range disagrees with its numeric coordinates");
822
+ }
823
+ if (compareRational(duration, zeroRational()) <= 0) {
824
+ throw new Error("INVALID_OPERATION: ripple-delete range must have positive duration");
825
+ }
826
+ const end = addRational(start, duration);
827
+ if (!isFrameAligned(start, zeroRational(), frameDuration) || !isFrameAligned(end, zeroRational(), frameDuration)) {
828
+ throw new Error("INVALID_OPERATION: ripple-delete range must be frame-aligned");
829
+ }
830
+ const timelineDuration = snapshot.timeline.durationTime ?? secondsToRational(snapshot.timeline.duration, frameDuration);
831
+ if (compareRational(start, zeroRational()) < 0 || compareRational(end, timelineDuration) > 0) {
832
+ throw new Error("INVALID_OPERATION: ripple-delete range must fit inside the active timeline");
833
+ }
834
+ return { start, end };
835
+ }
836
+ function assertRippleDeleteReadback(before, after, targetClip, range) {
837
+ const expected = projectCanonicalRippleDelete(before, range);
838
+ if (canonicalSnapshotDigest(normalizeRippleSnapshot(after)) !== canonicalSnapshotDigest(normalizeRippleSnapshot(expected))) {
839
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete readback differed from the exact canonical projection");
840
+ }
841
+ if (!after.timeline.durationTime || !expected.timeline.durationTime
842
+ || !sameRational(after.timeline.durationTime, expected.timeline.durationTime)) {
843
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete duration was not read back exactly");
844
+ }
845
+ const expectedTarget = expected.timeline.clips.find(({ id }) => id === targetClip.id);
846
+ const actualTarget = after.timeline.clips.find(({ id }) => id === targetClip.id);
847
+ if (Boolean(expectedTarget) !== Boolean(actualTarget)) {
848
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete target occurrence changed unexpectedly");
849
+ }
850
+ if (expectedTarget && actualTarget && (!sameRational(expectedTarget.startTime, actualTarget.startTime)
851
+ || !sameRational(expectedTarget.durationTime, actualTarget.durationTime))) {
852
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete target range was not read back exactly");
853
+ }
854
+ for (const expectedClip of expected.timeline.clips) {
855
+ const beforeClip = before.timeline.clips.find(({ id }) => id === expectedClip.id);
856
+ if (!beforeClip || compareRational(beforeClip.startTime, range.end) < 0)
857
+ continue;
858
+ const actualClip = after.timeline.clips.find(({ id }) => id === expectedClip.id);
859
+ if (!actualClip || !sameRational(actualClip.startTime, expectedClip.startTime)) {
860
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete did not preserve the shifted occurrence coordinates");
861
+ }
862
+ }
863
+ }
864
+ function normalizeRippleSnapshot(snapshot) {
865
+ const normalized = structuredClone(snapshot);
866
+ normalized.timeline.durationTime = normalized.timeline.durationTime
867
+ ? normalizeRationalTime(normalized.timeline.durationTime)
868
+ : normalized.timeline.durationTime;
869
+ normalized.timeline.clips = normalized.timeline.clips.map((clip) => ({
870
+ ...clip,
871
+ startTime: normalizeRationalTime(clip.startTime),
872
+ durationTime: normalizeRationalTime(clip.durationTime),
873
+ }));
874
+ normalized.timeline.storyElements = normalized.timeline.storyElements.map((element) => ({
875
+ ...element,
876
+ ...(element.startTime ? { startTime: normalizeRationalTime(element.startTime) } : {}),
877
+ ...(element.durationTime ? { durationTime: normalizeRationalTime(element.durationTime) } : {}),
878
+ }));
879
+ normalized.timeline.markers = normalized.timeline.markers.map((marker) => ({
880
+ ...marker,
881
+ ...(marker.startTime ? { startTime: normalizeRationalTime(marker.startTime) } : {}),
882
+ ...(marker.durationTime ? { durationTime: normalizeRationalTime(marker.durationTime) } : {}),
883
+ }));
884
+ normalized.timeline.captions = normalized.timeline.captions.map((caption) => ({
885
+ ...caption,
886
+ ...(caption.startTime ? { startTime: normalizeRationalTime(caption.startTime) } : {}),
887
+ ...(caption.durationTime ? { durationTime: normalizeRationalTime(caption.durationTime) } : {}),
888
+ }));
889
+ return normalized;
890
+ }
891
+ function normalizeRationalTime(value) {
892
+ const [numerator, denominator] = rationalParts(value);
893
+ return normalizeRational(numerator, denominator);
894
+ }
895
+ function canonicalMarkerRange(snapshot, marker) {
896
+ if (!marker.id.trim() || !marker.name.trim())
897
+ throw new Error("INVALID_OPERATION: marker id and name are required");
898
+ if (!Number.isFinite(marker.start) || !Number.isFinite(marker.duration) || marker.start < 0 || marker.duration < 0) {
899
+ throw new Error("INVALID_OPERATION: marker position and duration must be finite and non-negative");
900
+ }
901
+ const frameDuration = snapshot.timeline.frameDuration;
902
+ if (!frameDuration)
903
+ throw new Error("CAPABILITY_UNAVAILABLE: marker requires sequence frame duration");
904
+ const start = marker.startTime ?? secondsToRational(marker.start, frameDuration);
905
+ const duration = marker.durationTime ?? secondsToRational(marker.duration, frameDuration);
906
+ if (Math.abs(rationalSeconds(start) - marker.start) > 0.000001
907
+ || Math.abs(rationalSeconds(duration) - marker.duration) > 0.000001) {
908
+ throw new Error("INVALID_OPERATION: marker rational coordinates disagree with numeric coordinates");
909
+ }
910
+ const end = addRational(start, duration);
911
+ const timelineDuration = snapshot.timeline.durationTime ?? secondsToRational(snapshot.timeline.duration, frameDuration);
912
+ if (!isFrameAligned(start, zeroRational(), frameDuration) || !isFrameAligned(duration, zeroRational(), frameDuration)
913
+ || compareRational(end, timelineDuration) > 0) {
914
+ throw new Error("INVALID_OPERATION: marker must be frame-aligned and fit inside the active timeline");
915
+ }
916
+ return { start, duration, end };
917
+ }
918
+ function assertMarkerReadback(before, after, marker, range) {
919
+ const matches = after.timeline.markers.filter((candidate) => candidate.name === marker.name
920
+ && sameRational(candidate.startTime ?? secondsToRational(candidate.start), range.start)
921
+ && sameRational(candidate.durationTime ?? secondsToRational(candidate.duration), range.duration));
922
+ const beforeMatches = before.timeline.markers.filter((candidate) => candidate.name === marker.name
923
+ && sameRational(candidate.startTime ?? secondsToRational(candidate.start), range.start)
924
+ && sameRational(candidate.durationTime ?? secondsToRational(candidate.duration), range.duration));
925
+ if (matches.length !== beforeMatches.length + 1) {
926
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native marker was not uniquely read back at the requested rational position");
927
+ }
928
+ }
929
+ function assertCanonicalOperationAvailable(native, operation) {
930
+ if (operation.type === "trim-clip" && !native.trimSelectedClipToRange) {
931
+ throw new Error("CAPABILITY_UNAVAILABLE: final-cut native canonical trim");
932
+ }
933
+ }
934
+ function parseRationalTime(value, label) {
935
+ if (!value || !/^-?\d+$/.test(value.value) || !/^\d+$/.test(value.timescale) || value.timescale === "0") {
936
+ throw new Error(`${label} must be an integer rational`);
937
+ }
938
+ return { value: BigInt(value.value), timescale: BigInt(value.timescale) };
939
+ }
940
+ function validateCanonicalTrim(operation, clip, snapshot) {
941
+ if (!operation.durationTime) {
942
+ throw new Error("INVALID_OPERATION: native trim requires an exact durationTime");
943
+ }
944
+ const duration = parseRationalTime(operation.durationTime, "INVALID_OPERATION: trim durationTime");
945
+ const currentDuration = parseRationalTime(clip.durationTime, "INVALID_PROJECT_STATE: clip durationTime");
946
+ if (duration.value <= 0n || compareRational(operation.durationTime, clip.durationTime) >= 0) {
947
+ throw new Error("INVALID_OPERATION: native trim duration must be shorter than the current occurrence");
948
+ }
949
+ if (!Number.isFinite(operation.duration)
950
+ || Math.abs(operation.duration - Number(duration.value) / Number(duration.timescale)) > 1e-9) {
951
+ throw new Error("INVALID_OPERATION: trim duration and durationTime must agree");
952
+ }
953
+ const frame = snapshot.timeline.frameDuration;
954
+ if (!frame || !isFrameAligned(operation.durationTime, zeroRational(), frame)) {
955
+ throw new Error("FRAME_ALIGNMENT_REQUIRED: native trim duration must align to the sequence frame duration");
956
+ }
957
+ if (currentDuration.value <= 0n)
958
+ throw new Error("INVALID_PROJECT_STATE: clip durationTime must be positive");
959
+ return structuredClone(operation.durationTime);
500
960
  }
501
961
  function validateCanonicalRename(operation) {
502
962
  if (!operation.name.trim())
503
963
  throw new Error("INVALID_OPERATION: clip name cannot be empty");
504
964
  return operation;
505
965
  }
966
+ function validateCanonicalMarker(operation) {
967
+ return operation;
968
+ }
969
+ function validateCanonicalGain(operation) {
970
+ if (!Number.isFinite(operation.gainDb))
971
+ throw new Error("INVALID_OPERATION: gain must be finite");
972
+ if (operation.gainDb < -6 || operation.gainDb > 6) {
973
+ throw new Error("INVALID_OPERATION: gain must be between -6 and 6 dB");
974
+ }
975
+ return operation;
976
+ }
977
+ function sameRational(left, right) {
978
+ try {
979
+ const [leftValue, leftScale] = rationalParts(left);
980
+ const [rightValue, rightScale] = rationalParts(right);
981
+ return leftValue * rightScale === rightValue * leftScale;
982
+ }
983
+ catch {
984
+ return false;
985
+ }
986
+ }
987
+ function rationalParts(value) {
988
+ const numerator = BigInt(value.value);
989
+ const denominator = BigInt(value.timescale);
990
+ if (denominator <= 0n)
991
+ throw new Error("INVALID_OPERATION: rational timescale must be positive");
992
+ return [numerator, denominator];
993
+ }
994
+ function normalizeRational(numerator, denominator) {
995
+ const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);
996
+ return { value: (numerator / divisor).toString(), timescale: (denominator / divisor).toString() };
997
+ }
998
+ function gcd(left, right) {
999
+ let a = left;
1000
+ let b = right;
1001
+ while (b !== 0n) {
1002
+ const remainder = a % b;
1003
+ a = b;
1004
+ b = remainder;
1005
+ }
1006
+ return a || 1n;
1007
+ }
1008
+ function addRational(left, right) {
1009
+ const [leftValue, leftScale] = rationalParts(left);
1010
+ const [rightValue, rightScale] = rationalParts(right);
1011
+ return normalizeRational(leftValue * rightScale + rightValue * leftScale, leftScale * rightScale);
1012
+ }
1013
+ function subtractRational(left, right) {
1014
+ const [leftValue, leftScale] = rationalParts(left);
1015
+ const [rightValue, rightScale] = rationalParts(right);
1016
+ return normalizeRational(leftValue * rightScale - rightValue * leftScale, leftScale * rightScale);
1017
+ }
1018
+ function compareRational(left, right) {
1019
+ const [leftValue, leftScale] = rationalParts(left);
1020
+ const [rightValue, rightScale] = rationalParts(right);
1021
+ const difference = leftValue * rightScale - rightValue * leftScale;
1022
+ return difference < 0n ? -1 : difference > 0n ? 1 : 0;
1023
+ }
1024
+ function isFrameAligned(value, origin, frameDuration) {
1025
+ const [valueNumerator, valueDenominator] = rationalParts(normalizeRational(rationalParts(value)[0] * rationalParts(origin)[1] - rationalParts(origin)[0] * rationalParts(value)[1], rationalParts(value)[1] * rationalParts(origin)[1]));
1026
+ const [frameNumerator, frameDenominator] = rationalParts(frameDuration);
1027
+ return (valueNumerator * frameDenominator) % (valueDenominator * frameNumerator) === 0n;
1028
+ }
1029
+ function zeroRational() {
1030
+ return { value: "0", timescale: "1" };
1031
+ }
1032
+ function rationalSeconds(value) {
1033
+ const [numerator, denominator] = rationalParts(value);
1034
+ return Number(numerator) / Number(denominator);
1035
+ }
1036
+ function secondsToRational(seconds, frameDuration) {
1037
+ if (!Number.isFinite(seconds))
1038
+ throw new Error("INVALID_OPERATION: time must be finite");
1039
+ if (frameDuration) {
1040
+ const frameSeconds = rationalSeconds(frameDuration);
1041
+ const frames = Math.round(seconds / frameSeconds);
1042
+ if (Math.abs(seconds - frames * frameSeconds) > 0.000001)
1043
+ throw new Error("INVALID_OPERATION: time must be frame-aligned");
1044
+ const [frameValue, frameScale] = rationalParts(frameDuration);
1045
+ return normalizeRational(BigInt(frames) * frameValue, frameScale);
1046
+ }
1047
+ const scaled = BigInt(Math.round(seconds * 1_000_000_000));
1048
+ return normalizeRational(scaled, 1000000000n);
1049
+ }
506
1050
  function unavailableCanonicalSnapshot(reason) {
507
1051
  return {
508
1052
  available: false,