@morshoto/framekit 0.1.18 → 0.2.3

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 (192) hide show
  1. package/README.md +17 -12
  2. package/dist-package/adapters/final-cut/typescript/src/analyzers.d.ts +58 -0
  3. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +52 -13
  4. package/dist-package/adapters/final-cut/typescript/src/assets.d.ts +24 -0
  5. package/dist-package/adapters/final-cut/typescript/src/background-export.d.ts +98 -0
  6. package/dist-package/adapters/final-cut/typescript/src/background-materialization.d.ts +47 -0
  7. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +8 -2
  8. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.d.ts +32 -0
  9. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.js +275 -0
  10. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery.d.ts +22 -0
  11. package/dist-package/adapters/final-cut/typescript/src/canonical-verification.d.ts +11 -0
  12. package/dist-package/adapters/final-cut/typescript/src/canonical.d.ts +184 -0
  13. package/dist-package/adapters/final-cut/typescript/src/canonical.js +571 -78
  14. package/dist-package/adapters/final-cut/typescript/src/connection.d.ts +103 -0
  15. package/dist-package/adapters/final-cut/typescript/src/connection.js +6 -1
  16. package/dist-package/adapters/final-cut/typescript/src/disposable-native.d.ts +90 -0
  17. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +6 -0
  18. package/dist-package/adapters/final-cut/typescript/src/documents.d.ts +3 -0
  19. package/dist-package/adapters/final-cut/typescript/src/documents.js +3 -0
  20. package/dist-package/adapters/final-cut/typescript/src/experimental.d.ts +8 -0
  21. package/dist-package/adapters/final-cut/typescript/src/experimental.js +8 -0
  22. package/dist-package/adapters/final-cut/typescript/src/export.d.ts +125 -0
  23. package/dist-package/adapters/final-cut/typescript/src/fcpxml-console-experiment.d.ts +54 -0
  24. package/dist-package/adapters/final-cut/typescript/src/fcpxml.d.ts +75 -0
  25. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +28 -9
  26. package/dist-package/adapters/final-cut/typescript/src/index.d.ts +22 -0
  27. package/dist-package/adapters/final-cut/typescript/src/index.js +1 -7
  28. package/dist-package/adapters/final-cut/typescript/src/library-inspection.d.ts +101 -0
  29. package/dist-package/adapters/final-cut/typescript/src/live.d.ts +101 -0
  30. package/dist-package/adapters/final-cut/typescript/src/live.js +35 -2
  31. package/dist-package/adapters/final-cut/typescript/src/media.d.ts +12 -0
  32. package/dist-package/adapters/final-cut/typescript/src/native-operation.d.ts +6 -0
  33. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.d.ts +77 -0
  34. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.js +175 -0
  35. package/dist-package/adapters/final-cut/typescript/src/native-session.d.ts +130 -0
  36. package/dist-package/adapters/final-cut/typescript/src/native-session.js +11 -6
  37. package/dist-package/adapters/final-cut/typescript/src/native.d.ts +828 -0
  38. package/dist-package/adapters/final-cut/typescript/src/native.js +475 -189
  39. package/dist-package/adapters/final-cut/typescript/src/pasteboard-snapshot.d.ts +114 -0
  40. package/dist-package/adapters/final-cut/typescript/src/publish-readback.d.ts +26 -0
  41. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +19 -2
  42. package/dist-package/adapters/final-cut/typescript/src/publisher.d.ts +215 -0
  43. package/dist-package/adapters/final-cut/typescript/src/publisher.js +255 -14
  44. package/dist-package/adapters/final-cut/typescript/src/session.d.ts +43 -0
  45. package/dist-package/adapters/final-cut/typescript/src/session.js +43 -13
  46. package/dist-package/adapters/final-cut/typescript/src/shadow-mutation.d.ts +51 -0
  47. package/dist-package/adapters/final-cut/typescript/src/sqlite-experiment.d.ts +156 -0
  48. package/dist-package/adapters/final-cut/typescript/src/sqlite-inspection.d.ts +134 -0
  49. package/dist-package/adapters/final-cut/typescript/src/sqlite-materialization.d.ts +110 -0
  50. package/dist-package/adapters/final-cut/typescript/src/sqlite-wal-observation.d.ts +132 -0
  51. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.d.ts +61 -0
  52. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +31 -5
  53. package/dist-package/adapters/final-cut/typescript/src/unattended-editing.d.ts +54 -0
  54. package/dist-package/adapters/headless/typescript/src/audio-output.d.ts +3 -0
  55. package/dist-package/adapters/headless/typescript/src/audio-output.js +3 -0
  56. package/dist-package/adapters/headless/typescript/src/ffmpeg-media-probe.d.ts +11 -0
  57. package/dist-package/adapters/headless/typescript/src/ffmpeg-media-probe.js +26 -2
  58. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.d.ts +25 -0
  59. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +37 -14
  60. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.d.ts +15 -0
  61. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +9 -4
  62. package/dist-package/adapters/headless/typescript/src/index.d.ts +3 -0
  63. package/dist-package/apps/cli/src/dev-doctor.d.ts +25 -0
  64. package/dist-package/apps/cli/src/dev-doctor.js +198 -0
  65. package/dist-package/apps/cli/src/headless-projects.d.ts +3 -0
  66. package/dist-package/apps/cli/src/headless-projects.js +5 -0
  67. package/dist-package/apps/cli/src/main.d.ts +10 -0
  68. package/dist-package/apps/cli/src/main.js +42 -0
  69. package/dist-package/apps/mcp-server/runtime/ffmpeg-audio-backend.py +129 -0
  70. package/dist-package/apps/mcp-server/runtime/speech-analyzer-wrapper.mjs +54 -0
  71. package/dist-package/apps/mcp-server/runtime/whisper-speech-backend.py +271 -0
  72. package/dist-package/apps/mcp-server/src/build-alignment.d.ts +10 -0
  73. package/dist-package/apps/mcp-server/src/build-identity.d.ts +7 -0
  74. package/dist-package/apps/mcp-server/src/build-identity.json +2 -2
  75. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.d.ts +8 -0
  76. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.js +18 -0
  77. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.d.ts +5 -0
  78. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.js +3 -0
  79. package/dist-package/apps/mcp-server/src/headless-project-snapshot.d.ts +3 -0
  80. package/dist-package/apps/mcp-server/src/headless-sessions.d.ts +89 -0
  81. package/dist-package/apps/mcp-server/src/main.d.ts +1 -0
  82. package/dist-package/apps/mcp-server/src/main.js +24 -19
  83. package/dist-package/apps/mcp-server/src/materialization-jobs.d.ts +204 -0
  84. package/dist-package/apps/mcp-server/src/materialization-jobs.js +143 -10
  85. package/dist-package/apps/mcp-server/src/readback-policy.d.ts +18 -0
  86. package/dist-package/apps/mcp-server/src/routing.d.ts +90 -0
  87. package/dist-package/apps/mcp-server/src/routing.js +2 -0
  88. package/dist-package/apps/mcp-server/src/server.d.ts +75 -0
  89. package/dist-package/apps/mcp-server/src/server.js +813 -158
  90. package/dist-package/apps/mcp-server/src/tools/skills/catalog.d.ts +19 -0
  91. package/dist-package/apps/mcp-server/src/tools/skills/catalog.js +142 -0
  92. package/dist-package/apps/mcp-server/src/tools/skills/metadata.d.ts +37 -0
  93. package/dist-package/apps/mcp-server/src/tools/skills/metadata.js +71 -0
  94. package/dist-package/apps/mcp-server/src/tools/skills/register.d.ts +11 -0
  95. package/dist-package/apps/mcp-server/src/tools/skills/register.js +101 -0
  96. package/dist-package/apps/mcp-server/src/version.d.ts +4 -0
  97. package/dist-package/packages/headless-application/src/external-edit.d.ts +30 -0
  98. package/dist-package/packages/headless-application/src/external-edit.js +72 -0
  99. package/dist-package/packages/headless-application/src/headless-projects.d.ts +233 -0
  100. package/dist-package/{apps/mcp-server → packages/headless-application}/src/headless-projects.js +392 -59
  101. package/dist-package/packages/headless-application/src/index.d.ts +2 -0
  102. package/dist-package/packages/headless-application/src/index.js +2 -0
  103. package/dist-package/packages/runtime/src/application/duration-policy-service.d.ts +4 -0
  104. package/dist-package/packages/runtime/src/application/local-media.d.ts +46 -0
  105. package/dist-package/packages/runtime/src/application/media-analysis-service.d.ts +40 -0
  106. package/dist-package/packages/runtime/src/application/media-analysis-service.js +105 -15
  107. package/dist-package/packages/runtime/src/application/project-service.d.ts +35 -0
  108. package/dist-package/packages/runtime/src/application/project-service.js +5 -1
  109. package/dist-package/packages/runtime/src/application/project-store.d.ts +56 -0
  110. package/dist-package/packages/runtime/src/application/project-store.js +13 -36
  111. package/dist-package/packages/runtime/src/application/project-transactions.d.ts +51 -0
  112. package/dist-package/packages/runtime/src/application/runtime-options.d.ts +15 -0
  113. package/dist-package/packages/runtime/src/application/semantic-media-index-store.d.ts +28 -0
  114. package/dist-package/packages/runtime/src/application/transaction-store.d.ts +10 -0
  115. package/dist-package/packages/runtime/src/application/transaction-store.js +1 -1
  116. package/dist-package/packages/runtime/src/audio/analysis.d.ts +3 -0
  117. package/dist-package/packages/runtime/src/audio/analysis.js +95 -0
  118. package/dist-package/packages/runtime/src/audio/dialogue-normalization.d.ts +47 -0
  119. package/dist-package/packages/runtime/src/audio/noise-reduction.d.ts +34 -0
  120. package/dist-package/packages/runtime/src/capabilities.d.ts +45 -0
  121. package/dist-package/packages/runtime/src/capabilities.js +1 -1
  122. package/dist-package/packages/runtime/src/color-correction.d.ts +33 -0
  123. package/dist-package/packages/runtime/src/context/context-engine.d.ts +28 -0
  124. package/dist-package/packages/runtime/src/context/context-engine.js +22 -16
  125. package/dist-package/packages/runtime/src/context/context-service.d.ts +20 -0
  126. package/dist-package/packages/runtime/src/context/context-service.js +2 -2
  127. package/dist-package/packages/runtime/src/context/project-catalog.d.ts +12 -0
  128. package/dist-package/packages/runtime/src/context/revision.d.ts +2 -0
  129. package/dist-package/packages/runtime/src/domain/capabilities.d.ts +170 -0
  130. package/dist-package/packages/runtime/src/domain/context.d.ts +179 -0
  131. package/dist-package/packages/runtime/src/domain/diff.d.ts +104 -0
  132. package/dist-package/packages/runtime/src/domain/duration.d.ts +63 -0
  133. package/dist-package/packages/runtime/src/domain/editing.d.ts +227 -0
  134. package/dist-package/packages/runtime/src/domain/incremental-sync.d.ts +67 -0
  135. package/dist-package/packages/runtime/src/domain/index.d.ts +14 -0
  136. package/dist-package/packages/runtime/src/domain/media.d.ts +406 -0
  137. package/dist-package/packages/runtime/src/domain/ports.d.ts +62 -0
  138. package/dist-package/packages/runtime/src/domain/primitives.d.ts +21 -0
  139. package/dist-package/packages/runtime/src/domain/project.d.ts +119 -0
  140. package/dist-package/packages/runtime/src/domain/rough-cut.d.ts +27 -0
  141. package/dist-package/packages/runtime/src/domain/skills.d.ts +145 -0
  142. package/dist-package/packages/runtime/src/domain/timeline-target.d.ts +57 -0
  143. package/dist-package/packages/runtime/src/domain/timeline-target.js +19 -1
  144. package/dist-package/packages/runtime/src/domain/types.d.ts +5 -0
  145. package/dist-package/packages/runtime/src/domain/verification.d.ts +92 -0
  146. package/dist-package/packages/runtime/src/editing/dialogue-normalization-service.d.ts +18 -0
  147. package/dist-package/packages/runtime/src/editing/duration-policy.d.ts +3 -0
  148. package/dist-package/packages/runtime/src/editing/edit-service.d.ts +44 -0
  149. package/dist-package/packages/runtime/src/editing/edit-service.js +76 -10
  150. package/dist-package/packages/runtime/src/editing/filler-removal-service.d.ts +23 -0
  151. package/dist-package/packages/runtime/src/editing/intent.d.ts +97 -0
  152. package/dist-package/packages/runtime/src/editing/music-service.d.ts +9 -0
  153. package/dist-package/packages/runtime/src/index.d.ts +32 -0
  154. package/dist-package/packages/runtime/src/index.js +2 -0
  155. package/dist-package/packages/runtime/src/planning/rough-cut.d.ts +3 -0
  156. package/dist-package/packages/runtime/src/render/render-and-verify.d.ts +71 -0
  157. package/dist-package/packages/runtime/src/render/render-contract.d.ts +96 -0
  158. package/dist-package/packages/runtime/src/runtime.d.ts +85 -0
  159. package/dist-package/packages/runtime/src/runtime.js +16 -7
  160. package/dist-package/packages/runtime/src/skills/builtin.d.ts +2 -0
  161. package/dist-package/packages/runtime/src/skills/index.d.ts +3 -0
  162. package/dist-package/packages/runtime/src/skills/registry.d.ts +10 -0
  163. package/dist-package/packages/runtime/src/skills/requirements.d.ts +38 -0
  164. package/dist-package/packages/runtime/src/skills/runtime.d.ts +38 -0
  165. package/dist-package/packages/runtime/src/speech/analysis.d.ts +18 -0
  166. package/dist-package/packages/runtime/src/speech/analysis.js +67 -0
  167. package/dist-package/packages/runtime/src/speech/filler-detector.d.ts +49 -0
  168. package/dist-package/packages/runtime/src/speech/filler-removal.d.ts +37 -0
  169. package/dist-package/packages/runtime/src/speech/mapping.d.ts +56 -0
  170. package/dist-package/packages/runtime/src/speech/mapping.js +27 -4
  171. package/dist-package/packages/runtime/src/speech/safe-cut-resolver.d.ts +52 -0
  172. package/dist-package/packages/runtime/src/timeline/drift-reconciliation.d.ts +42 -0
  173. package/dist-package/packages/runtime/src/timeline/editing-session.d.ts +271 -0
  174. package/dist-package/packages/runtime/src/timeline/editing-session.js +48 -2
  175. package/dist-package/packages/runtime/src/timeline/fast-observation.d.ts +77 -0
  176. package/dist-package/packages/runtime/src/timeline/rational-time.d.ts +11 -0
  177. package/dist-package/packages/runtime/src/timeline/reorder-preview.d.ts +32 -0
  178. package/dist-package/packages/runtime/src/timeline/reorder-preview.js +202 -0
  179. package/dist-package/packages/runtime/src/timeline/snapshot-diff.d.ts +3 -0
  180. package/dist-package/packages/runtime/src/timeline/snapshot-diff.js +1 -0
  181. package/dist-package/packages/runtime/src/timeline/snapshot-digest.d.ts +3 -0
  182. package/dist-package/packages/runtime/src/timeline/snapshot-digest.js +1 -1
  183. package/dist-package/packages/runtime/src/verification/verification.d.ts +6 -0
  184. package/dist-package/packages/testkit/src/fixture-analyzers.d.ts +37 -0
  185. package/dist-package/packages/testkit/src/in-memory-editor.d.ts +55 -0
  186. package/dist-package/packages/testkit/src/in-memory-editor.js +3 -3
  187. package/dist-package/packages/testkit/src/index.d.ts +4 -0
  188. package/dist-package/packages/testkit/src/index.js +1 -0
  189. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.d.ts +47 -0
  190. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.js +192 -0
  191. package/dist-package/packages/testkit/src/skill-fixtures.d.ts +3 -0
  192. package/package.json +41 -14
@@ -1,9 +1,12 @@
1
1
  import { execFile as execFileCallback } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
2
4
  import { mkdtemp, rm, stat } from "node:fs/promises";
3
- import { basename, dirname, join } from "node:path";
5
+ import { basename, dirname, isAbsolute, join } from "node:path";
4
6
  import { homedir, tmpdir } from "node:os";
5
7
  import { promisify } from "node:util";
6
- import { canonicalSnapshotDigest, canonicalTimelineMode, assertTimelineTargetReadAfterWrite, createTimelineTarget, resolveTimelineTarget, reconcileProjectCatalog, validateProjectCatalog, withCapabilityFamilies, CapabilityUnavailableError, } from "../../../../packages/runtime/src/index.js";
8
+ import { fileURLToPath } from "node:url";
9
+ import { canonicalSnapshotDigest, canonicalTimelineMode, createProjectSelectionResult, projectSelectionMode, assertTimelineTargetReadAfterWrite, createTimelineTarget, resolveTimelineTarget, reconcileProjectCatalog, validateProjectCatalog, withCapabilityFamilies, CapabilityUnavailableError, } from "../../../../packages/runtime/src/index.js";
7
10
  import { recoverCanonicalNativeMutation } from "./canonical-recovery.js";
8
11
  import { verifyCanonicalReadback } from "./canonical-verification.js";
9
12
  import { FcpxmlDocumentAdapter } from "./fcpxml.js";
@@ -74,6 +77,7 @@ export function assessCanonicalLiveReadiness(capabilities) {
74
77
  ...(mode === "canonical-write" ? [] : ["canonical-write"]),
75
78
  ...(!editor.projectCatalogRead ? ["projectCatalogRead"] : []),
76
79
  ...(!editor.projectSelection ? ["projectSelection"] : []),
80
+ ...(editor.projectSelectionMode === "active-target-only" ? ["projectSelectionTransition"] : []),
77
81
  ...(!editor.timelineSnapshotRead ? ["timelineSnapshotRead"] : []),
78
82
  ...(!editor.timelineWrite ? ["timelineWrite"] : []),
79
83
  ...(!editor.readAfterWrite ? ["readAfterWrite"] : []),
@@ -570,7 +574,20 @@ ${chooseExportDirectory} end if
570
574
  end tell`;
571
575
  }
572
576
  export function createFinalCutNativeTargetResolver(native) {
573
- return async (clip, snapshot) => {
577
+ const resolve = async (clip, snapshot) => {
578
+ if (!clip.startTime || !clip.durationTime) {
579
+ throw new Error(`TARGET_MISMATCH: exact timeline coordinates are unavailable for ${clip.id}`);
580
+ }
581
+ try {
582
+ rationalParts(clip.startTime);
583
+ rationalParts(clip.durationTime);
584
+ }
585
+ catch {
586
+ throw new Error(`TARGET_MISMATCH: invalid timeline coordinates for ${clip.id}`);
587
+ }
588
+ if (compareRational(clip.durationTime, zeroRational()) <= 0) {
589
+ throw new Error(`TARGET_MISMATCH: nonpositive timeline duration for ${clip.id}`);
590
+ }
574
591
  if (!clip.mediaId)
575
592
  throw new Error(`TARGET_MISMATCH: occurrence ${clip.id} has no media binding`);
576
593
  const media = snapshot.media.find(({ mediaId }) => mediaId === clip.mediaId);
@@ -579,18 +596,69 @@ export function createFinalCutNativeTargetResolver(native) {
579
596
  const query = sourceBasename(media.source);
580
597
  if (!query)
581
598
  throw new Error(`TARGET_MISMATCH: media ${clip.mediaId} has no searchable source basename`);
582
- const matches = (await native.searchMedia(query)).filter((match) => match.name.toLocaleLowerCase() === query.toLocaleLowerCase());
599
+ const expectedSource = exactLocalSourcePath(media.source);
600
+ if (!expectedSource) {
601
+ throw new Error(`TARGET_MISMATCH: independently observed Browser source does not match the canonical source for ${clip.id}`);
602
+ }
603
+ const relatedClips = [clip];
604
+ for (const other of snapshot.timeline.clips) {
605
+ if (other.id === clip.id)
606
+ continue;
607
+ const otherMedia = snapshot.media.find(({ mediaId }) => mediaId === other.mediaId);
608
+ const otherSource = otherMedia?.source ? exactLocalSourcePath(otherMedia.source) : undefined;
609
+ // Discovery is source-scoped. Different resources can still alias one source.
610
+ // Unknown source identity cannot prove that another occurrence is unrelated.
611
+ if (other.mediaId !== clip.mediaId && otherSource && otherSource !== expectedSource)
612
+ continue;
613
+ if (!otherSource)
614
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: timeline occurrence source is incomplete");
615
+ relatedClips.push(other);
616
+ if (!other.startTime || !other.durationTime) {
617
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: timeline occurrence coordinates are incomplete");
618
+ }
619
+ try {
620
+ rationalParts(other.startTime);
621
+ rationalParts(other.durationTime);
622
+ }
623
+ catch {
624
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: timeline occurrence coordinates are invalid");
625
+ }
626
+ if (sameRational(other.startTime, clip.startTime) && sameRational(other.durationTime, clip.durationTime)) {
627
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: timeline occurrence coordinates are not unique for ${clip.id}`);
628
+ }
629
+ if (compareRational(other.durationTime, zeroRational()) <= 0) {
630
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: timeline occurrence coordinates have nonpositive duration");
631
+ }
632
+ if (compareRational(clip.startTime, addRational(other.startTime, other.durationTime)) < 0
633
+ && compareRational(other.startTime, addRational(clip.startTime, clip.durationTime)) < 0) {
634
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: same-source timeline occurrences overlap for ${clip.id}`);
635
+ }
636
+ }
637
+ const searchMedia = native.searchMediaForCanonicalTarget ?? native.searchMedia;
638
+ const matches = (await searchMedia.call(native, query))
639
+ .filter((match) => match.name.toLocaleLowerCase() === query.toLocaleLowerCase());
583
640
  if (matches.length === 0)
584
641
  throw new Error(`TARGET_MISMATCH: Final Cut Browser has no exact media match for ${query}`);
585
- if (matches.length > 1)
586
- throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut Browser has multiple exact media matches for ${query}`);
587
- const match = matches[0];
642
+ const observedSources = matches.map((candidate) => candidate.source ? exactLocalSourcePath(candidate.source) : undefined);
643
+ if (observedSources.some((source) => !source)) {
644
+ throw new Error(`TARGET_MISMATCH: independently observed Browser source does not match the canonical source for ${clip.id}`);
645
+ }
646
+ const sourceMatches = matches.filter((_candidate, index) => observedSources[index] === expectedSource);
647
+ if (sourceMatches.length === 0)
648
+ throw new Error(`TARGET_MISMATCH: Final Cut Browser has no canonical source match for ${clip.id}`);
649
+ if (sourceMatches.length > 1)
650
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut Browser has multiple matches for the canonical source of ${clip.id}`);
651
+ const match = sourceMatches[0];
588
652
  if (!match.sourceIdentity)
589
653
  throw new Error("TARGET_MISMATCH: exact Browser media has no stable source identity");
590
- const located = await native.locateOccurrence(match.handle);
654
+ const locate = native.locateOccurrenceForCanonicalTarget ?? native.locateOccurrence;
655
+ const located = await locate.call(native, match.handle);
591
656
  if (located.status === "none" || located.occurrences.length === 0) {
592
657
  throw new Error(`TARGET_MISMATCH: Final Cut timeline has no occurrence for ${query}`);
593
658
  }
659
+ if (located.occurrences.some((candidate) => !validRationalText(candidate.start) || !validRationalText(candidate.duration))) {
660
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: discovered occurrence coordinates are incomplete or invalid");
661
+ }
594
662
  const matchingOccurrences = located.occurrences.filter((candidate) => candidate.start && candidate.duration && clip.startTime && clip.durationTime
595
663
  && sameRationalText(candidate.start, clip.startTime)
596
664
  && sameRationalText(candidate.duration, clip.durationTime));
@@ -601,9 +669,26 @@ export function createFinalCutNativeTargetResolver(native) {
601
669
  throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut timeline occurrence coordinates are not unique for ${clip.id}`);
602
670
  }
603
671
  const occurrence = matchingOccurrences[0];
604
- await native.selectOccurrence?.(occurrence.handle);
672
+ for (const candidate of located.occurrences) {
673
+ if (candidate === occurrence)
674
+ continue;
675
+ const [startValue, startScale] = candidate.start.trim().split("/");
676
+ const [durationValue, durationScale] = candidate.duration.trim().split("/");
677
+ const start = { value: startValue, timescale: startScale };
678
+ const duration = { value: durationValue, timescale: durationScale };
679
+ if (compareRational(duration, zeroRational()) <= 0) {
680
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: discovered occurrence duration is invalid");
681
+ }
682
+ if (compareRational(clip.startTime, addRational(start, duration)) < 0
683
+ && compareRational(start, addRational(clip.startTime, clip.durationTime)) < 0) {
684
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: discovered timeline occurrences overlap for ${clip.id}`);
685
+ }
686
+ }
687
+ if (located.occurrences.length !== relatedClips.length || relatedClips.some((related) => located.occurrences.filter((candidate) => sameRationalText(candidate.start, related.startTime) && sameRationalText(candidate.duration, related.durationTime)).length !== 1)) {
688
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: native occurrence discovery is incomplete or inconsistent with the snapshot");
689
+ }
605
690
  const occurrenceIdentity = occurrence.identity ?? occurrence.nativeIdentity;
606
- if (!occurrenceIdentity && !native.selectOccurrence) {
691
+ if (!occurrenceIdentity) {
607
692
  throw new Error(`TARGET_MISMATCH: native occurrence has no stable identity for ${clip.id}`);
608
693
  }
609
694
  if (!occurrence.sequenceId) {
@@ -612,8 +697,8 @@ export function createFinalCutNativeTargetResolver(native) {
612
697
  if (occurrence.sequenceId !== snapshot.timeline.id) {
613
698
  throw new Error(`TARGET_MISMATCH: native occurrence sequence changed for ${clip.id}`);
614
699
  }
615
- if (occurrence.sourceIdentity && occurrence.sourceIdentity !== match.sourceIdentity) {
616
- throw new Error(`TARGET_MISMATCH: native occurrence source identity changed for ${clip.id}`);
700
+ if (!occurrence.sourceIdentity || occurrence.sourceIdentity !== match.sourceIdentity) {
701
+ throw new Error(`TARGET_MISMATCH: native occurrence source identity is unavailable or changed for ${clip.id}`);
617
702
  }
618
703
  if (!occurrence.start || !occurrence.duration || !clip.startTime || !clip.durationTime) {
619
704
  throw new Error(`TARGET_MISMATCH: exact timeline coordinates are unavailable for ${clip.id}`);
@@ -621,7 +706,49 @@ export function createFinalCutNativeTargetResolver(native) {
621
706
  if (!sameRationalText(occurrence.start, clip.startTime) || !sameRationalText(occurrence.duration, clip.durationTime)) {
622
707
  throw new Error(`TARGET_MISMATCH: native occurrence coordinates changed for ${clip.id}`);
623
708
  }
709
+ const expectedSelectedIdentity = occurrence.nativeIdentity ?? occurrence.identity;
710
+ let needsInspector;
711
+ try {
712
+ needsInspector = native.capabilities?.().timelineOccurrenceSourceBinding === true || Boolean(native.inspectSelectedOccurrenceSource);
713
+ }
714
+ catch {
715
+ throw new Error(`TARGET_MISMATCH: selected Inspector capability is unknown for ${clip.id}`);
716
+ }
717
+ if (needsInspector && (!native.inspectSelectedOccurrenceSource || !clip.sourceStartTime)) {
718
+ throw new Error(`TARGET_MISMATCH: selected Inspector verification is unavailable for ${clip.id}`);
719
+ }
720
+ if (!native.selectOccurrence)
721
+ throw new Error(`TARGET_MISMATCH: native occurrence selection is unavailable for ${clip.id}`);
722
+ const selected = await native.selectOccurrence(occurrence.handle);
723
+ if (selected?.target?.identity !== expectedSelectedIdentity) {
724
+ throw new Error(`TARGET_MISMATCH: selected native occurrence identity changed for ${clip.id}`);
725
+ }
726
+ if (needsInspector) {
727
+ const observed = await native.inspectSelectedOccurrenceSource();
728
+ if (!observed || observed.identity !== expectedSelectedIdentity || exactLocalSourcePath(observed.source) !== expectedSource
729
+ || !clip.sourceStartTime || !sameRational(observed.sourceStartTime, clip.sourceStartTime)
730
+ || !sameRational(observed.durationTime, clip.durationTime)) {
731
+ throw new Error(`TARGET_MISMATCH: selected Inspector source or range changed for ${clip.id}`);
732
+ }
733
+ }
624
734
  };
735
+ // Only an explicit source-observation capability with nonselecting discovery can enable source-bound edits.
736
+ Object.defineProperty(resolve, "sourceBindingAvailable", {
737
+ get: () => {
738
+ try {
739
+ return Boolean(native.locateOccurrenceForCanonicalTarget
740
+ && native.selectOccurrence
741
+ && native.inspectSelectedOccurrenceSource
742
+ && native.capabilities?.().timelineOccurrenceSourceBinding === true);
743
+ }
744
+ catch {
745
+ return false;
746
+ }
747
+ },
748
+ });
749
+ if (native.trackNativeDispatch)
750
+ resolve.trackNativeDispatch = native.trackNativeDispatch.bind(native);
751
+ return resolve;
625
752
  }
626
753
  /**
627
754
  * Canonical provider for the headed Final Cut UI path.
@@ -638,34 +765,46 @@ export class FinalCutCanonicalNativeProvider {
638
765
  resolveTarget;
639
766
  backgroundCatalog;
640
767
  lastDigest;
768
+ lastLiveRevision;
769
+ revisionEpoch = randomUUID();
641
770
  lastSnapshot;
771
+ readScope = new AsyncLocalStorage();
772
+ selectedTarget;
642
773
  revisionSequence = 0;
643
774
  revision;
644
775
  pending;
776
+ recoveryRequired = false;
777
+ recoveryGuard;
645
778
  constructor(options) {
646
779
  this.live = options.live;
647
780
  this.native = options.native;
648
781
  this.readSnapshotSource = options.readSnapshot;
649
782
  this.resolveTarget = options.resolveTarget;
650
783
  this.backgroundCatalog = options.backgroundCatalog;
784
+ this.recoveryGuard = options.recoveryGuard;
651
785
  }
652
786
  async getIdentity() {
653
787
  const identity = await this.live.getIdentity();
654
788
  return { ...identity, backend: "final-cut-native-canonical" };
655
789
  }
790
+ withCanonicalReadScope(operation) {
791
+ return this.readScope.getStore() ? operation() : this.readScope.run({}, operation);
792
+ }
656
793
  async getCapabilities(options = {}) {
657
794
  const backgroundCatalog = await this.resolveBackgroundCatalog();
658
- const snapshotProbe = backgroundCatalog && options.probeCanonicalSnapshot !== false
659
- ? await this.probeCanonicalSnapshot()
660
- : {
661
- available: false,
662
- reason: backgroundCatalog
663
- ? "canonical snapshot availability was not checked"
664
- : "canonical timeline snapshot requires a background project catalog",
665
- };
795
+ const liveSelection = await this.projectSelectionCapability();
796
+ const snapshotProbe = !backgroundCatalog
797
+ ? { available: false, reason: "canonical timeline snapshot requires a background project catalog" }
798
+ : options.probeCanonicalSnapshot !== false
799
+ ? await this.probeCanonicalSnapshot()
800
+ : await this.cachedCanonicalSnapshotAvailability();
801
+ const selection = liveSelection.available ? liveSelection : backgroundCatalog && snapshotProbe.available
802
+ ? { available: true, mode: "active-target-only" }
803
+ : liveSelection;
666
804
  const canonicalSnapshotCapability = snapshotProbe.available
667
- ? true
805
+ ? { available: true, backend: "final-cut-native-canonical", guarantee: "canonical-read", evidenceTier: "headed-native" }
668
806
  : unavailableCanonicalSnapshot(snapshotProbe.reason);
807
+ const sourceBindingAvailable = hasCanonicalSourceBinding(this.resolveTarget);
669
808
  const capabilities = withCapabilityFamilies({
670
809
  editor: {
671
810
  projectRead: snapshotProbe.available,
@@ -681,16 +820,17 @@ export class FinalCutCanonicalNativeProvider {
681
820
  frameCapture: false,
682
821
  playbackControl: false,
683
822
  projectCatalogRead: Boolean(backgroundCatalog),
684
- projectSelection: false,
685
- projectSelectionMode: "unavailable",
823
+ projectSelection: selection.available,
824
+ projectSelectionMode: selection.mode,
686
825
  backgroundLibraryInspection: Boolean(backgroundCatalog),
687
826
  compositeTransactions: snapshotProbe.available,
827
+ ...(snapshotProbe.available && this.native.addMarkerAtTime ? { markerIdentityMode: "editor-assigned" } : {}),
688
828
  semanticOperations: {
689
- "rename-clip": snapshotProbe.available,
690
- "trim-clip": snapshotProbe.available && Boolean(this.native.trimSelectedClipToRange),
829
+ "rename-clip": snapshotProbe.available && sourceBindingAvailable,
830
+ "trim-clip": snapshotProbe.available && sourceBindingAvailable && Boolean(this.native.trimSelectedClipToRange),
691
831
  "add-marker": snapshotProbe.available && Boolean(this.native.addMarkerAtTime),
692
- "ripple-delete": snapshotProbe.available && Boolean(this.native.rippleDeleteRange),
693
- "set-gain": snapshotProbe.available && Boolean(this.native.setSelectedClipGain),
832
+ "ripple-delete": snapshotProbe.available && sourceBindingAvailable && Boolean(this.native.rippleDeleteRange),
833
+ "set-gain": snapshotProbe.available && sourceBindingAvailable && Boolean(this.native.setSelectedClipGain),
694
834
  },
695
835
  },
696
836
  analyzers: {
@@ -704,7 +844,9 @@ export class FinalCutCanonicalNativeProvider {
704
844
  connectionBackend: "workflow-extension-ipc",
705
845
  canonicalDocument: {
706
846
  read: canonicalSnapshotCapability,
707
- write: canonicalSnapshotCapability,
847
+ write: snapshotProbe.available
848
+ ? { available: true, backend: "final-cut-native-canonical", guarantee: "canonical-write", evidenceTier: "headed-native" }
849
+ : canonicalSnapshotCapability,
708
850
  artifactWrite: false,
709
851
  },
710
852
  observation: {
@@ -718,7 +860,14 @@ export class FinalCutCanonicalNativeProvider {
718
860
  },
719
861
  });
720
862
  const readiness = assessCanonicalLiveReadiness(capabilities);
721
- if (readiness.ready)
863
+ let recoveryBlocked = this.recoveryRequired;
864
+ try {
865
+ await this.recoveryGuard?.assertClear();
866
+ }
867
+ catch {
868
+ recoveryBlocked = true;
869
+ }
870
+ if (readiness.ready && !recoveryBlocked)
722
871
  return capabilities;
723
872
  const canonicalReadReady = capabilities.editor.projectRead
724
873
  && capabilities.editor.timelineSnapshotRead
@@ -732,11 +881,12 @@ export class FinalCutCanonicalNativeProvider {
732
881
  readAfterWrite: false,
733
882
  rollback: false,
734
883
  compositeTransactions: false,
884
+ markerIdentityMode: undefined,
735
885
  semanticOperations: {},
736
886
  },
737
887
  }, {
738
888
  canonicalDocument: {
739
- read: true,
889
+ read: canonicalSnapshotCapability,
740
890
  write: false,
741
891
  artifactWrite: false,
742
892
  },
@@ -758,9 +908,28 @@ export class FinalCutCanonicalNativeProvider {
758
908
  },
759
909
  });
760
910
  }
911
+ async cachedCanonicalSnapshotAvailability() {
912
+ if (!this.lastSnapshot || !this.lastLiveRevision) {
913
+ return { available: false, reason: "canonical snapshot availability was not checked" };
914
+ }
915
+ try {
916
+ const live = await this.live.readLiveState();
917
+ if ((!this.selectedTarget || (live.project?.id === this.selectedTarget.projectId
918
+ && live.sequence?.id === this.selectedTarget.sequenceId))
919
+ && live.project?.id === this.lastSnapshot.projectId
920
+ && live.sequence?.id === this.lastSnapshot.timeline.id
921
+ && live.revision?.id === this.lastLiveRevision.id
922
+ && live.revision.sequence === this.lastLiveRevision.sequence)
923
+ return { available: true };
924
+ }
925
+ catch {
926
+ // A missing live observation cannot validate the cached target.
927
+ }
928
+ return { available: false, reason: "canonical snapshot evidence is stale or live state is unavailable" };
929
+ }
761
930
  async probeCanonicalSnapshot() {
762
931
  try {
763
- await this.readSnapshotSource();
932
+ await this.readProject();
764
933
  return { available: true };
765
934
  }
766
935
  catch (error) {
@@ -775,25 +944,54 @@ export class FinalCutCanonicalNativeProvider {
775
944
  return this.readProject();
776
945
  }
777
946
  async readProject() {
947
+ const scoped = this.readScope.getStore();
948
+ if (scoped?.snapshot && scoped.liveRevision) {
949
+ const live = await this.live.readLiveState();
950
+ if (live.project?.id === scoped.snapshot.projectId
951
+ && live.sequence?.id === scoped.snapshot.timeline.id
952
+ && live.revision?.id === scoped.liveRevision.id
953
+ && live.revision.sequence === scoped.liveRevision.sequence) {
954
+ this.assertSelectedTarget(live);
955
+ return structuredClone(scoped.snapshot);
956
+ }
957
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during scoped read");
958
+ }
959
+ const beforeLive = await this.live.readLiveState();
960
+ this.assertSelectedTarget(beforeLive);
778
961
  const snapshot = await this.readSnapshotSource();
779
- await this.assertActiveTarget(snapshot);
962
+ const live = await this.assertActiveTarget(snapshot);
963
+ if (!beforeLive.project?.id || !beforeLive.sequence?.id
964
+ || beforeLive.project.id !== live.project?.id || beforeLive.sequence.id !== live.sequence?.id
965
+ || !beforeLive.revision?.id || beforeLive.revision.id !== live.revision.id
966
+ || beforeLive.revision.sequence !== live.revision.sequence) {
967
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during snapshot export");
968
+ }
780
969
  const digest = canonicalSnapshotDigest(snapshot);
781
- if (digest !== this.lastDigest || !this.revision) {
970
+ if (digest !== this.lastDigest || !this.revision
971
+ || live.revision.id !== this.lastLiveRevision?.id
972
+ || live.revision.sequence !== this.lastLiveRevision.sequence) {
782
973
  this.revisionSequence = Math.max(this.revisionSequence + 1, snapshot.revision.sequence + 1);
783
974
  this.lastDigest = digest;
975
+ this.lastLiveRevision = { id: live.revision.id, sequence: live.revision.sequence };
784
976
  this.revision = {
785
- id: `canonical:${digest}`,
977
+ id: `canonical:${this.revisionEpoch}:${this.revisionSequence}:${digest}`,
786
978
  sequence: this.revisionSequence,
787
979
  timestamp: new Date().toISOString(),
788
980
  };
789
981
  }
790
982
  this.lastSnapshot = { ...snapshot, revision: this.revision };
983
+ if (scoped) {
984
+ scoped.snapshot = structuredClone(this.lastSnapshot);
985
+ scoped.liveRevision = { id: live.revision.id, sequence: live.revision.sequence };
986
+ }
791
987
  return structuredClone(this.lastSnapshot);
792
988
  }
793
989
  async previewTransaction(operations, expectedRevision) {
990
+ await this.assertRecoveryNotRequired();
794
991
  const before = await this.readProject();
795
992
  assertSameRevision(expectedRevision, before.revision);
796
993
  const operation = supportedCanonicalOperation(operations);
994
+ assertCanonicalSourceBindingAvailable(this.resolveTarget, operation);
797
995
  assertCanonicalOperationAvailable(this.native, operation);
798
996
  const preview = projectCanonicalOperation(before, operation);
799
997
  preview.revision = previewRevision(preview, before.revision);
@@ -804,16 +1002,22 @@ export class FinalCutCanonicalNativeProvider {
804
1002
  await this.apply(operation, expectedRevision);
805
1003
  }
806
1004
  async apply(operation, expectedRevision) {
1005
+ await this.assertRecoveryNotRequired();
1006
+ const baselineLive = await this.live.readLiveState();
807
1007
  const before = await this.readProject();
808
1008
  assertSameRevision(expectedRevision, before.revision);
809
1009
  const supported = supportedCanonicalOperation([operation]);
1010
+ assertCanonicalSourceBindingAvailable(this.resolveTarget, supported);
1011
+ if (supported.type === "add-marker" && before.timeline.markers.some(({ id }) => id === supported.marker.id)) {
1012
+ throw new Error(`MARKER_ALREADY_EXISTS: ${supported.marker.id}`);
1013
+ }
810
1014
  const markerRange = supported.type === "add-marker" ? canonicalMarkerRange(before, supported.marker) : undefined;
811
1015
  const clipTarget = supported.type === "rename-clip" || supported.type === "trim-clip" || supported.type === "set-gain"
812
1016
  ? canonicalTargetForOperation(before, supported)
813
1017
  : undefined;
814
1018
  const clip = clipTarget?.clip;
815
1019
  const rippleTarget = supported.type === "ripple-delete" ? canonicalTargetForOperation(before, supported) : undefined;
816
- const targetClip = clip;
1020
+ const targetClip = clip ?? rippleTarget?.clip;
817
1021
  const trimDuration = supported.type === "trim-clip"
818
1022
  ? validateCanonicalTrim(supported, clip, before)
819
1023
  : undefined;
@@ -825,27 +1029,104 @@ export class FinalCutCanonicalNativeProvider {
825
1029
  : {}),
826
1030
  });
827
1031
  resolveTimelineTarget(before, timelineTarget);
828
- if (targetClip)
829
- await this.resolveTarget(targetClip, before);
830
1032
  assertCanonicalOperationAvailable(this.native, supported);
831
- const nativeResult = supported.type === "rename-clip"
832
- ? await this.native.renameSelectedClip(supported.name)
833
- : supported.type === "trim-clip"
834
- ? await this.native.trimSelectedClipToRange({
835
- start: structuredClone(clip.startTime),
836
- end: addRational(clip.startTime, trimDuration),
837
- })
838
- : supported.type === "ripple-delete"
839
- ? await this.native.rippleDeleteRange(rippleTarget.range)
840
- : supported.type === "set-gain"
841
- ? await this.native.setSelectedClipGain(supported.gainDb)
842
- : await this.native.addMarkerAtTime({
843
- start: markerRange.start,
844
- duration: markerRange.duration,
845
- name: supported.marker.name,
846
- });
1033
+ if (targetClip && !this.recoveryGuard) {
1034
+ await this.resolveTarget(targetClip, before);
1035
+ assertCanonicalSourceBindingAvailable(this.resolveTarget, supported);
1036
+ }
1037
+ const currentLive = await this.live.readLiveState();
1038
+ if (!baselineLive.project?.id || !baselineLive.sequence?.id
1039
+ || baselineLive.project.id !== before.projectId || baselineLive.sequence.id !== before.timeline.id
1040
+ || currentLive.project?.id !== baselineLive.project.id || currentLive.sequence?.id !== baselineLive.sequence.id
1041
+ || !baselineLive.revision?.id || currentLive.revision?.id !== baselineLive.revision.id
1042
+ || currentLive.revision.sequence !== baselineLive.revision.sequence) {
1043
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during edit preparation");
1044
+ }
1045
+ if (this.recoveryGuard) {
1046
+ await this.recoveryGuard.begin({
1047
+ projectId: before.projectId, sequenceId: before.timeline.id,
1048
+ baseRevision: before.revision.id, beforeDigest: canonicalSnapshotDigest(before), operation: supported.type,
1049
+ });
1050
+ try {
1051
+ const afterCheckpoint = await this.live.readLiveState();
1052
+ if (afterCheckpoint.project?.id !== currentLive.project.id
1053
+ || afterCheckpoint.sequence?.id !== currentLive.sequence.id
1054
+ || afterCheckpoint.revision?.id !== currentLive.revision.id
1055
+ || afterCheckpoint.revision.sequence !== currentLive.revision.sequence) {
1056
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during recovery checkpoint acquisition");
1057
+ }
1058
+ }
1059
+ catch (error) {
1060
+ // No native command has been dispatched, so this checkpoint is safe to release.
1061
+ await this.recoveryGuard.complete();
1062
+ throw error;
1063
+ }
1064
+ if (targetClip) {
1065
+ let dispatched = typeof this.resolveTarget.trackNativeDispatch !== "function";
1066
+ try {
1067
+ const resolve = () => this.resolveTarget(targetClip, before);
1068
+ if (this.resolveTarget.trackNativeDispatch) {
1069
+ await this.resolveTarget.trackNativeDispatch(resolve, () => { dispatched = true; });
1070
+ }
1071
+ else {
1072
+ await resolve();
1073
+ }
1074
+ assertCanonicalSourceBindingAvailable(this.resolveTarget, supported);
1075
+ const afterTarget = await this.live.readLiveState();
1076
+ if (afterTarget.project?.id !== currentLive.project.id
1077
+ || afterTarget.sequence?.id !== currentLive.sequence.id
1078
+ || afterTarget.revision?.id !== currentLive.revision.id
1079
+ || afterTarget.revision.sequence !== currentLive.revision.sequence) {
1080
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during target preparation");
1081
+ }
1082
+ }
1083
+ catch (error) {
1084
+ if (!dispatched) {
1085
+ await this.recoveryGuard.complete();
1086
+ throw error;
1087
+ }
1088
+ this.recoveryRequired = true;
1089
+ const detail = error instanceof Error ? error.message : String(error);
1090
+ throw new Error(`FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: native target preparation outcome is uncertain: ${detail}`, { cause: error });
1091
+ }
1092
+ }
1093
+ else {
1094
+ try {
1095
+ assertCanonicalSourceBindingAvailable(this.resolveTarget, supported);
1096
+ }
1097
+ catch (error) {
1098
+ await this.recoveryGuard.complete();
1099
+ throw error;
1100
+ }
1101
+ }
1102
+ }
1103
+ let nativeResult;
1104
+ try {
1105
+ nativeResult = supported.type === "rename-clip"
1106
+ ? await this.native.renameSelectedClip(supported.name)
1107
+ : supported.type === "trim-clip"
1108
+ ? await this.native.trimSelectedClipToRange({
1109
+ start: structuredClone(clip.startTime),
1110
+ end: addRational(clip.startTime, trimDuration),
1111
+ })
1112
+ : supported.type === "ripple-delete"
1113
+ ? await this.native.rippleDeleteRange(rippleTarget.range)
1114
+ : supported.type === "set-gain"
1115
+ ? await this.native.setSelectedClipGain(supported.gainDb)
1116
+ : await this.native.addMarkerAtTime({
1117
+ start: markerRange.start,
1118
+ duration: markerRange.duration,
1119
+ name: supported.marker.name,
1120
+ });
1121
+ }
1122
+ catch (error) {
1123
+ this.recoveryRequired = true;
1124
+ const detail = error instanceof Error ? error.message : String(error);
1125
+ throw new Error(`FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: native edit outcome is uncertain: ${detail}`, { cause: error });
1126
+ }
847
1127
  if (!nativeResult.operationId || !nativeResult.undoAvailable) {
848
- throw new Error("FINAL_CUT_CANONICAL_UNDO_UNAVAILABLE: native edit did not expose Undo");
1128
+ this.recoveryRequired = true;
1129
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_UNAVAILABLE: native edit did not expose Undo; FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: further edits are blocked");
849
1130
  }
850
1131
  this.pending = {
851
1132
  operationId: nativeResult.operationId,
@@ -876,6 +1157,7 @@ export class FinalCutCanonicalNativeProvider {
876
1157
  if (readback.beforeDigest !== this.pending.beforeDigest) {
877
1158
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: canonical before digest changed during verification");
878
1159
  }
1160
+ assertExactCanonicalProjection(before, after, supported);
879
1161
  }
880
1162
  else if (supported.type === "trim-clip") {
881
1163
  const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
@@ -883,12 +1165,14 @@ export class FinalCutCanonicalNativeProvider {
883
1165
  || !sameRational(afterClip.durationTime, trimDuration)) {
884
1166
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: trimmed occurrence range was not read back from Final Cut");
885
1167
  }
1168
+ assertExactCanonicalProjection(before, after, supported);
886
1169
  }
887
1170
  else if (supported.type === "set-gain") {
888
1171
  const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
889
1172
  if (!afterClip || (afterClip.gainDb ?? 0) !== supported.gainDb) {
890
1173
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: gain was not read back from Final Cut");
891
1174
  }
1175
+ assertExactCanonicalProjection(before, after, supported);
892
1176
  }
893
1177
  else if (supported.type === "ripple-delete") {
894
1178
  assertRippleDeleteReadback(before, after, rippleTarget.clip, rippleTarget.range);
@@ -901,6 +1185,7 @@ export class FinalCutCanonicalNativeProvider {
901
1185
  }
902
1186
  assertTimelineTargetReadAfterWrite(timelineTarget, before, after, supported.type === "ripple-delete" ? { allowOccurrenceRemoval: true } : undefined);
903
1187
  this.pending.afterRevision = after.revision;
1188
+ await this.recoveryGuard?.complete();
904
1189
  return after.revision;
905
1190
  }
906
1191
  catch (error) {
@@ -909,14 +1194,22 @@ export class FinalCutCanonicalNativeProvider {
909
1194
  operationId: nativeResult.operationId,
910
1195
  before,
911
1196
  target: timelineTarget,
912
- undo: this.native.undo,
1197
+ undo: async (operationId) => {
1198
+ const live = await this.live.readLiveState();
1199
+ if (live.project?.id !== before.projectId || live.sequence?.id !== before.timeline.id || !live.revision?.id) {
1200
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: active target is not the edited project and sequence");
1201
+ }
1202
+ return this.native.undo(operationId);
1203
+ },
913
1204
  readSnapshot: () => this.readProject(),
914
1205
  });
1206
+ await this.recoveryGuard?.complete();
915
1207
  }
916
1208
  catch (rollbackError) {
1209
+ this.recoveryRequired = true;
917
1210
  const original = error instanceof Error ? error.message : String(error);
918
1211
  const rollback = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
919
- throw new Error(`FINAL_CUT_CANONICAL_ROLLBACK_FAILED: ${rollback}; original error: ${original}`);
1212
+ throw new Error(`FINAL_CUT_CANONICAL_ROLLBACK_FAILED: ${rollback}; original error: ${original}; FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: further edits are blocked`);
920
1213
  }
921
1214
  finally {
922
1215
  this.pending = undefined;
@@ -924,6 +1217,12 @@ export class FinalCutCanonicalNativeProvider {
924
1217
  throw error;
925
1218
  }
926
1219
  }
1220
+ async assertRecoveryNotRequired() {
1221
+ if (this.recoveryRequired) {
1222
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: a previous native edit could not be restored; further edits are blocked");
1223
+ }
1224
+ await this.recoveryGuard?.assertClear();
1225
+ }
927
1226
  async restore(snapshot, expectedRevision) {
928
1227
  const current = await this.readProject();
929
1228
  assertSameRevision(expectedRevision, current.revision);
@@ -934,15 +1233,51 @@ export class FinalCutCanonicalNativeProvider {
934
1233
  if (canonicalSnapshotDigest(snapshot) !== pending.beforeDigest) {
935
1234
  throw new Error("FINAL_CUT_CANONICAL_UNDO_TARGET_MISMATCH: rollback target differs from the applied edit");
936
1235
  }
937
- const undone = await this.native.undo(pending.operationId);
938
- if (!undone.undone || undone.verification?.verified !== true) {
939
- throw new Error("FINAL_CUT_CANONICAL_UNDO_FAILED: Final Cut did not verify native Undo");
1236
+ await this.assertRecoveryNotRequired();
1237
+ if (this.recoveryGuard) {
1238
+ const beforeCheckpoint = await this.live.readLiveState();
1239
+ if (beforeCheckpoint.project?.id !== current.projectId || beforeCheckpoint.sequence?.id !== current.timeline.id
1240
+ || beforeCheckpoint.revision?.id !== this.lastLiveRevision?.id
1241
+ || beforeCheckpoint.revision?.sequence !== this.lastLiveRevision?.sequence) {
1242
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed before Undo");
1243
+ }
1244
+ await this.recoveryGuard.begin({
1245
+ projectId: current.projectId, sequenceId: current.timeline.id,
1246
+ baseRevision: current.revision.id, beforeDigest: canonicalSnapshotDigest(current),
1247
+ operation: "undo", expectedRestoreDigest: pending.beforeDigest,
1248
+ });
1249
+ try {
1250
+ const afterCheckpoint = await this.live.readLiveState();
1251
+ if (afterCheckpoint.project?.id !== beforeCheckpoint.project?.id
1252
+ || afterCheckpoint.sequence?.id !== beforeCheckpoint.sequence?.id
1253
+ || afterCheckpoint.revision?.id !== beforeCheckpoint.revision?.id
1254
+ || afterCheckpoint.revision?.sequence !== beforeCheckpoint.revision?.sequence) {
1255
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during Undo checkpoint acquisition");
1256
+ }
1257
+ }
1258
+ catch (error) {
1259
+ // No Undo command has been dispatched, so this checkpoint is safe to release.
1260
+ await this.recoveryGuard.complete();
1261
+ throw error;
1262
+ }
1263
+ }
1264
+ try {
1265
+ const undone = await this.native.undo(pending.operationId);
1266
+ if (!undone.undone || undone.verification?.verified !== true) {
1267
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_FAILED: Final Cut did not verify native Undo");
1268
+ }
1269
+ const restored = await this.readProject();
1270
+ if (canonicalSnapshotDigest(restored) !== pending.beforeDigest) {
1271
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_FAILED: restored canonical digest does not match the pre-edit state");
1272
+ }
1273
+ await this.recoveryGuard?.complete();
1274
+ this.pending = undefined;
940
1275
  }
941
- const restored = await this.readProject();
942
- if (canonicalSnapshotDigest(restored) !== pending.beforeDigest) {
943
- throw new Error("FINAL_CUT_CANONICAL_UNDO_FAILED: restored canonical digest does not match the pre-edit state");
1276
+ catch (error) {
1277
+ this.recoveryRequired = true;
1278
+ const detail = error instanceof Error ? error.message : String(error);
1279
+ throw new Error(`FINAL_CUT_CANONICAL_UNDO_FAILED: ${detail}; FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: further edits are blocked`, { cause: error });
944
1280
  }
945
- this.pending = undefined;
946
1281
  }
947
1282
  async listProjects() {
948
1283
  const backgroundCatalog = await this.resolveBackgroundCatalog();
@@ -957,7 +1292,71 @@ export class FinalCutCanonicalNativeProvider {
957
1292
  return this.readBackgroundCatalog(backgroundCatalog);
958
1293
  }
959
1294
  async selectProject(selection) {
960
- throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project selection is not exposed by the background provider");
1295
+ const capability = await this.projectSelectionCapability();
1296
+ if (!capability.available || !this.live.selectProject) {
1297
+ if (!(await this.cachedCanonicalSnapshotAvailability()).available) {
1298
+ throw new Error("CAPABILITY_UNAVAILABLE: active-target-only rebind requires a current canonical snapshot");
1299
+ }
1300
+ const catalog = await this.listProjects();
1301
+ const project = catalog.projects.find((candidate) => candidate.id === selection.projectId);
1302
+ if (!project || catalog.activeProjectId !== selection.projectId) {
1303
+ throw new Error("TARGET_MISMATCH: requested project is not the active catalog target");
1304
+ }
1305
+ const sequenceId = selection.sequenceId ?? (project.sequences.length === 1 ? project.sequences[0]?.id : undefined);
1306
+ if (!sequenceId)
1307
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: sequenceId is required");
1308
+ if (!project.sequences.some((sequence) => sequence.id === sequenceId) || catalog.activeSequenceId !== sequenceId) {
1309
+ throw new Error("TARGET_MISMATCH: requested sequence is not the active catalog target");
1310
+ }
1311
+ if (!(await this.cachedCanonicalSnapshotAvailability()).available) {
1312
+ throw new Error("STALE_CONTEXT: canonical snapshot changed during active target rebind");
1313
+ }
1314
+ const live = await this.live.readLiveState();
1315
+ if (live.project?.id !== selection.projectId || live.sequence?.id !== sequenceId
1316
+ || !live.revision || live.revision.id !== this.lastLiveRevision?.id
1317
+ || live.revision.sequence !== this.lastLiveRevision.sequence) {
1318
+ throw new Error("STALE_CONTEXT: active target changed during rebind");
1319
+ }
1320
+ this.selectedTarget = { projectId: selection.projectId, sequenceId };
1321
+ return createProjectSelectionResult(catalog, this.selectedTarget, live.revision);
1322
+ }
1323
+ if (!selection.projectId.trim())
1324
+ throw new Error("INVALID_PROJECT_SELECTION: projectId is required");
1325
+ if (selection.sequenceId !== undefined && !selection.sequenceId.trim()) {
1326
+ throw new Error("INVALID_PROJECT_SELECTION: sequenceId cannot be empty");
1327
+ }
1328
+ const catalog = await this.listProjects();
1329
+ const project = catalog.projects.find((candidate) => candidate.id === selection.projectId);
1330
+ if (!project)
1331
+ throw new Error(`TARGET_MISMATCH: selected project ${selection.projectId} is absent from the project catalog`);
1332
+ const sequenceId = selection.sequenceId ?? (project.sequences.length === 1 ? project.sequences[0]?.id : undefined);
1333
+ if (!sequenceId)
1334
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: sequenceId is required for project ${selection.projectId}`);
1335
+ if (!project.sequences.some((sequence) => sequence.id === sequenceId)) {
1336
+ throw new Error(`TARGET_MISMATCH: selected sequence ${sequenceId} is absent from project ${selection.projectId}`);
1337
+ }
1338
+ const target = { projectId: selection.projectId, sequenceId };
1339
+ const result = await this.live.selectProject(target);
1340
+ validateProjectCatalog(result);
1341
+ if (result.activeProjectId !== target.projectId || result.activeSequenceId !== target.sequenceId
1342
+ || result.observedActiveTarget.projectId !== target.projectId
1343
+ || result.observedActiveTarget.sequenceId !== target.sequenceId
1344
+ || result.requestedTarget.projectId !== target.projectId
1345
+ || result.requestedTarget.sequenceId !== target.sequenceId) {
1346
+ throw new Error("TARGET_MISMATCH: live project selection did not confirm the requested project and sequence");
1347
+ }
1348
+ const live = await this.live.readLiveState();
1349
+ if (live.project?.id !== target.projectId || live.sequence?.id !== target.sequenceId) {
1350
+ throw new Error("TARGET_MISMATCH: active project or sequence differs from the selected target");
1351
+ }
1352
+ if (!live.revision?.id || !Number.isSafeInteger(live.revision.sequence)) {
1353
+ throw new Error("FINAL_CUT_CANONICAL_REVISION_UNAVAILABLE: live revision is incomplete after project selection");
1354
+ }
1355
+ if (result.observedRevision.id !== live.revision.id || result.observedRevision.sequence !== live.revision.sequence) {
1356
+ throw new Error("STALE_CONTEXT: live revision changed during project selection");
1357
+ }
1358
+ this.selectedTarget = target;
1359
+ return structuredClone(result);
961
1360
  }
962
1361
  async readLiveState() {
963
1362
  return this.live.readLiveState();
@@ -967,6 +1366,7 @@ export class FinalCutCanonicalNativeProvider {
967
1366
  }
968
1367
  async assertActiveTarget(snapshot) {
969
1368
  const live = await this.live.readLiveState();
1369
+ this.assertSelectedTarget(live);
970
1370
  if (!live.project || live.project.id !== snapshot.projectId) {
971
1371
  throw new Error(`TARGET_MISMATCH: active project identity ${live.project?.id ?? "<unavailable>"} does not match exported project ${snapshot.projectId}`);
972
1372
  }
@@ -979,6 +1379,10 @@ export class FinalCutCanonicalNativeProvider {
979
1379
  if (live.sequence.name !== snapshot.timeline.name) {
980
1380
  throw new Error(`TARGET_MISMATCH: exported sequence ${snapshot.timeline.name} is not active Final Cut sequence ${live.sequence.name}`);
981
1381
  }
1382
+ if (!live.revision?.id || !Number.isSafeInteger(live.revision.sequence)) {
1383
+ throw new Error("FINAL_CUT_CANONICAL_REVISION_UNAVAILABLE: live revision is incomplete");
1384
+ }
1385
+ return live;
982
1386
  }
983
1387
  async resolveBackgroundCatalog() {
984
1388
  if (this.backgroundCatalog)
@@ -986,7 +1390,7 @@ export class FinalCutCanonicalNativeProvider {
986
1390
  if (!this.live.listProjects || !this.live.getCapabilities)
987
1391
  return undefined;
988
1392
  try {
989
- const capabilities = await this.live.getCapabilities();
1393
+ const capabilities = await this.live.getCapabilities({ probeCanonicalSnapshot: false });
990
1394
  if (!capabilities.editor.projectCatalogRead)
991
1395
  return undefined;
992
1396
  const identity = await this.live.getIdentity();
@@ -999,12 +1403,38 @@ export class FinalCutCanonicalNativeProvider {
999
1403
  return undefined;
1000
1404
  }
1001
1405
  }
1406
+ async projectSelectionCapability() {
1407
+ if (!this.live.selectProject || !this.live.getCapabilities)
1408
+ return { available: false, mode: "unavailable" };
1409
+ try {
1410
+ const capabilities = await this.live.getCapabilities({ probeCanonicalSnapshot: false });
1411
+ const mode = projectSelectionMode(capabilities.editor);
1412
+ const available = capabilities.editor.projectSelection === true && mode !== "unavailable";
1413
+ return {
1414
+ available,
1415
+ mode: available ? mode : "unavailable",
1416
+ };
1417
+ }
1418
+ catch {
1419
+ return { available: false, mode: "unavailable" };
1420
+ }
1421
+ }
1422
+ assertSelectedTarget(live) {
1423
+ if (this.selectedTarget && (live.project?.id !== this.selectedTarget.projectId
1424
+ || live.sequence?.id !== this.selectedTarget.sequenceId)) {
1425
+ throw new Error(`TARGET_MISMATCH: active project or sequence differs from the explicitly selected target ${this.selectedTarget.projectId}/${this.selectedTarget.sequenceId}`);
1426
+ }
1427
+ }
1002
1428
  async readBackgroundCatalog(provider) {
1003
1429
  const before = await this.readLiveStateSafely();
1004
1430
  const catalog = await provider.listProjects();
1005
1431
  validateProjectCatalog(catalog);
1006
1432
  const after = await this.readLiveStateSafely();
1007
1433
  const liveIdentity = before && after ? await this.live.getIdentity() : undefined;
1434
+ const liveSelection = await this.projectSelectionCapability();
1435
+ const cached = await this.cachedCanonicalSnapshotAvailability();
1436
+ const selection = liveSelection.available ? liveSelection : cached.available
1437
+ ? { available: true, mode: "active-target-only" } : liveSelection;
1008
1438
  return reconcileProjectCatalog(catalog, {
1009
1439
  ...(before && after ? { before, after } : {}),
1010
1440
  provenance: {
@@ -1021,9 +1451,11 @@ export class FinalCutCanonicalNativeProvider {
1021
1451
  },
1022
1452
  } : {}),
1023
1453
  selection: {
1024
- available: false,
1025
- mode: "unavailable",
1026
- unavailableReason: "project selection is not exposed by the background provider",
1454
+ available: selection.available,
1455
+ mode: selection.mode,
1456
+ ...(!selection.available ? {
1457
+ unavailableReason: "project selection is not exposed by the background provider",
1458
+ } : {}),
1027
1459
  },
1028
1460
  },
1029
1461
  });
@@ -1037,6 +1469,19 @@ export class FinalCutCanonicalNativeProvider {
1037
1469
  }
1038
1470
  }
1039
1471
  }
1472
+ function assertCanonicalSourceBindingAvailable(resolver, operation) {
1473
+ if (operation.type !== "add-marker" && !hasCanonicalSourceBinding(resolver)) {
1474
+ throw new Error("CAPABILITY_UNAVAILABLE: native occurrence source binding cannot be independently observed");
1475
+ }
1476
+ }
1477
+ function hasCanonicalSourceBinding(resolver) {
1478
+ try {
1479
+ return resolver.sourceBindingAvailable === true;
1480
+ }
1481
+ catch {
1482
+ return false;
1483
+ }
1484
+ }
1040
1485
  function supportedCanonicalOperation(operations) {
1041
1486
  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")) {
1042
1487
  throw new Error("CAPABILITY_UNAVAILABLE: final-cut native canonical provider supports one rename-clip, trim-clip, add-marker, ripple-delete, or set-gain transaction");
@@ -1143,6 +1588,12 @@ function projectCanonicalOperation(snapshot, operation) {
1143
1588
  },
1144
1589
  };
1145
1590
  }
1591
+ function assertExactCanonicalProjection(before, after, operation) {
1592
+ const expected = projectCanonicalOperation(before, operation);
1593
+ if (canonicalSnapshotDigest(normalizeCanonicalSnapshot(after)) !== canonicalSnapshotDigest(normalizeCanonicalSnapshot(expected))) {
1594
+ throw new Error(`FINAL_CUT_CANONICAL_READBACK_FAILED: ${operation.type} readback differed from the exact canonical projection`);
1595
+ }
1596
+ }
1146
1597
  function projectCanonicalRippleDelete(snapshot, range) {
1147
1598
  const duration = subtractRational(range.end, range.start);
1148
1599
  const clips = snapshot.timeline.clips.flatMap((clip) => projectClipAfterRippleDelete(clip, range, duration));
@@ -1258,18 +1709,18 @@ function canonicalRippleRange(snapshot, range) {
1258
1709
  throw new Error("INVALID_OPERATION: ripple-delete range must have positive duration");
1259
1710
  }
1260
1711
  const end = addRational(start, duration);
1261
- if (!isFrameAligned(start, zeroRational(), frameDuration) || !isFrameAligned(end, zeroRational(), frameDuration)) {
1262
- throw new Error("INVALID_OPERATION: ripple-delete range must be frame-aligned");
1263
- }
1264
1712
  const timelineDuration = snapshot.timeline.durationTime ?? secondsToRational(snapshot.timeline.duration, frameDuration);
1265
1713
  if (compareRational(start, zeroRational()) < 0 || compareRational(end, timelineDuration) > 0) {
1266
- throw new Error("INVALID_OPERATION: ripple-delete range must fit inside the active timeline");
1714
+ throw new Error(`INVALID_OPERATION: ripple-delete range [${range.start}, ${range.end}) must fit timeline bounds [0, ${rationalSeconds(timelineDuration)})`);
1715
+ }
1716
+ if (!isFrameAligned(start, zeroRational(), frameDuration) || !isFrameAligned(end, zeroRational(), frameDuration)) {
1717
+ throw new Error("INVALID_OPERATION: ripple-delete range must be frame-aligned");
1267
1718
  }
1268
1719
  return { start, end };
1269
1720
  }
1270
1721
  function assertRippleDeleteReadback(before, after, targetClip, range) {
1271
1722
  const expected = projectCanonicalRippleDelete(before, range);
1272
- if (canonicalSnapshotDigest(normalizeRippleSnapshot(after)) !== canonicalSnapshotDigest(normalizeRippleSnapshot(expected))) {
1723
+ if (canonicalSnapshotDigest(normalizeCanonicalSnapshot(after)) !== canonicalSnapshotDigest(normalizeCanonicalSnapshot(expected))) {
1273
1724
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete readback differed from the exact canonical projection");
1274
1725
  }
1275
1726
  if (!after.timeline.durationTime || !expected.timeline.durationTime
@@ -1295,15 +1746,19 @@ function assertRippleDeleteReadback(before, after, targetClip, range) {
1295
1746
  }
1296
1747
  }
1297
1748
  }
1298
- function normalizeRippleSnapshot(snapshot) {
1749
+ function normalizeCanonicalSnapshot(snapshot) {
1299
1750
  const normalized = structuredClone(snapshot);
1300
1751
  normalized.timeline.durationTime = normalized.timeline.durationTime
1301
1752
  ? normalizeRationalTime(normalized.timeline.durationTime)
1302
1753
  : normalized.timeline.durationTime;
1754
+ normalized.timeline.frameDuration = normalized.timeline.frameDuration
1755
+ ? normalizeRationalTime(normalized.timeline.frameDuration)
1756
+ : normalized.timeline.frameDuration;
1303
1757
  normalized.timeline.clips = normalized.timeline.clips.map((clip) => ({
1304
1758
  ...clip,
1305
1759
  startTime: normalizeRationalTime(clip.startTime),
1306
1760
  durationTime: normalizeRationalTime(clip.durationTime),
1761
+ ...(clip.sourceStartTime ? { sourceStartTime: normalizeRationalTime(clip.sourceStartTime) } : {}),
1307
1762
  }));
1308
1763
  normalized.timeline.storyElements = normalized.timeline.storyElements.map((element) => ({
1309
1764
  ...element,
@@ -1359,6 +1814,23 @@ function assertMarkerReadback(before, after, marker, range) {
1359
1814
  if (matches.length !== beforeMatches.length + 1) {
1360
1815
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native marker was not uniquely read back at the requested rational position");
1361
1816
  }
1817
+ const priorIds = new Set(before.timeline.markers.map(({ id }) => id));
1818
+ const added = after.timeline.markers.filter(({ id }) => !priorIds.has(id));
1819
+ if (priorIds.size !== before.timeline.markers.length
1820
+ || new Set(after.timeline.markers.map(({ id }) => id)).size !== after.timeline.markers.length
1821
+ || added.length !== 1 || !matches.includes(added[0])) {
1822
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native marker identity is ambiguous");
1823
+ }
1824
+ const expected = projectCanonicalOperation(before, { type: "add-marker", timelineId: before.timeline.id, marker });
1825
+ expected.timeline.markers = expected.timeline.markers.map((candidate) => candidate.id === marker.id
1826
+ ? { ...candidate, id: added[0].id } : candidate);
1827
+ const normalizedExpected = normalizeCanonicalSnapshot(expected);
1828
+ const normalizedAfter = normalizeCanonicalSnapshot(after);
1829
+ normalizedExpected.timeline.markers.sort((left, right) => left.id.localeCompare(right.id));
1830
+ normalizedAfter.timeline.markers.sort((left, right) => left.id.localeCompare(right.id));
1831
+ if (canonicalSnapshotDigest(normalizedAfter) !== canonicalSnapshotDigest(normalizedExpected)) {
1832
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: marker readback differed from the exact canonical projection");
1833
+ }
1362
1834
  }
1363
1835
  function assertCanonicalOperationAvailable(native, operation) {
1364
1836
  if (operation.type === "trim-clip" && !native.trimSelectedClipToRange) {
@@ -1569,15 +2041,36 @@ async function readCanonicalExport(path, timeoutMs, pollIntervalMs, target, read
1569
2041
  throw new Error(`FINAL_CUT_CANONICAL_EXPORT_TIMEOUT: Final Cut did not provide a complete export at ${path}${detail}`);
1570
2042
  }
1571
2043
  function sourceBasename(source) {
1572
- const withoutQuery = source.split(/[?#]/, 1)[0] ?? source;
1573
2044
  try {
1574
- const url = new URL(withoutQuery);
1575
- return basename(decodeURIComponent(url.pathname));
2045
+ const url = new URL(source);
2046
+ return basename(url.protocol === "file:" ? fileURLToPath(url) : decodeURIComponent(url.pathname));
1576
2047
  }
1577
2048
  catch {
1578
- return basename(withoutQuery.replace(/^file:\/\//, ""));
2049
+ return basename(source);
1579
2050
  }
1580
2051
  }
2052
+ function exactLocalSourcePath(source) {
2053
+ try {
2054
+ const decoded = source.startsWith("file:") ? decodeURIComponent(source) : source;
2055
+ if (/(?:^|\/)\.{1,2}(?:\/|$)/.test(decoded) || decoded.includes("\0"))
2056
+ return undefined;
2057
+ if (source.startsWith("file:")) {
2058
+ const url = new URL(source);
2059
+ if (url.protocol !== "file:" || url.search || url.hash)
2060
+ return undefined;
2061
+ const path = fileURLToPath(url);
2062
+ return isAbsolute(path) ? path : undefined;
2063
+ }
2064
+ return isAbsolute(source) ? source : undefined;
2065
+ }
2066
+ catch {
2067
+ return undefined;
2068
+ }
2069
+ }
2070
+ function validRationalText(value) {
2071
+ const match = value?.trim().match(/^(-?\d+)\/(\d+)$/);
2072
+ return Boolean(match && BigInt(match[2]) > 0n);
2073
+ }
1581
2074
  function sameRationalText(value, expected) {
1582
2075
  const match = value.trim().match(/^(-?\d+)\/(\d+)$/);
1583
2076
  if (!match || Number(match[2]) <= 0 || Number(expected.timescale) <= 0)