@morshoto/framekit 0.1.18 → 0.2.2

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 (51) hide show
  1. package/README.md +17 -12
  2. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +8 -2
  3. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.js +275 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical.js +538 -77
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +6 -1
  6. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +6 -0
  7. package/dist-package/adapters/final-cut/typescript/src/experimental.js +8 -0
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +22 -8
  9. package/dist-package/adapters/final-cut/typescript/src/index.js +1 -7
  10. package/dist-package/adapters/final-cut/typescript/src/live.js +27 -2
  11. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.js +175 -0
  12. package/dist-package/adapters/final-cut/typescript/src/native-session.js +11 -6
  13. package/dist-package/adapters/final-cut/typescript/src/native.js +201 -82
  14. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +1 -0
  15. package/dist-package/adapters/final-cut/typescript/src/publisher.js +255 -14
  16. package/dist-package/adapters/final-cut/typescript/src/session.js +43 -13
  17. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +3 -1
  18. package/dist-package/adapters/headless/typescript/src/audio-output.js +3 -0
  19. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +32 -14
  20. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +9 -4
  21. package/dist-package/apps/cli/src/dev-doctor.js +198 -0
  22. package/dist-package/apps/cli/src/headless-projects.js +5 -0
  23. package/dist-package/apps/cli/src/main.js +42 -0
  24. package/dist-package/apps/mcp-server/runtime/speech-analyzer-wrapper.mjs +54 -0
  25. package/dist-package/apps/mcp-server/runtime/whisper-speech-backend.py +181 -0
  26. package/dist-package/apps/mcp-server/src/build-identity.json +2 -2
  27. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.js +18 -0
  28. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.js +3 -0
  29. package/dist-package/apps/mcp-server/src/main.js +24 -19
  30. package/dist-package/apps/mcp-server/src/materialization-jobs.js +143 -10
  31. package/dist-package/apps/mcp-server/src/routing.js +2 -0
  32. package/dist-package/apps/mcp-server/src/server.js +737 -152
  33. package/dist-package/apps/mcp-server/src/tools/skills/catalog.js +142 -0
  34. package/dist-package/apps/mcp-server/src/tools/skills/metadata.js +71 -0
  35. package/dist-package/apps/mcp-server/src/tools/skills/register.js +101 -0
  36. package/dist-package/{apps/mcp-server → packages/headless-application}/src/headless-projects.js +391 -58
  37. package/dist-package/packages/headless-application/src/index.js +1 -0
  38. package/dist-package/packages/runtime/src/application/project-service.js +5 -1
  39. package/dist-package/packages/runtime/src/application/project-store.js +13 -36
  40. package/dist-package/packages/runtime/src/application/transaction-store.js +1 -1
  41. package/dist-package/packages/runtime/src/capabilities.js +1 -1
  42. package/dist-package/packages/runtime/src/context/context-engine.js +22 -16
  43. package/dist-package/packages/runtime/src/context/context-service.js +2 -2
  44. package/dist-package/packages/runtime/src/editing/edit-service.js +76 -10
  45. package/dist-package/packages/runtime/src/index.js +1 -0
  46. package/dist-package/packages/runtime/src/runtime.js +16 -7
  47. package/dist-package/packages/runtime/src/timeline/editing-session.js +16 -0
  48. package/dist-package/packages/testkit/src/in-memory-editor.js +3 -3
  49. package/dist-package/packages/testkit/src/index.js +1 -0
  50. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.js +192 -0
  51. package/package.json +32 -10
@@ -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,17 @@ ${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
+ }
574
588
  if (!clip.mediaId)
575
589
  throw new Error(`TARGET_MISMATCH: occurrence ${clip.id} has no media binding`);
576
590
  const media = snapshot.media.find(({ mediaId }) => mediaId === clip.mediaId);
@@ -579,18 +593,58 @@ export function createFinalCutNativeTargetResolver(native) {
579
593
  const query = sourceBasename(media.source);
580
594
  if (!query)
581
595
  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());
596
+ const expectedSource = exactLocalSourcePath(media.source);
597
+ if (!expectedSource) {
598
+ throw new Error(`TARGET_MISMATCH: independently observed Browser source does not match the canonical source for ${clip.id}`);
599
+ }
600
+ for (const other of snapshot.timeline.clips) {
601
+ if (other.id === clip.id)
602
+ continue;
603
+ const otherMedia = snapshot.media.find(({ mediaId }) => mediaId === other.mediaId);
604
+ const otherSource = otherMedia?.source ? exactLocalSourcePath(otherMedia.source) : undefined;
605
+ // Discovery is source-scoped. Different resources can still alias one source.
606
+ // Unknown source identity cannot prove that another occurrence is unrelated.
607
+ if (other.mediaId !== clip.mediaId && otherSource && otherSource !== expectedSource)
608
+ continue;
609
+ if (!other.startTime || !other.durationTime) {
610
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: timeline occurrence coordinates are incomplete");
611
+ }
612
+ try {
613
+ rationalParts(other.startTime);
614
+ rationalParts(other.durationTime);
615
+ }
616
+ catch {
617
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: timeline occurrence coordinates are invalid");
618
+ }
619
+ if (sameRational(other.startTime, clip.startTime) && sameRational(other.durationTime, clip.durationTime)) {
620
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: timeline occurrence coordinates are not unique for ${clip.id}`);
621
+ }
622
+ }
623
+ const searchMedia = native.searchMediaForCanonicalTarget ?? native.searchMedia;
624
+ const matches = (await searchMedia.call(native, query))
625
+ .filter((match) => match.name.toLocaleLowerCase() === query.toLocaleLowerCase());
583
626
  if (matches.length === 0)
584
627
  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];
628
+ const observedSources = matches.map((candidate) => candidate.source ? exactLocalSourcePath(candidate.source) : undefined);
629
+ if (observedSources.some((source) => !source)) {
630
+ throw new Error(`TARGET_MISMATCH: independently observed Browser source does not match the canonical source for ${clip.id}`);
631
+ }
632
+ const sourceMatches = matches.filter((_candidate, index) => observedSources[index] === expectedSource);
633
+ if (sourceMatches.length === 0)
634
+ throw new Error(`TARGET_MISMATCH: Final Cut Browser has no canonical source match for ${clip.id}`);
635
+ if (sourceMatches.length > 1)
636
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut Browser has multiple matches for the canonical source of ${clip.id}`);
637
+ const match = sourceMatches[0];
588
638
  if (!match.sourceIdentity)
589
639
  throw new Error("TARGET_MISMATCH: exact Browser media has no stable source identity");
590
- const located = await native.locateOccurrence(match.handle);
640
+ const locate = native.locateOccurrenceForCanonicalTarget ?? native.locateOccurrence;
641
+ const located = await locate.call(native, match.handle);
591
642
  if (located.status === "none" || located.occurrences.length === 0) {
592
643
  throw new Error(`TARGET_MISMATCH: Final Cut timeline has no occurrence for ${query}`);
593
644
  }
645
+ if (located.occurrences.some((candidate) => !validRationalText(candidate.start) || !validRationalText(candidate.duration))) {
646
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: discovered occurrence coordinates are incomplete or invalid");
647
+ }
594
648
  const matchingOccurrences = located.occurrences.filter((candidate) => candidate.start && candidate.duration && clip.startTime && clip.durationTime
595
649
  && sameRationalText(candidate.start, clip.startTime)
596
650
  && sameRationalText(candidate.duration, clip.durationTime));
@@ -601,9 +655,8 @@ export function createFinalCutNativeTargetResolver(native) {
601
655
  throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut timeline occurrence coordinates are not unique for ${clip.id}`);
602
656
  }
603
657
  const occurrence = matchingOccurrences[0];
604
- await native.selectOccurrence?.(occurrence.handle);
605
658
  const occurrenceIdentity = occurrence.identity ?? occurrence.nativeIdentity;
606
- if (!occurrenceIdentity && !native.selectOccurrence) {
659
+ if (!occurrenceIdentity) {
607
660
  throw new Error(`TARGET_MISMATCH: native occurrence has no stable identity for ${clip.id}`);
608
661
  }
609
662
  if (!occurrence.sequenceId) {
@@ -612,8 +665,8 @@ export function createFinalCutNativeTargetResolver(native) {
612
665
  if (occurrence.sequenceId !== snapshot.timeline.id) {
613
666
  throw new Error(`TARGET_MISMATCH: native occurrence sequence changed for ${clip.id}`);
614
667
  }
615
- if (occurrence.sourceIdentity && occurrence.sourceIdentity !== match.sourceIdentity) {
616
- throw new Error(`TARGET_MISMATCH: native occurrence source identity changed for ${clip.id}`);
668
+ if (!occurrence.sourceIdentity || occurrence.sourceIdentity !== match.sourceIdentity) {
669
+ throw new Error(`TARGET_MISMATCH: native occurrence source identity is unavailable or changed for ${clip.id}`);
617
670
  }
618
671
  if (!occurrence.start || !occurrence.duration || !clip.startTime || !clip.durationTime) {
619
672
  throw new Error(`TARGET_MISMATCH: exact timeline coordinates are unavailable for ${clip.id}`);
@@ -621,7 +674,49 @@ export function createFinalCutNativeTargetResolver(native) {
621
674
  if (!sameRationalText(occurrence.start, clip.startTime) || !sameRationalText(occurrence.duration, clip.durationTime)) {
622
675
  throw new Error(`TARGET_MISMATCH: native occurrence coordinates changed for ${clip.id}`);
623
676
  }
677
+ const expectedSelectedIdentity = occurrence.nativeIdentity ?? occurrence.identity;
678
+ let needsInspector;
679
+ try {
680
+ needsInspector = native.capabilities?.().timelineOccurrenceSourceBinding === true || Boolean(native.inspectSelectedOccurrenceSource);
681
+ }
682
+ catch {
683
+ throw new Error(`TARGET_MISMATCH: selected Inspector capability is unknown for ${clip.id}`);
684
+ }
685
+ if (needsInspector && (!native.inspectSelectedOccurrenceSource || !clip.sourceStartTime)) {
686
+ throw new Error(`TARGET_MISMATCH: selected Inspector verification is unavailable for ${clip.id}`);
687
+ }
688
+ if (!native.selectOccurrence)
689
+ throw new Error(`TARGET_MISMATCH: native occurrence selection is unavailable for ${clip.id}`);
690
+ const selected = await native.selectOccurrence(occurrence.handle);
691
+ if (selected?.target?.identity !== expectedSelectedIdentity) {
692
+ throw new Error(`TARGET_MISMATCH: selected native occurrence identity changed for ${clip.id}`);
693
+ }
694
+ if (needsInspector) {
695
+ const observed = await native.inspectSelectedOccurrenceSource();
696
+ if (!observed || observed.identity !== expectedSelectedIdentity || exactLocalSourcePath(observed.source) !== expectedSource
697
+ || !clip.sourceStartTime || !sameRational(observed.sourceStartTime, clip.sourceStartTime)
698
+ || !sameRational(observed.durationTime, clip.durationTime)) {
699
+ throw new Error(`TARGET_MISMATCH: selected Inspector source or range changed for ${clip.id}`);
700
+ }
701
+ }
624
702
  };
703
+ // Only an explicit source-observation capability with nonselecting discovery can enable source-bound edits.
704
+ Object.defineProperty(resolve, "sourceBindingAvailable", {
705
+ get: () => {
706
+ try {
707
+ return Boolean(native.locateOccurrenceForCanonicalTarget
708
+ && native.selectOccurrence
709
+ && native.inspectSelectedOccurrenceSource
710
+ && native.capabilities?.().timelineOccurrenceSourceBinding === true);
711
+ }
712
+ catch {
713
+ return false;
714
+ }
715
+ },
716
+ });
717
+ if (native.trackNativeDispatch)
718
+ resolve.trackNativeDispatch = native.trackNativeDispatch.bind(native);
719
+ return resolve;
625
720
  }
626
721
  /**
627
722
  * Canonical provider for the headed Final Cut UI path.
@@ -638,34 +733,46 @@ export class FinalCutCanonicalNativeProvider {
638
733
  resolveTarget;
639
734
  backgroundCatalog;
640
735
  lastDigest;
736
+ lastLiveRevision;
737
+ revisionEpoch = randomUUID();
641
738
  lastSnapshot;
739
+ readScope = new AsyncLocalStorage();
740
+ selectedTarget;
642
741
  revisionSequence = 0;
643
742
  revision;
644
743
  pending;
744
+ recoveryRequired = false;
745
+ recoveryGuard;
645
746
  constructor(options) {
646
747
  this.live = options.live;
647
748
  this.native = options.native;
648
749
  this.readSnapshotSource = options.readSnapshot;
649
750
  this.resolveTarget = options.resolveTarget;
650
751
  this.backgroundCatalog = options.backgroundCatalog;
752
+ this.recoveryGuard = options.recoveryGuard;
651
753
  }
652
754
  async getIdentity() {
653
755
  const identity = await this.live.getIdentity();
654
756
  return { ...identity, backend: "final-cut-native-canonical" };
655
757
  }
758
+ withCanonicalReadScope(operation) {
759
+ return this.readScope.getStore() ? operation() : this.readScope.run({}, operation);
760
+ }
656
761
  async getCapabilities(options = {}) {
657
762
  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
- };
763
+ const liveSelection = await this.projectSelectionCapability();
764
+ const snapshotProbe = !backgroundCatalog
765
+ ? { available: false, reason: "canonical timeline snapshot requires a background project catalog" }
766
+ : options.probeCanonicalSnapshot !== false
767
+ ? await this.probeCanonicalSnapshot()
768
+ : await this.cachedCanonicalSnapshotAvailability();
769
+ const selection = liveSelection.available ? liveSelection : backgroundCatalog && snapshotProbe.available
770
+ ? { available: true, mode: "active-target-only" }
771
+ : liveSelection;
666
772
  const canonicalSnapshotCapability = snapshotProbe.available
667
- ? true
773
+ ? { available: true, backend: "final-cut-native-canonical", guarantee: "canonical-read", evidenceTier: "headed-native" }
668
774
  : unavailableCanonicalSnapshot(snapshotProbe.reason);
775
+ const sourceBindingAvailable = hasCanonicalSourceBinding(this.resolveTarget);
669
776
  const capabilities = withCapabilityFamilies({
670
777
  editor: {
671
778
  projectRead: snapshotProbe.available,
@@ -681,16 +788,17 @@ export class FinalCutCanonicalNativeProvider {
681
788
  frameCapture: false,
682
789
  playbackControl: false,
683
790
  projectCatalogRead: Boolean(backgroundCatalog),
684
- projectSelection: false,
685
- projectSelectionMode: "unavailable",
791
+ projectSelection: selection.available,
792
+ projectSelectionMode: selection.mode,
686
793
  backgroundLibraryInspection: Boolean(backgroundCatalog),
687
794
  compositeTransactions: snapshotProbe.available,
795
+ ...(snapshotProbe.available && this.native.addMarkerAtTime ? { markerIdentityMode: "editor-assigned" } : {}),
688
796
  semanticOperations: {
689
- "rename-clip": snapshotProbe.available,
690
- "trim-clip": snapshotProbe.available && Boolean(this.native.trimSelectedClipToRange),
797
+ "rename-clip": snapshotProbe.available && sourceBindingAvailable,
798
+ "trim-clip": snapshotProbe.available && sourceBindingAvailable && Boolean(this.native.trimSelectedClipToRange),
691
799
  "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),
800
+ "ripple-delete": snapshotProbe.available && sourceBindingAvailable && Boolean(this.native.rippleDeleteRange),
801
+ "set-gain": snapshotProbe.available && sourceBindingAvailable && Boolean(this.native.setSelectedClipGain),
694
802
  },
695
803
  },
696
804
  analyzers: {
@@ -704,7 +812,9 @@ export class FinalCutCanonicalNativeProvider {
704
812
  connectionBackend: "workflow-extension-ipc",
705
813
  canonicalDocument: {
706
814
  read: canonicalSnapshotCapability,
707
- write: canonicalSnapshotCapability,
815
+ write: snapshotProbe.available
816
+ ? { available: true, backend: "final-cut-native-canonical", guarantee: "canonical-write", evidenceTier: "headed-native" }
817
+ : canonicalSnapshotCapability,
708
818
  artifactWrite: false,
709
819
  },
710
820
  observation: {
@@ -718,7 +828,14 @@ export class FinalCutCanonicalNativeProvider {
718
828
  },
719
829
  });
720
830
  const readiness = assessCanonicalLiveReadiness(capabilities);
721
- if (readiness.ready)
831
+ let recoveryBlocked = this.recoveryRequired;
832
+ try {
833
+ await this.recoveryGuard?.assertClear();
834
+ }
835
+ catch {
836
+ recoveryBlocked = true;
837
+ }
838
+ if (readiness.ready && !recoveryBlocked)
722
839
  return capabilities;
723
840
  const canonicalReadReady = capabilities.editor.projectRead
724
841
  && capabilities.editor.timelineSnapshotRead
@@ -732,11 +849,12 @@ export class FinalCutCanonicalNativeProvider {
732
849
  readAfterWrite: false,
733
850
  rollback: false,
734
851
  compositeTransactions: false,
852
+ markerIdentityMode: undefined,
735
853
  semanticOperations: {},
736
854
  },
737
855
  }, {
738
856
  canonicalDocument: {
739
- read: true,
857
+ read: canonicalSnapshotCapability,
740
858
  write: false,
741
859
  artifactWrite: false,
742
860
  },
@@ -758,9 +876,28 @@ export class FinalCutCanonicalNativeProvider {
758
876
  },
759
877
  });
760
878
  }
879
+ async cachedCanonicalSnapshotAvailability() {
880
+ if (!this.lastSnapshot || !this.lastLiveRevision) {
881
+ return { available: false, reason: "canonical snapshot availability was not checked" };
882
+ }
883
+ try {
884
+ const live = await this.live.readLiveState();
885
+ if ((!this.selectedTarget || (live.project?.id === this.selectedTarget.projectId
886
+ && live.sequence?.id === this.selectedTarget.sequenceId))
887
+ && live.project?.id === this.lastSnapshot.projectId
888
+ && live.sequence?.id === this.lastSnapshot.timeline.id
889
+ && live.revision?.id === this.lastLiveRevision.id
890
+ && live.revision.sequence === this.lastLiveRevision.sequence)
891
+ return { available: true };
892
+ }
893
+ catch {
894
+ // A missing live observation cannot validate the cached target.
895
+ }
896
+ return { available: false, reason: "canonical snapshot evidence is stale or live state is unavailable" };
897
+ }
761
898
  async probeCanonicalSnapshot() {
762
899
  try {
763
- await this.readSnapshotSource();
900
+ await this.readProject();
764
901
  return { available: true };
765
902
  }
766
903
  catch (error) {
@@ -775,25 +912,54 @@ export class FinalCutCanonicalNativeProvider {
775
912
  return this.readProject();
776
913
  }
777
914
  async readProject() {
915
+ const scoped = this.readScope.getStore();
916
+ if (scoped?.snapshot && scoped.liveRevision) {
917
+ const live = await this.live.readLiveState();
918
+ if (live.project?.id === scoped.snapshot.projectId
919
+ && live.sequence?.id === scoped.snapshot.timeline.id
920
+ && live.revision?.id === scoped.liveRevision.id
921
+ && live.revision.sequence === scoped.liveRevision.sequence) {
922
+ this.assertSelectedTarget(live);
923
+ return structuredClone(scoped.snapshot);
924
+ }
925
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during scoped read");
926
+ }
927
+ const beforeLive = await this.live.readLiveState();
928
+ this.assertSelectedTarget(beforeLive);
778
929
  const snapshot = await this.readSnapshotSource();
779
- await this.assertActiveTarget(snapshot);
930
+ const live = await this.assertActiveTarget(snapshot);
931
+ if (!beforeLive.project?.id || !beforeLive.sequence?.id
932
+ || beforeLive.project.id !== live.project?.id || beforeLive.sequence.id !== live.sequence?.id
933
+ || !beforeLive.revision?.id || beforeLive.revision.id !== live.revision.id
934
+ || beforeLive.revision.sequence !== live.revision.sequence) {
935
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during snapshot export");
936
+ }
780
937
  const digest = canonicalSnapshotDigest(snapshot);
781
- if (digest !== this.lastDigest || !this.revision) {
938
+ if (digest !== this.lastDigest || !this.revision
939
+ || live.revision.id !== this.lastLiveRevision?.id
940
+ || live.revision.sequence !== this.lastLiveRevision.sequence) {
782
941
  this.revisionSequence = Math.max(this.revisionSequence + 1, snapshot.revision.sequence + 1);
783
942
  this.lastDigest = digest;
943
+ this.lastLiveRevision = { id: live.revision.id, sequence: live.revision.sequence };
784
944
  this.revision = {
785
- id: `canonical:${digest}`,
945
+ id: `canonical:${this.revisionEpoch}:${this.revisionSequence}:${digest}`,
786
946
  sequence: this.revisionSequence,
787
947
  timestamp: new Date().toISOString(),
788
948
  };
789
949
  }
790
950
  this.lastSnapshot = { ...snapshot, revision: this.revision };
951
+ if (scoped) {
952
+ scoped.snapshot = structuredClone(this.lastSnapshot);
953
+ scoped.liveRevision = { id: live.revision.id, sequence: live.revision.sequence };
954
+ }
791
955
  return structuredClone(this.lastSnapshot);
792
956
  }
793
957
  async previewTransaction(operations, expectedRevision) {
958
+ await this.assertRecoveryNotRequired();
794
959
  const before = await this.readProject();
795
960
  assertSameRevision(expectedRevision, before.revision);
796
961
  const operation = supportedCanonicalOperation(operations);
962
+ assertCanonicalSourceBindingAvailable(this.resolveTarget, operation);
797
963
  assertCanonicalOperationAvailable(this.native, operation);
798
964
  const preview = projectCanonicalOperation(before, operation);
799
965
  preview.revision = previewRevision(preview, before.revision);
@@ -804,9 +970,15 @@ export class FinalCutCanonicalNativeProvider {
804
970
  await this.apply(operation, expectedRevision);
805
971
  }
806
972
  async apply(operation, expectedRevision) {
973
+ await this.assertRecoveryNotRequired();
974
+ const baselineLive = await this.live.readLiveState();
807
975
  const before = await this.readProject();
808
976
  assertSameRevision(expectedRevision, before.revision);
809
977
  const supported = supportedCanonicalOperation([operation]);
978
+ assertCanonicalSourceBindingAvailable(this.resolveTarget, supported);
979
+ if (supported.type === "add-marker" && before.timeline.markers.some(({ id }) => id === supported.marker.id)) {
980
+ throw new Error(`MARKER_ALREADY_EXISTS: ${supported.marker.id}`);
981
+ }
810
982
  const markerRange = supported.type === "add-marker" ? canonicalMarkerRange(before, supported.marker) : undefined;
811
983
  const clipTarget = supported.type === "rename-clip" || supported.type === "trim-clip" || supported.type === "set-gain"
812
984
  ? canonicalTargetForOperation(before, supported)
@@ -825,27 +997,104 @@ export class FinalCutCanonicalNativeProvider {
825
997
  : {}),
826
998
  });
827
999
  resolveTimelineTarget(before, timelineTarget);
828
- if (targetClip)
829
- await this.resolveTarget(targetClip, before);
830
1000
  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
- });
1001
+ if (targetClip && !this.recoveryGuard) {
1002
+ await this.resolveTarget(targetClip, before);
1003
+ assertCanonicalSourceBindingAvailable(this.resolveTarget, supported);
1004
+ }
1005
+ const currentLive = await this.live.readLiveState();
1006
+ if (!baselineLive.project?.id || !baselineLive.sequence?.id
1007
+ || baselineLive.project.id !== before.projectId || baselineLive.sequence.id !== before.timeline.id
1008
+ || currentLive.project?.id !== baselineLive.project.id || currentLive.sequence?.id !== baselineLive.sequence.id
1009
+ || !baselineLive.revision?.id || currentLive.revision?.id !== baselineLive.revision.id
1010
+ || currentLive.revision.sequence !== baselineLive.revision.sequence) {
1011
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during edit preparation");
1012
+ }
1013
+ if (this.recoveryGuard) {
1014
+ await this.recoveryGuard.begin({
1015
+ projectId: before.projectId, sequenceId: before.timeline.id,
1016
+ baseRevision: before.revision.id, beforeDigest: canonicalSnapshotDigest(before), operation: supported.type,
1017
+ });
1018
+ try {
1019
+ const afterCheckpoint = await this.live.readLiveState();
1020
+ if (afterCheckpoint.project?.id !== currentLive.project.id
1021
+ || afterCheckpoint.sequence?.id !== currentLive.sequence.id
1022
+ || afterCheckpoint.revision?.id !== currentLive.revision.id
1023
+ || afterCheckpoint.revision.sequence !== currentLive.revision.sequence) {
1024
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during recovery checkpoint acquisition");
1025
+ }
1026
+ }
1027
+ catch (error) {
1028
+ // No native command has been dispatched, so this checkpoint is safe to release.
1029
+ await this.recoveryGuard.complete();
1030
+ throw error;
1031
+ }
1032
+ if (targetClip) {
1033
+ let dispatched = typeof this.resolveTarget.trackNativeDispatch !== "function";
1034
+ try {
1035
+ const resolve = () => this.resolveTarget(targetClip, before);
1036
+ if (this.resolveTarget.trackNativeDispatch) {
1037
+ await this.resolveTarget.trackNativeDispatch(resolve, () => { dispatched = true; });
1038
+ }
1039
+ else {
1040
+ await resolve();
1041
+ }
1042
+ assertCanonicalSourceBindingAvailable(this.resolveTarget, supported);
1043
+ const afterTarget = await this.live.readLiveState();
1044
+ if (afterTarget.project?.id !== currentLive.project.id
1045
+ || afterTarget.sequence?.id !== currentLive.sequence.id
1046
+ || afterTarget.revision?.id !== currentLive.revision.id
1047
+ || afterTarget.revision.sequence !== currentLive.revision.sequence) {
1048
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during target preparation");
1049
+ }
1050
+ }
1051
+ catch (error) {
1052
+ if (!dispatched) {
1053
+ await this.recoveryGuard.complete();
1054
+ throw error;
1055
+ }
1056
+ this.recoveryRequired = true;
1057
+ const detail = error instanceof Error ? error.message : String(error);
1058
+ throw new Error(`FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: native target preparation outcome is uncertain: ${detail}`, { cause: error });
1059
+ }
1060
+ }
1061
+ else {
1062
+ try {
1063
+ assertCanonicalSourceBindingAvailable(this.resolveTarget, supported);
1064
+ }
1065
+ catch (error) {
1066
+ await this.recoveryGuard.complete();
1067
+ throw error;
1068
+ }
1069
+ }
1070
+ }
1071
+ let nativeResult;
1072
+ try {
1073
+ nativeResult = supported.type === "rename-clip"
1074
+ ? await this.native.renameSelectedClip(supported.name)
1075
+ : supported.type === "trim-clip"
1076
+ ? await this.native.trimSelectedClipToRange({
1077
+ start: structuredClone(clip.startTime),
1078
+ end: addRational(clip.startTime, trimDuration),
1079
+ })
1080
+ : supported.type === "ripple-delete"
1081
+ ? await this.native.rippleDeleteRange(rippleTarget.range)
1082
+ : supported.type === "set-gain"
1083
+ ? await this.native.setSelectedClipGain(supported.gainDb)
1084
+ : await this.native.addMarkerAtTime({
1085
+ start: markerRange.start,
1086
+ duration: markerRange.duration,
1087
+ name: supported.marker.name,
1088
+ });
1089
+ }
1090
+ catch (error) {
1091
+ this.recoveryRequired = true;
1092
+ const detail = error instanceof Error ? error.message : String(error);
1093
+ throw new Error(`FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: native edit outcome is uncertain: ${detail}`, { cause: error });
1094
+ }
847
1095
  if (!nativeResult.operationId || !nativeResult.undoAvailable) {
848
- throw new Error("FINAL_CUT_CANONICAL_UNDO_UNAVAILABLE: native edit did not expose Undo");
1096
+ this.recoveryRequired = true;
1097
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_UNAVAILABLE: native edit did not expose Undo; FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: further edits are blocked");
849
1098
  }
850
1099
  this.pending = {
851
1100
  operationId: nativeResult.operationId,
@@ -876,6 +1125,7 @@ export class FinalCutCanonicalNativeProvider {
876
1125
  if (readback.beforeDigest !== this.pending.beforeDigest) {
877
1126
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: canonical before digest changed during verification");
878
1127
  }
1128
+ assertExactCanonicalProjection(before, after, supported);
879
1129
  }
880
1130
  else if (supported.type === "trim-clip") {
881
1131
  const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
@@ -883,12 +1133,14 @@ export class FinalCutCanonicalNativeProvider {
883
1133
  || !sameRational(afterClip.durationTime, trimDuration)) {
884
1134
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: trimmed occurrence range was not read back from Final Cut");
885
1135
  }
1136
+ assertExactCanonicalProjection(before, after, supported);
886
1137
  }
887
1138
  else if (supported.type === "set-gain") {
888
1139
  const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
889
1140
  if (!afterClip || (afterClip.gainDb ?? 0) !== supported.gainDb) {
890
1141
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: gain was not read back from Final Cut");
891
1142
  }
1143
+ assertExactCanonicalProjection(before, after, supported);
892
1144
  }
893
1145
  else if (supported.type === "ripple-delete") {
894
1146
  assertRippleDeleteReadback(before, after, rippleTarget.clip, rippleTarget.range);
@@ -901,6 +1153,7 @@ export class FinalCutCanonicalNativeProvider {
901
1153
  }
902
1154
  assertTimelineTargetReadAfterWrite(timelineTarget, before, after, supported.type === "ripple-delete" ? { allowOccurrenceRemoval: true } : undefined);
903
1155
  this.pending.afterRevision = after.revision;
1156
+ await this.recoveryGuard?.complete();
904
1157
  return after.revision;
905
1158
  }
906
1159
  catch (error) {
@@ -909,14 +1162,22 @@ export class FinalCutCanonicalNativeProvider {
909
1162
  operationId: nativeResult.operationId,
910
1163
  before,
911
1164
  target: timelineTarget,
912
- undo: this.native.undo,
1165
+ undo: async (operationId) => {
1166
+ const live = await this.live.readLiveState();
1167
+ if (live.project?.id !== before.projectId || live.sequence?.id !== before.timeline.id || !live.revision?.id) {
1168
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: active target is not the edited project and sequence");
1169
+ }
1170
+ return this.native.undo(operationId);
1171
+ },
913
1172
  readSnapshot: () => this.readProject(),
914
1173
  });
1174
+ await this.recoveryGuard?.complete();
915
1175
  }
916
1176
  catch (rollbackError) {
1177
+ this.recoveryRequired = true;
917
1178
  const original = error instanceof Error ? error.message : String(error);
918
1179
  const rollback = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
919
- throw new Error(`FINAL_CUT_CANONICAL_ROLLBACK_FAILED: ${rollback}; original error: ${original}`);
1180
+ throw new Error(`FINAL_CUT_CANONICAL_ROLLBACK_FAILED: ${rollback}; original error: ${original}; FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: further edits are blocked`);
920
1181
  }
921
1182
  finally {
922
1183
  this.pending = undefined;
@@ -924,6 +1185,12 @@ export class FinalCutCanonicalNativeProvider {
924
1185
  throw error;
925
1186
  }
926
1187
  }
1188
+ async assertRecoveryNotRequired() {
1189
+ if (this.recoveryRequired) {
1190
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: a previous native edit could not be restored; further edits are blocked");
1191
+ }
1192
+ await this.recoveryGuard?.assertClear();
1193
+ }
927
1194
  async restore(snapshot, expectedRevision) {
928
1195
  const current = await this.readProject();
929
1196
  assertSameRevision(expectedRevision, current.revision);
@@ -934,15 +1201,51 @@ export class FinalCutCanonicalNativeProvider {
934
1201
  if (canonicalSnapshotDigest(snapshot) !== pending.beforeDigest) {
935
1202
  throw new Error("FINAL_CUT_CANONICAL_UNDO_TARGET_MISMATCH: rollback target differs from the applied edit");
936
1203
  }
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");
1204
+ await this.assertRecoveryNotRequired();
1205
+ if (this.recoveryGuard) {
1206
+ const beforeCheckpoint = await this.live.readLiveState();
1207
+ if (beforeCheckpoint.project?.id !== current.projectId || beforeCheckpoint.sequence?.id !== current.timeline.id
1208
+ || beforeCheckpoint.revision?.id !== this.lastLiveRevision?.id
1209
+ || beforeCheckpoint.revision?.sequence !== this.lastLiveRevision?.sequence) {
1210
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed before Undo");
1211
+ }
1212
+ await this.recoveryGuard.begin({
1213
+ projectId: current.projectId, sequenceId: current.timeline.id,
1214
+ baseRevision: current.revision.id, beforeDigest: canonicalSnapshotDigest(current),
1215
+ operation: "undo", expectedRestoreDigest: pending.beforeDigest,
1216
+ });
1217
+ try {
1218
+ const afterCheckpoint = await this.live.readLiveState();
1219
+ if (afterCheckpoint.project?.id !== beforeCheckpoint.project?.id
1220
+ || afterCheckpoint.sequence?.id !== beforeCheckpoint.sequence?.id
1221
+ || afterCheckpoint.revision?.id !== beforeCheckpoint.revision?.id
1222
+ || afterCheckpoint.revision?.sequence !== beforeCheckpoint.revision?.sequence) {
1223
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_STALE: live target or revision changed during Undo checkpoint acquisition");
1224
+ }
1225
+ }
1226
+ catch (error) {
1227
+ // No Undo command has been dispatched, so this checkpoint is safe to release.
1228
+ await this.recoveryGuard.complete();
1229
+ throw error;
1230
+ }
1231
+ }
1232
+ try {
1233
+ const undone = await this.native.undo(pending.operationId);
1234
+ if (!undone.undone || undone.verification?.verified !== true) {
1235
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_FAILED: Final Cut did not verify native Undo");
1236
+ }
1237
+ const restored = await this.readProject();
1238
+ if (canonicalSnapshotDigest(restored) !== pending.beforeDigest) {
1239
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_FAILED: restored canonical digest does not match the pre-edit state");
1240
+ }
1241
+ await this.recoveryGuard?.complete();
1242
+ this.pending = undefined;
940
1243
  }
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");
1244
+ catch (error) {
1245
+ this.recoveryRequired = true;
1246
+ const detail = error instanceof Error ? error.message : String(error);
1247
+ throw new Error(`FINAL_CUT_CANONICAL_UNDO_FAILED: ${detail}; FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: further edits are blocked`, { cause: error });
944
1248
  }
945
- this.pending = undefined;
946
1249
  }
947
1250
  async listProjects() {
948
1251
  const backgroundCatalog = await this.resolveBackgroundCatalog();
@@ -957,7 +1260,71 @@ export class FinalCutCanonicalNativeProvider {
957
1260
  return this.readBackgroundCatalog(backgroundCatalog);
958
1261
  }
959
1262
  async selectProject(selection) {
960
- throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project selection is not exposed by the background provider");
1263
+ const capability = await this.projectSelectionCapability();
1264
+ if (!capability.available || !this.live.selectProject) {
1265
+ if (!(await this.cachedCanonicalSnapshotAvailability()).available) {
1266
+ throw new Error("CAPABILITY_UNAVAILABLE: active-target-only rebind requires a current canonical snapshot");
1267
+ }
1268
+ const catalog = await this.listProjects();
1269
+ const project = catalog.projects.find((candidate) => candidate.id === selection.projectId);
1270
+ if (!project || catalog.activeProjectId !== selection.projectId) {
1271
+ throw new Error("TARGET_MISMATCH: requested project is not the active catalog target");
1272
+ }
1273
+ const sequenceId = selection.sequenceId ?? (project.sequences.length === 1 ? project.sequences[0]?.id : undefined);
1274
+ if (!sequenceId)
1275
+ throw new Error("AMBIGUOUS_PROJECT_TARGET: sequenceId is required");
1276
+ if (!project.sequences.some((sequence) => sequence.id === sequenceId) || catalog.activeSequenceId !== sequenceId) {
1277
+ throw new Error("TARGET_MISMATCH: requested sequence is not the active catalog target");
1278
+ }
1279
+ if (!(await this.cachedCanonicalSnapshotAvailability()).available) {
1280
+ throw new Error("STALE_CONTEXT: canonical snapshot changed during active target rebind");
1281
+ }
1282
+ const live = await this.live.readLiveState();
1283
+ if (live.project?.id !== selection.projectId || live.sequence?.id !== sequenceId
1284
+ || !live.revision || live.revision.id !== this.lastLiveRevision?.id
1285
+ || live.revision.sequence !== this.lastLiveRevision.sequence) {
1286
+ throw new Error("STALE_CONTEXT: active target changed during rebind");
1287
+ }
1288
+ this.selectedTarget = { projectId: selection.projectId, sequenceId };
1289
+ return createProjectSelectionResult(catalog, this.selectedTarget, live.revision);
1290
+ }
1291
+ if (!selection.projectId.trim())
1292
+ throw new Error("INVALID_PROJECT_SELECTION: projectId is required");
1293
+ if (selection.sequenceId !== undefined && !selection.sequenceId.trim()) {
1294
+ throw new Error("INVALID_PROJECT_SELECTION: sequenceId cannot be empty");
1295
+ }
1296
+ const catalog = await this.listProjects();
1297
+ const project = catalog.projects.find((candidate) => candidate.id === selection.projectId);
1298
+ if (!project)
1299
+ throw new Error(`TARGET_MISMATCH: selected project ${selection.projectId} is absent from the project catalog`);
1300
+ const sequenceId = selection.sequenceId ?? (project.sequences.length === 1 ? project.sequences[0]?.id : undefined);
1301
+ if (!sequenceId)
1302
+ throw new Error(`AMBIGUOUS_PROJECT_TARGET: sequenceId is required for project ${selection.projectId}`);
1303
+ if (!project.sequences.some((sequence) => sequence.id === sequenceId)) {
1304
+ throw new Error(`TARGET_MISMATCH: selected sequence ${sequenceId} is absent from project ${selection.projectId}`);
1305
+ }
1306
+ const target = { projectId: selection.projectId, sequenceId };
1307
+ const result = await this.live.selectProject(target);
1308
+ validateProjectCatalog(result);
1309
+ if (result.activeProjectId !== target.projectId || result.activeSequenceId !== target.sequenceId
1310
+ || result.observedActiveTarget.projectId !== target.projectId
1311
+ || result.observedActiveTarget.sequenceId !== target.sequenceId
1312
+ || result.requestedTarget.projectId !== target.projectId
1313
+ || result.requestedTarget.sequenceId !== target.sequenceId) {
1314
+ throw new Error("TARGET_MISMATCH: live project selection did not confirm the requested project and sequence");
1315
+ }
1316
+ const live = await this.live.readLiveState();
1317
+ if (live.project?.id !== target.projectId || live.sequence?.id !== target.sequenceId) {
1318
+ throw new Error("TARGET_MISMATCH: active project or sequence differs from the selected target");
1319
+ }
1320
+ if (!live.revision?.id || !Number.isSafeInteger(live.revision.sequence)) {
1321
+ throw new Error("FINAL_CUT_CANONICAL_REVISION_UNAVAILABLE: live revision is incomplete after project selection");
1322
+ }
1323
+ if (result.observedRevision.id !== live.revision.id || result.observedRevision.sequence !== live.revision.sequence) {
1324
+ throw new Error("STALE_CONTEXT: live revision changed during project selection");
1325
+ }
1326
+ this.selectedTarget = target;
1327
+ return structuredClone(result);
961
1328
  }
962
1329
  async readLiveState() {
963
1330
  return this.live.readLiveState();
@@ -967,6 +1334,7 @@ export class FinalCutCanonicalNativeProvider {
967
1334
  }
968
1335
  async assertActiveTarget(snapshot) {
969
1336
  const live = await this.live.readLiveState();
1337
+ this.assertSelectedTarget(live);
970
1338
  if (!live.project || live.project.id !== snapshot.projectId) {
971
1339
  throw new Error(`TARGET_MISMATCH: active project identity ${live.project?.id ?? "<unavailable>"} does not match exported project ${snapshot.projectId}`);
972
1340
  }
@@ -979,6 +1347,10 @@ export class FinalCutCanonicalNativeProvider {
979
1347
  if (live.sequence.name !== snapshot.timeline.name) {
980
1348
  throw new Error(`TARGET_MISMATCH: exported sequence ${snapshot.timeline.name} is not active Final Cut sequence ${live.sequence.name}`);
981
1349
  }
1350
+ if (!live.revision?.id || !Number.isSafeInteger(live.revision.sequence)) {
1351
+ throw new Error("FINAL_CUT_CANONICAL_REVISION_UNAVAILABLE: live revision is incomplete");
1352
+ }
1353
+ return live;
982
1354
  }
983
1355
  async resolveBackgroundCatalog() {
984
1356
  if (this.backgroundCatalog)
@@ -986,7 +1358,7 @@ export class FinalCutCanonicalNativeProvider {
986
1358
  if (!this.live.listProjects || !this.live.getCapabilities)
987
1359
  return undefined;
988
1360
  try {
989
- const capabilities = await this.live.getCapabilities();
1361
+ const capabilities = await this.live.getCapabilities({ probeCanonicalSnapshot: false });
990
1362
  if (!capabilities.editor.projectCatalogRead)
991
1363
  return undefined;
992
1364
  const identity = await this.live.getIdentity();
@@ -999,12 +1371,38 @@ export class FinalCutCanonicalNativeProvider {
999
1371
  return undefined;
1000
1372
  }
1001
1373
  }
1374
+ async projectSelectionCapability() {
1375
+ if (!this.live.selectProject || !this.live.getCapabilities)
1376
+ return { available: false, mode: "unavailable" };
1377
+ try {
1378
+ const capabilities = await this.live.getCapabilities({ probeCanonicalSnapshot: false });
1379
+ const mode = projectSelectionMode(capabilities.editor);
1380
+ const available = capabilities.editor.projectSelection === true && mode !== "unavailable";
1381
+ return {
1382
+ available,
1383
+ mode: available ? mode : "unavailable",
1384
+ };
1385
+ }
1386
+ catch {
1387
+ return { available: false, mode: "unavailable" };
1388
+ }
1389
+ }
1390
+ assertSelectedTarget(live) {
1391
+ if (this.selectedTarget && (live.project?.id !== this.selectedTarget.projectId
1392
+ || live.sequence?.id !== this.selectedTarget.sequenceId)) {
1393
+ throw new Error(`TARGET_MISMATCH: active project or sequence differs from the explicitly selected target ${this.selectedTarget.projectId}/${this.selectedTarget.sequenceId}`);
1394
+ }
1395
+ }
1002
1396
  async readBackgroundCatalog(provider) {
1003
1397
  const before = await this.readLiveStateSafely();
1004
1398
  const catalog = await provider.listProjects();
1005
1399
  validateProjectCatalog(catalog);
1006
1400
  const after = await this.readLiveStateSafely();
1007
1401
  const liveIdentity = before && after ? await this.live.getIdentity() : undefined;
1402
+ const liveSelection = await this.projectSelectionCapability();
1403
+ const cached = await this.cachedCanonicalSnapshotAvailability();
1404
+ const selection = liveSelection.available ? liveSelection : cached.available
1405
+ ? { available: true, mode: "active-target-only" } : liveSelection;
1008
1406
  return reconcileProjectCatalog(catalog, {
1009
1407
  ...(before && after ? { before, after } : {}),
1010
1408
  provenance: {
@@ -1021,9 +1419,11 @@ export class FinalCutCanonicalNativeProvider {
1021
1419
  },
1022
1420
  } : {}),
1023
1421
  selection: {
1024
- available: false,
1025
- mode: "unavailable",
1026
- unavailableReason: "project selection is not exposed by the background provider",
1422
+ available: selection.available,
1423
+ mode: selection.mode,
1424
+ ...(!selection.available ? {
1425
+ unavailableReason: "project selection is not exposed by the background provider",
1426
+ } : {}),
1027
1427
  },
1028
1428
  },
1029
1429
  });
@@ -1037,6 +1437,19 @@ export class FinalCutCanonicalNativeProvider {
1037
1437
  }
1038
1438
  }
1039
1439
  }
1440
+ function assertCanonicalSourceBindingAvailable(resolver, operation) {
1441
+ if (operation.type !== "add-marker" && !hasCanonicalSourceBinding(resolver)) {
1442
+ throw new Error("CAPABILITY_UNAVAILABLE: native occurrence source binding cannot be independently observed");
1443
+ }
1444
+ }
1445
+ function hasCanonicalSourceBinding(resolver) {
1446
+ try {
1447
+ return resolver.sourceBindingAvailable === true;
1448
+ }
1449
+ catch {
1450
+ return false;
1451
+ }
1452
+ }
1040
1453
  function supportedCanonicalOperation(operations) {
1041
1454
  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
1455
  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 +1556,12 @@ function projectCanonicalOperation(snapshot, operation) {
1143
1556
  },
1144
1557
  };
1145
1558
  }
1559
+ function assertExactCanonicalProjection(before, after, operation) {
1560
+ const expected = projectCanonicalOperation(before, operation);
1561
+ if (canonicalSnapshotDigest(normalizeCanonicalSnapshot(after)) !== canonicalSnapshotDigest(normalizeCanonicalSnapshot(expected))) {
1562
+ throw new Error(`FINAL_CUT_CANONICAL_READBACK_FAILED: ${operation.type} readback differed from the exact canonical projection`);
1563
+ }
1564
+ }
1146
1565
  function projectCanonicalRippleDelete(snapshot, range) {
1147
1566
  const duration = subtractRational(range.end, range.start);
1148
1567
  const clips = snapshot.timeline.clips.flatMap((clip) => projectClipAfterRippleDelete(clip, range, duration));
@@ -1258,18 +1677,18 @@ function canonicalRippleRange(snapshot, range) {
1258
1677
  throw new Error("INVALID_OPERATION: ripple-delete range must have positive duration");
1259
1678
  }
1260
1679
  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
1680
  const timelineDuration = snapshot.timeline.durationTime ?? secondsToRational(snapshot.timeline.duration, frameDuration);
1265
1681
  if (compareRational(start, zeroRational()) < 0 || compareRational(end, timelineDuration) > 0) {
1266
- throw new Error("INVALID_OPERATION: ripple-delete range must fit inside the active timeline");
1682
+ throw new Error(`INVALID_OPERATION: ripple-delete range [${range.start}, ${range.end}) must fit timeline bounds [0, ${rationalSeconds(timelineDuration)})`);
1683
+ }
1684
+ if (!isFrameAligned(start, zeroRational(), frameDuration) || !isFrameAligned(end, zeroRational(), frameDuration)) {
1685
+ throw new Error("INVALID_OPERATION: ripple-delete range must be frame-aligned");
1267
1686
  }
1268
1687
  return { start, end };
1269
1688
  }
1270
1689
  function assertRippleDeleteReadback(before, after, targetClip, range) {
1271
1690
  const expected = projectCanonicalRippleDelete(before, range);
1272
- if (canonicalSnapshotDigest(normalizeRippleSnapshot(after)) !== canonicalSnapshotDigest(normalizeRippleSnapshot(expected))) {
1691
+ if (canonicalSnapshotDigest(normalizeCanonicalSnapshot(after)) !== canonicalSnapshotDigest(normalizeCanonicalSnapshot(expected))) {
1273
1692
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete readback differed from the exact canonical projection");
1274
1693
  }
1275
1694
  if (!after.timeline.durationTime || !expected.timeline.durationTime
@@ -1295,15 +1714,19 @@ function assertRippleDeleteReadback(before, after, targetClip, range) {
1295
1714
  }
1296
1715
  }
1297
1716
  }
1298
- function normalizeRippleSnapshot(snapshot) {
1717
+ function normalizeCanonicalSnapshot(snapshot) {
1299
1718
  const normalized = structuredClone(snapshot);
1300
1719
  normalized.timeline.durationTime = normalized.timeline.durationTime
1301
1720
  ? normalizeRationalTime(normalized.timeline.durationTime)
1302
1721
  : normalized.timeline.durationTime;
1722
+ normalized.timeline.frameDuration = normalized.timeline.frameDuration
1723
+ ? normalizeRationalTime(normalized.timeline.frameDuration)
1724
+ : normalized.timeline.frameDuration;
1303
1725
  normalized.timeline.clips = normalized.timeline.clips.map((clip) => ({
1304
1726
  ...clip,
1305
1727
  startTime: normalizeRationalTime(clip.startTime),
1306
1728
  durationTime: normalizeRationalTime(clip.durationTime),
1729
+ ...(clip.sourceStartTime ? { sourceStartTime: normalizeRationalTime(clip.sourceStartTime) } : {}),
1307
1730
  }));
1308
1731
  normalized.timeline.storyElements = normalized.timeline.storyElements.map((element) => ({
1309
1732
  ...element,
@@ -1359,6 +1782,23 @@ function assertMarkerReadback(before, after, marker, range) {
1359
1782
  if (matches.length !== beforeMatches.length + 1) {
1360
1783
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native marker was not uniquely read back at the requested rational position");
1361
1784
  }
1785
+ const priorIds = new Set(before.timeline.markers.map(({ id }) => id));
1786
+ const added = after.timeline.markers.filter(({ id }) => !priorIds.has(id));
1787
+ if (priorIds.size !== before.timeline.markers.length
1788
+ || new Set(after.timeline.markers.map(({ id }) => id)).size !== after.timeline.markers.length
1789
+ || added.length !== 1 || !matches.includes(added[0])) {
1790
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native marker identity is ambiguous");
1791
+ }
1792
+ const expected = projectCanonicalOperation(before, { type: "add-marker", timelineId: before.timeline.id, marker });
1793
+ expected.timeline.markers = expected.timeline.markers.map((candidate) => candidate.id === marker.id
1794
+ ? { ...candidate, id: added[0].id } : candidate);
1795
+ const normalizedExpected = normalizeCanonicalSnapshot(expected);
1796
+ const normalizedAfter = normalizeCanonicalSnapshot(after);
1797
+ normalizedExpected.timeline.markers.sort((left, right) => left.id.localeCompare(right.id));
1798
+ normalizedAfter.timeline.markers.sort((left, right) => left.id.localeCompare(right.id));
1799
+ if (canonicalSnapshotDigest(normalizedAfter) !== canonicalSnapshotDigest(normalizedExpected)) {
1800
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: marker readback differed from the exact canonical projection");
1801
+ }
1362
1802
  }
1363
1803
  function assertCanonicalOperationAvailable(native, operation) {
1364
1804
  if (operation.type === "trim-clip" && !native.trimSelectedClipToRange) {
@@ -1569,15 +2009,36 @@ async function readCanonicalExport(path, timeoutMs, pollIntervalMs, target, read
1569
2009
  throw new Error(`FINAL_CUT_CANONICAL_EXPORT_TIMEOUT: Final Cut did not provide a complete export at ${path}${detail}`);
1570
2010
  }
1571
2011
  function sourceBasename(source) {
1572
- const withoutQuery = source.split(/[?#]/, 1)[0] ?? source;
1573
2012
  try {
1574
- const url = new URL(withoutQuery);
1575
- return basename(decodeURIComponent(url.pathname));
2013
+ const url = new URL(source);
2014
+ return basename(url.protocol === "file:" ? fileURLToPath(url) : decodeURIComponent(url.pathname));
1576
2015
  }
1577
2016
  catch {
1578
- return basename(withoutQuery.replace(/^file:\/\//, ""));
2017
+ return basename(source);
1579
2018
  }
1580
2019
  }
2020
+ function exactLocalSourcePath(source) {
2021
+ try {
2022
+ const decoded = source.startsWith("file:") ? decodeURIComponent(source) : source;
2023
+ if (/(?:^|\/)\.{1,2}(?:\/|$)/.test(decoded) || decoded.includes("\0"))
2024
+ return undefined;
2025
+ if (source.startsWith("file:")) {
2026
+ const url = new URL(source);
2027
+ if (url.protocol !== "file:" || url.search || url.hash)
2028
+ return undefined;
2029
+ const path = fileURLToPath(url);
2030
+ return isAbsolute(path) ? path : undefined;
2031
+ }
2032
+ return isAbsolute(source) ? source : undefined;
2033
+ }
2034
+ catch {
2035
+ return undefined;
2036
+ }
2037
+ }
2038
+ function validRationalText(value) {
2039
+ const match = value?.trim().match(/^(-?\d+)\/(\d+)$/);
2040
+ return Boolean(match && BigInt(match[2]) > 0n);
2041
+ }
1581
2042
  function sameRationalText(value, expected) {
1582
2043
  const match = value.trim().match(/^(-?\d+)\/(\d+)$/);
1583
2044
  if (!match || Number(match[2]) <= 0 || Number(expected.timescale) <= 0)