@morshoto/framekit 0.1.18 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/README.md +17 -12
  2. package/dist-package/adapters/final-cut/typescript/src/analyzers.d.ts +58 -0
  3. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +52 -13
  4. package/dist-package/adapters/final-cut/typescript/src/assets.d.ts +24 -0
  5. package/dist-package/adapters/final-cut/typescript/src/background-export.d.ts +98 -0
  6. package/dist-package/adapters/final-cut/typescript/src/background-materialization.d.ts +47 -0
  7. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +8 -2
  8. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.d.ts +32 -0
  9. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.js +275 -0
  10. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery.d.ts +22 -0
  11. package/dist-package/adapters/final-cut/typescript/src/canonical-verification.d.ts +11 -0
  12. package/dist-package/adapters/final-cut/typescript/src/canonical.d.ts +184 -0
  13. package/dist-package/adapters/final-cut/typescript/src/canonical.js +571 -78
  14. package/dist-package/adapters/final-cut/typescript/src/connection.d.ts +103 -0
  15. package/dist-package/adapters/final-cut/typescript/src/connection.js +6 -1
  16. package/dist-package/adapters/final-cut/typescript/src/disposable-native.d.ts +90 -0
  17. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +6 -0
  18. package/dist-package/adapters/final-cut/typescript/src/documents.d.ts +3 -0
  19. package/dist-package/adapters/final-cut/typescript/src/documents.js +3 -0
  20. package/dist-package/adapters/final-cut/typescript/src/experimental.d.ts +8 -0
  21. package/dist-package/adapters/final-cut/typescript/src/experimental.js +8 -0
  22. package/dist-package/adapters/final-cut/typescript/src/export.d.ts +125 -0
  23. package/dist-package/adapters/final-cut/typescript/src/fcpxml-console-experiment.d.ts +54 -0
  24. package/dist-package/adapters/final-cut/typescript/src/fcpxml.d.ts +75 -0
  25. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +28 -9
  26. package/dist-package/adapters/final-cut/typescript/src/index.d.ts +22 -0
  27. package/dist-package/adapters/final-cut/typescript/src/index.js +1 -7
  28. package/dist-package/adapters/final-cut/typescript/src/library-inspection.d.ts +101 -0
  29. package/dist-package/adapters/final-cut/typescript/src/live.d.ts +101 -0
  30. package/dist-package/adapters/final-cut/typescript/src/live.js +35 -2
  31. package/dist-package/adapters/final-cut/typescript/src/media.d.ts +12 -0
  32. package/dist-package/adapters/final-cut/typescript/src/native-operation.d.ts +6 -0
  33. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.d.ts +77 -0
  34. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.js +175 -0
  35. package/dist-package/adapters/final-cut/typescript/src/native-session.d.ts +130 -0
  36. package/dist-package/adapters/final-cut/typescript/src/native-session.js +11 -6
  37. package/dist-package/adapters/final-cut/typescript/src/native.d.ts +828 -0
  38. package/dist-package/adapters/final-cut/typescript/src/native.js +475 -189
  39. package/dist-package/adapters/final-cut/typescript/src/pasteboard-snapshot.d.ts +114 -0
  40. package/dist-package/adapters/final-cut/typescript/src/publish-readback.d.ts +26 -0
  41. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +19 -2
  42. package/dist-package/adapters/final-cut/typescript/src/publisher.d.ts +215 -0
  43. package/dist-package/adapters/final-cut/typescript/src/publisher.js +255 -14
  44. package/dist-package/adapters/final-cut/typescript/src/session.d.ts +43 -0
  45. package/dist-package/adapters/final-cut/typescript/src/session.js +43 -13
  46. package/dist-package/adapters/final-cut/typescript/src/shadow-mutation.d.ts +51 -0
  47. package/dist-package/adapters/final-cut/typescript/src/sqlite-experiment.d.ts +156 -0
  48. package/dist-package/adapters/final-cut/typescript/src/sqlite-inspection.d.ts +134 -0
  49. package/dist-package/adapters/final-cut/typescript/src/sqlite-materialization.d.ts +110 -0
  50. package/dist-package/adapters/final-cut/typescript/src/sqlite-wal-observation.d.ts +132 -0
  51. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.d.ts +61 -0
  52. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +31 -5
  53. package/dist-package/adapters/final-cut/typescript/src/unattended-editing.d.ts +54 -0
  54. package/dist-package/adapters/headless/typescript/src/audio-output.d.ts +3 -0
  55. package/dist-package/adapters/headless/typescript/src/audio-output.js +3 -0
  56. package/dist-package/adapters/headless/typescript/src/ffmpeg-media-probe.d.ts +11 -0
  57. package/dist-package/adapters/headless/typescript/src/ffmpeg-media-probe.js +26 -2
  58. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.d.ts +25 -0
  59. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +37 -14
  60. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.d.ts +15 -0
  61. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +9 -4
  62. package/dist-package/adapters/headless/typescript/src/index.d.ts +3 -0
  63. package/dist-package/apps/cli/src/dev-doctor.d.ts +25 -0
  64. package/dist-package/apps/cli/src/dev-doctor.js +198 -0
  65. package/dist-package/apps/cli/src/headless-projects.d.ts +3 -0
  66. package/dist-package/apps/cli/src/headless-projects.js +5 -0
  67. package/dist-package/apps/cli/src/main.d.ts +10 -0
  68. package/dist-package/apps/cli/src/main.js +42 -0
  69. package/dist-package/apps/mcp-server/runtime/ffmpeg-audio-backend.py +129 -0
  70. package/dist-package/apps/mcp-server/runtime/speech-analyzer-wrapper.mjs +54 -0
  71. package/dist-package/apps/mcp-server/runtime/whisper-speech-backend.py +271 -0
  72. package/dist-package/apps/mcp-server/src/build-alignment.d.ts +10 -0
  73. package/dist-package/apps/mcp-server/src/build-identity.d.ts +7 -0
  74. package/dist-package/apps/mcp-server/src/build-identity.json +2 -2
  75. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.d.ts +8 -0
  76. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.js +18 -0
  77. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.d.ts +5 -0
  78. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.js +3 -0
  79. package/dist-package/apps/mcp-server/src/headless-project-snapshot.d.ts +3 -0
  80. package/dist-package/apps/mcp-server/src/headless-sessions.d.ts +89 -0
  81. package/dist-package/apps/mcp-server/src/main.d.ts +1 -0
  82. package/dist-package/apps/mcp-server/src/main.js +24 -19
  83. package/dist-package/apps/mcp-server/src/materialization-jobs.d.ts +204 -0
  84. package/dist-package/apps/mcp-server/src/materialization-jobs.js +143 -10
  85. package/dist-package/apps/mcp-server/src/readback-policy.d.ts +18 -0
  86. package/dist-package/apps/mcp-server/src/routing.d.ts +90 -0
  87. package/dist-package/apps/mcp-server/src/routing.js +2 -0
  88. package/dist-package/apps/mcp-server/src/server.d.ts +75 -0
  89. package/dist-package/apps/mcp-server/src/server.js +813 -158
  90. package/dist-package/apps/mcp-server/src/tools/skills/catalog.d.ts +19 -0
  91. package/dist-package/apps/mcp-server/src/tools/skills/catalog.js +142 -0
  92. package/dist-package/apps/mcp-server/src/tools/skills/metadata.d.ts +37 -0
  93. package/dist-package/apps/mcp-server/src/tools/skills/metadata.js +71 -0
  94. package/dist-package/apps/mcp-server/src/tools/skills/register.d.ts +11 -0
  95. package/dist-package/apps/mcp-server/src/tools/skills/register.js +101 -0
  96. package/dist-package/apps/mcp-server/src/version.d.ts +4 -0
  97. package/dist-package/packages/headless-application/src/external-edit.d.ts +30 -0
  98. package/dist-package/packages/headless-application/src/external-edit.js +72 -0
  99. package/dist-package/packages/headless-application/src/headless-projects.d.ts +233 -0
  100. package/dist-package/{apps/mcp-server → packages/headless-application}/src/headless-projects.js +392 -59
  101. package/dist-package/packages/headless-application/src/index.d.ts +2 -0
  102. package/dist-package/packages/headless-application/src/index.js +2 -0
  103. package/dist-package/packages/runtime/src/application/duration-policy-service.d.ts +4 -0
  104. package/dist-package/packages/runtime/src/application/local-media.d.ts +46 -0
  105. package/dist-package/packages/runtime/src/application/media-analysis-service.d.ts +40 -0
  106. package/dist-package/packages/runtime/src/application/media-analysis-service.js +105 -15
  107. package/dist-package/packages/runtime/src/application/project-service.d.ts +35 -0
  108. package/dist-package/packages/runtime/src/application/project-service.js +5 -1
  109. package/dist-package/packages/runtime/src/application/project-store.d.ts +56 -0
  110. package/dist-package/packages/runtime/src/application/project-store.js +13 -36
  111. package/dist-package/packages/runtime/src/application/project-transactions.d.ts +51 -0
  112. package/dist-package/packages/runtime/src/application/runtime-options.d.ts +15 -0
  113. package/dist-package/packages/runtime/src/application/semantic-media-index-store.d.ts +28 -0
  114. package/dist-package/packages/runtime/src/application/transaction-store.d.ts +10 -0
  115. package/dist-package/packages/runtime/src/application/transaction-store.js +1 -1
  116. package/dist-package/packages/runtime/src/audio/analysis.d.ts +3 -0
  117. package/dist-package/packages/runtime/src/audio/analysis.js +95 -0
  118. package/dist-package/packages/runtime/src/audio/dialogue-normalization.d.ts +47 -0
  119. package/dist-package/packages/runtime/src/audio/noise-reduction.d.ts +34 -0
  120. package/dist-package/packages/runtime/src/capabilities.d.ts +45 -0
  121. package/dist-package/packages/runtime/src/capabilities.js +1 -1
  122. package/dist-package/packages/runtime/src/color-correction.d.ts +33 -0
  123. package/dist-package/packages/runtime/src/context/context-engine.d.ts +28 -0
  124. package/dist-package/packages/runtime/src/context/context-engine.js +22 -16
  125. package/dist-package/packages/runtime/src/context/context-service.d.ts +20 -0
  126. package/dist-package/packages/runtime/src/context/context-service.js +2 -2
  127. package/dist-package/packages/runtime/src/context/project-catalog.d.ts +12 -0
  128. package/dist-package/packages/runtime/src/context/revision.d.ts +2 -0
  129. package/dist-package/packages/runtime/src/domain/capabilities.d.ts +170 -0
  130. package/dist-package/packages/runtime/src/domain/context.d.ts +179 -0
  131. package/dist-package/packages/runtime/src/domain/diff.d.ts +104 -0
  132. package/dist-package/packages/runtime/src/domain/duration.d.ts +63 -0
  133. package/dist-package/packages/runtime/src/domain/editing.d.ts +227 -0
  134. package/dist-package/packages/runtime/src/domain/incremental-sync.d.ts +67 -0
  135. package/dist-package/packages/runtime/src/domain/index.d.ts +14 -0
  136. package/dist-package/packages/runtime/src/domain/media.d.ts +406 -0
  137. package/dist-package/packages/runtime/src/domain/ports.d.ts +62 -0
  138. package/dist-package/packages/runtime/src/domain/primitives.d.ts +21 -0
  139. package/dist-package/packages/runtime/src/domain/project.d.ts +119 -0
  140. package/dist-package/packages/runtime/src/domain/rough-cut.d.ts +27 -0
  141. package/dist-package/packages/runtime/src/domain/skills.d.ts +145 -0
  142. package/dist-package/packages/runtime/src/domain/timeline-target.d.ts +57 -0
  143. package/dist-package/packages/runtime/src/domain/timeline-target.js +19 -1
  144. package/dist-package/packages/runtime/src/domain/types.d.ts +5 -0
  145. package/dist-package/packages/runtime/src/domain/verification.d.ts +92 -0
  146. package/dist-package/packages/runtime/src/editing/dialogue-normalization-service.d.ts +18 -0
  147. package/dist-package/packages/runtime/src/editing/duration-policy.d.ts +3 -0
  148. package/dist-package/packages/runtime/src/editing/edit-service.d.ts +44 -0
  149. package/dist-package/packages/runtime/src/editing/edit-service.js +76 -10
  150. package/dist-package/packages/runtime/src/editing/filler-removal-service.d.ts +23 -0
  151. package/dist-package/packages/runtime/src/editing/intent.d.ts +97 -0
  152. package/dist-package/packages/runtime/src/editing/music-service.d.ts +9 -0
  153. package/dist-package/packages/runtime/src/index.d.ts +32 -0
  154. package/dist-package/packages/runtime/src/index.js +2 -0
  155. package/dist-package/packages/runtime/src/planning/rough-cut.d.ts +3 -0
  156. package/dist-package/packages/runtime/src/render/render-and-verify.d.ts +71 -0
  157. package/dist-package/packages/runtime/src/render/render-contract.d.ts +96 -0
  158. package/dist-package/packages/runtime/src/runtime.d.ts +85 -0
  159. package/dist-package/packages/runtime/src/runtime.js +16 -7
  160. package/dist-package/packages/runtime/src/skills/builtin.d.ts +2 -0
  161. package/dist-package/packages/runtime/src/skills/index.d.ts +3 -0
  162. package/dist-package/packages/runtime/src/skills/registry.d.ts +10 -0
  163. package/dist-package/packages/runtime/src/skills/requirements.d.ts +38 -0
  164. package/dist-package/packages/runtime/src/skills/runtime.d.ts +38 -0
  165. package/dist-package/packages/runtime/src/speech/analysis.d.ts +18 -0
  166. package/dist-package/packages/runtime/src/speech/analysis.js +67 -0
  167. package/dist-package/packages/runtime/src/speech/filler-detector.d.ts +49 -0
  168. package/dist-package/packages/runtime/src/speech/filler-removal.d.ts +37 -0
  169. package/dist-package/packages/runtime/src/speech/mapping.d.ts +56 -0
  170. package/dist-package/packages/runtime/src/speech/mapping.js +27 -4
  171. package/dist-package/packages/runtime/src/speech/safe-cut-resolver.d.ts +52 -0
  172. package/dist-package/packages/runtime/src/timeline/drift-reconciliation.d.ts +42 -0
  173. package/dist-package/packages/runtime/src/timeline/editing-session.d.ts +271 -0
  174. package/dist-package/packages/runtime/src/timeline/editing-session.js +48 -2
  175. package/dist-package/packages/runtime/src/timeline/fast-observation.d.ts +77 -0
  176. package/dist-package/packages/runtime/src/timeline/rational-time.d.ts +11 -0
  177. package/dist-package/packages/runtime/src/timeline/reorder-preview.d.ts +32 -0
  178. package/dist-package/packages/runtime/src/timeline/reorder-preview.js +202 -0
  179. package/dist-package/packages/runtime/src/timeline/snapshot-diff.d.ts +3 -0
  180. package/dist-package/packages/runtime/src/timeline/snapshot-diff.js +1 -0
  181. package/dist-package/packages/runtime/src/timeline/snapshot-digest.d.ts +3 -0
  182. package/dist-package/packages/runtime/src/timeline/snapshot-digest.js +1 -1
  183. package/dist-package/packages/runtime/src/verification/verification.d.ts +6 -0
  184. package/dist-package/packages/testkit/src/fixture-analyzers.d.ts +37 -0
  185. package/dist-package/packages/testkit/src/in-memory-editor.d.ts +55 -0
  186. package/dist-package/packages/testkit/src/in-memory-editor.js +3 -3
  187. package/dist-package/packages/testkit/src/index.d.ts +4 -0
  188. package/dist-package/packages/testkit/src/index.js +1 -0
  189. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.d.ts +47 -0
  190. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.js +192 -0
  191. package/dist-package/packages/testkit/src/skill-fixtures.d.ts +3 -0
  192. package/package.json +41 -14
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
3
3
  import { execFile as execFileCallback } from "node:child_process";
4
4
  import { access, constants, readdir, stat } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
- import { basename, dirname, extname, resolve } from "node:path";
6
+ import { basename, dirname, extname, isAbsolute, resolve } from "node:path";
7
7
  import { promisify } from "node:util";
8
8
  import { assertValidTimelineTarget } from "../../../../packages/runtime/src/index.js";
9
9
  const execFile = promisify(execFileCallback);
@@ -17,6 +17,16 @@ class NativeFinalCutPreflightError extends Error {
17
17
  this.name = "NativeFinalCutPreflightError";
18
18
  }
19
19
  }
20
+ export function nativeMediaSearchQueryError(query) {
21
+ if (!/[*?]/.test(query))
22
+ return undefined;
23
+ return {
24
+ code: "FINAL_CUT_NATIVE_SEARCH_WILDCARD_UNSUPPORTED",
25
+ message: "Final Cut Browser search accepts literal text; wildcard operators * and ? are unsupported",
26
+ querySemantics: "literal",
27
+ unsupportedSyntax: "wildcard",
28
+ };
29
+ }
20
30
  export class NativeFinalCutMediaImportError extends Error {
21
31
  code;
22
32
  details;
@@ -72,11 +82,13 @@ export function serializeNativeFinalCutPartialMutationError(error) {
72
82
  }
73
83
  export class FinalCutNativeAutomationAdapter {
74
84
  enabled;
85
+ homeDirectory;
75
86
  titleDiscoveryAvailable;
76
87
  executor;
77
88
  nativeMouseExecutor;
78
89
  canDriveNativeMouse;
79
90
  liveState;
91
+ importSourceObserver;
80
92
  nativeOperationLease;
81
93
  suspendLiveConnection;
82
94
  resumeLiveConnection;
@@ -87,6 +99,7 @@ export class FinalCutNativeAutomationAdapter {
87
99
  mediaImportDiscoveryTimeoutMs;
88
100
  mediaImportPollMs;
89
101
  requestContext = new AsyncLocalStorage();
102
+ dispatchContext = new AsyncLocalStorage();
90
103
  nativeUiDepth = 0;
91
104
  operations = new Map();
92
105
  latestOperationId;
@@ -105,11 +118,13 @@ export class FinalCutNativeAutomationAdapter {
105
118
  transitionPreviews = new Map();
106
119
  constructor(options = {}) {
107
120
  this.enabled = options.enabled ?? process.env.FRAMEKIT_FINAL_CUT_NATIVE_WRITES === "1";
121
+ this.homeDirectory = options.homeDirectory ?? homedir();
108
122
  this.titleDiscoveryAvailable = this.enabled;
109
123
  this.executor = options.executor ?? runAppleScript;
110
124
  this.nativeMouseExecutor = options.nativeMouseExecutor;
111
125
  this.canDriveNativeMouse = options.executor === undefined;
112
126
  this.liveState = options.liveState;
127
+ this.importSourceObserver = options.importSourceObserver;
113
128
  this.nativeOperationLease = options.nativeOperationLease;
114
129
  this.suspendLiveConnection = options.suspendLiveConnection;
115
130
  this.resumeLiveConnection = options.resumeLiveConnection;
@@ -125,10 +140,11 @@ export class FinalCutNativeAutomationAdapter {
125
140
  selectionEdit: this.enabled,
126
141
  undo: this.enabled,
127
142
  mediaLibrarySearch: this.enabled,
128
- mediaImport: this.enabled,
143
+ mediaImport: this.enabled && Boolean(this.importSourceObserver),
129
144
  mediaSelection: this.enabled,
130
145
  mediaAppendSelected: this.enabled,
131
146
  timelineOccurrenceLocate: this.enabled,
147
+ timelineOccurrenceSourceBinding: false,
132
148
  bladeAtPlayhead: this.enabled,
133
149
  deleteRange: this.enabled,
134
150
  trimToDuration: this.enabled,
@@ -172,7 +188,39 @@ export class FinalCutNativeAutomationAdapter {
172
188
  return unavailableContext("CAPABILITY_UNAVAILABLE", "Final Cut native writes are disabled; set FRAMEKIT_FINAL_CUT_NATIVE_WRITES=1");
173
189
  }
174
190
  try {
175
- return await this.attachLiveState(await this.ensureTimelineReady());
191
+ const focused = await this.attachLiveState(await this.ensureTimelineReady());
192
+ if (!this.liveState || focused.target.kind === "selected-clip")
193
+ return focused;
194
+ // Timeline focus and target selection are separate Accessibility states.
195
+ // Re-read the bounded selection tree after focus so a selected occurrence
196
+ // is not reported as a playhead-only target.
197
+ const reread = await this.inspectRawNative(undefined, passiveTimelinePreflightScript());
198
+ if (!reread.available)
199
+ return reread;
200
+ const targetScope = (context) => {
201
+ const target = context.target;
202
+ if (!target.projectId || !target.sequenceId || !target.revision?.id || !Number.isInteger(target.revision.sequence)) {
203
+ return undefined;
204
+ }
205
+ return {
206
+ projectId: target.projectId,
207
+ sequenceId: target.sequenceId,
208
+ revisionId: target.revision.id,
209
+ revisionSequence: target.revision.sequence,
210
+ };
211
+ };
212
+ const beforeScope = targetScope(focused);
213
+ const afterScope = targetScope(reread);
214
+ if (!beforeScope || !afterScope) {
215
+ return unavailableContext("FINAL_CUT_NATIVE_TARGET_BINDING_UNAVAILABLE", "Final Cut project, sequence, and revision could not be confirmed across focus recovery", reread);
216
+ }
217
+ if (beforeScope.projectId !== afterScope.projectId
218
+ || beforeScope.sequenceId !== afterScope.sequenceId
219
+ || beforeScope.revisionId !== afterScope.revisionId
220
+ || beforeScope.revisionSequence !== afterScope.revisionSequence) {
221
+ return unavailableContext("STALE_CONTEXT", "Final Cut project, sequence, or revision changed while resolving the selected occurrence", reread);
222
+ }
223
+ return reread;
176
224
  }
177
225
  catch (error) {
178
226
  return unavailableContext(nativeErrorCode(error), nativeErrorMessage(error), preflightContext(error));
@@ -196,10 +244,19 @@ export class FinalCutNativeAutomationAdapter {
196
244
  context.playheadTime = live.playheadTime
197
245
  ? `${live.playheadTime.value}/${live.playheadTime.timescale}`
198
246
  : undefined;
247
+ if (live.project?.id && live.sequence?.id) {
248
+ context.target = {
249
+ ...context.target,
250
+ projectId: live.project.id,
251
+ sequenceId: live.sequence.id,
252
+ revision: structuredClone(live.revision),
253
+ };
254
+ }
199
255
  }
200
256
  catch {
201
257
  // Native UI inspection remains useful when the optional live socket is down.
202
258
  }
259
+ context.readiness = readinessForContext(context);
203
260
  return context;
204
261
  }
205
262
  async readLiveState() {
@@ -220,6 +277,9 @@ export class FinalCutNativeAutomationAdapter {
220
277
  async edit(operation, options = {}) {
221
278
  return this.withNativeUi(() => this.editNative(operation), options.signal);
222
279
  }
280
+ async trackNativeDispatch(operation, onDispatch) {
281
+ return this.dispatchContext.run(onDispatch, operation);
282
+ }
223
283
  async trimSelectedClipToRange(range, options = {}) {
224
284
  return this.withNativeUi(() => this.trimSelectedClipToRangeNative(range), options.signal);
225
285
  }
@@ -343,8 +403,40 @@ export class FinalCutNativeAutomationAdapter {
343
403
  throw new Error(`FINAL_CUT_NATIVE_UNDO_UNAVAILABLE: unknown operation ${operationId}`);
344
404
  if (this.latestOperationId !== operationId)
345
405
  throw new Error("FINAL_CUT_NATIVE_UNDO_STALE: operation is no longer the latest native edit");
406
+ if (operation.kind === "blade" && operation.undoDispatched) {
407
+ throw new Error("FINAL_CUT_NATIVE_UNDO_OUTCOME_UNCERTAIN: Blade Undo may already have been dispatched; recovery is required");
408
+ }
409
+ if (operation.kind === "media-insertion" && operation.undoDispatched) {
410
+ throw new Error("FINAL_CUT_NATIVE_UNDO_UNCERTAIN: placement Undo may already have been dispatched");
411
+ }
346
412
  const before = await this.requireTimelineContext();
347
413
  const currentLive = await this.readLiveState();
414
+ if (operation.kind === "blade") {
415
+ const projectId = operation.beforeLive?.project?.id;
416
+ const sequenceId = operation.beforeLive?.sequence?.id;
417
+ if (!projectId || !sequenceId || operation.afterLive?.project?.id !== projectId
418
+ || operation.afterLive?.sequence?.id !== sequenceId || currentLive?.project?.id !== projectId
419
+ || currentLive?.sequence?.id !== sequenceId || before.target.projectId !== projectId
420
+ || before.target.sequenceId !== sequenceId || before.target.revision?.id !== currentLive?.revision.id
421
+ || before.target.revision?.sequence !== currentLive?.revision.sequence
422
+ || operation.afterLive.revision.sequence !== currentLive?.revision.sequence) {
423
+ throw new Error("FINAL_CUT_NATIVE_UNDO_TARGET_CHANGED: Blade target or revision is unavailable or changed");
424
+ }
425
+ }
426
+ if (operation.kind === "media-insertion") {
427
+ const expectedProject = operation.beforeLive?.project?.id;
428
+ const expectedSequence = operation.beforeLive?.sequence?.id;
429
+ if (!expectedProject || !expectedSequence
430
+ || operation.afterLive?.project?.id !== expectedProject || operation.afterLive?.sequence?.id !== expectedSequence
431
+ || currentLive?.project?.id !== expectedProject || currentLive?.sequence?.id !== expectedSequence
432
+ || before.target.projectId !== expectedProject || before.target.sequenceId !== expectedSequence
433
+ || !before.target.revision?.id || before.target.revision.id !== currentLive.revision?.id
434
+ || before.target.revision.sequence !== currentLive.revision?.sequence
435
+ || operation.afterLive.revision.id !== currentLive.revision?.id
436
+ || operation.afterLive.revision.sequence !== currentLive.revision?.sequence) {
437
+ throw new Error("FINAL_CUT_NATIVE_UNDO_TARGET_CHANGED: placement target is unavailable or changed");
438
+ }
439
+ }
348
440
  if (operation.afterLive && currentLive && operation.afterLive.revision.id !== currentLive.revision.id) {
349
441
  throw new Error("FINAL_CUT_NATIVE_UNDO_STALE: Final Cut timeline changed after the native edit");
350
442
  }
@@ -364,16 +456,33 @@ export class FinalCutNativeAutomationAdapter {
364
456
  throw new Error("FINAL_CUT_NATIVE_UNDO_COMMAND_CHANGED: Final Cut's current Undo command does not match the native edit");
365
457
  }
366
458
  try {
367
- await this.executeNativeCommand(undoScript(operation.undoCommand), (recovered) => {
368
- this.assertRetryContext(before, recovered);
369
- if (!recovered.undoAvailable || recovered.undoCommand !== operation.undoCommand) {
370
- throw new Error("FINAL_CUT_NATIVE_UNDO_COMMAND_CHANGED: Final Cut's current Undo command does not match the native edit");
459
+ if (operation.kind === "blade" || operation.kind === "media-insertion") {
460
+ if (operation.undoDispatched) {
461
+ throw new Error(operation.kind === "blade"
462
+ ? "FINAL_CUT_NATIVE_UNDO_OUTCOME_UNCERTAIN: Blade Undo may already have been dispatched; recovery is required"
463
+ : "FINAL_CUT_NATIVE_UNDO_UNCERTAIN: placement Undo may already have been dispatched");
371
464
  }
372
- });
465
+ // Once invocation begins, neither an error nor stale readback proves Undo did not run.
466
+ operation.undoDispatched = true;
467
+ await this.executeNativeScript(undoScript(operation.undoCommand));
468
+ }
469
+ else {
470
+ await this.executeNativeCommand(undoScript(operation.undoCommand), (recovered) => {
471
+ this.assertRetryContext(before, recovered);
472
+ if (!recovered.undoAvailable || recovered.undoCommand !== operation.undoCommand) {
473
+ throw new Error("FINAL_CUT_NATIVE_UNDO_COMMAND_CHANGED: Final Cut's current Undo command does not match the native edit");
474
+ }
475
+ });
476
+ }
373
477
  }
374
478
  catch (error) {
479
+ if (operation.kind === "blade")
480
+ throw new Error(`FINAL_CUT_NATIVE_UNDO_OUTCOME_UNCERTAIN: Blade Undo may have been applied; recovery is required: ${String(error)}`);
375
481
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
376
482
  }
483
+ if (operation.kind === "blade") {
484
+ throw new Error("FINAL_CUT_NATIVE_UNDO_VERIFICATION_FAILED: canonical restoration and source coverage are unavailable; recovery is required");
485
+ }
377
486
  const after = await this.requireTimelineContext();
378
487
  const afterLive = await this.waitForUndo(operation);
379
488
  const verification = verifyNativeUndo(operation, after, afterLive);
@@ -384,7 +493,19 @@ export class FinalCutNativeAutomationAdapter {
384
493
  return { operationId, undone: true, context: after, verification };
385
494
  }
386
495
  async importMedia(sourcePath, options = {}) {
387
- return this.withNativeUi(() => this.importMediaNative(sourcePath), options.signal);
496
+ this.assertEnabled();
497
+ if (!this.importSourceObserver) {
498
+ throw new NativeFinalCutMediaImportError("CAPABILITY_UNAVAILABLE", "native media import requires independently observed original source binding", {
499
+ stage: "pre-import-browser-discovery", elapsedMs: 0, stageElapsedMs: 0, partialImportPossible: false,
500
+ });
501
+ }
502
+ const expectedTarget = normalizeNativeImportTarget(options.expectedImportTarget);
503
+ if (!expectedTarget) {
504
+ throw new NativeFinalCutMediaImportError("TARGET_MISMATCH", "an approved native import target is required", {
505
+ stage: "pre-import-browser-discovery", elapsedMs: 0, stageElapsedMs: 0, partialImportPossible: false,
506
+ });
507
+ }
508
+ return this.withNativeUi(() => this.importMediaNative(sourcePath, expectedTarget), options.signal);
388
509
  }
389
510
  async previewImportMediaDirectory(directoryPath, options = {}) {
390
511
  return this.requestContext.run(options, () => this.previewImportMediaDirectoryNative(directoryPath));
@@ -394,14 +515,16 @@ export class FinalCutNativeAutomationAdapter {
394
515
  const trimmedPath = directoryPath.trim();
395
516
  if (!trimmedPath)
396
517
  throw new Error("INVALID_OPERATION: local media directory path cannot be empty");
397
- const normalizedPath = resolveLocalPath(trimmedPath);
518
+ const normalizedPath = resolveLocalPath(trimmedPath, this.homeDirectory);
398
519
  const snapshot = await snapshotSupportedVideoFiles(normalizedPath);
520
+ const expectedImportTarget = normalizeNativeImportTarget(this.requestContext.getStore()?.expectedImportTarget);
399
521
  const expiresAt = this.now() + 30_000;
400
522
  const previewToken = opaqueHandle("media-directory-preview");
401
523
  this.mediaImportDirectoryPreviews.set(previewToken, {
402
524
  directoryPath: normalizedPath,
403
525
  files: snapshot.files,
404
526
  fileIdentities: snapshot.fileIdentities,
527
+ ...(expectedImportTarget ? { expectedImportTarget } : {}),
405
528
  expiresAt,
406
529
  });
407
530
  return {
@@ -409,13 +532,19 @@ export class FinalCutNativeAutomationAdapter {
409
532
  directoryPath: normalizedPath,
410
533
  files: structuredClone(snapshot.files),
411
534
  command: "Import all previewed video files",
535
+ ...(expectedImportTarget ? { expectedImportTarget } : {}),
412
536
  expiresAt: new Date(expiresAt).toISOString(),
413
537
  };
414
538
  }
415
539
  async executeImportMediaDirectory(previewToken, confirm, options = {}) {
540
+ if (!this.importSourceObserver)
541
+ return this.executeImportMediaDirectoryNative(previewToken, confirm);
542
+ if (!this.mediaImportDirectoryPreviews.get(previewToken)?.expectedImportTarget) {
543
+ throw new Error("TARGET_MISMATCH: an approved native import target must be bound to the directory preview");
544
+ }
416
545
  return this.withNativeUi(() => this.executeImportMediaDirectoryNative(previewToken, confirm), options.signal);
417
546
  }
418
- async importMediaNative(sourcePath) {
547
+ async importMediaNative(sourcePath, approvedTarget) {
419
548
  this.assertEnabled();
420
549
  const importStartedAt = this.now();
421
550
  let stage = "pre-import-browser-discovery";
@@ -434,7 +563,7 @@ export class FinalCutNativeAutomationAdapter {
434
563
  ...(diagnostics ? { diagnostics } : {}),
435
564
  });
436
565
  };
437
- const normalizedPath = resolveLocalPath(sourcePath);
566
+ const normalizedPath = resolveLocalPath(sourcePath, this.homeDirectory);
438
567
  const name = basename(normalizedPath);
439
568
  if (!sourcePath.trim())
440
569
  throw new Error("INVALID_OPERATION: local media path cannot be empty");
@@ -452,6 +581,14 @@ export class FinalCutNativeAutomationAdapter {
452
581
  throw new Error(`FINAL_CUT_NATIVE_MEDIA_PATH_UNAVAILABLE: ${normalizedPath} is not a readable local media file (${String(error)})`);
453
582
  }
454
583
  try {
584
+ const observer = this.importSourceObserver;
585
+ if (!observer)
586
+ return fail("CAPABILITY_UNAVAILABLE", "independent original source observation is unavailable", false);
587
+ const expectedTarget = normalizeNativeImportTarget(await observer.captureTarget());
588
+ if (!expectedTarget)
589
+ return fail("CAPABILITY_UNAVAILABLE", "independent native import target observation is unavailable", false);
590
+ if (!sameNativeImportTarget(approvedTarget, expectedTarget))
591
+ return fail("TARGET_MISMATCH", "observed native import target does not match approval", false);
455
592
  const beforeDiscoveryDeadline = this.now() + this.mediaImportDiscoveryTimeoutMs;
456
593
  await this.ensureBrowserReady(beforeDiscoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
457
594
  const beforeMatches = await this.searchMediaNative(name, beforeDiscoveryDeadline, "FINAL_CUT_NATIVE_MEDIA_IMPORT_DISCOVERY_TIMEOUT");
@@ -463,6 +600,12 @@ export class FinalCutNativeAutomationAdapter {
463
600
  if (hasIndistinguishablePreExistingMatch) {
464
601
  fail("FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE", `Final Cut did not expose an immutable Browser source identity for pre-existing ${name}`, false);
465
602
  }
603
+ // Browser discovery can change the active context. Recheck immediately
604
+ // before dispatch; this does not replace receiver-side target fencing.
605
+ const dispatchTarget = normalizeNativeImportTarget(await observer.captureTarget());
606
+ if (!sameNativeImportTarget(expectedTarget, dispatchTarget)) {
607
+ return fail("TARGET_MISMATCH", "native import target changed during Browser discovery", false);
608
+ }
466
609
  beginStage("native-import-ui");
467
610
  partialImportPossible = true;
468
611
  try {
@@ -510,6 +653,19 @@ export class FinalCutNativeAutomationAdapter {
510
653
  fail("FINAL_CUT_NATIVE_MEDIA_IMPORT_IDENTITY_UNAVAILABLE", `Final Cut did not expose an immutable Browser source identity for ${name}`, true);
511
654
  throw new Error("unreachable");
512
655
  }
656
+ // The observer receives only the independently identified Browser item,
657
+ // never the requested source path. A matching name or requested path is
658
+ // not evidence that the item actually references the original source.
659
+ const observed = await observer.observeImportedSource(identity);
660
+ const observedTarget = normalizeNativeImportTarget(observed?.target);
661
+ const currentTarget = normalizeNativeImportTarget(await observer.captureTarget());
662
+ if (!observed || observed.sourceIdentity !== identity
663
+ || typeof observed.originalSourcePath !== "string" || !isAbsolute(observed.originalSourcePath)
664
+ || observed.originalSourcePath !== normalizedPath
665
+ || !sameNativeImportTarget(expectedTarget, observedTarget)
666
+ || !sameNativeImportTarget(expectedTarget, currentTarget)) {
667
+ return fail("FINAL_CUT_NATIVE_MEDIA_IMPORT_SOURCE_MISMATCH", "independent original source or native target observation does not match the approved import", true);
668
+ }
513
669
  const mediaHandle = this.stableMediaHandle(identity);
514
670
  const stableMatch = { ...match, handle: mediaHandle };
515
671
  this.stableMediaHandles.set(identity, mediaHandle);
@@ -523,7 +679,7 @@ export class FinalCutNativeAutomationAdapter {
523
679
  verification: {
524
680
  verified: true,
525
681
  stage: "post-import-browser-discovery",
526
- detail: "Final Cut exposed one newly imported Browser asset with immutable source identity",
682
+ detail: "An independent observation bound the imported Browser identity to the original source and native target",
527
683
  },
528
684
  };
529
685
  }
@@ -556,9 +712,14 @@ export class FinalCutNativeAutomationAdapter {
556
712
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: media directory preview has expired");
557
713
  await assertMediaImportDirectoryPreviewFresh(preview);
558
714
  const results = [];
715
+ let stopped = false;
559
716
  for (const file of preview.files) {
717
+ if (stopped) {
718
+ results.push({ sourcePath: file.sourcePath, name: file.name, status: "not-attempted" });
719
+ continue;
720
+ }
560
721
  try {
561
- const media = await this.importMedia(file.sourcePath);
722
+ const media = await this.importMedia(file.sourcePath, { expectedImportTarget: preview.expectedImportTarget });
562
723
  results.push({
563
724
  sourcePath: file.sourcePath,
564
725
  name: file.name,
@@ -567,6 +728,9 @@ export class FinalCutNativeAutomationAdapter {
567
728
  });
568
729
  }
569
730
  catch (error) {
731
+ // A failed provider may have dispatched or scheduled work even when
732
+ // it did not acknowledge it. Do not start another file in this batch.
733
+ stopped = true;
570
734
  const serializedError = serializeNativeFinalCutMediaImportError(error);
571
735
  results.push({
572
736
  sourcePath: file.sourcePath,
@@ -580,7 +744,8 @@ export class FinalCutNativeAutomationAdapter {
580
744
  }
581
745
  }
582
746
  const importedCount = results.filter((result) => result.status === "imported").length;
583
- const failedCount = results.length - importedCount;
747
+ const failedCount = results.filter((result) => result.status === "failed").length;
748
+ const notAttemptedCount = results.filter((result) => result.status === "not-attempted").length;
584
749
  return {
585
750
  previewToken,
586
751
  directoryPath: preview.directoryPath,
@@ -588,14 +753,24 @@ export class FinalCutNativeAutomationAdapter {
588
753
  results,
589
754
  importedCount,
590
755
  failedCount,
756
+ ...(notAttemptedCount > 0 ? { notAttemptedCount } : {}),
591
757
  partial: importedCount > 0 && failedCount > 0,
592
758
  status: failedCount === 0 ? "completed" : importedCount > 0 ? "partial" : "failed",
593
759
  };
594
760
  }
595
761
  async searchMedia(query, options = {}) {
762
+ const queryError = nativeMediaSearchQueryError(query);
763
+ if (queryError)
764
+ throw new Error(`${queryError.code}: ${queryError.message}`);
765
+ return this.withNativeUi(() => this.searchMediaNative(query), options.signal);
766
+ }
767
+ async searchMediaForCanonicalTarget(query, options = {}) {
768
+ const queryError = nativeMediaSearchQueryError(query);
769
+ if (queryError)
770
+ throw new Error(`${queryError.code}: ${queryError.message}`);
596
771
  return this.withNativeUi(() => this.searchMediaNative(query), options.signal);
597
772
  }
598
- async searchMediaNative(query, deadline, timeoutCode = "FINAL_CUT_NATIVE_MEDIA_IMPORT_TIMEOUT") {
773
+ async searchMediaNative(query, deadline, timeoutCode = "FINAL_CUT_NATIVE_SEARCH_TIMEOUT") {
599
774
  this.assertEnabled();
600
775
  if (!query.trim())
601
776
  throw new Error("INVALID_OPERATION: media search query cannot be empty");
@@ -604,11 +779,24 @@ export class FinalCutNativeAutomationAdapter {
604
779
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's Browser must be frontmost");
605
780
  try {
606
781
  const searchDeadline = deadline ?? this.now() + this.mediaImportDiscoveryTimeoutMs;
607
- const output = await this.executeNativeScript(searchMediaScript(query), searchDeadline, timeoutCode);
782
+ const response = await this.executeNativeScript(searchMediaScript(query), searchDeadline, timeoutCode);
783
+ if (!response.trim())
784
+ throw new Error("FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE: missing Browser media scan output");
785
+ const output = response.trim() === "__FRAMEKIT_BROWSER_SCAN_EMPTY__" ? "" : response;
786
+ if (output.split(String.fromCharCode(30)).some((record) => record === "__FRAMEKIT_BROWSER_SCAN_INCOMPLETE__")) {
787
+ throw new Error("FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE: Browser media scan was incomplete");
788
+ }
608
789
  const explicitFailure = output.trim();
609
790
  if (explicitFailure.startsWith("FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE")) {
610
791
  throw new Error(explicitFailure);
611
792
  }
793
+ if (explicitFailure && (!explicitFailure.endsWith(String.fromCharCode(30))
794
+ || explicitFailure.slice(0, -1).split(String.fromCharCode(30)).some((record) => {
795
+ const fields = record.split(String.fromCharCode(31));
796
+ return fields.length !== 4 || !fields[0]?.trim() || !fields[1]?.trim();
797
+ }))) {
798
+ throw new Error("FINAL_CUT_NATIVE_SEARCH_UNAVAILABLE: malformed Browser media scan output");
799
+ }
612
800
  const rawMatches = parseMediaMatches(output);
613
801
  const normalizedQuery = query.toLocaleLowerCase();
614
802
  if (rawMatches.some((match) => !browserMediaIdentity(match) && match.name.toLocaleLowerCase().includes(normalizedQuery))) {
@@ -712,14 +900,21 @@ export class FinalCutNativeAutomationAdapter {
712
900
  }
713
901
  const after = await this.requireAvailableContext();
714
902
  this.selectedMediaHandle = handle;
715
- return {
903
+ const context = {
716
904
  ...after,
717
905
  target: { kind: "browser-media", name: match.name, ...(match.role ? { role: match.role } : {}) },
718
906
  };
907
+ return { ...context, readiness: readinessForContext(context) };
719
908
  }
720
909
  async locateOccurrence(mediaHandle, options = {}) {
721
910
  return this.withNativeUi(() => this.locateOccurrenceNative(mediaHandle), options.signal);
722
911
  }
912
+ async locateOccurrenceForCanonicalTarget(mediaHandle, options = {}) {
913
+ if (this.capabilities().timelineOccurrenceSourceBinding !== true) {
914
+ throw new Error("CAPABILITY_UNAVAILABLE: canonical occurrence source binding is unavailable");
915
+ }
916
+ return this.withNativeUi(() => this.locateOccurrenceNative(mediaHandle, false, false), options.signal);
917
+ }
723
918
  async selectOccurrence(occurrenceHandle, options = {}) {
724
919
  return this.withNativeUi(() => this.selectOccurrenceNative(occurrenceHandle), options.signal);
725
920
  }
@@ -753,6 +948,9 @@ export class FinalCutNativeAutomationAdapter {
753
948
  throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_UNAVAILABLE: deterministic targeting requires live playhead state");
754
949
  }
755
950
  const occurrence = located.occurrences[0];
951
+ if (!occurrence.sourceIdentity || occurrence.sourceIdentity !== media.sourceIdentity) {
952
+ throw new Error("FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: timeline occurrence source identity was not independently observed");
953
+ }
756
954
  const occurrenceIdentity = occurrence.identity ?? occurrence.nativeIdentity;
757
955
  if (!occurrenceIdentity) {
758
956
  throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_IDENTITY_UNAVAILABLE: timeline occurrence has no stable identity");
@@ -769,10 +967,10 @@ export class FinalCutNativeAutomationAdapter {
769
967
  revision: structuredClone(live.revision),
770
968
  timelineStartTime: structuredClone(live.sequence.startTime),
771
969
  frameDuration: structuredClone(live.sequence.frameDuration),
772
- mediaId: occurrence.sourceIdentity ?? media.sourceIdentity,
970
+ mediaId: occurrence.sourceIdentity,
773
971
  occurrence: {
774
972
  id: occurrenceIdentity,
775
- mediaId: occurrence.sourceIdentity ?? media.sourceIdentity,
973
+ mediaId: occurrence.sourceIdentity,
776
974
  startTime: parseRationalString(occurrence.start, "occurrence start"),
777
975
  durationTime: parseRationalString(occurrence.duration, "occurrence duration"),
778
976
  },
@@ -788,7 +986,7 @@ export class FinalCutNativeAutomationAdapter {
788
986
  playheadTime: `${live.playheadTime.value}/${live.playheadTime.timescale}`,
789
987
  };
790
988
  }
791
- async locateOccurrenceNative(mediaHandle, scanAll = false) {
989
+ async locateOccurrenceNative(mediaHandle, scanAll = false, selectForIdentity = true) {
792
990
  this.assertEnabled();
793
991
  const match = this.mediaHandles.get(mediaHandle);
794
992
  if (!match)
@@ -801,20 +999,21 @@ export class FinalCutNativeAutomationAdapter {
801
999
  try {
802
1000
  const liveBefore = this.liveState ? await this.liveState().catch(() => undefined) : undefined;
803
1001
  let occurrenceOutput = "";
804
- for (let attempt = 0; attempt < 2; attempt += 1) {
1002
+ const maxAttempts = selectForIdentity ? 2 : 1;
1003
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
805
1004
  try {
806
- occurrenceOutput = await this.executeNativeScript(locateOccurrenceScript(match, scanAll));
1005
+ occurrenceOutput = await this.executeNativeScript(locateOccurrenceScript(match, scanAll, selectForIdentity));
807
1006
  break;
808
1007
  }
809
1008
  catch (error) {
810
- if (attempt > 0)
1009
+ if (attempt + 1 >= maxAttempts)
811
1010
  throw error;
812
1011
  await this.sleep(300);
813
1012
  }
814
1013
  }
815
1014
  const occurrences = parseOccurrences(occurrenceOutput, mediaHandle);
816
1015
  normalizeOccurrenceTimes(occurrences, liveBefore?.sequence);
817
- if (occurrences.length === 1 && this.canDriveNativeMouse) {
1016
+ if (selectForIdentity && occurrences.length === 1 && this.canDriveNativeMouse) {
818
1017
  const timelineOffset = occurrences[0]?.timelineOffset;
819
1018
  if (timelineOffset === undefined) {
820
1019
  throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_POSITION_UNAVAILABLE: unique timeline occurrence has no selectable position");
@@ -866,6 +1065,10 @@ export class FinalCutNativeAutomationAdapter {
866
1065
  if (context.target.kind !== "selected-clip") {
867
1066
  throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_SELECTION_UNAVAILABLE: Final Cut did not expose the selected occurrence");
868
1067
  }
1068
+ const expectedIdentity = occurrence.nativeIdentity ?? occurrence.identity;
1069
+ if (expectedIdentity && context.target.identity !== expectedIdentity) {
1070
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected native occurrence identity changed");
1071
+ }
869
1072
  if (context.target.identity)
870
1073
  occurrence.nativeIdentity = context.target.identity;
871
1074
  return context;
@@ -910,12 +1113,17 @@ export class FinalCutNativeAutomationAdapter {
910
1113
  if (context.target.name && context.target.name !== occurrence.name) {
911
1114
  throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected timeline occurrence changed");
912
1115
  }
1116
+ if (!occurrence.nativeIdentity || context.target.identity !== occurrence.nativeIdentity) {
1117
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected timeline occurrence identity is unavailable or changed");
1118
+ }
913
1119
  await this.validateOccurrenceBinding(occurrence);
914
1120
  if (!context.bladeAvailable)
915
1121
  throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_OUTSIDE_OCCURRENCE: Final Cut has disabled Blade for the current selection/playhead");
1122
+ const live = await this.readLiveState();
1123
+ const media = this.mediaHandles.get(occurrence.mediaHandle);
916
1124
  const expiresAtMs = this.now() + 30_000;
917
1125
  const previewToken = opaqueHandle("blade-preview");
918
- this.bladePreviews.set(previewToken, { occurrence, expiresAt: expiresAtMs });
1126
+ this.bladePreviews.set(previewToken, { occurrence: structuredClone(occurrence), ...(media ? { media: structuredClone(media) } : {}), context: structuredClone(context), ...(live ? { live: structuredClone(live) } : {}), expiresAt: expiresAtMs });
919
1127
  return {
920
1128
  previewToken,
921
1129
  occurrence,
@@ -1085,51 +1293,88 @@ export class FinalCutNativeAutomationAdapter {
1085
1293
  if (before.target.name && before.target.name !== preview.occurrence.name) {
1086
1294
  throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected timeline occurrence changed");
1087
1295
  }
1296
+ this.assertBladePreviewBinding(preview, before, beforeLive);
1088
1297
  await this.validateOccurrenceBinding(preview.occurrence);
1089
- if (!before.bladeAvailable)
1298
+ const finalContext = await this.requireNativeWriteContext();
1299
+ const finalLive = await this.readLiveState();
1300
+ this.assertBladePreviewBinding(preview, finalContext, finalLive);
1301
+ if (!finalContext.frontmost)
1302
+ throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
1303
+ if (!finalContext.bladeAvailable)
1090
1304
  throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_OUTSIDE_OCCURRENCE: Final Cut has disabled Blade for the current selection/playhead");
1305
+ const media = this.mediaHandles.get(preview.occurrence.mediaHandle);
1306
+ if (!preview.media || !media || media.name !== preview.occurrence.name || media.name !== preview.media.name
1307
+ || !browserMediaIdentity(media) || browserMediaIdentity(media) !== browserMediaIdentity(preview.media)) {
1308
+ throw new Error("FINAL_CUT_NATIVE_MEDIA_HANDLE_STALE: Blade Browser identity is unavailable or changed");
1309
+ }
1091
1310
  try {
1092
- await this.executeNativeCommand(bladeScript(), async (recovered) => {
1093
- this.assertRetryContext(before, recovered, true);
1094
- await this.validateOccurrenceBinding(preview.occurrence);
1095
- if (!recovered.bladeAvailable)
1096
- throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_OUTSIDE_OCCURRENCE: Final Cut has disabled Blade for the current selection/playhead");
1097
- });
1311
+ await this.executeNativeScript(bladeScript());
1098
1312
  }
1099
1313
  catch (error) {
1100
- throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
1314
+ throw new Error(`FINAL_CUT_NATIVE_BLADE_OUTCOME_UNCERTAIN: Blade may have been applied; do not retry without recovery: ${String(error)}`);
1101
1315
  }
1102
- const after = await this.requireTimelineContext();
1103
- if (!after.frontmost)
1104
- throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut changed focus during Blade");
1105
- const afterLive = await this.readLiveState();
1106
- const resultingSegments = parseOccurrences(await this.executeNativeScript(locateOccurrenceScript({ handle: preview.occurrence.mediaHandle, name: preview.occurrence.name }, true)), preview.occurrence.mediaHandle);
1107
- normalizeOccurrenceTimes(resultingSegments, afterLive?.sequence);
1108
- if (resultingSegments.length < 2) {
1109
- throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut did not expose two resulting timeline segments after Blade");
1316
+ try {
1317
+ const after = await this.requireTimelineContext();
1318
+ if (!after.frontmost)
1319
+ throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut changed focus during Blade");
1320
+ const afterLive = await this.readLiveState();
1321
+ const resultingSegments = parseOccurrences(await this.executeNativeScript(locateOccurrenceScript(media, true)), preview.occurrence.mediaHandle);
1322
+ normalizeOccurrenceTimes(resultingSegments, afterLive?.sequence);
1323
+ if (resultingSegments.length < 2) {
1324
+ throw new Error("FINAL_CUT_NATIVE_VERIFICATION_FAILED: Final Cut did not expose two resulting timeline segments after Blade");
1325
+ }
1326
+ const operationId = opaqueHandle("native-blade");
1327
+ const operation = {
1328
+ kind: "blade",
1329
+ before: finalContext,
1330
+ after,
1331
+ beforeLive: finalLive,
1332
+ afterLive,
1333
+ undoCommand: after.undoCommand,
1334
+ };
1335
+ this.rememberOperation(operationId, operation);
1336
+ this.assertNativeRollbackReady(operationId, "Blade", operation);
1337
+ return {
1338
+ operationId,
1339
+ previewToken,
1340
+ occurrence: preview.occurrence,
1341
+ resultingSegments,
1342
+ before: finalContext,
1343
+ after,
1344
+ verification: { verified: false, detail: "Final Cut exposed UI rows after Blade; original source and canonical split remain unverified; do not retry without recovery" },
1345
+ undoAvailable: after.undoAvailable,
1346
+ ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
1347
+ };
1348
+ }
1349
+ catch (error) {
1350
+ if (error instanceof NativeFinalCutPartialMutationError)
1351
+ throw error;
1352
+ throw new Error(`FINAL_CUT_NATIVE_BLADE_OUTCOME_UNCERTAIN: Blade may have been applied; do not retry without recovery: ${String(error)}`);
1353
+ }
1354
+ }
1355
+ assertBladePreviewBinding(preview, before, beforeLive) {
1356
+ const original = preview.live;
1357
+ const originalScope = preview.context.target;
1358
+ const currentScope = before.target;
1359
+ if (!original?.project?.id || !original.sequence?.id || !original.playheadTime
1360
+ || !beforeLive?.project?.id || !beforeLive.sequence?.id || !beforeLive.playheadTime
1361
+ || !preview.context.playheadTime || !before.playheadTime
1362
+ || currentScope.kind !== "selected-clip" || !preview.occurrence.nativeIdentity
1363
+ || originalScope.identity !== preview.occurrence.nativeIdentity || currentScope.identity !== preview.occurrence.nativeIdentity
1364
+ || currentScope.name !== originalScope.name
1365
+ || originalScope.projectId !== original.project.id || originalScope.sequenceId !== original.sequence.id
1366
+ || originalScope.revision?.id !== original.revision.id || originalScope.revision?.sequence !== original.revision.sequence
1367
+ || currentScope.projectId !== beforeLive.project.id || currentScope.sequenceId !== beforeLive.sequence.id
1368
+ || currentScope.revision?.id !== beforeLive.revision.id || currentScope.revision?.sequence !== beforeLive.revision.sequence
1369
+ || original.project.id !== beforeLive.project.id || original.sequence.id !== beforeLive.sequence.id
1370
+ || original.revision.id !== beforeLive.revision.id || original.revision.sequence !== beforeLive.revision.sequence
1371
+ || compareRational(parseRationalString(preview.context.playheadTime, "preview playhead"), original.playheadTime) !== 0
1372
+ || compareRational(parseRationalString(before.playheadTime, "current playhead"), beforeLive.playheadTime) !== 0
1373
+ || compareRational(original.playheadTime, beforeLive.playheadTime) !== 0
1374
+ || compareRational(original.sequence.startTime, beforeLive.sequence.startTime) !== 0
1375
+ || compareRational(original.sequence.frameDuration, beforeLive.sequence.frameDuration) !== 0) {
1376
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: Blade target, frame grid, revision, or playhead changed or is unavailable");
1110
1377
  }
1111
- const operationId = opaqueHandle("native-blade");
1112
- const operation = {
1113
- kind: "blade",
1114
- before,
1115
- after,
1116
- beforeLive,
1117
- afterLive,
1118
- undoCommand: after.undoCommand,
1119
- };
1120
- this.rememberOperation(operationId, operation);
1121
- this.assertNativeRollbackReady(operationId, "Blade", operation);
1122
- return {
1123
- operationId,
1124
- previewToken,
1125
- occurrence: preview.occurrence,
1126
- resultingSegments,
1127
- before,
1128
- after,
1129
- verification: { verified: true, detail: "Final Cut accepted the Blade command while the target remained frontmost" },
1130
- undoAvailable: after.undoAvailable,
1131
- ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
1132
- };
1133
1378
  }
1134
1379
  async previewDeleteRange(range, options = {}) {
1135
1380
  return this.withNativeUi(() => this.previewRangeNative("delete-range", range), options.signal);
@@ -1771,6 +2016,10 @@ export class FinalCutNativeAutomationAdapter {
1771
2016
  if (!context.frontmost)
1772
2017
  throw new Error("FINAL_CUT_NATIVE_NOT_FRONTMOST: Final Cut's timeline must be frontmost");
1773
2018
  const live = await this.requireLiveState();
2019
+ if (!live.project?.id)
2020
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project identity is required for media insertion");
2021
+ if (!live.sequence?.id)
2022
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut sequence identity is required for media insertion");
1774
2023
  const sequenceStart = live.sequenceTimeRange?.start ?? live.sequence?.startTime;
1775
2024
  const beforeDuration = live.sequenceTimeRange?.duration ?? live.sequence?.duration;
1776
2025
  if (!sequenceStart || !beforeDuration)
@@ -1788,7 +2037,8 @@ export class FinalCutNativeAutomationAdapter {
1788
2037
  selectionMode,
1789
2038
  beforeDuration,
1790
2039
  insertionTime,
1791
- sequenceId: live.sequence?.id,
2040
+ projectId: live.project.id,
2041
+ sequenceId: live.sequence.id,
1792
2042
  revision: live.revision.id,
1793
2043
  expiresAt,
1794
2044
  });
@@ -1834,21 +2084,19 @@ export class FinalCutNativeAutomationAdapter {
1834
2084
  if (preview.selectionMode === "handle")
1835
2085
  await this.selectMediaNative(preview.mediaHandle);
1836
2086
  await this.focusTimelineForMediaInsertion();
1837
- await this.executeNativeCommand(mediaInsertionScript(preview.operation), async (recovered) => {
1838
- this.assertRetryContext(before, recovered, preview.operation === "insert");
1839
- if (preview.selectionMode === "handle")
1840
- await this.selectMediaNative(preview.mediaHandle);
1841
- const refocused = await this.prepareNativeRetry();
1842
- this.assertRetryContext(before, refocused, preview.operation === "insert");
1843
- await this.focusTimelineForMediaInsertion();
1844
- this.validateMediaInsertionBinding(preview, await this.requireLiveState());
1845
- if (preview.selectionMode === "selected")
1846
- await this.validateSelectedMediaBinding(media);
1847
- });
2087
+ this.validateMediaInsertionBinding(preview, await this.requireLiveState());
1848
2088
  }
1849
2089
  catch (error) {
1850
2090
  throw new Error(`${nativeErrorCode(error)}: ${String(error)}`);
1851
2091
  }
2092
+ try {
2093
+ // A transport or focus error can arrive after the shortcut was issued.
2094
+ // Without a receiver completion receipt, retrying can duplicate the edit.
2095
+ await this.executeNativeScript(mediaInsertionScript(preview.operation));
2096
+ }
2097
+ catch (error) {
2098
+ throw new Error(`FINAL_CUT_NATIVE_PLACEMENT_OUTCOME_UNCERTAIN: placement may have been applied; recovery is required before retry: ${String(error)}`);
2099
+ }
1852
2100
  const operationId = opaqueHandle(`native-${preview.operation}-media`);
1853
2101
  let after;
1854
2102
  let afterLive;
@@ -1857,30 +2105,10 @@ export class FinalCutNativeAutomationAdapter {
1857
2105
  afterLive = await this.waitForMediaInsertion(preview.beforeDuration, beforeLive.revision.id);
1858
2106
  }
1859
2107
  catch (error) {
1860
- const observedContext = after ?? await this.inspectRawNative();
1861
- const observedLive = afterLive ?? await this.readLiveState();
1862
- if (observedLive && mediaInsertionMutationObserved(beforeLive, observedLive) && observedContext.undoCommand) {
1863
- this.rememberOperation(operationId, {
1864
- kind: "media-insertion",
1865
- before,
1866
- after: observedContext,
1867
- beforeLive,
1868
- afterLive: observedLive,
1869
- beforeDuration: preview.beforeDuration,
1870
- undoCommand: observedContext.undoCommand,
1871
- });
1872
- try {
1873
- await this.undo(operationId);
1874
- }
1875
- catch (rollbackError) {
1876
- throw new Error(`${nativeErrorCode(error)}: ${String(error)}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
1877
- }
1878
- throw new Error(`${nativeErrorCode(error)}: ${String(error)}; insertion was rolled back`);
1879
- }
1880
- throw new Error(`${nativeErrorCode(error)}: ${String(error)}; post-command state was not safely recoverable, so no Undo handle was retained`);
2108
+ throw new Error(`${nativeErrorCode(error)}: ${String(error)}; placement may have been applied and recovery is required before retry`);
1881
2109
  }
1882
2110
  const afterDuration = afterLive.sequenceTimeRange?.duration ?? afterLive.sequence?.duration;
1883
- const verification = mediaInsertionVerificationDetail(afterDuration, preview.beforeDuration, afterLive.revision.id, beforeLive.revision.id);
2111
+ const observation = mediaInsertionVerificationDetail(afterDuration, preview.beforeDuration, afterLive.revision.id, beforeLive.revision.id);
1884
2112
  const operation = {
1885
2113
  kind: "media-insertion",
1886
2114
  before,
@@ -1890,18 +2118,8 @@ export class FinalCutNativeAutomationAdapter {
1890
2118
  beforeDuration: preview.beforeDuration,
1891
2119
  undoCommand: after.undoCommand,
1892
2120
  };
1893
- if (!verification.verified) {
1894
- if (mediaInsertionMutationObserved(beforeLive, afterLive) && after.undoAvailable && after.undoCommand) {
1895
- this.rememberOperation(operationId, operation);
1896
- try {
1897
- await this.undo(operationId);
1898
- }
1899
- catch (rollbackError) {
1900
- throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; operationId=${operationId}; native rollback failed: ${String(rollbackError)}`);
1901
- }
1902
- throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}; insertion was rolled back`);
1903
- }
1904
- throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${verification.detail}`);
2121
+ if (!observation.verified) {
2122
+ throw new Error(`FINAL_CUT_NATIVE_VERIFICATION_FAILED: ${observation.detail}; placement may have been applied and recovery is required before retry`);
1905
2123
  }
1906
2124
  this.rememberOperation(operationId, operation);
1907
2125
  this.assertNativeRollbackReady(operationId, `${preview.operation} media insertion`, operation);
@@ -1916,7 +2134,7 @@ export class FinalCutNativeAutomationAdapter {
1916
2134
  afterDuration: afterDuration,
1917
2135
  beforeRevision: beforeLive.revision,
1918
2136
  afterRevision: afterLive.revision,
1919
- verification,
2137
+ verification: { verified: false, detail: `${observation.detail}; canonical source and placement are unverified; recovery is required` },
1920
2138
  undoAvailable: after.undoAvailable,
1921
2139
  ...(after.undoCommand ? { undoCommand: after.undoCommand } : {}),
1922
2140
  };
@@ -2082,7 +2300,9 @@ export class FinalCutNativeAutomationAdapter {
2082
2300
  return this.liveState();
2083
2301
  }
2084
2302
  validateMediaInsertionBinding(preview, live) {
2085
- if (preview.sequenceId && live.sequence?.id !== preview.sequenceId)
2303
+ if (live.project?.id !== preview.projectId)
2304
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active project changed");
2305
+ if (live.sequence?.id !== preview.sequenceId)
2086
2306
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: active sequence changed");
2087
2307
  if (live.revision.id !== preview.revision)
2088
2308
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead or timeline revision changed");
@@ -2090,6 +2310,10 @@ export class FinalCutNativeAutomationAdapter {
2090
2310
  if (!currentDuration || compareRational(currentDuration, preview.beforeDuration) !== 0) {
2091
2311
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: sequence duration changed");
2092
2312
  }
2313
+ const currentStart = live.sequenceTimeRange?.start ?? live.sequence?.startTime;
2314
+ if (preview.operation === "append" && (!currentStart || compareRational(addRational(currentStart, currentDuration), preview.insertionTime) !== 0)) {
2315
+ throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: append insertion position changed");
2316
+ }
2093
2317
  if (preview.operation === "insert" && (!live.playheadTime || compareRational(live.playheadTime, preview.insertionTime) !== 0)) {
2094
2318
  throw new Error("FINAL_CUT_NATIVE_PREVIEW_STALE: playhead changed");
2095
2319
  }
@@ -2208,9 +2432,13 @@ export class FinalCutNativeAutomationAdapter {
2208
2432
  : expected.target.occurrenceIndex !== undefined && recovered.target.occurrenceIndex !== undefined
2209
2433
  ? expected.target.occurrenceIndex !== recovered.target.occurrenceIndex
2210
2434
  : true);
2435
+ const scopeChanged = expected.target.projectId !== recovered.target.projectId
2436
+ || expected.target.sequenceId !== recovered.target.sequenceId
2437
+ || expected.target.revision?.id !== recovered.target.revision?.id
2438
+ || expected.target.revision?.sequence !== recovered.target.revision?.sequence;
2211
2439
  const playheadChanged = requirePlayhead
2212
2440
  && (!expected.playheadTime || !recovered.playheadTime || expected.playheadTime !== recovered.playheadTime);
2213
- if (targetChanged || occurrenceChanged || playheadChanged) {
2441
+ if (targetChanged || occurrenceChanged || scopeChanged || playheadChanged) {
2214
2442
  throw new Error("FINAL_CUT_NATIVE_RETRY_TARGET_CHANGED: Final Cut selection or playhead changed during focus recovery");
2215
2443
  }
2216
2444
  }
@@ -2410,6 +2638,9 @@ export class FinalCutNativeAutomationAdapter {
2410
2638
  if (!context.readiness.selectedTarget) {
2411
2639
  throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: position the playhead or select a timeline target in Final Cut Pro");
2412
2640
  }
2641
+ if (context.target.kind === "selected-clip" && !context.readiness.targetBound) {
2642
+ throw new Error("FINAL_CUT_NATIVE_TARGET_BINDING_UNAVAILABLE: selected occurrence is not bound to the active project, sequence, and revision");
2643
+ }
2413
2644
  }
2414
2645
  assertNativeRollbackReady(operationId, operation, record) {
2415
2646
  const evidence = record.rollbackEvidence ?? nativeRollbackEvidence(record);
@@ -2584,6 +2815,7 @@ export class FinalCutNativeAutomationAdapter {
2584
2815
  }
2585
2816
  async executeNativeMouseScript(source) {
2586
2817
  if (this.nativeMouseExecutor) {
2818
+ this.dispatchContext.getStore()?.();
2587
2819
  await this.nativeMouseExecutor(source);
2588
2820
  return;
2589
2821
  }
@@ -2616,6 +2848,7 @@ export class FinalCutNativeAutomationAdapter {
2616
2848
  requestSignal.addEventListener("abort", cancelListener, { once: true });
2617
2849
  })
2618
2850
  : undefined;
2851
+ this.dispatchContext.getStore()?.();
2619
2852
  const execution = execFile("swift", ["-e", source], { signal: controller.signal });
2620
2853
  try {
2621
2854
  await Promise.race([execution, timeout, ...(cancellation ? [cancellation] : [])]);
@@ -2668,6 +2901,7 @@ export class FinalCutNativeAutomationAdapter {
2668
2901
  requestSignal.addEventListener("abort", cancelListener, { once: true });
2669
2902
  })
2670
2903
  : undefined;
2904
+ this.dispatchContext.getStore()?.();
2671
2905
  const execution = this.executor(script, { signal: controller.signal });
2672
2906
  try {
2673
2907
  return await Promise.race([execution, timeout, ...(cancellation ? [cancellation] : [])]);
@@ -2742,6 +2976,14 @@ function nativeRollbackEvidence(record) {
2742
2976
  };
2743
2977
  }
2744
2978
  function verifyNativeUndo(operation, after, afterLive) {
2979
+ if (operation.kind === "media-insertion") {
2980
+ const expectedProject = operation.beforeLive?.project?.id;
2981
+ const expectedSequence = operation.beforeLive?.sequence?.id;
2982
+ if (!expectedProject || !expectedSequence || afterLive?.project?.id !== expectedProject || afterLive?.sequence?.id !== expectedSequence) {
2983
+ return { verified: false, detail: "project or sequence target changed during Undo" };
2984
+ }
2985
+ return { verified: false, detail: "canonical restoration and source integrity are unavailable; recovery is required" };
2986
+ }
2745
2987
  const liveRevisionAdvanced = Boolean(operation.afterLive
2746
2988
  && afterLive
2747
2989
  && afterLive.revision.id !== operation.afterLive.revision.id);
@@ -3249,9 +3491,10 @@ using terms from application "System Events"
3249
3491
  return parts
3250
3492
  end splitText
3251
3493
 
3252
- on selectedTimelineItem(containerItem, depth, mainOrigin, mainSize)
3253
- if depth > 6 then return ""
3254
- set output to ""
3494
+ on selectedTimelineSelection(containerItem, depth, mainOrigin, mainSize)
3495
+ if depth > 6 then return {0, ""}
3496
+ set selectedCount to 0
3497
+ set selectedRecord to ""
3255
3498
  repeat with candidateRef in UI elements of containerItem
3256
3499
  try
3257
3500
  set candidate to contents of candidateRef
@@ -3269,32 +3512,37 @@ using terms from application "System Events"
3269
3512
  set candidateSelected to (selected of candidate) is true
3270
3513
  end try
3271
3514
  if candidateSelected then
3272
- set candidateRole to role of candidate as text
3273
- set candidateName to ""
3274
- try
3275
- set candidateName to description of candidate as text
3276
- end try
3277
- if candidateName is "" then
3515
+ set selectedCount to selectedCount + 1
3516
+ if selectedRecord is "" then
3517
+ set candidateRole to role of candidate as text
3518
+ set candidateName to ""
3278
3519
  try
3279
- set candidateName to value of candidate as text
3520
+ set candidateName to description of candidate as text
3521
+ end try
3522
+ if candidateName is "" then
3523
+ try
3524
+ set candidateName to value of candidate as text
3525
+ end try
3526
+ end if
3527
+ if candidateName is "missing value" then set candidateName to ""
3528
+ set candidateIdentity to ""
3529
+ try
3530
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
3280
3531
  end try
3532
+ set selectedRecord to candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateIdentity
3281
3533
  end if
3282
- if candidateName is "missing value" then set candidateName to ""
3283
- set candidateIdentity to ""
3284
- try
3285
- set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
3286
- end try
3287
- return candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateIdentity
3534
+ else
3535
+ set nestedSelection to my selectedTimelineSelection(candidate, depth + 1, mainOrigin, mainSize)
3536
+ set selectedCount to selectedCount + (item 1 of nestedSelection)
3537
+ if selectedRecord is "" then set selectedRecord to item 2 of nestedSelection
3288
3538
  end if
3289
- set output to my selectedTimelineItem(candidate, depth + 1, mainOrigin, mainSize)
3290
- if output is not "" then return output
3291
3539
  end if
3292
3540
  on error
3293
3541
  -- Ignore inaccessible descendants and continue the bounded scan.
3294
3542
  end try
3295
3543
  end repeat
3296
- return ""
3297
- end selectedTimelineItem
3544
+ return {selectedCount, selectedRecord}
3545
+ end selectedTimelineSelection
3298
3546
 
3299
3547
  on selectedTimelineOccurrenceIndex(timelineArea)
3300
3548
  set occurrenceIndex to 0
@@ -3352,14 +3600,15 @@ tell application "System Events"
3352
3600
  try
3353
3601
  set timelineArea to UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of frontWindow
3354
3602
  set selectionLookupAvailable to true
3355
- set selectedRecord to my selectedTimelineItem(timelineArea, 0, mainOrigin, mainSize)
3603
+ set selectionResult to my selectedTimelineSelection(timelineArea, 0, mainOrigin, mainSize)
3604
+ set selectedCount to item 1 of selectionResult
3605
+ set selectedRecord to item 2 of selectionResult
3356
3606
  set selectedOccurrenceIndex to my selectedTimelineOccurrenceIndex(timelineArea)
3357
- if selectedRecord is not "" then
3607
+ if selectedCount is 1 and selectedRecord is not "" then
3358
3608
  set selectedFields to my splitText(selectedRecord, ASCII character 31)
3359
3609
  set selectedName to item 1 of selectedFields
3360
3610
  set selectedRole to item 2 of selectedFields
3361
3611
  set selectedIdentity to item 3 of selectedFields
3362
- set selectedCount to 1
3363
3612
  end if
3364
3613
  end try
3365
3614
  if not selectionLookupAvailable then set selectedCount to -1
@@ -3700,9 +3949,10 @@ function inspectScript() {
3700
3949
  return parts
3701
3950
  end splitText
3702
3951
 
3703
- on selectedTimelineItem(containerItem, depth, mainOrigin, mainSize)
3704
- if depth > 12 then return ""
3705
- set output to ""
3952
+ on selectedTimelineSelection(containerItem, depth, mainOrigin, mainSize)
3953
+ if depth > 12 then return {0, ""}
3954
+ set selectedCount to 0
3955
+ set selectedRecord to ""
3706
3956
  repeat with candidateRef in UI elements of containerItem
3707
3957
  try
3708
3958
  set candidate to contents of candidateRef
@@ -3721,32 +3971,37 @@ function inspectScript() {
3721
3971
  set candidateSelected to (selected of candidate) is true
3722
3972
  end try
3723
3973
  if candidateSelected then
3724
- set candidateRole to role of candidate as text
3725
- set candidateName to ""
3726
- try
3727
- set candidateName to description of candidate as text
3728
- end try
3729
- if candidateName is "" then
3974
+ set selectedCount to selectedCount + 1
3975
+ if selectedRecord is "" then
3976
+ set candidateRole to role of candidate as text
3977
+ set candidateName to ""
3730
3978
  try
3731
- set candidateName to value of candidate as text
3979
+ set candidateName to description of candidate as text
3732
3980
  end try
3981
+ if candidateName is "" then
3982
+ try
3983
+ set candidateName to value of candidate as text
3984
+ end try
3985
+ end if
3986
+ if candidateName is "missing value" then set candidateName to ""
3987
+ set candidateIdentity to ""
3988
+ try
3989
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
3990
+ end try
3991
+ set selectedRecord to candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateIdentity
3733
3992
  end if
3734
- if candidateName is "missing value" then set candidateName to ""
3735
- set candidateIdentity to ""
3736
- try
3737
- set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
3738
- end try
3739
- return candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateIdentity
3993
+ else
3994
+ set nestedSelection to my selectedTimelineSelection(candidate, depth + 1, mainOrigin, mainSize)
3995
+ set selectedCount to selectedCount + (item 1 of nestedSelection)
3996
+ if selectedRecord is "" then set selectedRecord to item 2 of nestedSelection
3740
3997
  end if
3741
- set output to my selectedTimelineItem(candidate, depth + 1, mainOrigin, mainSize)
3742
- if output is not "" then return output
3743
3998
  end if
3744
3999
  on error
3745
4000
  -- Ignore inaccessible descendants and continue the bounded scan.
3746
4001
  end try
3747
4002
  end repeat
3748
- return ""
3749
- end selectedTimelineItem
4003
+ return {selectedCount, selectedRecord}
4004
+ end selectedTimelineSelection
3750
4005
 
3751
4006
  on selectedTimelineOccurrenceIndex(timelineArea)
3752
4007
  set occurrenceIndex to 0
@@ -3830,15 +4085,16 @@ function inspectScript() {
3830
4085
  try
3831
4086
  set timelineArea to UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of UI element 1 of frontWindow
3832
4087
  set selectionLookupAvailable to true
3833
- set selectedRecord to my selectedTimelineItem(timelineArea, 0, mainOrigin, mainSize)
4088
+ set selectionResult to my selectedTimelineSelection(timelineArea, 0, mainOrigin, mainSize)
4089
+ set selectedCount to item 1 of selectionResult
4090
+ set selectedRecord to item 2 of selectionResult
3834
4091
  set selectedOccurrenceIndex to my selectedTimelineOccurrenceIndex(timelineArea)
3835
4092
  end try
3836
- if selectedRecord is not "" then
4093
+ if selectedCount is 1 and selectedRecord is not "" then
3837
4094
  set selectedFields to my splitText(selectedRecord, ASCII character 31)
3838
4095
  set selectedName to item 1 of selectedFields
3839
4096
  set selectedRole to item 2 of selectedFields
3840
4097
  set selectedIdentity to item 3 of selectedFields
3841
- set selectedCount to 1
3842
4098
  end if
3843
4099
  set inspectorName to my findInspectorName(frontWindow, 0)
3844
4100
  if inspectorName is not "" and selectedCount is 1 then set selectedName to inspectorName
@@ -3896,6 +4152,7 @@ function searchMediaScript(query) {
3896
4152
  key code 36
3897
4153
  delay 0.5
3898
4154
  set output to my collectBrowserMedia(browserRoot, 0, searchQuery, origin, browserRootContext, {}, "root")
4155
+ if output is "" then return "__FRAMEKIT_BROWSER_SCAN_EMPTY__"
3899
4156
  return output
3900
4157
  end tell
3901
4158
  end tell`;
@@ -4348,7 +4605,15 @@ function browserMediaTraversalScript() {
4348
4605
  on collectBrowserMedia(containerItem, depth, searchQuery, origin, inheritedContext, seenIdentities, browserPath)
4349
4606
  set maxDepth to 12
4350
4607
  if inheritedContext then set maxDepth to 6
4351
- if depth > maxDepth then return ""
4608
+ if depth > maxDepth then
4609
+ try
4610
+ tell application "System Events" to set remainingItems to UI elements of containerItem
4611
+ if (count of remainingItems) > 0 then return "__FRAMEKIT_BROWSER_SCAN_INCOMPLETE__" & (ASCII character 30)
4612
+ return ""
4613
+ on error
4614
+ return "__FRAMEKIT_BROWSER_SCAN_INCOMPLETE__" & (ASCII character 30)
4615
+ end try
4616
+ end if
4352
4617
  set output to ""
4353
4618
  set mediaContext to my mediaContainer(containerItem, inheritedContext)
4354
4619
  tell application "System Events"
@@ -4408,7 +4673,8 @@ function browserMediaTraversalScript() {
4408
4673
  end if
4409
4674
  set output to output & my collectBrowserMedia(candidate, depth + 1, searchQuery, origin, candidateMediaContext, seenIdentities, candidatePath)
4410
4675
  on error
4411
- -- Ignore inaccessible descendants and continue enumerating Browser results.
4676
+ -- Preserve incomplete-scan evidence rather than reporting an empty result.
4677
+ set output to output & "__FRAMEKIT_BROWSER_SCAN_INCOMPLETE__" & (ASCII character 30)
4412
4678
  end try
4413
4679
  end repeat
4414
4680
  on error
@@ -4717,11 +4983,11 @@ function selectMediaScript(match) {
4717
4983
  end tell
4718
4984
  end tell`;
4719
4985
  }
4720
- function locateOccurrenceScript(match, scanAll) {
4986
+ function locateOccurrenceScript(match, scanAll, zoomToFit = true) {
4721
4987
  return `
4722
4988
  using terms from application "System Events"
4723
4989
  on collectTimelineClipMatches(containerItem, depth, targetName, sourceIdentity, mainOrigin, mainSize)
4724
- if depth > 12 then return ""
4990
+ if depth > 12 then error "timeline traversal depth exceeded"
4725
4991
  set output to ""
4726
4992
  set candidateItems to UI elements of containerItem
4727
4993
  repeat with candidateRef in candidateItems
@@ -4732,6 +4998,7 @@ function locateOccurrenceScript(match, scanAll) {
4732
4998
  try
4733
4999
  set candidateDescription to description of candidate as text
4734
5000
  end try
5001
+ if candidateRole is "AXLayoutItem" and candidateDescription is "" then error "timeline item description unavailable"
4735
5002
  if candidateRole is "AXLayoutItem" and candidateDescription contains ("Video-Clip:" & targetName) then
4736
5003
  set candidatePosition to position of candidate
4737
5004
  set candidateStart to ""
@@ -4747,15 +5014,14 @@ function locateOccurrenceScript(match, scanAll) {
4747
5014
  if childRole is "AXHandle" and childDescription is "Leading Edge" then set candidateStart to value of child as text
4748
5015
  end try
4749
5016
  end repeat
4750
- if candidateStart is not "" and candidateDuration is not "" then
4751
- set candidateOffset to ((item 1 of candidatePosition) + 10) - (item 1 of mainOrigin)
5017
+ if candidateStart is "" or candidateDuration is "" then error "timeline clip has no complete range"
5018
+ set candidateOffset to ((item 1 of candidatePosition) + 10) - (item 1 of mainOrigin)
4752
5019
  set candidateIdentity to ""
4753
5020
  try
4754
5021
  set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
4755
5022
  end try
4756
5023
  if candidateIdentity is "" then error "FINAL_CUT_NATIVE_OCCURRENCE_ID_UNAVAILABLE: timeline clip has no AXIdentifier"
4757
- set output to output & targetName & (ASCII character 31) & candidateRole & (ASCII character 31) & sourceIdentity & (ASCII character 31) & (candidateOffset as text) & (ASCII character 31) & candidateStart & (ASCII character 31) & candidateDuration & (ASCII character 31) & candidateIdentity & (ASCII character 30)
4758
- end if
5024
+ set output to output & targetName & (ASCII character 31) & candidateRole & (ASCII character 31) & "" & (ASCII character 31) & (candidateOffset as text) & (ASCII character 31) & candidateStart & (ASCII character 31) & candidateDuration & (ASCII character 31) & candidateIdentity & (ASCII character 30)
4759
5025
  else
4760
5026
  set shouldDescend to false
4761
5027
  try
@@ -4768,12 +5034,13 @@ function locateOccurrenceScript(match, scanAll) {
4768
5034
  set timelineLeft to (item 1 of mainOrigin) + ((item 1 of mainSize) * 0.25)
4769
5035
  set timelineTop to (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.55)
4770
5036
  set shouldDescend to (candidateX + candidateWidth) is greater than timelineLeft and (candidateY + candidateHeight) is greater than timelineTop
5037
+ on error
5038
+ error "timeline node geometry unavailable"
4771
5039
  end try
4772
5040
  if shouldDescend then set output to output & my collectTimelineClipMatches(candidate, depth + 1, targetName, sourceIdentity, mainOrigin, mainSize)
4773
5041
  end if
4774
5042
  on error
4775
- -- Accessibility nodes can disappear while Final Cut redraws the
4776
- -- timeline. Ignore that node and continue the bounded traversal.
5043
+ error "FINAL_CUT_NATIVE_OCCURRENCE_SCAN_INCOMPLETE: a timeline node could not be inspected"
4777
5044
  end try
4778
5045
  end repeat
4779
5046
  return output
@@ -4789,13 +5056,12 @@ function locateOccurrenceScript(match, scanAll) {
4789
5056
  set origin to position of mainWindow
4790
5057
  set windowSize to size of mainWindow
4791
5058
  set targetName to ${appleScriptString(match.name)}
4792
- -- Make every occurrence visible before scanning. This keeps discovery
4793
- -- independent of the current timeline zoom/playhead viewport.
5059
+ ${zoomToFit ? `-- Make every occurrence visible before scanning.
4794
5060
  try
4795
5061
  click menu bar item "View" of menu bar 1
4796
5062
  click menu item "Zoom to Fit" of menu 1 of menu bar item "View" of menu bar 1
4797
5063
  delay 0.5
4798
- end try
5064
+ end try` : "-- Canonical discovery does not change the timeline view."}
4799
5065
  return my collectTimelineClipMatches(mainWindow, 0, targetName, sourceIdentity, origin, windowSize)
4800
5066
  end tell
4801
5067
  end tell`;
@@ -5915,14 +6181,16 @@ function parseContext(output) {
5915
6181
  : "none";
5916
6182
  const target = selectedCount < 0
5917
6183
  ? { kind: "unknown" }
5918
- : selectedCount === 1
6184
+ : selectedCount === 1 && (Boolean(targetIdentity) || Boolean(occurrenceIndex && Number.isInteger(occurrenceIndex) && occurrenceIndex > 0))
5919
6185
  ? { kind: "selected-clip", ...(selectedName ? { name: selectedName } : {}), ...(selectedRole ? { role: selectedRole } : {}), ...(targetIdentity ? { identity: targetIdentity } : {}), ...(occurrenceIndex && Number.isInteger(occurrenceIndex) && occurrenceIndex > 0 ? { occurrenceIndex } : {}) }
5920
- : selectedCount > 1
6186
+ : selectedCount === 1
5921
6187
  ? { kind: "unknown" }
5922
- : (focusedRole === "AXTextField" && (focusedDescription === "text field" || focusedDescription === "Title")
5923
- || focusedRole === "AXTextArea" && focusedDescription === "text entry area") && focusedName
5924
- ? { kind: "selected-clip", name: focusedName, role: focusedRole }
5925
- : { kind: "playhead" };
6188
+ : selectedCount > 1
6189
+ ? { kind: "unknown" }
6190
+ : (focusedRole === "AXTextField" && (focusedDescription === "text field" || focusedDescription === "Title")
6191
+ || focusedRole === "AXTextArea" && focusedDescription === "text entry area") && focusedName
6192
+ ? { kind: "selected-clip", name: focusedName, role: focusedRole }
6193
+ : { kind: "playhead" };
5926
6194
  const context = {
5927
6195
  available: true,
5928
6196
  application: "Final Cut Pro",
@@ -5980,6 +6248,18 @@ function classifyNativeFocusTarget(focusedRole, focusedDescription, focusedName)
5980
6248
  return "browser";
5981
6249
  return "unknown";
5982
6250
  }
6251
+ function normalizeNativeImportTarget(value) {
6252
+ if (!value || typeof value !== "object")
6253
+ return undefined;
6254
+ const { libraryId, eventId, projectId, sequenceId, revision } = value;
6255
+ if (![libraryId, eventId, projectId, sequenceId, revision].every((item) => typeof item === "string" && item.trim().length > 0))
6256
+ return undefined;
6257
+ return { libraryId, eventId, projectId, sequenceId, revision };
6258
+ }
6259
+ function sameNativeImportTarget(expected, actual) {
6260
+ return Boolean(actual && expected.libraryId === actual.libraryId && expected.eventId === actual.eventId
6261
+ && expected.projectId === actual.projectId && expected.sequenceId === actual.sequenceId && expected.revision === actual.revision);
6262
+ }
5983
6263
  function parseMediaMatches(output) {
5984
6264
  return output
5985
6265
  .split(String.fromCharCode(30))
@@ -6055,12 +6335,12 @@ function timelineTimecodeToRational(value, sequence, label, absolute) {
6055
6335
  function opaqueHandle(kind, suffix) {
6056
6336
  return `${kind}-${Date.now().toString(36)}-${suffix ?? Math.random().toString(36).slice(2, 8)}`;
6057
6337
  }
6058
- function resolveLocalPath(sourcePath) {
6338
+ function resolveLocalPath(sourcePath, homeDirectory = homedir()) {
6059
6339
  const trimmed = sourcePath.trim();
6060
6340
  if (trimmed === "~")
6061
- return homedir();
6341
+ return homeDirectory;
6062
6342
  if (trimmed.startsWith("~/"))
6063
- return resolve(homedir(), trimmed.slice(2));
6343
+ return resolve(homeDirectory, trimmed.slice(2));
6064
6344
  if (trimmed.startsWith("~"))
6065
6345
  throw new Error(`INVALID_OPERATION: local media path must be absolute or start with ~/`);
6066
6346
  return resolve(trimmed);
@@ -6265,15 +6545,13 @@ function mediaInsertionVerificationDetail(actual, before, revision, previousRevi
6265
6545
  return { verified: false, detail: "Final Cut did not expose a new revision after media insertion" };
6266
6546
  return { verified: true, detail: `Final Cut exposed resulting duration ${actual.value}/${actual.timescale} at revision ${revision}` };
6267
6547
  }
6268
- function mediaInsertionMutationObserved(before, after) {
6269
- const beforeDuration = before.sequenceTimeRange?.duration ?? before.sequence?.duration;
6270
- const afterDuration = after.sequenceTimeRange?.duration ?? after.sequence?.duration;
6271
- return Boolean(beforeDuration && afterDuration && compareRational(afterDuration, beforeDuration) > 0);
6272
- }
6273
6548
  function readinessForContext(context) {
6274
6549
  const selectedTarget = context.target.kind !== "none" && context.target.kind !== "unknown";
6550
+ const targetBound = context.target.kind === "selected-clip"
6551
+ && Boolean(context.target.identity && context.target.projectId && context.target.sequenceId && context.target.revision);
6552
+ const targetReady = selectedTarget && (context.target.kind !== "selected-clip" || targetBound);
6275
6553
  const state = context.error?.state
6276
- ?? (context.available && context.frontmost && context.timelineWindowAvailable && context.timelineFocused && !context.overlayBlocked && selectedTarget
6554
+ ?? (context.available && context.frontmost && context.timelineWindowAvailable && context.timelineFocused && !context.overlayBlocked && targetReady
6277
6555
  ? "ready"
6278
6556
  : "unavailable");
6279
6557
  const overlay = context.overlayBlocked
@@ -6295,7 +6573,7 @@ function readinessForContext(context) {
6295
6573
  ? "frontmost"
6296
6574
  : !context.timelineFocused
6297
6575
  ? "timeline-focus"
6298
- : !selectedTarget
6576
+ : !targetReady
6299
6577
  ? "target"
6300
6578
  : undefined;
6301
6579
  const retryable = context.error?.retryable ?? state !== "ready";
@@ -6314,7 +6592,9 @@ function readinessForContext(context) {
6314
6592
  : firstMissing === "timeline-focus"
6315
6593
  ? "Focus the Final Cut Pro timeline and retry"
6316
6594
  : firstMissing === "target"
6317
- ? "Select a single timeline target and retry"
6595
+ ? context.target.kind === "selected-clip"
6596
+ ? "Re-read the selected occurrence after its live project, sequence, and revision are available"
6597
+ : "Select a single timeline target and retry"
6318
6598
  : state === "ready"
6319
6599
  ? "Native Final Cut is ready for a guarded mutation; verify operation-specific Undo after execution"
6320
6600
  : state === "timeout"
@@ -6332,6 +6612,8 @@ function readinessForContext(context) {
6332
6612
  frontmost: context.frontmost,
6333
6613
  timelineFocus: context.timelineFocused,
6334
6614
  selectedTarget,
6615
+ targetKind: context.target.kind,
6616
+ targetBound,
6335
6617
  overlay,
6336
6618
  permission: context.error?.code.includes("PERMISSION") ? "required" : context.available ? "granted" : "unknown",
6337
6619
  undo: context.available ? context.undoAvailable ? "available" : "unavailable" : "unknown",
@@ -6347,6 +6629,10 @@ function readinessStateForError(code) {
6347
6629
  return "stale";
6348
6630
  return "unavailable";
6349
6631
  }
6632
+ /** Construct the disabled focus response without invoking a native provider. */
6633
+ export function disabledNativeFocusContext() {
6634
+ return unavailableContext("CAPABILITY_UNAVAILABLE", "Final Cut native writes are disabled; set FRAMEKIT_FINAL_CUT_NATIVE_WRITES=1");
6635
+ }
6350
6636
  function unavailableContext(code, message, observed) {
6351
6637
  const state = readinessStateForError(code);
6352
6638
  const error = { code, message, state, retryable: state !== "unavailable" || code !== "CAPABILITY_UNAVAILABLE" };