@morshoto/framekit 0.1.17 → 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 (58) hide show
  1. package/README.md +25 -14
  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 +557 -84
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +10 -3
  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 +150 -37
  9. package/dist-package/adapters/final-cut/typescript/src/index.js +2 -7
  10. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +60 -1
  11. package/dist-package/adapters/final-cut/typescript/src/live.js +29 -4
  12. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.js +175 -0
  13. package/dist-package/adapters/final-cut/typescript/src/native-session.js +11 -6
  14. package/dist-package/adapters/final-cut/typescript/src/native.js +201 -82
  15. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +214 -0
  16. package/dist-package/adapters/final-cut/typescript/src/publisher.js +1008 -243
  17. package/dist-package/adapters/final-cut/typescript/src/session.js +49 -14
  18. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +203 -49
  19. package/dist-package/adapters/headless/typescript/src/audio-output.js +3 -0
  20. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +48 -20
  21. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +9 -4
  22. package/dist-package/apps/cli/src/dev-doctor.js +198 -0
  23. package/dist-package/apps/cli/src/headless-projects.js +5 -0
  24. package/dist-package/apps/cli/src/main.js +76 -19
  25. package/dist-package/apps/mcp-server/runtime/speech-analyzer-wrapper.mjs +54 -0
  26. package/dist-package/apps/mcp-server/runtime/whisper-speech-backend.py +181 -0
  27. package/dist-package/apps/mcp-server/src/build-alignment.js +59 -0
  28. package/dist-package/apps/mcp-server/src/build-identity.js +30 -0
  29. package/dist-package/apps/mcp-server/src/build-identity.json +5 -0
  30. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.js +18 -0
  31. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.js +3 -0
  32. package/dist-package/apps/mcp-server/src/headless-project-snapshot.js +101 -0
  33. package/dist-package/apps/mcp-server/src/main.js +50 -21
  34. package/dist-package/apps/mcp-server/src/materialization-jobs.js +143 -10
  35. package/dist-package/apps/mcp-server/src/routing.js +2 -0
  36. package/dist-package/apps/mcp-server/src/server.js +986 -180
  37. package/dist-package/apps/mcp-server/src/tools/skills/catalog.js +142 -0
  38. package/dist-package/apps/mcp-server/src/tools/skills/metadata.js +71 -0
  39. package/dist-package/apps/mcp-server/src/tools/skills/register.js +101 -0
  40. package/dist-package/apps/mcp-server/src/version.js +21 -2
  41. package/dist-package/packages/headless-application/src/headless-projects.js +942 -0
  42. package/dist-package/packages/headless-application/src/index.js +1 -0
  43. package/dist-package/packages/runtime/src/application/media-analysis-service.js +15 -5
  44. package/dist-package/packages/runtime/src/application/project-service.js +5 -1
  45. package/dist-package/packages/runtime/src/application/project-store.js +13 -36
  46. package/dist-package/packages/runtime/src/application/transaction-store.js +1 -1
  47. package/dist-package/packages/runtime/src/capabilities.js +1 -1
  48. package/dist-package/packages/runtime/src/context/context-engine.js +22 -16
  49. package/dist-package/packages/runtime/src/context/context-service.js +2 -2
  50. package/dist-package/packages/runtime/src/editing/edit-service.js +76 -10
  51. package/dist-package/packages/runtime/src/index.js +1 -0
  52. package/dist-package/packages/runtime/src/runtime.js +22 -7
  53. package/dist-package/packages/runtime/src/timeline/editing-session.js +23 -2
  54. package/dist-package/packages/testkit/src/in-memory-editor.js +3 -3
  55. package/dist-package/packages/testkit/src/index.js +1 -0
  56. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.js +192 -0
  57. package/package.json +36 -14
  58. package/dist-package/apps/mcp-server/src/headless-projects.js +0 -370
@@ -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"] : []),
@@ -87,12 +91,17 @@ export class FinalCutCanonicalSnapshotSource {
87
91
  exportTimeoutMs;
88
92
  pollIntervalMs;
89
93
  target;
94
+ readbackTarget;
90
95
  stageOnDesktop;
91
96
  constructor(options = {}) {
92
97
  this.executor = options.executor ?? executeCanonicalAppleScript;
93
98
  this.exportTimeoutMs = Math.max(1_000, options.exportTimeoutMs ?? 30_000);
94
99
  this.pollIntervalMs = Math.max(10, options.pollIntervalMs ?? 100);
95
100
  this.target = options.target;
101
+ this.readbackTarget = options.readbackTarget;
102
+ if (this.target && this.readbackTarget) {
103
+ throw new Error("FINAL_CUT_CANONICAL_TARGET_INVALID: FCPXML UID and catalog readback bindings cannot be combined");
104
+ }
96
105
  this.stageOnDesktop = !options.executor;
97
106
  }
98
107
  async readSnapshot() {
@@ -108,7 +117,7 @@ export class FinalCutCanonicalSnapshotSource {
108
117
  for (let attempt = 1; attempt <= 2; attempt += 1) {
109
118
  const result = parseFinalCutCanonicalExportResult(await this.executor(buildFinalCutCanonicalExportScript(exportPath)));
110
119
  if (result.status === "export-requested") {
111
- return await readCanonicalExport(exportPath, this.exportTimeoutMs, this.pollIntervalMs, this.target);
120
+ return await readCanonicalExport(exportPath, this.exportTimeoutMs, this.pollIntervalMs, this.target, this.readbackTarget);
112
121
  }
113
122
  const error = new FinalCutCanonicalExportError(result);
114
123
  if (!error.retryable || error.cleanup !== "complete" || attempt === 2)
@@ -133,10 +142,7 @@ export class FinalCutCanonicalSnapshotSource {
133
142
  export function buildFinalCutCanonicalExportScript(exportPath) {
134
143
  const exportDirectory = dirname(exportPath);
135
144
  const exportName = basename(exportPath);
136
- const defaultDesktop = join(homedir(), "Desktop");
137
- const chooseExportDirectory = exportDirectory === defaultDesktop
138
- ? ""
139
- : ` keystroke "g" using {command down, shift down}
145
+ const chooseExportDirectory = ` keystroke "g" using {command down, shift down}
140
146
  delay 1
141
147
  try
142
148
  set pathField to text field 1 of sheet 1 of window "Export XML"
@@ -568,7 +574,17 @@ ${chooseExportDirectory} end if
568
574
  end tell`;
569
575
  }
570
576
  export function createFinalCutNativeTargetResolver(native) {
571
- 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
+ }
572
588
  if (!clip.mediaId)
573
589
  throw new Error(`TARGET_MISMATCH: occurrence ${clip.id} has no media binding`);
574
590
  const media = snapshot.media.find(({ mediaId }) => mediaId === clip.mediaId);
@@ -577,18 +593,58 @@ export function createFinalCutNativeTargetResolver(native) {
577
593
  const query = sourceBasename(media.source);
578
594
  if (!query)
579
595
  throw new Error(`TARGET_MISMATCH: media ${clip.mediaId} has no searchable source basename`);
580
- 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());
581
626
  if (matches.length === 0)
582
627
  throw new Error(`TARGET_MISMATCH: Final Cut Browser has no exact media match for ${query}`);
583
- if (matches.length > 1)
584
- throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut Browser has multiple exact media matches for ${query}`);
585
- 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];
586
638
  if (!match.sourceIdentity)
587
639
  throw new Error("TARGET_MISMATCH: exact Browser media has no stable source identity");
588
- const located = await native.locateOccurrence(match.handle);
640
+ const locate = native.locateOccurrenceForCanonicalTarget ?? native.locateOccurrence;
641
+ const located = await locate.call(native, match.handle);
589
642
  if (located.status === "none" || located.occurrences.length === 0) {
590
643
  throw new Error(`TARGET_MISMATCH: Final Cut timeline has no occurrence for ${query}`);
591
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
+ }
592
648
  const matchingOccurrences = located.occurrences.filter((candidate) => candidate.start && candidate.duration && clip.startTime && clip.durationTime
593
649
  && sameRationalText(candidate.start, clip.startTime)
594
650
  && sameRationalText(candidate.duration, clip.durationTime));
@@ -599,9 +655,8 @@ export function createFinalCutNativeTargetResolver(native) {
599
655
  throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut timeline occurrence coordinates are not unique for ${clip.id}`);
600
656
  }
601
657
  const occurrence = matchingOccurrences[0];
602
- await native.selectOccurrence?.(occurrence.handle);
603
658
  const occurrenceIdentity = occurrence.identity ?? occurrence.nativeIdentity;
604
- if (!occurrenceIdentity && !native.selectOccurrence) {
659
+ if (!occurrenceIdentity) {
605
660
  throw new Error(`TARGET_MISMATCH: native occurrence has no stable identity for ${clip.id}`);
606
661
  }
607
662
  if (!occurrence.sequenceId) {
@@ -610,8 +665,8 @@ export function createFinalCutNativeTargetResolver(native) {
610
665
  if (occurrence.sequenceId !== snapshot.timeline.id) {
611
666
  throw new Error(`TARGET_MISMATCH: native occurrence sequence changed for ${clip.id}`);
612
667
  }
613
- if (occurrence.sourceIdentity && occurrence.sourceIdentity !== match.sourceIdentity) {
614
- 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}`);
615
670
  }
616
671
  if (!occurrence.start || !occurrence.duration || !clip.startTime || !clip.durationTime) {
617
672
  throw new Error(`TARGET_MISMATCH: exact timeline coordinates are unavailable for ${clip.id}`);
@@ -619,7 +674,49 @@ export function createFinalCutNativeTargetResolver(native) {
619
674
  if (!sameRationalText(occurrence.start, clip.startTime) || !sameRationalText(occurrence.duration, clip.durationTime)) {
620
675
  throw new Error(`TARGET_MISMATCH: native occurrence coordinates changed for ${clip.id}`);
621
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
+ }
622
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;
623
720
  }
624
721
  /**
625
722
  * Canonical provider for the headed Final Cut UI path.
@@ -636,34 +733,46 @@ export class FinalCutCanonicalNativeProvider {
636
733
  resolveTarget;
637
734
  backgroundCatalog;
638
735
  lastDigest;
736
+ lastLiveRevision;
737
+ revisionEpoch = randomUUID();
639
738
  lastSnapshot;
739
+ readScope = new AsyncLocalStorage();
740
+ selectedTarget;
640
741
  revisionSequence = 0;
641
742
  revision;
642
743
  pending;
744
+ recoveryRequired = false;
745
+ recoveryGuard;
643
746
  constructor(options) {
644
747
  this.live = options.live;
645
748
  this.native = options.native;
646
749
  this.readSnapshotSource = options.readSnapshot;
647
750
  this.resolveTarget = options.resolveTarget;
648
751
  this.backgroundCatalog = options.backgroundCatalog;
752
+ this.recoveryGuard = options.recoveryGuard;
649
753
  }
650
754
  async getIdentity() {
651
755
  const identity = await this.live.getIdentity();
652
756
  return { ...identity, backend: "final-cut-native-canonical" };
653
757
  }
758
+ withCanonicalReadScope(operation) {
759
+ return this.readScope.getStore() ? operation() : this.readScope.run({}, operation);
760
+ }
654
761
  async getCapabilities(options = {}) {
655
762
  const backgroundCatalog = await this.resolveBackgroundCatalog();
656
- const snapshotProbe = backgroundCatalog && options.probeCanonicalSnapshot !== false
657
- ? await this.probeCanonicalSnapshot()
658
- : {
659
- available: false,
660
- reason: backgroundCatalog
661
- ? "canonical snapshot availability was not checked"
662
- : "canonical timeline snapshot requires a background project catalog",
663
- };
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;
664
772
  const canonicalSnapshotCapability = snapshotProbe.available
665
- ? true
773
+ ? { available: true, backend: "final-cut-native-canonical", guarantee: "canonical-read", evidenceTier: "headed-native" }
666
774
  : unavailableCanonicalSnapshot(snapshotProbe.reason);
775
+ const sourceBindingAvailable = hasCanonicalSourceBinding(this.resolveTarget);
667
776
  const capabilities = withCapabilityFamilies({
668
777
  editor: {
669
778
  projectRead: snapshotProbe.available,
@@ -679,16 +788,17 @@ export class FinalCutCanonicalNativeProvider {
679
788
  frameCapture: false,
680
789
  playbackControl: false,
681
790
  projectCatalogRead: Boolean(backgroundCatalog),
682
- projectSelection: false,
683
- projectSelectionMode: "unavailable",
791
+ projectSelection: selection.available,
792
+ projectSelectionMode: selection.mode,
684
793
  backgroundLibraryInspection: Boolean(backgroundCatalog),
685
794
  compositeTransactions: snapshotProbe.available,
795
+ ...(snapshotProbe.available && this.native.addMarkerAtTime ? { markerIdentityMode: "editor-assigned" } : {}),
686
796
  semanticOperations: {
687
- "rename-clip": snapshotProbe.available,
688
- "trim-clip": snapshotProbe.available && Boolean(this.native.trimSelectedClipToRange),
797
+ "rename-clip": snapshotProbe.available && sourceBindingAvailable,
798
+ "trim-clip": snapshotProbe.available && sourceBindingAvailable && Boolean(this.native.trimSelectedClipToRange),
689
799
  "add-marker": snapshotProbe.available && Boolean(this.native.addMarkerAtTime),
690
- "ripple-delete": snapshotProbe.available && Boolean(this.native.rippleDeleteRange),
691
- "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),
692
802
  },
693
803
  },
694
804
  analyzers: {
@@ -702,7 +812,9 @@ export class FinalCutCanonicalNativeProvider {
702
812
  connectionBackend: "workflow-extension-ipc",
703
813
  canonicalDocument: {
704
814
  read: canonicalSnapshotCapability,
705
- write: canonicalSnapshotCapability,
815
+ write: snapshotProbe.available
816
+ ? { available: true, backend: "final-cut-native-canonical", guarantee: "canonical-write", evidenceTier: "headed-native" }
817
+ : canonicalSnapshotCapability,
706
818
  artifactWrite: false,
707
819
  },
708
820
  observation: {
@@ -716,7 +828,14 @@ export class FinalCutCanonicalNativeProvider {
716
828
  },
717
829
  });
718
830
  const readiness = assessCanonicalLiveReadiness(capabilities);
719
- 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)
720
839
  return capabilities;
721
840
  const canonicalReadReady = capabilities.editor.projectRead
722
841
  && capabilities.editor.timelineSnapshotRead
@@ -730,11 +849,12 @@ export class FinalCutCanonicalNativeProvider {
730
849
  readAfterWrite: false,
731
850
  rollback: false,
732
851
  compositeTransactions: false,
852
+ markerIdentityMode: undefined,
733
853
  semanticOperations: {},
734
854
  },
735
855
  }, {
736
856
  canonicalDocument: {
737
- read: true,
857
+ read: canonicalSnapshotCapability,
738
858
  write: false,
739
859
  artifactWrite: false,
740
860
  },
@@ -756,9 +876,28 @@ export class FinalCutCanonicalNativeProvider {
756
876
  },
757
877
  });
758
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
+ }
759
898
  async probeCanonicalSnapshot() {
760
899
  try {
761
- await this.readSnapshotSource();
900
+ await this.readProject();
762
901
  return { available: true };
763
902
  }
764
903
  catch (error) {
@@ -773,25 +912,54 @@ export class FinalCutCanonicalNativeProvider {
773
912
  return this.readProject();
774
913
  }
775
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);
776
929
  const snapshot = await this.readSnapshotSource();
777
- 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
+ }
778
937
  const digest = canonicalSnapshotDigest(snapshot);
779
- 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) {
780
941
  this.revisionSequence = Math.max(this.revisionSequence + 1, snapshot.revision.sequence + 1);
781
942
  this.lastDigest = digest;
943
+ this.lastLiveRevision = { id: live.revision.id, sequence: live.revision.sequence };
782
944
  this.revision = {
783
- id: `canonical:${digest}`,
945
+ id: `canonical:${this.revisionEpoch}:${this.revisionSequence}:${digest}`,
784
946
  sequence: this.revisionSequence,
785
947
  timestamp: new Date().toISOString(),
786
948
  };
787
949
  }
788
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
+ }
789
955
  return structuredClone(this.lastSnapshot);
790
956
  }
791
957
  async previewTransaction(operations, expectedRevision) {
958
+ await this.assertRecoveryNotRequired();
792
959
  const before = await this.readProject();
793
960
  assertSameRevision(expectedRevision, before.revision);
794
961
  const operation = supportedCanonicalOperation(operations);
962
+ assertCanonicalSourceBindingAvailable(this.resolveTarget, operation);
795
963
  assertCanonicalOperationAvailable(this.native, operation);
796
964
  const preview = projectCanonicalOperation(before, operation);
797
965
  preview.revision = previewRevision(preview, before.revision);
@@ -802,9 +970,15 @@ export class FinalCutCanonicalNativeProvider {
802
970
  await this.apply(operation, expectedRevision);
803
971
  }
804
972
  async apply(operation, expectedRevision) {
973
+ await this.assertRecoveryNotRequired();
974
+ const baselineLive = await this.live.readLiveState();
805
975
  const before = await this.readProject();
806
976
  assertSameRevision(expectedRevision, before.revision);
807
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
+ }
808
982
  const markerRange = supported.type === "add-marker" ? canonicalMarkerRange(before, supported.marker) : undefined;
809
983
  const clipTarget = supported.type === "rename-clip" || supported.type === "trim-clip" || supported.type === "set-gain"
810
984
  ? canonicalTargetForOperation(before, supported)
@@ -823,27 +997,104 @@ export class FinalCutCanonicalNativeProvider {
823
997
  : {}),
824
998
  });
825
999
  resolveTimelineTarget(before, timelineTarget);
826
- if (targetClip)
827
- await this.resolveTarget(targetClip, before);
828
1000
  assertCanonicalOperationAvailable(this.native, supported);
829
- const nativeResult = supported.type === "rename-clip"
830
- ? await this.native.renameSelectedClip(supported.name)
831
- : supported.type === "trim-clip"
832
- ? await this.native.trimSelectedClipToRange({
833
- start: structuredClone(clip.startTime),
834
- end: addRational(clip.startTime, trimDuration),
835
- })
836
- : supported.type === "ripple-delete"
837
- ? await this.native.rippleDeleteRange(rippleTarget.range)
838
- : supported.type === "set-gain"
839
- ? await this.native.setSelectedClipGain(supported.gainDb)
840
- : await this.native.addMarkerAtTime({
841
- start: markerRange.start,
842
- duration: markerRange.duration,
843
- name: supported.marker.name,
844
- });
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
+ }
845
1095
  if (!nativeResult.operationId || !nativeResult.undoAvailable) {
846
- 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");
847
1098
  }
848
1099
  this.pending = {
849
1100
  operationId: nativeResult.operationId,
@@ -874,6 +1125,7 @@ export class FinalCutCanonicalNativeProvider {
874
1125
  if (readback.beforeDigest !== this.pending.beforeDigest) {
875
1126
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: canonical before digest changed during verification");
876
1127
  }
1128
+ assertExactCanonicalProjection(before, after, supported);
877
1129
  }
878
1130
  else if (supported.type === "trim-clip") {
879
1131
  const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
@@ -881,12 +1133,14 @@ export class FinalCutCanonicalNativeProvider {
881
1133
  || !sameRational(afterClip.durationTime, trimDuration)) {
882
1134
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: trimmed occurrence range was not read back from Final Cut");
883
1135
  }
1136
+ assertExactCanonicalProjection(before, after, supported);
884
1137
  }
885
1138
  else if (supported.type === "set-gain") {
886
1139
  const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
887
1140
  if (!afterClip || (afterClip.gainDb ?? 0) !== supported.gainDb) {
888
1141
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: gain was not read back from Final Cut");
889
1142
  }
1143
+ assertExactCanonicalProjection(before, after, supported);
890
1144
  }
891
1145
  else if (supported.type === "ripple-delete") {
892
1146
  assertRippleDeleteReadback(before, after, rippleTarget.clip, rippleTarget.range);
@@ -899,6 +1153,7 @@ export class FinalCutCanonicalNativeProvider {
899
1153
  }
900
1154
  assertTimelineTargetReadAfterWrite(timelineTarget, before, after, supported.type === "ripple-delete" ? { allowOccurrenceRemoval: true } : undefined);
901
1155
  this.pending.afterRevision = after.revision;
1156
+ await this.recoveryGuard?.complete();
902
1157
  return after.revision;
903
1158
  }
904
1159
  catch (error) {
@@ -907,14 +1162,22 @@ export class FinalCutCanonicalNativeProvider {
907
1162
  operationId: nativeResult.operationId,
908
1163
  before,
909
1164
  target: timelineTarget,
910
- 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
+ },
911
1172
  readSnapshot: () => this.readProject(),
912
1173
  });
1174
+ await this.recoveryGuard?.complete();
913
1175
  }
914
1176
  catch (rollbackError) {
1177
+ this.recoveryRequired = true;
915
1178
  const original = error instanceof Error ? error.message : String(error);
916
1179
  const rollback = rollbackError instanceof Error ? rollbackError.message : String(rollbackError);
917
- 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`);
918
1181
  }
919
1182
  finally {
920
1183
  this.pending = undefined;
@@ -922,6 +1185,12 @@ export class FinalCutCanonicalNativeProvider {
922
1185
  throw error;
923
1186
  }
924
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
+ }
925
1194
  async restore(snapshot, expectedRevision) {
926
1195
  const current = await this.readProject();
927
1196
  assertSameRevision(expectedRevision, current.revision);
@@ -932,15 +1201,51 @@ export class FinalCutCanonicalNativeProvider {
932
1201
  if (canonicalSnapshotDigest(snapshot) !== pending.beforeDigest) {
933
1202
  throw new Error("FINAL_CUT_CANONICAL_UNDO_TARGET_MISMATCH: rollback target differs from the applied edit");
934
1203
  }
935
- const undone = await this.native.undo(pending.operationId);
936
- if (!undone.undone || undone.verification?.verified !== true) {
937
- 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
+ }
938
1231
  }
939
- const restored = await this.readProject();
940
- if (canonicalSnapshotDigest(restored) !== pending.beforeDigest) {
941
- throw new Error("FINAL_CUT_CANONICAL_UNDO_FAILED: restored canonical digest does not match the pre-edit state");
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;
1243
+ }
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 });
942
1248
  }
943
- this.pending = undefined;
944
1249
  }
945
1250
  async listProjects() {
946
1251
  const backgroundCatalog = await this.resolveBackgroundCatalog();
@@ -955,7 +1260,71 @@ export class FinalCutCanonicalNativeProvider {
955
1260
  return this.readBackgroundCatalog(backgroundCatalog);
956
1261
  }
957
1262
  async selectProject(selection) {
958
- 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);
959
1328
  }
960
1329
  async readLiveState() {
961
1330
  return this.live.readLiveState();
@@ -965,6 +1334,7 @@ export class FinalCutCanonicalNativeProvider {
965
1334
  }
966
1335
  async assertActiveTarget(snapshot) {
967
1336
  const live = await this.live.readLiveState();
1337
+ this.assertSelectedTarget(live);
968
1338
  if (!live.project || live.project.id !== snapshot.projectId) {
969
1339
  throw new Error(`TARGET_MISMATCH: active project identity ${live.project?.id ?? "<unavailable>"} does not match exported project ${snapshot.projectId}`);
970
1340
  }
@@ -977,6 +1347,10 @@ export class FinalCutCanonicalNativeProvider {
977
1347
  if (live.sequence.name !== snapshot.timeline.name) {
978
1348
  throw new Error(`TARGET_MISMATCH: exported sequence ${snapshot.timeline.name} is not active Final Cut sequence ${live.sequence.name}`);
979
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;
980
1354
  }
981
1355
  async resolveBackgroundCatalog() {
982
1356
  if (this.backgroundCatalog)
@@ -984,7 +1358,7 @@ export class FinalCutCanonicalNativeProvider {
984
1358
  if (!this.live.listProjects || !this.live.getCapabilities)
985
1359
  return undefined;
986
1360
  try {
987
- const capabilities = await this.live.getCapabilities();
1361
+ const capabilities = await this.live.getCapabilities({ probeCanonicalSnapshot: false });
988
1362
  if (!capabilities.editor.projectCatalogRead)
989
1363
  return undefined;
990
1364
  const identity = await this.live.getIdentity();
@@ -997,12 +1371,38 @@ export class FinalCutCanonicalNativeProvider {
997
1371
  return undefined;
998
1372
  }
999
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
+ }
1000
1396
  async readBackgroundCatalog(provider) {
1001
1397
  const before = await this.readLiveStateSafely();
1002
1398
  const catalog = await provider.listProjects();
1003
1399
  validateProjectCatalog(catalog);
1004
1400
  const after = await this.readLiveStateSafely();
1005
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;
1006
1406
  return reconcileProjectCatalog(catalog, {
1007
1407
  ...(before && after ? { before, after } : {}),
1008
1408
  provenance: {
@@ -1019,9 +1419,11 @@ export class FinalCutCanonicalNativeProvider {
1019
1419
  },
1020
1420
  } : {}),
1021
1421
  selection: {
1022
- available: false,
1023
- mode: "unavailable",
1024
- 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
+ } : {}),
1025
1427
  },
1026
1428
  },
1027
1429
  });
@@ -1035,6 +1437,19 @@ export class FinalCutCanonicalNativeProvider {
1035
1437
  }
1036
1438
  }
1037
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
+ }
1038
1453
  function supportedCanonicalOperation(operations) {
1039
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")) {
1040
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");
@@ -1141,6 +1556,12 @@ function projectCanonicalOperation(snapshot, operation) {
1141
1556
  },
1142
1557
  };
1143
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
+ }
1144
1565
  function projectCanonicalRippleDelete(snapshot, range) {
1145
1566
  const duration = subtractRational(range.end, range.start);
1146
1567
  const clips = snapshot.timeline.clips.flatMap((clip) => projectClipAfterRippleDelete(clip, range, duration));
@@ -1256,18 +1677,18 @@ function canonicalRippleRange(snapshot, range) {
1256
1677
  throw new Error("INVALID_OPERATION: ripple-delete range must have positive duration");
1257
1678
  }
1258
1679
  const end = addRational(start, duration);
1259
- if (!isFrameAligned(start, zeroRational(), frameDuration) || !isFrameAligned(end, zeroRational(), frameDuration)) {
1260
- throw new Error("INVALID_OPERATION: ripple-delete range must be frame-aligned");
1261
- }
1262
1680
  const timelineDuration = snapshot.timeline.durationTime ?? secondsToRational(snapshot.timeline.duration, frameDuration);
1263
1681
  if (compareRational(start, zeroRational()) < 0 || compareRational(end, timelineDuration) > 0) {
1264
- 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");
1265
1686
  }
1266
1687
  return { start, end };
1267
1688
  }
1268
1689
  function assertRippleDeleteReadback(before, after, targetClip, range) {
1269
1690
  const expected = projectCanonicalRippleDelete(before, range);
1270
- if (canonicalSnapshotDigest(normalizeRippleSnapshot(after)) !== canonicalSnapshotDigest(normalizeRippleSnapshot(expected))) {
1691
+ if (canonicalSnapshotDigest(normalizeCanonicalSnapshot(after)) !== canonicalSnapshotDigest(normalizeCanonicalSnapshot(expected))) {
1271
1692
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete readback differed from the exact canonical projection");
1272
1693
  }
1273
1694
  if (!after.timeline.durationTime || !expected.timeline.durationTime
@@ -1293,15 +1714,19 @@ function assertRippleDeleteReadback(before, after, targetClip, range) {
1293
1714
  }
1294
1715
  }
1295
1716
  }
1296
- function normalizeRippleSnapshot(snapshot) {
1717
+ function normalizeCanonicalSnapshot(snapshot) {
1297
1718
  const normalized = structuredClone(snapshot);
1298
1719
  normalized.timeline.durationTime = normalized.timeline.durationTime
1299
1720
  ? normalizeRationalTime(normalized.timeline.durationTime)
1300
1721
  : normalized.timeline.durationTime;
1722
+ normalized.timeline.frameDuration = normalized.timeline.frameDuration
1723
+ ? normalizeRationalTime(normalized.timeline.frameDuration)
1724
+ : normalized.timeline.frameDuration;
1301
1725
  normalized.timeline.clips = normalized.timeline.clips.map((clip) => ({
1302
1726
  ...clip,
1303
1727
  startTime: normalizeRationalTime(clip.startTime),
1304
1728
  durationTime: normalizeRationalTime(clip.durationTime),
1729
+ ...(clip.sourceStartTime ? { sourceStartTime: normalizeRationalTime(clip.sourceStartTime) } : {}),
1305
1730
  }));
1306
1731
  normalized.timeline.storyElements = normalized.timeline.storyElements.map((element) => ({
1307
1732
  ...element,
@@ -1357,6 +1782,23 @@ function assertMarkerReadback(before, after, marker, range) {
1357
1782
  if (matches.length !== beforeMatches.length + 1) {
1358
1783
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native marker was not uniquely read back at the requested rational position");
1359
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
+ }
1360
1802
  }
1361
1803
  function assertCanonicalOperationAvailable(native, operation) {
1362
1804
  if (operation.type === "trim-clip" && !native.trimSelectedClipToRange) {
@@ -1520,7 +1962,7 @@ async function executeCanonicalAppleScript(script) {
1520
1962
  throw new Error(`FINAL_CUT_CANONICAL_AUTOMATION_FAILED: ${detail}`);
1521
1963
  }
1522
1964
  }
1523
- async function readCanonicalExport(path, timeoutMs, pollIntervalMs, target) {
1965
+ async function readCanonicalExport(path, timeoutMs, pollIntervalMs, target, readbackTarget) {
1524
1966
  const deadline = Date.now() + timeoutMs;
1525
1967
  let previousSignature;
1526
1968
  let lastReadError;
@@ -1542,7 +1984,17 @@ async function readCanonicalExport(path, timeoutMs, pollIntervalMs, target) {
1542
1984
  }
1543
1985
  if (readablePath && signature && signature === previousSignature) {
1544
1986
  try {
1545
- return await new FcpxmlDocumentAdapter(readablePath, target).readProject();
1987
+ const snapshot = await new FcpxmlDocumentAdapter(readablePath, target, {
1988
+ allowMissingImmutableIdsForReadback: Boolean(readbackTarget),
1989
+ }).readProject();
1990
+ if (readbackTarget) {
1991
+ if (snapshot.projectName !== readbackTarget.projectName || snapshot.timeline.name !== readbackTarget.sequenceName) {
1992
+ throw new Error("TARGET_MISMATCH: canonical export project and sequence names differ from the catalog-bound created target");
1993
+ }
1994
+ snapshot.projectId = readbackTarget.projectId;
1995
+ snapshot.timeline.id = readbackTarget.sequenceId;
1996
+ }
1997
+ return snapshot;
1546
1998
  }
1547
1999
  catch (error) {
1548
2000
  lastReadError = error;
@@ -1557,15 +2009,36 @@ async function readCanonicalExport(path, timeoutMs, pollIntervalMs, target) {
1557
2009
  throw new Error(`FINAL_CUT_CANONICAL_EXPORT_TIMEOUT: Final Cut did not provide a complete export at ${path}${detail}`);
1558
2010
  }
1559
2011
  function sourceBasename(source) {
1560
- const withoutQuery = source.split(/[?#]/, 1)[0] ?? source;
1561
2012
  try {
1562
- const url = new URL(withoutQuery);
1563
- return basename(decodeURIComponent(url.pathname));
2013
+ const url = new URL(source);
2014
+ return basename(url.protocol === "file:" ? fileURLToPath(url) : decodeURIComponent(url.pathname));
1564
2015
  }
1565
2016
  catch {
1566
- return basename(withoutQuery.replace(/^file:\/\//, ""));
2017
+ return basename(source);
1567
2018
  }
1568
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
+ }
1569
2042
  function sameRationalText(value, expected) {
1570
2043
  const match = value.trim().match(/^(-?\d+)\/(\d+)$/);
1571
2044
  if (!match || Number(match[2]) <= 0 || Number(expected.timescale) <= 0)