@morshoto/framekit 0.1.17 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +25 -14
  2. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +8 -2
  3. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.js +275 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical.js +557 -84
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +10 -3
  6. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +6 -0
  7. package/dist-package/adapters/final-cut/typescript/src/experimental.js +8 -0
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +150 -37
  9. package/dist-package/adapters/final-cut/typescript/src/index.js +2 -7
  10. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +60 -1
  11. package/dist-package/adapters/final-cut/typescript/src/live.js +29 -4
  12. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.js +175 -0
  13. package/dist-package/adapters/final-cut/typescript/src/native-session.js +11 -6
  14. package/dist-package/adapters/final-cut/typescript/src/native.js +201 -82
  15. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +214 -0
  16. package/dist-package/adapters/final-cut/typescript/src/publisher.js +1008 -243
  17. package/dist-package/adapters/final-cut/typescript/src/session.js +49 -14
  18. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +203 -49
  19. package/dist-package/adapters/headless/typescript/src/audio-output.js +3 -0
  20. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +48 -20
  21. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +9 -4
  22. package/dist-package/apps/cli/src/dev-doctor.js +198 -0
  23. package/dist-package/apps/cli/src/headless-projects.js +5 -0
  24. package/dist-package/apps/cli/src/main.js +76 -19
  25. package/dist-package/apps/mcp-server/runtime/speech-analyzer-wrapper.mjs +54 -0
  26. package/dist-package/apps/mcp-server/runtime/whisper-speech-backend.py +181 -0
  27. package/dist-package/apps/mcp-server/src/build-alignment.js +59 -0
  28. package/dist-package/apps/mcp-server/src/build-identity.js +30 -0
  29. package/dist-package/apps/mcp-server/src/build-identity.json +5 -0
  30. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.js +18 -0
  31. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.js +3 -0
  32. package/dist-package/apps/mcp-server/src/headless-project-snapshot.js +101 -0
  33. package/dist-package/apps/mcp-server/src/main.js +50 -21
  34. package/dist-package/apps/mcp-server/src/materialization-jobs.js +143 -10
  35. package/dist-package/apps/mcp-server/src/routing.js +2 -0
  36. package/dist-package/apps/mcp-server/src/server.js +986 -180
  37. package/dist-package/apps/mcp-server/src/tools/skills/catalog.js +142 -0
  38. package/dist-package/apps/mcp-server/src/tools/skills/metadata.js +71 -0
  39. package/dist-package/apps/mcp-server/src/tools/skills/register.js +101 -0
  40. package/dist-package/apps/mcp-server/src/version.js +21 -2
  41. package/dist-package/packages/headless-application/src/headless-projects.js +942 -0
  42. package/dist-package/packages/headless-application/src/index.js +1 -0
  43. package/dist-package/packages/runtime/src/application/media-analysis-service.js +15 -5
  44. package/dist-package/packages/runtime/src/application/project-service.js +5 -1
  45. package/dist-package/packages/runtime/src/application/project-store.js +13 -36
  46. package/dist-package/packages/runtime/src/application/transaction-store.js +1 -1
  47. package/dist-package/packages/runtime/src/capabilities.js +1 -1
  48. package/dist-package/packages/runtime/src/context/context-engine.js +22 -16
  49. package/dist-package/packages/runtime/src/context/context-service.js +2 -2
  50. package/dist-package/packages/runtime/src/editing/edit-service.js +76 -10
  51. package/dist-package/packages/runtime/src/index.js +1 -0
  52. package/dist-package/packages/runtime/src/runtime.js +22 -7
  53. package/dist-package/packages/runtime/src/timeline/editing-session.js +23 -2
  54. package/dist-package/packages/testkit/src/in-memory-editor.js +3 -3
  55. package/dist-package/packages/testkit/src/index.js +1 -0
  56. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.js +192 -0
  57. package/package.json +36 -14
  58. package/dist-package/apps/mcp-server/src/headless-projects.js +0 -370
@@ -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,6 +82,7 @@ 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;
@@ -87,6 +98,7 @@ export class FinalCutNativeAutomationAdapter {
87
98
  mediaImportDiscoveryTimeoutMs;
88
99
  mediaImportPollMs;
89
100
  requestContext = new AsyncLocalStorage();
101
+ dispatchContext = new AsyncLocalStorage();
90
102
  nativeUiDepth = 0;
91
103
  operations = new Map();
92
104
  latestOperationId;
@@ -105,6 +117,7 @@ export class FinalCutNativeAutomationAdapter {
105
117
  transitionPreviews = new Map();
106
118
  constructor(options = {}) {
107
119
  this.enabled = options.enabled ?? process.env.FRAMEKIT_FINAL_CUT_NATIVE_WRITES === "1";
120
+ this.homeDirectory = options.homeDirectory ?? homedir();
108
121
  this.titleDiscoveryAvailable = this.enabled;
109
122
  this.executor = options.executor ?? runAppleScript;
110
123
  this.nativeMouseExecutor = options.nativeMouseExecutor;
@@ -129,6 +142,7 @@ export class FinalCutNativeAutomationAdapter {
129
142
  mediaSelection: this.enabled,
130
143
  mediaAppendSelected: this.enabled,
131
144
  timelineOccurrenceLocate: this.enabled,
145
+ timelineOccurrenceSourceBinding: false,
132
146
  bladeAtPlayhead: this.enabled,
133
147
  deleteRange: this.enabled,
134
148
  trimToDuration: this.enabled,
@@ -172,7 +186,39 @@ export class FinalCutNativeAutomationAdapter {
172
186
  return unavailableContext("CAPABILITY_UNAVAILABLE", "Final Cut native writes are disabled; set FRAMEKIT_FINAL_CUT_NATIVE_WRITES=1");
173
187
  }
174
188
  try {
175
- return await this.attachLiveState(await this.ensureTimelineReady());
189
+ const focused = await this.attachLiveState(await this.ensureTimelineReady());
190
+ if (!this.liveState || focused.target.kind === "selected-clip")
191
+ return focused;
192
+ // Timeline focus and target selection are separate Accessibility states.
193
+ // Re-read the bounded selection tree after focus so a selected occurrence
194
+ // is not reported as a playhead-only target.
195
+ const reread = await this.inspectRawNative(undefined, passiveTimelinePreflightScript());
196
+ if (!reread.available)
197
+ return reread;
198
+ const targetScope = (context) => {
199
+ const target = context.target;
200
+ if (!target.projectId || !target.sequenceId || !target.revision?.id || !Number.isInteger(target.revision.sequence)) {
201
+ return undefined;
202
+ }
203
+ return {
204
+ projectId: target.projectId,
205
+ sequenceId: target.sequenceId,
206
+ revisionId: target.revision.id,
207
+ revisionSequence: target.revision.sequence,
208
+ };
209
+ };
210
+ const beforeScope = targetScope(focused);
211
+ const afterScope = targetScope(reread);
212
+ if (!beforeScope || !afterScope) {
213
+ return unavailableContext("FINAL_CUT_NATIVE_TARGET_BINDING_UNAVAILABLE", "Final Cut project, sequence, and revision could not be confirmed across focus recovery", reread);
214
+ }
215
+ if (beforeScope.projectId !== afterScope.projectId
216
+ || beforeScope.sequenceId !== afterScope.sequenceId
217
+ || beforeScope.revisionId !== afterScope.revisionId
218
+ || beforeScope.revisionSequence !== afterScope.revisionSequence) {
219
+ return unavailableContext("STALE_CONTEXT", "Final Cut project, sequence, or revision changed while resolving the selected occurrence", reread);
220
+ }
221
+ return reread;
176
222
  }
177
223
  catch (error) {
178
224
  return unavailableContext(nativeErrorCode(error), nativeErrorMessage(error), preflightContext(error));
@@ -196,10 +242,19 @@ export class FinalCutNativeAutomationAdapter {
196
242
  context.playheadTime = live.playheadTime
197
243
  ? `${live.playheadTime.value}/${live.playheadTime.timescale}`
198
244
  : undefined;
245
+ if (live.project?.id && live.sequence?.id) {
246
+ context.target = {
247
+ ...context.target,
248
+ projectId: live.project.id,
249
+ sequenceId: live.sequence.id,
250
+ revision: structuredClone(live.revision),
251
+ };
252
+ }
199
253
  }
200
254
  catch {
201
255
  // Native UI inspection remains useful when the optional live socket is down.
202
256
  }
257
+ context.readiness = readinessForContext(context);
203
258
  return context;
204
259
  }
205
260
  async readLiveState() {
@@ -220,6 +275,9 @@ export class FinalCutNativeAutomationAdapter {
220
275
  async edit(operation, options = {}) {
221
276
  return this.withNativeUi(() => this.editNative(operation), options.signal);
222
277
  }
278
+ async trackNativeDispatch(operation, onDispatch) {
279
+ return this.dispatchContext.run(onDispatch, operation);
280
+ }
223
281
  async trimSelectedClipToRange(range, options = {}) {
224
282
  return this.withNativeUi(() => this.trimSelectedClipToRangeNative(range), options.signal);
225
283
  }
@@ -394,7 +452,7 @@ export class FinalCutNativeAutomationAdapter {
394
452
  const trimmedPath = directoryPath.trim();
395
453
  if (!trimmedPath)
396
454
  throw new Error("INVALID_OPERATION: local media directory path cannot be empty");
397
- const normalizedPath = resolveLocalPath(trimmedPath);
455
+ const normalizedPath = resolveLocalPath(trimmedPath, this.homeDirectory);
398
456
  const snapshot = await snapshotSupportedVideoFiles(normalizedPath);
399
457
  const expiresAt = this.now() + 30_000;
400
458
  const previewToken = opaqueHandle("media-directory-preview");
@@ -434,7 +492,7 @@ export class FinalCutNativeAutomationAdapter {
434
492
  ...(diagnostics ? { diagnostics } : {}),
435
493
  });
436
494
  };
437
- const normalizedPath = resolveLocalPath(sourcePath);
495
+ const normalizedPath = resolveLocalPath(sourcePath, this.homeDirectory);
438
496
  const name = basename(normalizedPath);
439
497
  if (!sourcePath.trim())
440
498
  throw new Error("INVALID_OPERATION: local media path cannot be empty");
@@ -593,9 +651,18 @@ export class FinalCutNativeAutomationAdapter {
593
651
  };
594
652
  }
595
653
  async searchMedia(query, options = {}) {
654
+ const queryError = nativeMediaSearchQueryError(query);
655
+ if (queryError)
656
+ throw new Error(`${queryError.code}: ${queryError.message}`);
596
657
  return this.withNativeUi(() => this.searchMediaNative(query), options.signal);
597
658
  }
598
- async searchMediaNative(query, deadline, timeoutCode = "FINAL_CUT_NATIVE_MEDIA_IMPORT_TIMEOUT") {
659
+ async searchMediaForCanonicalTarget(query, options = {}) {
660
+ const queryError = nativeMediaSearchQueryError(query);
661
+ if (queryError)
662
+ throw new Error(`${queryError.code}: ${queryError.message}`);
663
+ return this.withNativeUi(() => this.searchMediaNative(query), options.signal);
664
+ }
665
+ async searchMediaNative(query, deadline, timeoutCode = "FINAL_CUT_NATIVE_SEARCH_TIMEOUT") {
599
666
  this.assertEnabled();
600
667
  if (!query.trim())
601
668
  throw new Error("INVALID_OPERATION: media search query cannot be empty");
@@ -712,14 +779,21 @@ export class FinalCutNativeAutomationAdapter {
712
779
  }
713
780
  const after = await this.requireAvailableContext();
714
781
  this.selectedMediaHandle = handle;
715
- return {
782
+ const context = {
716
783
  ...after,
717
784
  target: { kind: "browser-media", name: match.name, ...(match.role ? { role: match.role } : {}) },
718
785
  };
786
+ return { ...context, readiness: readinessForContext(context) };
719
787
  }
720
788
  async locateOccurrence(mediaHandle, options = {}) {
721
789
  return this.withNativeUi(() => this.locateOccurrenceNative(mediaHandle), options.signal);
722
790
  }
791
+ async locateOccurrenceForCanonicalTarget(mediaHandle, options = {}) {
792
+ if (this.capabilities().timelineOccurrenceSourceBinding !== true) {
793
+ throw new Error("CAPABILITY_UNAVAILABLE: canonical occurrence source binding is unavailable");
794
+ }
795
+ return this.withNativeUi(() => this.locateOccurrenceNative(mediaHandle, false, false), options.signal);
796
+ }
723
797
  async selectOccurrence(occurrenceHandle, options = {}) {
724
798
  return this.withNativeUi(() => this.selectOccurrenceNative(occurrenceHandle), options.signal);
725
799
  }
@@ -753,6 +827,9 @@ export class FinalCutNativeAutomationAdapter {
753
827
  throw new Error("FINAL_CUT_NATIVE_PLAYHEAD_UNAVAILABLE: deterministic targeting requires live playhead state");
754
828
  }
755
829
  const occurrence = located.occurrences[0];
830
+ if (!occurrence.sourceIdentity || occurrence.sourceIdentity !== media.sourceIdentity) {
831
+ throw new Error("FINAL_CUT_NATIVE_MEDIA_ID_UNAVAILABLE: timeline occurrence source identity was not independently observed");
832
+ }
756
833
  const occurrenceIdentity = occurrence.identity ?? occurrence.nativeIdentity;
757
834
  if (!occurrenceIdentity) {
758
835
  throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_IDENTITY_UNAVAILABLE: timeline occurrence has no stable identity");
@@ -769,10 +846,10 @@ export class FinalCutNativeAutomationAdapter {
769
846
  revision: structuredClone(live.revision),
770
847
  timelineStartTime: structuredClone(live.sequence.startTime),
771
848
  frameDuration: structuredClone(live.sequence.frameDuration),
772
- mediaId: occurrence.sourceIdentity ?? media.sourceIdentity,
849
+ mediaId: occurrence.sourceIdentity,
773
850
  occurrence: {
774
851
  id: occurrenceIdentity,
775
- mediaId: occurrence.sourceIdentity ?? media.sourceIdentity,
852
+ mediaId: occurrence.sourceIdentity,
776
853
  startTime: parseRationalString(occurrence.start, "occurrence start"),
777
854
  durationTime: parseRationalString(occurrence.duration, "occurrence duration"),
778
855
  },
@@ -788,7 +865,7 @@ export class FinalCutNativeAutomationAdapter {
788
865
  playheadTime: `${live.playheadTime.value}/${live.playheadTime.timescale}`,
789
866
  };
790
867
  }
791
- async locateOccurrenceNative(mediaHandle, scanAll = false) {
868
+ async locateOccurrenceNative(mediaHandle, scanAll = false, selectForIdentity = true) {
792
869
  this.assertEnabled();
793
870
  const match = this.mediaHandles.get(mediaHandle);
794
871
  if (!match)
@@ -801,20 +878,21 @@ export class FinalCutNativeAutomationAdapter {
801
878
  try {
802
879
  const liveBefore = this.liveState ? await this.liveState().catch(() => undefined) : undefined;
803
880
  let occurrenceOutput = "";
804
- for (let attempt = 0; attempt < 2; attempt += 1) {
881
+ const maxAttempts = selectForIdentity ? 2 : 1;
882
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
805
883
  try {
806
- occurrenceOutput = await this.executeNativeScript(locateOccurrenceScript(match, scanAll));
884
+ occurrenceOutput = await this.executeNativeScript(locateOccurrenceScript(match, scanAll, selectForIdentity));
807
885
  break;
808
886
  }
809
887
  catch (error) {
810
- if (attempt > 0)
888
+ if (attempt + 1 >= maxAttempts)
811
889
  throw error;
812
890
  await this.sleep(300);
813
891
  }
814
892
  }
815
893
  const occurrences = parseOccurrences(occurrenceOutput, mediaHandle);
816
894
  normalizeOccurrenceTimes(occurrences, liveBefore?.sequence);
817
- if (occurrences.length === 1 && this.canDriveNativeMouse) {
895
+ if (selectForIdentity && occurrences.length === 1 && this.canDriveNativeMouse) {
818
896
  const timelineOffset = occurrences[0]?.timelineOffset;
819
897
  if (timelineOffset === undefined) {
820
898
  throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_POSITION_UNAVAILABLE: unique timeline occurrence has no selectable position");
@@ -866,6 +944,10 @@ export class FinalCutNativeAutomationAdapter {
866
944
  if (context.target.kind !== "selected-clip") {
867
945
  throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_SELECTION_UNAVAILABLE: Final Cut did not expose the selected occurrence");
868
946
  }
947
+ const expectedIdentity = occurrence.nativeIdentity ?? occurrence.identity;
948
+ if (expectedIdentity && context.target.identity !== expectedIdentity) {
949
+ throw new Error("FINAL_CUT_NATIVE_OCCURRENCE_HANDLE_STALE: selected native occurrence identity changed");
950
+ }
869
951
  if (context.target.identity)
870
952
  occurrence.nativeIdentity = context.target.identity;
871
953
  return context;
@@ -2208,9 +2290,13 @@ export class FinalCutNativeAutomationAdapter {
2208
2290
  : expected.target.occurrenceIndex !== undefined && recovered.target.occurrenceIndex !== undefined
2209
2291
  ? expected.target.occurrenceIndex !== recovered.target.occurrenceIndex
2210
2292
  : true);
2293
+ const scopeChanged = expected.target.projectId !== recovered.target.projectId
2294
+ || expected.target.sequenceId !== recovered.target.sequenceId
2295
+ || expected.target.revision?.id !== recovered.target.revision?.id
2296
+ || expected.target.revision?.sequence !== recovered.target.revision?.sequence;
2211
2297
  const playheadChanged = requirePlayhead
2212
2298
  && (!expected.playheadTime || !recovered.playheadTime || expected.playheadTime !== recovered.playheadTime);
2213
- if (targetChanged || occurrenceChanged || playheadChanged) {
2299
+ if (targetChanged || occurrenceChanged || scopeChanged || playheadChanged) {
2214
2300
  throw new Error("FINAL_CUT_NATIVE_RETRY_TARGET_CHANGED: Final Cut selection or playhead changed during focus recovery");
2215
2301
  }
2216
2302
  }
@@ -2410,6 +2496,9 @@ export class FinalCutNativeAutomationAdapter {
2410
2496
  if (!context.readiness.selectedTarget) {
2411
2497
  throw new Error("FINAL_CUT_NATIVE_SELECTION_REQUIRED: position the playhead or select a timeline target in Final Cut Pro");
2412
2498
  }
2499
+ if (context.target.kind === "selected-clip" && !context.readiness.targetBound) {
2500
+ throw new Error("FINAL_CUT_NATIVE_TARGET_BINDING_UNAVAILABLE: selected occurrence is not bound to the active project, sequence, and revision");
2501
+ }
2413
2502
  }
2414
2503
  assertNativeRollbackReady(operationId, operation, record) {
2415
2504
  const evidence = record.rollbackEvidence ?? nativeRollbackEvidence(record);
@@ -2584,6 +2673,7 @@ export class FinalCutNativeAutomationAdapter {
2584
2673
  }
2585
2674
  async executeNativeMouseScript(source) {
2586
2675
  if (this.nativeMouseExecutor) {
2676
+ this.dispatchContext.getStore()?.();
2587
2677
  await this.nativeMouseExecutor(source);
2588
2678
  return;
2589
2679
  }
@@ -2616,6 +2706,7 @@ export class FinalCutNativeAutomationAdapter {
2616
2706
  requestSignal.addEventListener("abort", cancelListener, { once: true });
2617
2707
  })
2618
2708
  : undefined;
2709
+ this.dispatchContext.getStore()?.();
2619
2710
  const execution = execFile("swift", ["-e", source], { signal: controller.signal });
2620
2711
  try {
2621
2712
  await Promise.race([execution, timeout, ...(cancellation ? [cancellation] : [])]);
@@ -2668,6 +2759,7 @@ export class FinalCutNativeAutomationAdapter {
2668
2759
  requestSignal.addEventListener("abort", cancelListener, { once: true });
2669
2760
  })
2670
2761
  : undefined;
2762
+ this.dispatchContext.getStore()?.();
2671
2763
  const execution = this.executor(script, { signal: controller.signal });
2672
2764
  try {
2673
2765
  return await Promise.race([execution, timeout, ...(cancellation ? [cancellation] : [])]);
@@ -3249,9 +3341,10 @@ using terms from application "System Events"
3249
3341
  return parts
3250
3342
  end splitText
3251
3343
 
3252
- on selectedTimelineItem(containerItem, depth, mainOrigin, mainSize)
3253
- if depth > 6 then return ""
3254
- set output to ""
3344
+ on selectedTimelineSelection(containerItem, depth, mainOrigin, mainSize)
3345
+ if depth > 6 then return {0, ""}
3346
+ set selectedCount to 0
3347
+ set selectedRecord to ""
3255
3348
  repeat with candidateRef in UI elements of containerItem
3256
3349
  try
3257
3350
  set candidate to contents of candidateRef
@@ -3269,32 +3362,37 @@ using terms from application "System Events"
3269
3362
  set candidateSelected to (selected of candidate) is true
3270
3363
  end try
3271
3364
  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
3365
+ set selectedCount to selectedCount + 1
3366
+ if selectedRecord is "" then
3367
+ set candidateRole to role of candidate as text
3368
+ set candidateName to ""
3278
3369
  try
3279
- set candidateName to value of candidate as text
3370
+ set candidateName to description of candidate as text
3280
3371
  end try
3372
+ if candidateName is "" then
3373
+ try
3374
+ set candidateName to value of candidate as text
3375
+ end try
3376
+ end if
3377
+ if candidateName is "missing value" then set candidateName to ""
3378
+ set candidateIdentity to ""
3379
+ try
3380
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
3381
+ end try
3382
+ set selectedRecord to candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateIdentity
3281
3383
  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
3384
+ else
3385
+ set nestedSelection to my selectedTimelineSelection(candidate, depth + 1, mainOrigin, mainSize)
3386
+ set selectedCount to selectedCount + (item 1 of nestedSelection)
3387
+ if selectedRecord is "" then set selectedRecord to item 2 of nestedSelection
3288
3388
  end if
3289
- set output to my selectedTimelineItem(candidate, depth + 1, mainOrigin, mainSize)
3290
- if output is not "" then return output
3291
3389
  end if
3292
3390
  on error
3293
3391
  -- Ignore inaccessible descendants and continue the bounded scan.
3294
3392
  end try
3295
3393
  end repeat
3296
- return ""
3297
- end selectedTimelineItem
3394
+ return {selectedCount, selectedRecord}
3395
+ end selectedTimelineSelection
3298
3396
 
3299
3397
  on selectedTimelineOccurrenceIndex(timelineArea)
3300
3398
  set occurrenceIndex to 0
@@ -3352,14 +3450,15 @@ tell application "System Events"
3352
3450
  try
3353
3451
  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
3452
  set selectionLookupAvailable to true
3355
- set selectedRecord to my selectedTimelineItem(timelineArea, 0, mainOrigin, mainSize)
3453
+ set selectionResult to my selectedTimelineSelection(timelineArea, 0, mainOrigin, mainSize)
3454
+ set selectedCount to item 1 of selectionResult
3455
+ set selectedRecord to item 2 of selectionResult
3356
3456
  set selectedOccurrenceIndex to my selectedTimelineOccurrenceIndex(timelineArea)
3357
- if selectedRecord is not "" then
3457
+ if selectedCount is 1 and selectedRecord is not "" then
3358
3458
  set selectedFields to my splitText(selectedRecord, ASCII character 31)
3359
3459
  set selectedName to item 1 of selectedFields
3360
3460
  set selectedRole to item 2 of selectedFields
3361
3461
  set selectedIdentity to item 3 of selectedFields
3362
- set selectedCount to 1
3363
3462
  end if
3364
3463
  end try
3365
3464
  if not selectionLookupAvailable then set selectedCount to -1
@@ -3700,9 +3799,10 @@ function inspectScript() {
3700
3799
  return parts
3701
3800
  end splitText
3702
3801
 
3703
- on selectedTimelineItem(containerItem, depth, mainOrigin, mainSize)
3704
- if depth > 12 then return ""
3705
- set output to ""
3802
+ on selectedTimelineSelection(containerItem, depth, mainOrigin, mainSize)
3803
+ if depth > 12 then return {0, ""}
3804
+ set selectedCount to 0
3805
+ set selectedRecord to ""
3706
3806
  repeat with candidateRef in UI elements of containerItem
3707
3807
  try
3708
3808
  set candidate to contents of candidateRef
@@ -3721,32 +3821,37 @@ function inspectScript() {
3721
3821
  set candidateSelected to (selected of candidate) is true
3722
3822
  end try
3723
3823
  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
3824
+ set selectedCount to selectedCount + 1
3825
+ if selectedRecord is "" then
3826
+ set candidateRole to role of candidate as text
3827
+ set candidateName to ""
3730
3828
  try
3731
- set candidateName to value of candidate as text
3829
+ set candidateName to description of candidate as text
3732
3830
  end try
3831
+ if candidateName is "" then
3832
+ try
3833
+ set candidateName to value of candidate as text
3834
+ end try
3835
+ end if
3836
+ if candidateName is "missing value" then set candidateName to ""
3837
+ set candidateIdentity to ""
3838
+ try
3839
+ set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
3840
+ end try
3841
+ set selectedRecord to candidateName & (ASCII character 31) & candidateRole & (ASCII character 31) & candidateIdentity
3733
3842
  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
3843
+ else
3844
+ set nestedSelection to my selectedTimelineSelection(candidate, depth + 1, mainOrigin, mainSize)
3845
+ set selectedCount to selectedCount + (item 1 of nestedSelection)
3846
+ if selectedRecord is "" then set selectedRecord to item 2 of nestedSelection
3740
3847
  end if
3741
- set output to my selectedTimelineItem(candidate, depth + 1, mainOrigin, mainSize)
3742
- if output is not "" then return output
3743
3848
  end if
3744
3849
  on error
3745
3850
  -- Ignore inaccessible descendants and continue the bounded scan.
3746
3851
  end try
3747
3852
  end repeat
3748
- return ""
3749
- end selectedTimelineItem
3853
+ return {selectedCount, selectedRecord}
3854
+ end selectedTimelineSelection
3750
3855
 
3751
3856
  on selectedTimelineOccurrenceIndex(timelineArea)
3752
3857
  set occurrenceIndex to 0
@@ -3830,15 +3935,16 @@ function inspectScript() {
3830
3935
  try
3831
3936
  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
3937
  set selectionLookupAvailable to true
3833
- set selectedRecord to my selectedTimelineItem(timelineArea, 0, mainOrigin, mainSize)
3938
+ set selectionResult to my selectedTimelineSelection(timelineArea, 0, mainOrigin, mainSize)
3939
+ set selectedCount to item 1 of selectionResult
3940
+ set selectedRecord to item 2 of selectionResult
3834
3941
  set selectedOccurrenceIndex to my selectedTimelineOccurrenceIndex(timelineArea)
3835
3942
  end try
3836
- if selectedRecord is not "" then
3943
+ if selectedCount is 1 and selectedRecord is not "" then
3837
3944
  set selectedFields to my splitText(selectedRecord, ASCII character 31)
3838
3945
  set selectedName to item 1 of selectedFields
3839
3946
  set selectedRole to item 2 of selectedFields
3840
3947
  set selectedIdentity to item 3 of selectedFields
3841
- set selectedCount to 1
3842
3948
  end if
3843
3949
  set inspectorName to my findInspectorName(frontWindow, 0)
3844
3950
  if inspectorName is not "" and selectedCount is 1 then set selectedName to inspectorName
@@ -4717,11 +4823,11 @@ function selectMediaScript(match) {
4717
4823
  end tell
4718
4824
  end tell`;
4719
4825
  }
4720
- function locateOccurrenceScript(match, scanAll) {
4826
+ function locateOccurrenceScript(match, scanAll, zoomToFit = true) {
4721
4827
  return `
4722
4828
  using terms from application "System Events"
4723
4829
  on collectTimelineClipMatches(containerItem, depth, targetName, sourceIdentity, mainOrigin, mainSize)
4724
- if depth > 12 then return ""
4830
+ if depth > 12 then error "timeline traversal depth exceeded"
4725
4831
  set output to ""
4726
4832
  set candidateItems to UI elements of containerItem
4727
4833
  repeat with candidateRef in candidateItems
@@ -4732,6 +4838,7 @@ function locateOccurrenceScript(match, scanAll) {
4732
4838
  try
4733
4839
  set candidateDescription to description of candidate as text
4734
4840
  end try
4841
+ if candidateRole is "AXLayoutItem" and candidateDescription is "" then error "timeline item description unavailable"
4735
4842
  if candidateRole is "AXLayoutItem" and candidateDescription contains ("Video-Clip:" & targetName) then
4736
4843
  set candidatePosition to position of candidate
4737
4844
  set candidateStart to ""
@@ -4747,15 +4854,14 @@ function locateOccurrenceScript(match, scanAll) {
4747
4854
  if childRole is "AXHandle" and childDescription is "Leading Edge" then set candidateStart to value of child as text
4748
4855
  end try
4749
4856
  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)
4857
+ if candidateStart is "" or candidateDuration is "" then error "timeline clip has no complete range"
4858
+ set candidateOffset to ((item 1 of candidatePosition) + 10) - (item 1 of mainOrigin)
4752
4859
  set candidateIdentity to ""
4753
4860
  try
4754
4861
  set candidateIdentity to value of attribute "AXIdentifier" of candidate as text
4755
4862
  end try
4756
4863
  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
4864
+ 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
4865
  else
4760
4866
  set shouldDescend to false
4761
4867
  try
@@ -4768,12 +4874,13 @@ function locateOccurrenceScript(match, scanAll) {
4768
4874
  set timelineLeft to (item 1 of mainOrigin) + ((item 1 of mainSize) * 0.25)
4769
4875
  set timelineTop to (item 2 of mainOrigin) + ((item 2 of mainSize) * 0.55)
4770
4876
  set shouldDescend to (candidateX + candidateWidth) is greater than timelineLeft and (candidateY + candidateHeight) is greater than timelineTop
4877
+ on error
4878
+ error "timeline node geometry unavailable"
4771
4879
  end try
4772
4880
  if shouldDescend then set output to output & my collectTimelineClipMatches(candidate, depth + 1, targetName, sourceIdentity, mainOrigin, mainSize)
4773
4881
  end if
4774
4882
  on error
4775
- -- Accessibility nodes can disappear while Final Cut redraws the
4776
- -- timeline. Ignore that node and continue the bounded traversal.
4883
+ error "FINAL_CUT_NATIVE_OCCURRENCE_SCAN_INCOMPLETE: a timeline node could not be inspected"
4777
4884
  end try
4778
4885
  end repeat
4779
4886
  return output
@@ -4789,13 +4896,12 @@ function locateOccurrenceScript(match, scanAll) {
4789
4896
  set origin to position of mainWindow
4790
4897
  set windowSize to size of mainWindow
4791
4898
  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.
4899
+ ${zoomToFit ? `-- Make every occurrence visible before scanning.
4794
4900
  try
4795
4901
  click menu bar item "View" of menu bar 1
4796
4902
  click menu item "Zoom to Fit" of menu 1 of menu bar item "View" of menu bar 1
4797
4903
  delay 0.5
4798
- end try
4904
+ end try` : "-- Canonical discovery does not change the timeline view."}
4799
4905
  return my collectTimelineClipMatches(mainWindow, 0, targetName, sourceIdentity, origin, windowSize)
4800
4906
  end tell
4801
4907
  end tell`;
@@ -5915,14 +6021,16 @@ function parseContext(output) {
5915
6021
  : "none";
5916
6022
  const target = selectedCount < 0
5917
6023
  ? { kind: "unknown" }
5918
- : selectedCount === 1
6024
+ : selectedCount === 1 && (Boolean(targetIdentity) || Boolean(occurrenceIndex && Number.isInteger(occurrenceIndex) && occurrenceIndex > 0))
5919
6025
  ? { kind: "selected-clip", ...(selectedName ? { name: selectedName } : {}), ...(selectedRole ? { role: selectedRole } : {}), ...(targetIdentity ? { identity: targetIdentity } : {}), ...(occurrenceIndex && Number.isInteger(occurrenceIndex) && occurrenceIndex > 0 ? { occurrenceIndex } : {}) }
5920
- : selectedCount > 1
6026
+ : selectedCount === 1
5921
6027
  ? { 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" };
6028
+ : selectedCount > 1
6029
+ ? { kind: "unknown" }
6030
+ : (focusedRole === "AXTextField" && (focusedDescription === "text field" || focusedDescription === "Title")
6031
+ || focusedRole === "AXTextArea" && focusedDescription === "text entry area") && focusedName
6032
+ ? { kind: "selected-clip", name: focusedName, role: focusedRole }
6033
+ : { kind: "playhead" };
5926
6034
  const context = {
5927
6035
  available: true,
5928
6036
  application: "Final Cut Pro",
@@ -6055,12 +6163,12 @@ function timelineTimecodeToRational(value, sequence, label, absolute) {
6055
6163
  function opaqueHandle(kind, suffix) {
6056
6164
  return `${kind}-${Date.now().toString(36)}-${suffix ?? Math.random().toString(36).slice(2, 8)}`;
6057
6165
  }
6058
- function resolveLocalPath(sourcePath) {
6166
+ function resolveLocalPath(sourcePath, homeDirectory = homedir()) {
6059
6167
  const trimmed = sourcePath.trim();
6060
6168
  if (trimmed === "~")
6061
- return homedir();
6169
+ return homeDirectory;
6062
6170
  if (trimmed.startsWith("~/"))
6063
- return resolve(homedir(), trimmed.slice(2));
6171
+ return resolve(homeDirectory, trimmed.slice(2));
6064
6172
  if (trimmed.startsWith("~"))
6065
6173
  throw new Error(`INVALID_OPERATION: local media path must be absolute or start with ~/`);
6066
6174
  return resolve(trimmed);
@@ -6272,8 +6380,11 @@ function mediaInsertionMutationObserved(before, after) {
6272
6380
  }
6273
6381
  function readinessForContext(context) {
6274
6382
  const selectedTarget = context.target.kind !== "none" && context.target.kind !== "unknown";
6383
+ const targetBound = context.target.kind === "selected-clip"
6384
+ && Boolean(context.target.identity && context.target.projectId && context.target.sequenceId && context.target.revision);
6385
+ const targetReady = selectedTarget && (context.target.kind !== "selected-clip" || targetBound);
6275
6386
  const state = context.error?.state
6276
- ?? (context.available && context.frontmost && context.timelineWindowAvailable && context.timelineFocused && !context.overlayBlocked && selectedTarget
6387
+ ?? (context.available && context.frontmost && context.timelineWindowAvailable && context.timelineFocused && !context.overlayBlocked && targetReady
6277
6388
  ? "ready"
6278
6389
  : "unavailable");
6279
6390
  const overlay = context.overlayBlocked
@@ -6295,7 +6406,7 @@ function readinessForContext(context) {
6295
6406
  ? "frontmost"
6296
6407
  : !context.timelineFocused
6297
6408
  ? "timeline-focus"
6298
- : !selectedTarget
6409
+ : !targetReady
6299
6410
  ? "target"
6300
6411
  : undefined;
6301
6412
  const retryable = context.error?.retryable ?? state !== "ready";
@@ -6314,7 +6425,9 @@ function readinessForContext(context) {
6314
6425
  : firstMissing === "timeline-focus"
6315
6426
  ? "Focus the Final Cut Pro timeline and retry"
6316
6427
  : firstMissing === "target"
6317
- ? "Select a single timeline target and retry"
6428
+ ? context.target.kind === "selected-clip"
6429
+ ? "Re-read the selected occurrence after its live project, sequence, and revision are available"
6430
+ : "Select a single timeline target and retry"
6318
6431
  : state === "ready"
6319
6432
  ? "Native Final Cut is ready for a guarded mutation; verify operation-specific Undo after execution"
6320
6433
  : state === "timeout"
@@ -6332,6 +6445,8 @@ function readinessForContext(context) {
6332
6445
  frontmost: context.frontmost,
6333
6446
  timelineFocus: context.timelineFocused,
6334
6447
  selectedTarget,
6448
+ targetKind: context.target.kind,
6449
+ targetBound,
6335
6450
  overlay,
6336
6451
  permission: context.error?.code.includes("PERMISSION") ? "required" : context.available ? "granted" : "unknown",
6337
6452
  undo: context.available ? context.undoAvailable ? "available" : "unavailable" : "unknown",
@@ -6347,6 +6462,10 @@ function readinessStateForError(code) {
6347
6462
  return "stale";
6348
6463
  return "unavailable";
6349
6464
  }
6465
+ /** Construct the disabled focus response without invoking a native provider. */
6466
+ export function disabledNativeFocusContext() {
6467
+ return unavailableContext("CAPABILITY_UNAVAILABLE", "Final Cut native writes are disabled; set FRAMEKIT_FINAL_CUT_NATIVE_WRITES=1");
6468
+ }
6350
6469
  function unavailableContext(code, message, observed) {
6351
6470
  const state = readinessStateForError(code);
6352
6471
  const error = { code, message, state, retryable: state !== "unavailable" || code !== "CAPABILITY_UNAVAILABLE" };