@morshoto/framekit 0.1.11 → 0.1.13

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 (29) hide show
  1. package/README.md +1 -0
  2. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +68 -5
  3. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery.js +31 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical-verification.js +16 -0
  5. package/dist-package/adapters/final-cut/typescript/src/canonical.js +978 -98
  6. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +26 -7
  7. package/dist-package/adapters/final-cut/typescript/src/index.js +3 -0
  8. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +2 -0
  9. package/dist-package/adapters/final-cut/typescript/src/native.js +321 -19
  10. package/dist-package/adapters/final-cut/typescript/src/shadow-mutation.js +71 -17
  11. package/dist-package/adapters/final-cut/typescript/src/sqlite-experiment.js +472 -0
  12. package/dist-package/adapters/final-cut/typescript/src/sqlite-materialization.js +230 -0
  13. package/dist-package/apps/mcp-server/src/headless-sessions.js +47 -4
  14. package/dist-package/apps/mcp-server/src/main.js +33 -1
  15. package/dist-package/apps/mcp-server/src/routing.js +17 -0
  16. package/dist-package/apps/mcp-server/src/server.js +87 -28
  17. package/dist-package/packages/runtime/src/application/media-analysis-service.js +52 -6
  18. package/dist-package/packages/runtime/src/context/context-engine.js +313 -8
  19. package/dist-package/packages/runtime/src/context/context-service.js +5 -2
  20. package/dist-package/packages/runtime/src/context/project-catalog.js +58 -2
  21. package/dist-package/packages/runtime/src/domain/incremental-sync.js +153 -0
  22. package/dist-package/packages/runtime/src/domain/index.js +1 -0
  23. package/dist-package/packages/runtime/src/editing/edit-service.js +8 -2
  24. package/dist-package/packages/runtime/src/runtime.js +5 -2
  25. package/dist-package/packages/runtime/src/skills/builtin.js +99 -8
  26. package/dist-package/packages/runtime/src/skills/runtime.js +1 -0
  27. package/dist-package/packages/runtime/src/timeline/editing-session.js +13 -0
  28. package/dist-package/packages/runtime/src/timeline/snapshot-diff.js +169 -10
  29. package/package.json +9 -5
@@ -1,31 +1,116 @@
1
1
  import { execFile as execFileCallback } from "node:child_process";
2
2
  import { mkdtemp, rm, stat } from "node:fs/promises";
3
- import { basename, join } from "node:path";
3
+ import { basename, dirname, join } from "node:path";
4
4
  import { tmpdir } from "node:os";
5
5
  import { promisify } from "node:util";
6
- import { canonicalSnapshotDigest, assertTimelineTargetReadAfterWrite, createTimelineTarget, resolveTimelineTarget, reconcileProjectCatalog, validateProjectCatalog, withCapabilityFamilies, CapabilityUnavailableError, } from "../../../../packages/runtime/src/index.js";
6
+ import { canonicalSnapshotDigest, canonicalTimelineMode, assertTimelineTargetReadAfterWrite, createTimelineTarget, resolveTimelineTarget, reconcileProjectCatalog, validateProjectCatalog, withCapabilityFamilies, CapabilityUnavailableError, } from "../../../../packages/runtime/src/index.js";
7
+ import { recoverCanonicalNativeMutation } from "./canonical-recovery.js";
8
+ import { verifyCanonicalReadback } from "./canonical-verification.js";
7
9
  import { FcpxmlDocumentAdapter } from "./fcpxml.js";
8
10
  const execFile = promisify(execFileCallback);
11
+ /** Structured failure returned when headed Export XML recovery can be retried. */
12
+ export class FinalCutCanonicalExportError extends Error {
13
+ code;
14
+ retryable;
15
+ cleanup;
16
+ constructor(result) {
17
+ super(`${result.code}: ${result.message}`);
18
+ this.name = "FinalCutCanonicalExportError";
19
+ this.code = result.code;
20
+ this.retryable = result.status === "retryable";
21
+ this.cleanup = result.cleanup;
22
+ }
23
+ toJSON() {
24
+ return {
25
+ code: this.code,
26
+ message: this.message,
27
+ retryable: this.retryable,
28
+ cleanup: this.cleanup,
29
+ };
30
+ }
31
+ }
32
+ /** Parse the JSON envelope returned by the headed canonical export workflow. */
33
+ export function parseFinalCutCanonicalExportResult(input) {
34
+ if (input === "canonical-export-requested")
35
+ return { status: "export-requested" };
36
+ let payload;
37
+ try {
38
+ payload = typeof input === "string" ? JSON.parse(input) : input;
39
+ }
40
+ catch (error) {
41
+ throw new Error(`FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response was not valid JSON (${String(error)})`);
42
+ }
43
+ if (!payload || typeof payload !== "object") {
44
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response must be an object");
45
+ }
46
+ const result = payload;
47
+ if (result.status === "export-requested")
48
+ return { status: "export-requested" };
49
+ if (result.status !== "retryable" && result.status !== "failed") {
50
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response status is unsupported");
51
+ }
52
+ if (typeof result.code !== "string" || !result.code.trim()) {
53
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response code is required");
54
+ }
55
+ if (typeof result.message !== "string" || !result.message.trim()) {
56
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response message is required");
57
+ }
58
+ if (result.cleanup !== "complete" && result.cleanup !== "incomplete") {
59
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_RESULT_INVALID: response cleanup status is unsupported");
60
+ }
61
+ return {
62
+ status: result.status,
63
+ code: result.code,
64
+ message: result.message,
65
+ cleanup: result.cleanup,
66
+ };
67
+ }
68
+ /** Report the complete guarantees required before claiming canonical live support. */
69
+ export function assessCanonicalLiveReadiness(capabilities) {
70
+ const mode = canonicalTimelineMode(capabilities);
71
+ const editor = capabilities.editor;
72
+ const missing = [
73
+ ...(mode === "canonical-write" ? [] : ["canonical-write"]),
74
+ ...(!editor.projectCatalogRead ? ["projectCatalogRead"] : []),
75
+ ...(!editor.projectSelection ? ["projectSelection"] : []),
76
+ ...(!editor.timelineSnapshotRead ? ["timelineSnapshotRead"] : []),
77
+ ...(!editor.timelineWrite ? ["timelineWrite"] : []),
78
+ ...(!editor.readAfterWrite ? ["readAfterWrite"] : []),
79
+ ...(!editor.rollback ? ["rollback"] : []),
80
+ ];
81
+ return { ready: missing.length === 0, mode, missing };
82
+ }
9
83
  /** Reads the active Final Cut project through its headed Export XML command. */
10
84
  export class FinalCutCanonicalSnapshotSource {
11
85
  executor;
12
86
  exportTimeoutMs;
13
87
  pollIntervalMs;
88
+ target;
14
89
  constructor(options = {}) {
15
90
  this.executor = options.executor ?? executeCanonicalAppleScript;
16
91
  this.exportTimeoutMs = Math.max(1_000, options.exportTimeoutMs ?? 30_000);
17
92
  this.pollIntervalMs = Math.max(10, options.pollIntervalMs ?? 100);
93
+ this.target = options.target;
18
94
  }
19
95
  async readSnapshot() {
20
96
  const directory = await mkdtemp(join(tmpdir(), "framekit-finalcut-canonical-"));
21
97
  const exportPath = join(directory, "active.fcpxml");
22
98
  try {
23
- await this.executor(buildFinalCutCanonicalExportScript(exportPath));
24
- return await readCanonicalExport(exportPath, this.exportTimeoutMs, this.pollIntervalMs);
99
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
100
+ const result = parseFinalCutCanonicalExportResult(await this.executor(buildFinalCutCanonicalExportScript(exportPath)));
101
+ if (result.status === "export-requested") {
102
+ return await readCanonicalExport(exportPath, this.exportTimeoutMs, this.pollIntervalMs, this.target);
103
+ }
104
+ const error = new FinalCutCanonicalExportError(result);
105
+ if (!error.retryable || error.cleanup !== "complete" || attempt === 2)
106
+ throw error;
107
+ await new Promise((resolve) => setTimeout(resolve, 100));
108
+ }
109
+ throw new Error("FINAL_CUT_CANONICAL_EXPORT_FAILED: retry attempts exhausted");
25
110
  }
26
111
  catch (error) {
27
112
  const detail = error instanceof Error ? error.message : String(error);
28
- if (detail.includes("FINAL_CUT_CANONICAL_"))
113
+ if (detail.includes("FINAL_CUT_CANONICAL_") || detail.includes("TARGET_MISMATCH"))
29
114
  throw error;
30
115
  throw new Error(`FINAL_CUT_CANONICAL_EXPORT_FAILED: ${detail}`);
31
116
  }
@@ -35,6 +120,8 @@ export class FinalCutCanonicalSnapshotSource {
35
120
  }
36
121
  }
37
122
  export function buildFinalCutCanonicalExportScript(exportPath) {
123
+ const exportDirectory = dirname(exportPath);
124
+ const exportName = basename(exportPath);
38
125
  return `
39
126
  using terms from application "System Events"
40
127
 
@@ -67,71 +154,320 @@ on findWindow(finalCut, expectedNames, timeoutSeconds, timeoutMessage)
67
154
  end repeat
68
155
  end findWindow
69
156
 
70
- on pressButtonIfPresent(targetWindow, expectedNames)
71
- repeat with candidate in (buttons of targetWindow)
157
+ on roleIsExpected(candidateRole, expectedRoles)
158
+ repeat with expectedRole in expectedRoles
159
+ if candidateRole is (expectedRole as text) then return true
160
+ end repeat
161
+ return false
162
+ end roleIsExpected
163
+
164
+ on accessibilityMatchesExpectedName(candidate, expectedNames)
165
+ repeat with attributeName in {"AXDescription", "AXTitle", "AXIdentifier"}
72
166
  try
73
- set candidateName to name of candidate as text
167
+ set candidateLabel to value of attribute (attributeName as text) of candidate as text
74
168
  repeat with expectedName in expectedNames
75
- if candidateName is (expectedName as text) and enabled of candidate then
76
- perform action "AXPress" of candidate
77
- return true
78
- end if
169
+ if candidateLabel is (expectedName as text) then return true
79
170
  end repeat
80
171
  end try
81
172
  end repeat
173
+ try
174
+ set candidateLabel to name of candidate as text
175
+ repeat with expectedName in expectedNames
176
+ if candidateLabel is (expectedName as text) then return true
177
+ end repeat
178
+ on error
179
+ return false
180
+ end try
82
181
  return false
83
- end pressButtonIfPresent
182
+ end accessibilityMatchesExpectedName
84
183
 
85
- end using terms from
184
+ on findAccessibilityDescendant(container, expectedRoles, depth)
185
+ if depth > 12 then return missing value
186
+ try
187
+ if my roleIsExpected(role of container as text, expectedRoles) then return container
188
+ end try
189
+ try
190
+ repeat with childRef in (UI elements of container)
191
+ set candidate to contents of childRef
192
+ set found to my findAccessibilityDescendant(candidate, expectedRoles, depth + 1)
193
+ if found is not missing value then return found
194
+ end repeat
195
+ end try
196
+ return missing value
197
+ end findAccessibilityDescendant
86
198
 
87
- tell application "System Events"
88
- tell process "Final Cut Pro"
89
- set frontmost to true
199
+ on accessibilityContainsPathMarker(candidate)
200
+ repeat with attributeName in {"AXDescription", "AXTitle", "AXIdentifier"}
201
+ try
202
+ set candidateLabel to value of attribute (attributeName as text) of candidate as text
203
+ if candidateLabel contains "Go to the folder" or candidateLabel contains "path" or candidateLabel contains "Path" or candidateLabel contains "location" or candidateLabel contains "Location" then return true
204
+ end try
205
+ end repeat
206
+ try
207
+ set candidateLabel to name of candidate as text
208
+ if candidateLabel contains "Go to the folder" or candidateLabel contains "path" or candidateLabel contains "Path" or candidateLabel contains "location" or candidateLabel contains "Location" then return true
209
+ end try
210
+ return false
211
+ end accessibilityContainsPathMarker
212
+
213
+ on matchesCanonicalPathField(candidate)
214
+ try
215
+ if not my roleIsExpected(role of candidate as text, {"AXTextField", "AXTextArea", "AXComboBox"}) then return false
216
+ end try
217
+ try
218
+ set candidateIdentifier to value of attribute "AXIdentifier" of candidate as text
219
+ if candidateIdentifier is "path" or candidateIdentifier is "location" then return true
220
+ end try
221
+ return my accessibilityContainsPathMarker(candidate)
222
+ end matchesCanonicalPathField
223
+
224
+ on findFocusedCanonicalPathField(container, focusedCandidate, depth, insidePathContainer)
225
+ if depth > 12 then return missing value
226
+ set candidateInsidePathContainer to insidePathContainer
227
+ try
228
+ set candidateRole to role of container as text
229
+ if candidateRole is "AXSheet" or candidateRole is "AXDialog" then set candidateInsidePathContainer to true
230
+ if my accessibilityContainsPathMarker(container) then set candidateInsidePathContainer to true
231
+ if my roleIsExpected(candidateRole, {"AXTextField", "AXTextArea", "AXComboBox"}) and candidateInsidePathContainer then
232
+ if container is focusedCandidate then return container
233
+ end if
234
+ end try
235
+ try
236
+ repeat with childRef in (UI elements of container)
237
+ set candidate to contents of childRef
238
+ set found to my findFocusedCanonicalPathField(candidate, focusedCandidate, depth + 1, candidateInsidePathContainer)
239
+ if found is not missing value then return found
240
+ end repeat
241
+ end try
242
+ return missing value
243
+ end findFocusedCanonicalPathField
244
+
245
+ on findCanonicalPathField(container, depth)
246
+ if depth > 12 then return missing value
247
+ try
248
+ if my matchesCanonicalPathField(container) then return container
249
+ end try
250
+ try
251
+ repeat with childRef in (UI elements of container)
252
+ set candidate to contents of childRef
253
+ set found to my findCanonicalPathField(candidate, depth + 1)
254
+ if found is not missing value then return found
255
+ end repeat
256
+ end try
257
+ return missing value
258
+ end findCanonicalPathField
259
+
260
+ on findSavePathField(saveWindow, timeoutSeconds, timeoutMessage)
261
+ set deadline to (current date) + timeoutSeconds
262
+ repeat
263
+ set focusedCandidate to missing value
264
+ try
265
+ set focusedCandidate to value of attribute "AXFocusedUIElement"
266
+ end try
267
+ try
268
+ if my matchesCanonicalPathField(focusedCandidate) then return focusedCandidate
269
+ end try
270
+ set candidate to my findFocusedCanonicalPathField(saveWindow, focusedCandidate, 0, false)
271
+ if candidate is not missing value then return candidate
272
+ set candidate to my findCanonicalPathField(saveWindow, 0)
273
+ if candidate is not missing value then return candidate
274
+ if (current date) > deadline then error timeoutMessage
90
275
  delay 0.1
91
- if not frontmost then error "FINAL_CUT_CANONICAL_NOT_FRONTMOST: Final Cut Pro must be frontmost"
92
- set finalCut to it
93
- set fileMenu to menu "File" of menu bar 1
94
- set exportCommand to missing value
276
+ end repeat
277
+ end findSavePathField
278
+
279
+ on matchesCanonicalSaveNameField(candidate)
280
+ try
281
+ if not my roleIsExpected(role of candidate as text, {"AXTextField", "AXTextArea", "AXComboBox"}) then return false
282
+ end try
283
+ repeat with attributeName in {"AXIdentifier", "AXDescription", "AXTitle"}
95
284
  try
96
- set exportCommand to my findMenuItem(fileMenu, {"Export XML…", "Export XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export XML was not exposed")
285
+ set candidateLabel to value of attribute (attributeName as text) of candidate as text
286
+ if candidateLabel is "saveAsNameTextField" or candidateLabel is "Save As:" or candidateLabel is "Save As" then return true
287
+ end try
288
+ end repeat
289
+ return false
290
+ end matchesCanonicalSaveNameField
291
+
292
+ on findCanonicalSaveNameFieldDescendant(container, depth)
293
+ if depth > 12 then return missing value
294
+ try
295
+ if my matchesCanonicalSaveNameField(container) then return container
296
+ end try
297
+ try
298
+ repeat with childRef in (UI elements of container)
299
+ set candidate to contents of childRef
300
+ set found to my findCanonicalSaveNameFieldDescendant(candidate, depth + 1)
301
+ if found is not missing value then return found
302
+ end repeat
303
+ end try
304
+ return missing value
305
+ end findCanonicalSaveNameFieldDescendant
306
+
307
+ on findCanonicalSaveNameField(saveWindow, timeoutSeconds, timeoutMessage)
308
+ set deadline to (current date) + timeoutSeconds
309
+ repeat
310
+ set candidate to my findCanonicalSaveNameFieldDescendant(saveWindow, 0)
311
+ if candidate is not missing value then return candidate
312
+ if (current date) > deadline then error timeoutMessage
313
+ delay 0.1
314
+ end repeat
315
+ end findCanonicalSaveNameField
316
+
317
+ on findAccessibilityButton(container, expectedNames, depth)
318
+ if depth > 12 then return missing value
319
+ try
320
+ if (role of container as text) is "AXButton" then
321
+ if my accessibilityMatchesExpectedName(container, expectedNames) then return container
322
+ end if
323
+ end try
324
+ try
325
+ repeat with childRef in (UI elements of container)
326
+ set candidate to contents of childRef
327
+ set found to my findAccessibilityButton(candidate, expectedNames, depth + 1)
328
+ if found is not missing value then return found
329
+ end repeat
330
+ end try
331
+ return missing value
332
+ end findAccessibilityButton
333
+
334
+ on pressAccessibilityButtonIfPresent(container, expectedNames)
335
+ set candidate to my findAccessibilityButton(container, expectedNames, 0)
336
+ if candidate is missing value then return false
337
+ try
338
+ perform action "AXPress" of candidate
339
+ return true
340
+ on error
341
+ try
342
+ click candidate
343
+ return true
97
344
  on error
98
- set exportMenuItem to my findMenuItem(fileMenu, {"Export"}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export was not exposed")
99
- perform action "AXPress" of exportMenuItem
100
- set exportMenu to missing value
101
- repeat 100 times
102
- try
103
- if exists menu "Export" of exportMenuItem then
104
- set exportMenu to menu "Export" of exportMenuItem
105
- exit repeat
106
- end if
107
- end try
108
- delay 0.1
109
- end repeat
110
- if exportMenu is missing value then error "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export submenu was not exposed"
111
- set exportCommand to my findMenuItem(exportMenu, {"XML…", "XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export XML command was not exposed")
345
+ return false
346
+ end try
347
+ end try
348
+ end pressAccessibilityButtonIfPresent
349
+
350
+ on cancelCanonicalWindowIfOpen(finalCut, windowName)
351
+ repeat 20 times
352
+ try
353
+ if not (exists window windowName of finalCut) then return true
354
+ set targetWindow to window windowName of finalCut
355
+ if not my pressAccessibilityButtonIfPresent(targetWindow, {"Cancel", "Close"}) then key code 53
112
356
  end try
113
- perform action "AXPress" of exportCommand
114
- set exportWindow to my findWindow(finalCut, {"Export XML", "XML"}, 15, "FINAL_CUT_CANONICAL_EXPORT_WINDOW_UNAVAILABLE: Export XML window did not appear")
115
- my pressButtonIfPresent(exportWindow, {"Next…", "Next...", "Export"})
116
- delay 0.2
117
- set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
118
- keystroke "g" using {command down, shift down}
119
- repeat 50 times
357
+ delay 0.1
358
+ end repeat
359
+ try
360
+ return not (exists window windowName of finalCut)
361
+ on error
362
+ return false
363
+ end try
364
+ end cancelCanonicalWindowIfOpen
365
+
366
+ on cleanupCanonicalExport(finalCut)
367
+ repeat 5 times
368
+ set foundWindow to false
369
+ repeat with candidateName in {"Save", "Export XML", "XML"}
120
370
  try
121
- if exists sheet 1 of saveWindow then exit repeat
371
+ set candidateNameText to candidateName as text
372
+ if exists window candidateNameText of finalCut then
373
+ set foundWindow to true
374
+ my cancelCanonicalWindowIfOpen(finalCut, candidateNameText)
375
+ end if
122
376
  end try
123
- delay 0.1
124
377
  end repeat
125
- if not (exists sheet 1 of saveWindow) then error "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: save path sheet did not appear"
126
- set pathSheet to sheet 1 of saveWindow
127
- if (count of text fields of pathSheet) is 0 then error "FINAL_CUT_CANONICAL_SAVE_PATH_UNAVAILABLE: save path field did not appear"
128
- set value of text field 1 of pathSheet to ${appleScriptString(exportPath)}
129
- key code 36
130
- delay 0.2
131
- if exists button "Save" of saveWindow then click button "Save" of saveWindow
132
- delay 0.2
133
- if exists button "Replace" of saveWindow then click button "Replace" of saveWindow
134
- return "canonical-export-requested"
378
+ if not foundWindow then exit repeat
379
+ end repeat
380
+ repeat with candidateName in {"Save", "Export XML", "XML"}
381
+ try
382
+ if exists window (candidateName as text) of finalCut then return false
383
+ end try
384
+ end repeat
385
+ return true
386
+ end cleanupCanonicalExport
387
+
388
+ on canonicalExportCode(errorMessage)
389
+ if errorMessage contains "not authorized" or errorMessage contains "-1743" or errorMessage contains "-25211" then return "FINAL_CUT_CANONICAL_PERMISSION_REQUIRED"
390
+ set knownCodes to {"FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE", "FINAL_CUT_CANONICAL_EXPORT_WINDOW_UNAVAILABLE", "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE", "FINAL_CUT_CANONICAL_SAVE_PATH_UNAVAILABLE", "FINAL_CUT_CANONICAL_SAVE_NAME_UNAVAILABLE", "FINAL_CUT_CANONICAL_SAVE_BUTTON_UNAVAILABLE"}
391
+ repeat with candidateCode in knownCodes
392
+ set candidateCodeText to candidateCode as text
393
+ if errorMessage contains candidateCodeText then return candidateCodeText
394
+ end repeat
395
+ return "FINAL_CUT_CANONICAL_EXPORT_RECOVERY_REQUIRED"
396
+ end canonicalExportCode
397
+
398
+ on canonicalExportResponse(statusValue, codeValue, messageValue, cleanupValue)
399
+ return "{" & quote & "status" & quote & ":" & quote & statusValue & quote & "," & quote & "code" & quote & ":" & quote & codeValue & quote & "," & quote & "message" & quote & ":" & quote & messageValue & quote & "," & quote & "cleanup" & quote & ":" & quote & cleanupValue & quote & "}"
400
+ end canonicalExportResponse
401
+
402
+ end using terms from
403
+
404
+ tell application "System Events"
405
+ tell process "Final Cut Pro"
406
+ set finalCut to it
407
+ try
408
+ set frontmost to true
409
+ delay 0.1
410
+ if not frontmost then error "FINAL_CUT_CANONICAL_NOT_FRONTMOST: Final Cut Pro must be frontmost"
411
+ set fileMenu to menu "File" of menu bar 1
412
+ set exportCommand to missing value
413
+ try
414
+ set exportCommand to my findMenuItem(fileMenu, {"Export XML…", "Export XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export XML was not exposed")
415
+ on error
416
+ set exportMenuItem to my findMenuItem(fileMenu, {"Export"}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: File > Export was not exposed")
417
+ perform action "AXPress" of exportMenuItem
418
+ set exportMenu to missing value
419
+ repeat 100 times
420
+ try
421
+ if exists menu "Export" of exportMenuItem then
422
+ set exportMenu to menu "Export" of exportMenuItem
423
+ exit repeat
424
+ end if
425
+ end try
426
+ delay 0.1
427
+ end repeat
428
+ if exportMenu is missing value then error "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export submenu was not exposed"
429
+ set exportCommand to my findMenuItem(exportMenu, {"XML…", "XML..."}, 10, "FINAL_CUT_CANONICAL_EXPORT_MENU_UNAVAILABLE: Export XML command was not exposed")
430
+ end try
431
+ perform action "AXPress" of exportCommand
432
+ set exportWindow to my findWindow(finalCut, {"Export XML", "XML"}, 15, "FINAL_CUT_CANONICAL_EXPORT_WINDOW_UNAVAILABLE: Export XML window did not appear")
433
+ my pressAccessibilityButtonIfPresent(exportWindow, {"Next…", "Next...", "Export"})
434
+ delay 0.2
435
+ set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
436
+ keystroke "g" using {command down, shift down}
437
+ set pathField to my findSavePathField(saveWindow, 5, "FINAL_CUT_CANONICAL_SAVE_PATH_UNAVAILABLE: save path field did not appear")
438
+ set value of pathField to ${appleScriptString(exportDirectory)}
439
+ delay 0.2
440
+ key code 36
441
+ delay 0.2
442
+ set saveWindow to my findWindow(finalCut, {"Save", "Export XML"}, 15, "FINAL_CUT_CANONICAL_SAVE_WINDOW_UNAVAILABLE: XML save window did not appear")
443
+ set nameField to my findCanonicalSaveNameField(saveWindow, 5, "FINAL_CUT_CANONICAL_SAVE_NAME_UNAVAILABLE: save filename field did not appear")
444
+ set value of nameField to ${appleScriptString(exportName)}
445
+ if not my pressAccessibilityButtonIfPresent(saveWindow, {"Save"}) then error "FINAL_CUT_CANONICAL_SAVE_BUTTON_UNAVAILABLE: Save button was not exposed"
446
+ repeat 10 times
447
+ set savePanelOpen to false
448
+ repeat with saveWindowName in {"Save", "Export XML"}
449
+ try
450
+ if exists window (saveWindowName as text) of finalCut then
451
+ set savePanelOpen to true
452
+ set saveWindow to window (saveWindowName as text) of finalCut
453
+ exit repeat
454
+ end if
455
+ end try
456
+ end repeat
457
+ if not savePanelOpen then exit repeat
458
+ if not my pressAccessibilityButtonIfPresent(saveWindow, {"Save"}) then key code 36
459
+ delay 0.2
460
+ end repeat
461
+ my pressAccessibilityButtonIfPresent(saveWindow, {"Replace"})
462
+ return my canonicalExportResponse("export-requested", "", "", "complete")
463
+ on error errorMessage number errorNumber
464
+ set cleanupComplete to my cleanupCanonicalExport(finalCut)
465
+ set codeValue to my canonicalExportCode(errorMessage as text)
466
+ if cleanupComplete and codeValue is not "FINAL_CUT_CANONICAL_PERMISSION_REQUIRED" then
467
+ return my canonicalExportResponse("retryable", codeValue, "Final Cut Export XML did not complete; generated dialogs were closed and retry is safe", "complete")
468
+ end if
469
+ return my canonicalExportResponse("failed", codeValue, "Final Cut Export XML recovery could not complete safely", "incomplete")
470
+ end try
135
471
  end tell
136
472
  end tell`;
137
473
  }
@@ -225,7 +561,7 @@ export class FinalCutCanonicalNativeProvider {
225
561
  const canonicalSnapshotCapability = snapshotProbe.available
226
562
  ? true
227
563
  : unavailableCanonicalSnapshot(snapshotProbe.reason);
228
- return withCapabilityFamilies({
564
+ const capabilities = withCapabilityFamilies({
229
565
  editor: {
230
566
  projectRead: snapshotProbe.available,
231
567
  timelineSnapshotRead: snapshotProbe.available,
@@ -244,6 +580,13 @@ export class FinalCutCanonicalNativeProvider {
244
580
  projectSelectionMode: "unavailable",
245
581
  backgroundLibraryInspection: Boolean(backgroundCatalog),
246
582
  compositeTransactions: snapshotProbe.available,
583
+ semanticOperations: {
584
+ "rename-clip": snapshotProbe.available,
585
+ "trim-clip": snapshotProbe.available && Boolean(this.native.trimSelectedClipToRange),
586
+ "add-marker": snapshotProbe.available && Boolean(this.native.addMarkerAtTime),
587
+ "ripple-delete": snapshotProbe.available && Boolean(this.native.rippleDeleteRange),
588
+ "set-gain": snapshotProbe.available && Boolean(this.native.setSelectedClipGain),
589
+ },
247
590
  },
248
591
  analyzers: {
249
592
  speechTranscribe: false,
@@ -269,6 +612,46 @@ export class FinalCutCanonicalNativeProvider {
269
612
  : false,
270
613
  },
271
614
  });
615
+ const readiness = assessCanonicalLiveReadiness(capabilities);
616
+ if (readiness.ready)
617
+ return capabilities;
618
+ const canonicalReadReady = capabilities.editor.projectRead
619
+ && capabilities.editor.timelineSnapshotRead
620
+ && capabilities.editor.projectCatalogRead;
621
+ if (canonicalReadReady) {
622
+ return withCapabilityFamilies({
623
+ ...capabilities,
624
+ editor: {
625
+ ...capabilities.editor,
626
+ timelineWrite: false,
627
+ readAfterWrite: false,
628
+ rollback: false,
629
+ compositeTransactions: false,
630
+ semanticOperations: {},
631
+ },
632
+ }, {
633
+ canonicalDocument: {
634
+ read: true,
635
+ write: false,
636
+ artifactWrite: false,
637
+ },
638
+ editing: {
639
+ compositeTransactions: false,
640
+ },
641
+ });
642
+ }
643
+ return withCapabilityFamilies({
644
+ ...capabilities,
645
+ editor: {
646
+ ...capabilities.editor,
647
+ projectRead: false,
648
+ timelineSnapshotRead: false,
649
+ timelineWrite: false,
650
+ readAfterWrite: false,
651
+ rollback: false,
652
+ compositeTransactions: false,
653
+ },
654
+ });
272
655
  }
273
656
  async probeCanonicalSnapshot() {
274
657
  try {
@@ -306,11 +689,8 @@ export class FinalCutCanonicalNativeProvider {
306
689
  const before = await this.readProject();
307
690
  assertSameRevision(expectedRevision, before.revision);
308
691
  const operation = supportedCanonicalOperation(operations);
309
- const clip = before.timeline.clips.find(({ id }) => id === operation.clipId);
310
- if (!clip)
311
- throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
312
- const preview = structuredClone(before);
313
- preview.timeline.clips = preview.timeline.clips.map((candidate) => (candidate.id === operation.clipId ? { ...candidate, name: operation.name } : candidate));
692
+ assertCanonicalOperationAvailable(this.native, operation);
693
+ const preview = projectCanonicalOperation(before, operation);
314
694
  preview.revision = previewRevision(preview, before.revision);
315
695
  return preview;
316
696
  }
@@ -321,22 +701,46 @@ export class FinalCutCanonicalNativeProvider {
321
701
  async apply(operation, expectedRevision) {
322
702
  const before = await this.readProject();
323
703
  assertSameRevision(expectedRevision, before.revision);
324
- if (operation.type !== "rename-clip") {
325
- throw new Error(`CAPABILITY_UNAVAILABLE: final-cut native canonical provider does not support ${operation.type}`);
326
- }
327
- validateCanonicalRename(operation);
328
- const clip = before.timeline.clips.find(({ id }) => id === operation.clipId);
329
- if (!clip)
330
- throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
704
+ const supported = supportedCanonicalOperation([operation]);
705
+ const markerRange = supported.type === "add-marker" ? canonicalMarkerRange(before, supported.marker) : undefined;
706
+ const clipTarget = supported.type === "rename-clip" || supported.type === "trim-clip" || supported.type === "set-gain"
707
+ ? canonicalTargetForOperation(before, supported)
708
+ : undefined;
709
+ const clip = clipTarget?.clip;
710
+ const rippleTarget = supported.type === "ripple-delete" ? canonicalTargetForOperation(before, supported) : undefined;
711
+ const targetClip = clip;
712
+ const trimDuration = supported.type === "trim-clip"
713
+ ? validateCanonicalTrim(supported, clip, before)
714
+ : undefined;
331
715
  const timelineTarget = createTimelineTarget(before, {
332
- occurrenceId: clip.id,
333
- mediaId: clip.mediaId,
716
+ ...(targetClip ? { occurrenceId: targetClip.id, mediaId: targetClip.mediaId } : {}),
717
+ ...(rippleTarget?.range ? { range: rippleTarget.range } : {}),
718
+ ...(markerRange && compareRational(markerRange.duration, zeroRational()) > 0
719
+ ? { range: { start: markerRange.start, end: markerRange.end } }
720
+ : {}),
334
721
  });
335
722
  resolveTimelineTarget(before, timelineTarget);
336
- await this.resolveTarget(clip, before);
337
- const nativeResult = await this.native.renameSelectedClip(operation.name);
723
+ if (targetClip)
724
+ await this.resolveTarget(targetClip, before);
725
+ assertCanonicalOperationAvailable(this.native, supported);
726
+ const nativeResult = supported.type === "rename-clip"
727
+ ? await this.native.renameSelectedClip(supported.name)
728
+ : supported.type === "trim-clip"
729
+ ? await this.native.trimSelectedClipToRange({
730
+ start: structuredClone(clip.startTime),
731
+ end: addRational(clip.startTime, trimDuration),
732
+ })
733
+ : supported.type === "ripple-delete"
734
+ ? await this.native.rippleDeleteRange(rippleTarget.range)
735
+ : supported.type === "set-gain"
736
+ ? await this.native.setSelectedClipGain(supported.gainDb)
737
+ : await this.native.addMarkerAtTime({
738
+ start: markerRange.start,
739
+ duration: markerRange.duration,
740
+ name: supported.marker.name,
741
+ });
338
742
  if (!nativeResult.operationId || !nativeResult.undoAvailable) {
339
- throw new Error("FINAL_CUT_CANONICAL_UNDO_UNAVAILABLE: native rename did not expose Undo");
743
+ throw new Error("FINAL_CUT_CANONICAL_UNDO_UNAVAILABLE: native edit did not expose Undo");
340
744
  }
341
745
  this.pending = {
342
746
  operationId: nativeResult.operationId,
@@ -346,27 +750,63 @@ export class FinalCutCanonicalNativeProvider {
346
750
  };
347
751
  try {
348
752
  const after = await this.readProject();
349
- const afterClip = after.timeline.clips.find(({ id }) => id === operation.clipId);
350
- if (!afterClip || afterClip.name !== operation.name) {
351
- throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: renamed occurrence was not read back from Final Cut");
753
+ if (supported.type === "rename-clip") {
754
+ const readback = verifyCanonicalReadback(before, after, timelineTarget, {
755
+ validateDiff: (diff) => {
756
+ const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
757
+ const changed = diff.modified.filter(({ itemId }) => itemId === supported.clipId);
758
+ if (!afterClip || afterClip.name !== supported.name
759
+ || diff.added.length !== 0
760
+ || diff.removed.length !== 0
761
+ || diff.modified.length !== 1
762
+ || changed.length !== 1
763
+ || diff.markerChanges.length !== 0
764
+ || diff.storyElementChanges.length !== 0
765
+ || diff.captionChanges.length !== 0
766
+ || diff.mediaChanges.length !== 0) {
767
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: renamed occurrence was not read back as a rename-only diff from Final Cut");
768
+ }
769
+ },
770
+ });
771
+ if (readback.beforeDigest !== this.pending.beforeDigest) {
772
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: canonical before digest changed during verification");
773
+ }
774
+ }
775
+ else if (supported.type === "trim-clip") {
776
+ const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
777
+ if (!afterClip || !sameRational(afterClip.startTime, clip.startTime)
778
+ || !sameRational(afterClip.durationTime, trimDuration)) {
779
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: trimmed occurrence range was not read back from Final Cut");
780
+ }
781
+ }
782
+ else if (supported.type === "set-gain") {
783
+ const afterClip = after.timeline.clips.find(({ id }) => id === supported.clipId);
784
+ if (!afterClip || (afterClip.gainDb ?? 0) !== supported.gainDb) {
785
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: gain was not read back from Final Cut");
786
+ }
787
+ }
788
+ else if (supported.type === "ripple-delete") {
789
+ assertRippleDeleteReadback(before, after, rippleTarget.clip, rippleTarget.range);
790
+ }
791
+ else {
792
+ assertMarkerReadback(before, after, supported.marker, markerRange);
352
793
  }
353
794
  if (canonicalSnapshotDigest(after) === this.pending.beforeDigest) {
354
795
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native edit did not change the canonical digest");
355
796
  }
356
- assertTimelineTargetReadAfterWrite(timelineTarget, before, after);
797
+ assertTimelineTargetReadAfterWrite(timelineTarget, before, after, supported.type === "ripple-delete" ? { allowOccurrenceRemoval: true } : undefined);
357
798
  this.pending.afterRevision = after.revision;
358
799
  return after.revision;
359
800
  }
360
801
  catch (error) {
361
802
  try {
362
- const undone = await this.native.undo(nativeResult.operationId);
363
- if (!undone.undone || undone.verification?.verified !== true) {
364
- throw new Error("native Undo did not verify restoration");
365
- }
366
- const restored = await this.readProject();
367
- if (canonicalSnapshotDigest(restored) !== this.pending.beforeDigest) {
368
- throw new Error("restored canonical digest does not match the pre-edit state");
369
- }
803
+ await recoverCanonicalNativeMutation({
804
+ operationId: nativeResult.operationId,
805
+ before,
806
+ target: timelineTarget,
807
+ undo: this.native.undo,
808
+ readSnapshot: () => this.readProject(),
809
+ });
370
810
  }
371
811
  catch (rollbackError) {
372
812
  const original = error instanceof Error ? error.message : String(error);
@@ -493,16 +933,449 @@ export class FinalCutCanonicalNativeProvider {
493
933
  }
494
934
  }
495
935
  function supportedCanonicalOperation(operations) {
496
- if (operations.length !== 1 || operations[0]?.type !== "rename-clip") {
497
- throw new Error("CAPABILITY_UNAVAILABLE: final-cut native canonical provider supports one rename-clip transaction");
936
+ 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")) {
937
+ throw new Error("CAPABILITY_UNAVAILABLE: final-cut native canonical provider supports one rename-clip, trim-clip, add-marker, ripple-delete, or set-gain transaction");
938
+ }
939
+ return operations[0].type === "rename-clip"
940
+ ? validateCanonicalRename(operations[0])
941
+ : operations[0].type === "add-marker"
942
+ ? validateCanonicalMarker(operations[0])
943
+ : operations[0].type === "set-gain"
944
+ ? validateCanonicalGain(operations[0])
945
+ : operations[0];
946
+ }
947
+ function canonicalTargetForOperation(snapshot, operation) {
948
+ if (operation.type === "rename-clip" || operation.type === "trim-clip" || operation.type === "set-gain") {
949
+ const clip = snapshot.timeline.clips.find(({ id }) => id === operation.clipId);
950
+ if (!clip)
951
+ throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
952
+ return { clip };
953
+ }
954
+ if (operation.timelineId !== snapshot.timeline.id) {
955
+ throw new Error(`TIMELINE_NOT_FOUND: ${operation.timelineId}`);
956
+ }
957
+ const range = canonicalRippleRange(snapshot, operation.range);
958
+ const candidates = snapshot.timeline.clips.filter((candidate) => {
959
+ const end = addRational(candidate.startTime, candidate.durationTime);
960
+ return compareRational(candidate.startTime, range.end) < 0 && compareRational(end, range.start) > 0;
961
+ });
962
+ if (candidates.length === 0) {
963
+ throw new Error("TARGET_NOT_FOUND: ripple-delete range does not intersect a timeline occurrence");
964
+ }
965
+ if (candidates.length > 1) {
966
+ throw new Error("AMBIGUOUS_TIMELINE_TARGET: ripple-delete range intersects multiple timeline occurrences");
967
+ }
968
+ const clip = candidates[0];
969
+ const clipEnd = addRational(clip.startTime, clip.durationTime);
970
+ if (compareRational(range.start, clip.startTime) < 0 || compareRational(range.end, clipEnd) > 0) {
971
+ throw new Error("INVALID_OPERATION: ripple-delete range must fit inside one timeline occurrence");
972
+ }
973
+ if (compareRational(range.start, clip.startTime) > 0 && compareRational(range.end, clipEnd) < 0) {
974
+ throw new Error("INVALID_OPERATION: ripple-delete middle-of-clip range requires a source-preserving split");
975
+ }
976
+ return { clip, range };
977
+ }
978
+ function projectCanonicalOperation(snapshot, operation) {
979
+ if (operation.type === "rename-clip" || operation.type === "set-gain") {
980
+ const { clip } = canonicalTargetForOperation(snapshot, operation);
981
+ return {
982
+ ...structuredClone(snapshot),
983
+ timeline: {
984
+ ...structuredClone(snapshot.timeline),
985
+ clips: snapshot.timeline.clips.map((candidate) => {
986
+ if (candidate.id !== clip.id)
987
+ return candidate;
988
+ return operation.type === "rename-clip"
989
+ ? { ...candidate, name: operation.name }
990
+ : { ...candidate, gainDb: operation.gainDb };
991
+ }),
992
+ },
993
+ };
994
+ }
995
+ if (operation.type === "trim-clip") {
996
+ const preview = structuredClone(snapshot);
997
+ const { clip } = canonicalTargetForOperation(preview, operation);
998
+ const trimDuration = validateCanonicalTrim(operation, clip, preview);
999
+ const updatedClip = {
1000
+ ...clip,
1001
+ duration: rationalSeconds(trimDuration),
1002
+ durationTime: trimDuration,
1003
+ };
1004
+ preview.timeline.clips = preview.timeline.clips.map((candidate) => (candidate.id === clip.id ? updatedClip : candidate));
1005
+ preview.timeline.storyElements = preview.timeline.storyElements.map((element) => (element.id === clip.id
1006
+ ? { ...element, duration: updatedClip.duration, durationTime: updatedClip.durationTime }
1007
+ : element));
1008
+ const oldTimelineEnd = snapshot.timeline.durationTime
1009
+ ? addRational(clip.startTime, clip.durationTime)
1010
+ : undefined;
1011
+ if (oldTimelineEnd && snapshot.timeline.durationTime && sameRational(oldTimelineEnd, snapshot.timeline.durationTime)) {
1012
+ const nextTimelineEnd = addRational(clip.startTime, trimDuration);
1013
+ preview.timeline.durationTime = nextTimelineEnd;
1014
+ preview.timeline.duration = rationalSeconds(nextTimelineEnd);
1015
+ }
1016
+ return preview;
1017
+ }
1018
+ if (operation.type === "ripple-delete") {
1019
+ const target = canonicalTargetForOperation(snapshot, operation);
1020
+ return projectCanonicalRippleDelete(snapshot, target.range);
1021
+ }
1022
+ const range = canonicalMarkerRange(snapshot, operation.marker);
1023
+ if (snapshot.timeline.markers.some(({ id }) => id === operation.marker.id)) {
1024
+ throw new Error(`MARKER_ALREADY_EXISTS: ${operation.marker.id}`);
1025
+ }
1026
+ const marker = {
1027
+ ...structuredClone(operation.marker),
1028
+ start: rationalSeconds(range.start),
1029
+ duration: rationalSeconds(range.duration),
1030
+ startTime: range.start,
1031
+ durationTime: range.duration,
1032
+ };
1033
+ return {
1034
+ ...structuredClone(snapshot),
1035
+ timeline: {
1036
+ ...structuredClone(snapshot.timeline),
1037
+ markers: [...snapshot.timeline.markers, marker],
1038
+ },
1039
+ };
1040
+ }
1041
+ function projectCanonicalRippleDelete(snapshot, range) {
1042
+ const duration = subtractRational(range.end, range.start);
1043
+ const clips = snapshot.timeline.clips.flatMap((clip) => projectClipAfterRippleDelete(clip, range, duration));
1044
+ const storyElements = snapshot.timeline.storyElements.flatMap((element) => projectStoryElementAfterRippleDelete(element, range, duration));
1045
+ const markers = snapshot.timeline.markers.flatMap((marker) => projectMarkerAfterRippleDelete(marker, range, duration));
1046
+ const captions = snapshot.timeline.captions.flatMap((caption) => projectCaptionAfterRippleDelete(caption, range, duration));
1047
+ const timelineDuration = subtractRational(snapshot.timeline.durationTime ?? secondsToRational(snapshot.timeline.duration, snapshot.timeline.frameDuration), duration);
1048
+ return {
1049
+ ...structuredClone(snapshot),
1050
+ timeline: {
1051
+ ...structuredClone(snapshot.timeline),
1052
+ duration: rationalSeconds(timelineDuration),
1053
+ durationTime: timelineDuration,
1054
+ clips,
1055
+ storyElements,
1056
+ markers,
1057
+ captions,
1058
+ },
1059
+ };
1060
+ }
1061
+ function projectClipAfterRippleDelete(clip, range, removedDuration) {
1062
+ const clipEnd = addRational(clip.startTime, clip.durationTime);
1063
+ if (compareRational(clipEnd, range.start) <= 0)
1064
+ return [structuredClone(clip)];
1065
+ if (compareRational(clip.startTime, range.end) >= 0) {
1066
+ const startTime = subtractRational(clip.startTime, removedDuration);
1067
+ return [{ ...structuredClone(clip), start: rationalSeconds(startTime), startTime }];
1068
+ }
1069
+ if (compareRational(clip.startTime, range.start) < 0) {
1070
+ const duration = subtractRational(range.start, clip.startTime);
1071
+ return compareRational(duration, zeroRational()) > 0
1072
+ ? [{ ...structuredClone(clip), duration: rationalSeconds(duration), durationTime: duration }]
1073
+ : [];
1074
+ }
1075
+ if (compareRational(clipEnd, range.end) > 0) {
1076
+ const duration = subtractRational(clipEnd, range.end);
1077
+ return [{
1078
+ ...structuredClone(clip),
1079
+ start: rationalSeconds(range.start),
1080
+ startTime: structuredClone(range.start),
1081
+ duration: rationalSeconds(duration),
1082
+ durationTime: duration,
1083
+ }];
1084
+ }
1085
+ return [];
1086
+ }
1087
+ function projectStoryElementAfterRippleDelete(element, range, removedDuration) {
1088
+ if (!element.startTime || !element.durationTime)
1089
+ return [structuredClone(element)];
1090
+ const elementEnd = addRational(element.startTime, element.durationTime);
1091
+ if (compareRational(elementEnd, range.start) <= 0)
1092
+ return [structuredClone(element)];
1093
+ if (compareRational(element.startTime, range.end) >= 0) {
1094
+ const startTime = subtractRational(element.startTime, removedDuration);
1095
+ return [{ ...structuredClone(element), start: rationalSeconds(startTime), startTime }];
1096
+ }
1097
+ if (compareRational(element.startTime, range.start) < 0) {
1098
+ const duration = subtractRational(range.start, element.startTime);
1099
+ return compareRational(duration, zeroRational()) > 0
1100
+ ? [{ ...structuredClone(element), duration: rationalSeconds(duration), durationTime: duration }]
1101
+ : [];
1102
+ }
1103
+ if (compareRational(elementEnd, range.end) > 0) {
1104
+ const duration = subtractRational(elementEnd, range.end);
1105
+ return [{
1106
+ ...structuredClone(element),
1107
+ start: rationalSeconds(range.start),
1108
+ startTime: structuredClone(range.start),
1109
+ duration: rationalSeconds(duration),
1110
+ durationTime: duration,
1111
+ }];
1112
+ }
1113
+ return [];
1114
+ }
1115
+ function projectMarkerAfterRippleDelete(marker, range, removedDuration) {
1116
+ const start = marker.startTime ?? secondsToRational(marker.start, undefined);
1117
+ const duration = marker.durationTime ?? secondsToRational(marker.duration, undefined);
1118
+ const end = addRational(start, duration);
1119
+ if (compareRational(end, range.start) <= 0)
1120
+ return [structuredClone(marker)];
1121
+ if (compareRational(start, range.end) >= 0) {
1122
+ const shifted = subtractRational(start, removedDuration);
1123
+ return [{ ...structuredClone(marker), start: rationalSeconds(shifted), startTime: shifted }];
1124
+ }
1125
+ return [];
1126
+ }
1127
+ function projectCaptionAfterRippleDelete(caption, range, removedDuration) {
1128
+ const start = caption.startTime ?? secondsToRational(caption.start, undefined);
1129
+ const duration = caption.durationTime ?? secondsToRational(caption.duration, undefined);
1130
+ const end = addRational(start, duration);
1131
+ if (compareRational(end, range.start) <= 0)
1132
+ return [structuredClone(caption)];
1133
+ if (compareRational(start, range.end) >= 0) {
1134
+ const shifted = subtractRational(start, removedDuration);
1135
+ return [{ ...structuredClone(caption), start: rationalSeconds(shifted), startTime: shifted }];
1136
+ }
1137
+ return [];
1138
+ }
1139
+ function canonicalRippleRange(snapshot, range) {
1140
+ const frameDuration = snapshot.timeline.frameDuration;
1141
+ if (!frameDuration)
1142
+ throw new Error("CAPABILITY_UNAVAILABLE: ripple-delete requires sequence frame duration");
1143
+ if (!Number.isFinite(range.start) || !Number.isFinite(range.end) || range.end <= range.start) {
1144
+ throw new Error("INVALID_OPERATION: ripple-delete range must be finite and increasing");
1145
+ }
1146
+ const start = range.startTime ?? secondsToRational(range.start, frameDuration);
1147
+ const duration = range.durationTime ?? secondsToRational(range.end - range.start, frameDuration);
1148
+ if (Math.abs(rationalSeconds(start) - range.start) > 0.000001
1149
+ || Math.abs(rationalSeconds(duration) - (range.end - range.start)) > 0.000001) {
1150
+ throw new Error("INVALID_OPERATION: ripple-delete rational range disagrees with its numeric coordinates");
1151
+ }
1152
+ if (compareRational(duration, zeroRational()) <= 0) {
1153
+ throw new Error("INVALID_OPERATION: ripple-delete range must have positive duration");
1154
+ }
1155
+ const end = addRational(start, duration);
1156
+ if (!isFrameAligned(start, zeroRational(), frameDuration) || !isFrameAligned(end, zeroRational(), frameDuration)) {
1157
+ throw new Error("INVALID_OPERATION: ripple-delete range must be frame-aligned");
1158
+ }
1159
+ const timelineDuration = snapshot.timeline.durationTime ?? secondsToRational(snapshot.timeline.duration, frameDuration);
1160
+ if (compareRational(start, zeroRational()) < 0 || compareRational(end, timelineDuration) > 0) {
1161
+ throw new Error("INVALID_OPERATION: ripple-delete range must fit inside the active timeline");
498
1162
  }
499
- return validateCanonicalRename(operations[0]);
1163
+ return { start, end };
1164
+ }
1165
+ function assertRippleDeleteReadback(before, after, targetClip, range) {
1166
+ const expected = projectCanonicalRippleDelete(before, range);
1167
+ if (canonicalSnapshotDigest(normalizeRippleSnapshot(after)) !== canonicalSnapshotDigest(normalizeRippleSnapshot(expected))) {
1168
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete readback differed from the exact canonical projection");
1169
+ }
1170
+ if (!after.timeline.durationTime || !expected.timeline.durationTime
1171
+ || !sameRational(after.timeline.durationTime, expected.timeline.durationTime)) {
1172
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete duration was not read back exactly");
1173
+ }
1174
+ const expectedTarget = expected.timeline.clips.find(({ id }) => id === targetClip.id);
1175
+ const actualTarget = after.timeline.clips.find(({ id }) => id === targetClip.id);
1176
+ if (Boolean(expectedTarget) !== Boolean(actualTarget)) {
1177
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete target occurrence changed unexpectedly");
1178
+ }
1179
+ if (expectedTarget && actualTarget && (!sameRational(expectedTarget.startTime, actualTarget.startTime)
1180
+ || !sameRational(expectedTarget.durationTime, actualTarget.durationTime))) {
1181
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete target range was not read back exactly");
1182
+ }
1183
+ for (const expectedClip of expected.timeline.clips) {
1184
+ const beforeClip = before.timeline.clips.find(({ id }) => id === expectedClip.id);
1185
+ if (!beforeClip || compareRational(beforeClip.startTime, range.end) < 0)
1186
+ continue;
1187
+ const actualClip = after.timeline.clips.find(({ id }) => id === expectedClip.id);
1188
+ if (!actualClip || !sameRational(actualClip.startTime, expectedClip.startTime)) {
1189
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: ripple-delete did not preserve the shifted occurrence coordinates");
1190
+ }
1191
+ }
1192
+ }
1193
+ function normalizeRippleSnapshot(snapshot) {
1194
+ const normalized = structuredClone(snapshot);
1195
+ normalized.timeline.durationTime = normalized.timeline.durationTime
1196
+ ? normalizeRationalTime(normalized.timeline.durationTime)
1197
+ : normalized.timeline.durationTime;
1198
+ normalized.timeline.clips = normalized.timeline.clips.map((clip) => ({
1199
+ ...clip,
1200
+ startTime: normalizeRationalTime(clip.startTime),
1201
+ durationTime: normalizeRationalTime(clip.durationTime),
1202
+ }));
1203
+ normalized.timeline.storyElements = normalized.timeline.storyElements.map((element) => ({
1204
+ ...element,
1205
+ ...(element.startTime ? { startTime: normalizeRationalTime(element.startTime) } : {}),
1206
+ ...(element.durationTime ? { durationTime: normalizeRationalTime(element.durationTime) } : {}),
1207
+ }));
1208
+ normalized.timeline.markers = normalized.timeline.markers.map((marker) => ({
1209
+ ...marker,
1210
+ ...(marker.startTime ? { startTime: normalizeRationalTime(marker.startTime) } : {}),
1211
+ ...(marker.durationTime ? { durationTime: normalizeRationalTime(marker.durationTime) } : {}),
1212
+ }));
1213
+ normalized.timeline.captions = normalized.timeline.captions.map((caption) => ({
1214
+ ...caption,
1215
+ ...(caption.startTime ? { startTime: normalizeRationalTime(caption.startTime) } : {}),
1216
+ ...(caption.durationTime ? { durationTime: normalizeRationalTime(caption.durationTime) } : {}),
1217
+ }));
1218
+ return normalized;
1219
+ }
1220
+ function normalizeRationalTime(value) {
1221
+ const [numerator, denominator] = rationalParts(value);
1222
+ return normalizeRational(numerator, denominator);
1223
+ }
1224
+ function canonicalMarkerRange(snapshot, marker) {
1225
+ if (!marker.id.trim() || !marker.name.trim())
1226
+ throw new Error("INVALID_OPERATION: marker id and name are required");
1227
+ if (!Number.isFinite(marker.start) || !Number.isFinite(marker.duration) || marker.start < 0 || marker.duration < 0) {
1228
+ throw new Error("INVALID_OPERATION: marker position and duration must be finite and non-negative");
1229
+ }
1230
+ const frameDuration = snapshot.timeline.frameDuration;
1231
+ if (!frameDuration)
1232
+ throw new Error("CAPABILITY_UNAVAILABLE: marker requires sequence frame duration");
1233
+ const start = marker.startTime ?? secondsToRational(marker.start, frameDuration);
1234
+ const duration = marker.durationTime ?? secondsToRational(marker.duration, frameDuration);
1235
+ if (Math.abs(rationalSeconds(start) - marker.start) > 0.000001
1236
+ || Math.abs(rationalSeconds(duration) - marker.duration) > 0.000001) {
1237
+ throw new Error("INVALID_OPERATION: marker rational coordinates disagree with numeric coordinates");
1238
+ }
1239
+ const end = addRational(start, duration);
1240
+ const timelineDuration = snapshot.timeline.durationTime ?? secondsToRational(snapshot.timeline.duration, frameDuration);
1241
+ if (!isFrameAligned(start, zeroRational(), frameDuration) || !isFrameAligned(duration, zeroRational(), frameDuration)
1242
+ || compareRational(end, timelineDuration) > 0) {
1243
+ throw new Error("INVALID_OPERATION: marker must be frame-aligned and fit inside the active timeline");
1244
+ }
1245
+ return { start, duration, end };
1246
+ }
1247
+ function assertMarkerReadback(before, after, marker, range) {
1248
+ const matches = after.timeline.markers.filter((candidate) => candidate.name === marker.name
1249
+ && sameRational(candidate.startTime ?? secondsToRational(candidate.start), range.start)
1250
+ && sameRational(candidate.durationTime ?? secondsToRational(candidate.duration), range.duration));
1251
+ const beforeMatches = before.timeline.markers.filter((candidate) => candidate.name === marker.name
1252
+ && sameRational(candidate.startTime ?? secondsToRational(candidate.start), range.start)
1253
+ && sameRational(candidate.durationTime ?? secondsToRational(candidate.duration), range.duration));
1254
+ if (matches.length !== beforeMatches.length + 1) {
1255
+ throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native marker was not uniquely read back at the requested rational position");
1256
+ }
1257
+ }
1258
+ function assertCanonicalOperationAvailable(native, operation) {
1259
+ if (operation.type === "trim-clip" && !native.trimSelectedClipToRange) {
1260
+ throw new Error("CAPABILITY_UNAVAILABLE: final-cut native canonical trim");
1261
+ }
1262
+ }
1263
+ function parseRationalTime(value, label) {
1264
+ if (!value || !/^-?\d+$/.test(value.value) || !/^\d+$/.test(value.timescale) || value.timescale === "0") {
1265
+ throw new Error(`${label} must be an integer rational`);
1266
+ }
1267
+ return { value: BigInt(value.value), timescale: BigInt(value.timescale) };
1268
+ }
1269
+ function validateCanonicalTrim(operation, clip, snapshot) {
1270
+ if (!operation.durationTime) {
1271
+ throw new Error("INVALID_OPERATION: native trim requires an exact durationTime");
1272
+ }
1273
+ const duration = parseRationalTime(operation.durationTime, "INVALID_OPERATION: trim durationTime");
1274
+ const currentDuration = parseRationalTime(clip.durationTime, "INVALID_PROJECT_STATE: clip durationTime");
1275
+ if (duration.value <= 0n || compareRational(operation.durationTime, clip.durationTime) >= 0) {
1276
+ throw new Error("INVALID_OPERATION: native trim duration must be shorter than the current occurrence");
1277
+ }
1278
+ if (!Number.isFinite(operation.duration)
1279
+ || Math.abs(operation.duration - Number(duration.value) / Number(duration.timescale)) > 1e-9) {
1280
+ throw new Error("INVALID_OPERATION: trim duration and durationTime must agree");
1281
+ }
1282
+ const frame = snapshot.timeline.frameDuration;
1283
+ if (!frame || !isFrameAligned(operation.durationTime, zeroRational(), frame)) {
1284
+ throw new Error("FRAME_ALIGNMENT_REQUIRED: native trim duration must align to the sequence frame duration");
1285
+ }
1286
+ if (currentDuration.value <= 0n)
1287
+ throw new Error("INVALID_PROJECT_STATE: clip durationTime must be positive");
1288
+ return structuredClone(operation.durationTime);
500
1289
  }
501
1290
  function validateCanonicalRename(operation) {
502
1291
  if (!operation.name.trim())
503
1292
  throw new Error("INVALID_OPERATION: clip name cannot be empty");
504
1293
  return operation;
505
1294
  }
1295
+ function validateCanonicalMarker(operation) {
1296
+ return operation;
1297
+ }
1298
+ function validateCanonicalGain(operation) {
1299
+ if (!Number.isFinite(operation.gainDb))
1300
+ throw new Error("INVALID_OPERATION: gain must be finite");
1301
+ if (operation.gainDb < -6 || operation.gainDb > 6) {
1302
+ throw new Error("INVALID_OPERATION: gain must be between -6 and 6 dB");
1303
+ }
1304
+ return operation;
1305
+ }
1306
+ function sameRational(left, right) {
1307
+ try {
1308
+ const [leftValue, leftScale] = rationalParts(left);
1309
+ const [rightValue, rightScale] = rationalParts(right);
1310
+ return leftValue * rightScale === rightValue * leftScale;
1311
+ }
1312
+ catch {
1313
+ return false;
1314
+ }
1315
+ }
1316
+ function rationalParts(value) {
1317
+ const numerator = BigInt(value.value);
1318
+ const denominator = BigInt(value.timescale);
1319
+ if (denominator <= 0n)
1320
+ throw new Error("INVALID_OPERATION: rational timescale must be positive");
1321
+ return [numerator, denominator];
1322
+ }
1323
+ function normalizeRational(numerator, denominator) {
1324
+ const divisor = gcd(numerator < 0n ? -numerator : numerator, denominator);
1325
+ return { value: (numerator / divisor).toString(), timescale: (denominator / divisor).toString() };
1326
+ }
1327
+ function gcd(left, right) {
1328
+ let a = left;
1329
+ let b = right;
1330
+ while (b !== 0n) {
1331
+ const remainder = a % b;
1332
+ a = b;
1333
+ b = remainder;
1334
+ }
1335
+ return a || 1n;
1336
+ }
1337
+ function addRational(left, right) {
1338
+ const [leftValue, leftScale] = rationalParts(left);
1339
+ const [rightValue, rightScale] = rationalParts(right);
1340
+ return normalizeRational(leftValue * rightScale + rightValue * leftScale, leftScale * rightScale);
1341
+ }
1342
+ function subtractRational(left, right) {
1343
+ const [leftValue, leftScale] = rationalParts(left);
1344
+ const [rightValue, rightScale] = rationalParts(right);
1345
+ return normalizeRational(leftValue * rightScale - rightValue * leftScale, leftScale * rightScale);
1346
+ }
1347
+ function compareRational(left, right) {
1348
+ const [leftValue, leftScale] = rationalParts(left);
1349
+ const [rightValue, rightScale] = rationalParts(right);
1350
+ const difference = leftValue * rightScale - rightValue * leftScale;
1351
+ return difference < 0n ? -1 : difference > 0n ? 1 : 0;
1352
+ }
1353
+ function isFrameAligned(value, origin, frameDuration) {
1354
+ const [valueNumerator, valueDenominator] = rationalParts(normalizeRational(rationalParts(value)[0] * rationalParts(origin)[1] - rationalParts(origin)[0] * rationalParts(value)[1], rationalParts(value)[1] * rationalParts(origin)[1]));
1355
+ const [frameNumerator, frameDenominator] = rationalParts(frameDuration);
1356
+ return (valueNumerator * frameDenominator) % (valueDenominator * frameNumerator) === 0n;
1357
+ }
1358
+ function zeroRational() {
1359
+ return { value: "0", timescale: "1" };
1360
+ }
1361
+ function rationalSeconds(value) {
1362
+ const [numerator, denominator] = rationalParts(value);
1363
+ return Number(numerator) / Number(denominator);
1364
+ }
1365
+ function secondsToRational(seconds, frameDuration) {
1366
+ if (!Number.isFinite(seconds))
1367
+ throw new Error("INVALID_OPERATION: time must be finite");
1368
+ if (frameDuration) {
1369
+ const frameSeconds = rationalSeconds(frameDuration);
1370
+ const frames = Math.round(seconds / frameSeconds);
1371
+ if (Math.abs(seconds - frames * frameSeconds) > 0.000001)
1372
+ throw new Error("INVALID_OPERATION: time must be frame-aligned");
1373
+ const [frameValue, frameScale] = rationalParts(frameDuration);
1374
+ return normalizeRational(BigInt(frames) * frameValue, frameScale);
1375
+ }
1376
+ const scaled = BigInt(Math.round(seconds * 1_000_000_000));
1377
+ return normalizeRational(scaled, 1000000000n);
1378
+ }
506
1379
  function unavailableCanonicalSnapshot(reason) {
507
1380
  return {
508
1381
  available: false,
@@ -538,27 +1411,34 @@ async function executeCanonicalAppleScript(script) {
538
1411
  throw new Error(`FINAL_CUT_CANONICAL_AUTOMATION_FAILED: ${detail}`);
539
1412
  }
540
1413
  }
541
- async function readCanonicalExport(path, timeoutMs, pollIntervalMs) {
1414
+ async function readCanonicalExport(path, timeoutMs, pollIntervalMs, target) {
542
1415
  const deadline = Date.now() + timeoutMs;
543
1416
  let previousSignature;
544
1417
  let lastReadError;
545
1418
  while (Date.now() <= deadline) {
1419
+ let readablePath;
546
1420
  let signature;
547
- try {
548
- const details = await stat(path);
549
- if (details.isFile() && details.size > 0) {
550
- signature = `${details.size}:${details.mtimeMs}`;
1421
+ for (const candidatePath of [path, join(`${path}.fcpxmld`, "Info.fcpxml")]) {
1422
+ try {
1423
+ const details = await stat(candidatePath);
1424
+ if (details.isFile() && details.size > 0) {
1425
+ readablePath = candidatePath;
1426
+ signature = `${candidatePath}:${details.size}:${details.mtimeMs}`;
1427
+ break;
1428
+ }
1429
+ }
1430
+ catch {
1431
+ // The Save dialog or Final Cut directory package may still be open.
551
1432
  }
552
1433
  }
553
- catch {
554
- // The Save dialog may still be open.
555
- }
556
- if (signature && signature === previousSignature) {
1434
+ if (readablePath && signature && signature === previousSignature) {
557
1435
  try {
558
- return await new FcpxmlDocumentAdapter(path).readProject();
1436
+ return await new FcpxmlDocumentAdapter(readablePath, target).readProject();
559
1437
  }
560
1438
  catch (error) {
561
1439
  lastReadError = error;
1440
+ if (error instanceof Error && error.message.includes("TARGET_MISMATCH"))
1441
+ throw error;
562
1442
  }
563
1443
  }
564
1444
  previousSignature = signature;