@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
@@ -21,6 +21,7 @@ const DEFAULT_EXTENSION_NAME = "FramekitFinalCutWorkflow.app";
21
21
  export class FinalCutConnectionManager {
22
22
  socketPath;
23
23
  headless;
24
+ existingSocketOnly;
24
25
  canonicalProviderRequired;
25
26
  extensionSourcePath;
26
27
  extensionInstallPath;
@@ -36,6 +37,7 @@ export class FinalCutConnectionManager {
36
37
  activateExtension;
37
38
  restartFinalCut;
38
39
  restartAfterInstall;
40
+ installBeforeProbe;
39
41
  probe;
40
42
  sleep;
41
43
  status;
@@ -44,6 +46,7 @@ export class FinalCutConnectionManager {
44
46
  constructor(options = {}) {
45
47
  this.socketPath = options.socketPath ?? process.env.FRAMEKIT_FINAL_CUT_SOCKET ?? DEFAULT_FINAL_CUT_LIVE_SOCKET;
46
48
  this.headless = options.headless ?? process.env.FRAMEKIT_FINAL_CUT_HEADLESS === "1";
49
+ this.existingSocketOnly = options.existingSocketOnly ?? false;
47
50
  this.canonicalProviderRequired = options.canonicalProviderRequired
48
51
  ?? process.env.FRAMEKIT_FINAL_CUT_CANONICAL_REQUIRED === "1";
49
52
  this.extensionInstallPath = options.extensionInstallPath
@@ -66,6 +69,7 @@ export class FinalCutConnectionManager {
66
69
  this.registerExtension = options.registerExtension ?? (() => defaultRegisterExtension(this.extensionInstallPath));
67
70
  this.activateExtension = options.activateExtension ?? ((activationOptions) => defaultActivateFinalCut(activationOptions));
68
71
  this.restartAfterInstall = options.restartAfterInstall ?? false;
72
+ this.installBeforeProbe = options.installBeforeProbe ?? false;
69
73
  this.restartFinalCut = options.restartFinalCut ?? (() => defaultRestartFinalCut(this.detectFinalCut, this.launchFinalCut, this.sleep));
70
74
  this.probe = options.probe ?? defaultProbe(this.socketPath);
71
75
  this.sleep = options.sleep ?? ((milliseconds) => new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds)));
@@ -105,12 +109,15 @@ export class FinalCutConnectionManager {
105
109
  this.update({ state: "detecting", lastError: undefined });
106
110
  const existing = await this.tryProbe();
107
111
  this.update({ extensionInstalled: await pathExists(this.extensionInstallPath) });
108
- if (existing.result)
112
+ if (existing.result && (this.existingSocketOnly || !this.installBeforeProbe))
109
113
  return this.ready(existing.result);
110
- if (this.canonicalProviderRequired) {
114
+ if (this.existingSocketOnly) {
115
+ return this.fail("FINAL_CUT_EXISTING_SOCKET_UNAVAILABLE", `No existing Workflow Extension responds at ${this.socketPath}; automatic setup is disabled`, "needs-user-action");
116
+ }
117
+ if (this.canonicalProviderRequired && !existing.result) {
111
118
  return this.fail("FINAL_CUT_CANONICAL_PROVIDER_UNAVAILABLE", `Canonical live provider is unavailable at ${this.socketPath}; metadata-only fallback is disabled`, "needs-user-action");
112
119
  }
113
- if (this.headless) {
120
+ if (this.headless && !existing.result) {
114
121
  this.update({ state: "waiting-for-socket" });
115
122
  const waiting = await this.waitForHeadlessBridge(existing.error);
116
123
  if (waiting.result)
@@ -20,6 +20,12 @@ export class DisposableNativeEditWorkflow {
20
20
  throw new Error("INVALID_OPERATION: disposable native maxOperations must be a positive integer");
21
21
  }
22
22
  }
23
+ async trackNativeDispatch(operation, onDispatch) {
24
+ if (this.options.native.trackNativeDispatch)
25
+ return this.options.native.trackNativeDispatch(operation, onDispatch);
26
+ onDispatch();
27
+ return operation();
28
+ }
23
29
  async preview(request) {
24
30
  validateRequest(request);
25
31
  const before = await this.readCanonical("preview");
@@ -0,0 +1,8 @@
1
+ export * from "./sqlite-inspection.js";
2
+ export * from "./sqlite-wal-observation.js";
3
+ export * from "./sqlite-experiment.js";
4
+ export * from "./sqlite-materialization.js";
5
+ export * from "./shadow-mutation.js";
6
+ export * from "./fcpxml-console-experiment.js";
7
+ export * from "./unattended-editing.js";
8
+ export * from "./pasteboard-snapshot.js";
@@ -5,6 +5,17 @@ import { dirname, isAbsolute, resolve } from "node:path";
5
5
  import { XMLBuilder, XMLParser } from "fast-xml-parser";
6
6
  import { createProjectSelectionResult, withCapabilityFamilies } from "../../../../packages/runtime/src/index.js";
7
7
  const CLIP_KINDS = new Set(["asset-clip", "clip", "ref-clip", "sync-clip", "mc-clip", "audio", "video"]);
8
+ const MARKER_HOST_KINDS = new Set([...CLIP_KINDS, "gap", "title", "live-drawing"]);
9
+ const MARKER_FOLLOWING_CHILD_KINDS = new Set([
10
+ "audio-channel-source",
11
+ "audio-role-source",
12
+ "sync-source",
13
+ "filter-video",
14
+ "filter-video-mask",
15
+ "filter-audio",
16
+ "metadata",
17
+ "reserved",
18
+ ]);
8
19
  const TIMELINE_KINDS = new Set([
9
20
  ...CLIP_KINDS,
10
21
  "gap",
@@ -38,9 +49,11 @@ export class FcpxmlDocumentAdapter {
38
49
  sequence = 0;
39
50
  fileSignature;
40
51
  history = new Map();
41
- constructor(filePath, target) {
52
+ allowMissingImmutableIdsForReadback;
53
+ constructor(filePath, target, options = {}) {
42
54
  this.filePath = filePath;
43
55
  this.target = target;
56
+ this.allowMissingImmutableIdsForReadback = options.allowMissingImmutableIdsForReadback ?? false;
44
57
  }
45
58
  async getIdentity() {
46
59
  return { name: "Final Cut Pro", version: "FCPXML", backend: "fcpxml-document" };
@@ -284,17 +297,27 @@ export class FcpxmlDocumentAdapter {
284
297
  }
285
298
  }
286
299
  identity(project, sequence) {
287
- const projectUid = immutableUid(project, "PROJECT");
300
+ const projectUid = optionalImmutableUid(project);
301
+ if (!projectUid && !this.allowMissingImmutableIdsForReadback)
302
+ immutableUid(project, "PROJECT");
288
303
  if (this.target && projectUid !== this.target.projectUid) {
289
304
  throw new Error(`TARGET_MISMATCH: exported project UID ${projectUid} does not match live project UID ${this.target.projectUid}`);
290
305
  }
291
- const exportedSequenceUid = sequence ? attribute(sequence, "uid") : undefined;
306
+ const exportedSequenceUid = sequence ? optionalImmutableUid(sequence) : undefined;
307
+ if (!exportedSequenceUid && !projectUid && !this.target?.sequenceId && !this.allowMissingImmutableIdsForReadback) {
308
+ immutableUid(sequence, "SEQUENCE");
309
+ }
292
310
  if (this.target && exportedSequenceUid !== undefined && String(exportedSequenceUid) !== this.target.sequenceId) {
293
311
  throw new Error(`TARGET_MISMATCH: exported sequence UID ${String(exportedSequenceUid)} does not match live sequence UID ${this.target.sequenceId}`);
294
312
  }
295
313
  return {
296
- projectId: this.target?.projectId ?? `fcpxml:project:${projectUid}`,
297
- sequenceId: this.target?.sequenceId ?? stableSequenceId(sequence),
314
+ projectId: this.target?.projectId ?? (projectUid
315
+ ? `fcpxml:project:${projectUid}`
316
+ : `fcpxml:readback-project:${hash(`${this.filePath}\0${attribute(project, "name") ?? "Final Cut Project"}`)}`),
317
+ sequenceId: this.target?.sequenceId ?? (exportedSequenceUid
318
+ ? `fcpxml:sequence:${exportedSequenceUid}`
319
+ : projectUid ? `fcpxml:sequence:${projectUid}`
320
+ : `fcpxml:readback-sequence:${hash(`${this.filePath}\0${attribute(sequence ?? {}, "name") ?? "Final Cut Sequence"}`)}`),
298
321
  };
299
322
  }
300
323
  applyOperation(operation) {
@@ -346,20 +369,12 @@ export class FcpxmlDocumentAdapter {
346
369
  case "ripple-delete":
347
370
  if (operation.timelineId !== timelineId)
348
371
  throw new Error(`TIMELINE_NOT_FOUND: ${operation.timelineId}`);
349
- this.applyRippleDelete(spine, operation.range.start, operation.range.end);
372
+ this.applyRippleDelete(spine, operation.range.start, operation.range.end, attribute(sequence, "duration") === undefined
373
+ ? rationalSeconds(timelineDuration(timelineEntries(spine)))
374
+ : rationalSeconds(parseRational(attribute(sequence, "duration"))));
350
375
  break;
351
376
  case "add-marker": {
352
- if (operation.timelineId !== timelineId) {
353
- throw new Error(`TIMELINE_NOT_FOUND: ${operation.timelineId}`);
354
- }
355
- appendChild(spine, "marker", {
356
- ":@": {
357
- "@_id": operation.marker.id,
358
- "@_start": formatSeconds(operation.marker.start),
359
- "@_duration": formatSeconds(operation.marker.duration),
360
- "@_value": operation.marker.name,
361
- },
362
- });
377
+ this.applyMarker(spine, timelineId, operation);
363
378
  break;
364
379
  }
365
380
  case "timeline.media.add":
@@ -392,6 +407,40 @@ export class FcpxmlDocumentAdapter {
392
407
  }
393
408
  this.updateSequenceDuration(sequence, spine);
394
409
  }
410
+ applyMarker(spine, timelineId, operation) {
411
+ if (operation.timelineId !== timelineId) {
412
+ throw new Error(`TIMELINE_NOT_FOUND: ${operation.timelineId}`);
413
+ }
414
+ const markerStart = parseRational(formatSeconds(operation.marker.start));
415
+ const markerDuration = parseRational(formatSeconds(operation.marker.duration));
416
+ const markerEnd = addRational(markerStart, markerDuration);
417
+ const host = timelineEntries(spine).find((entry) => {
418
+ if (!MARKER_HOST_KINDS.has(entry.kind))
419
+ return false;
420
+ const hostEnd = addRational(entry.startTime, entry.durationTime);
421
+ return compareRational(markerStart, entry.startTime) >= 0
422
+ && compareRational(markerEnd, hostEnd) <= 0;
423
+ });
424
+ if (!host) {
425
+ throw new Error("FCPXML_MARKER_TARGET_UNAVAILABLE: marker must fit inside an existing story element");
426
+ }
427
+ const sourceStart = parseRational(attribute(host.node, "start") ?? "0s");
428
+ const localStart = addRational(sourceStart, subtractRational(markerStart, host.startTime));
429
+ const marker = elementNode("marker", {
430
+ start: formatRational(localStart),
431
+ duration: formatRational(markerDuration),
432
+ value: operation.marker.name,
433
+ note: `com.framekit.id:${operation.marker.id}`,
434
+ });
435
+ const firstFollowingChild = storyEntries(host.node)
436
+ .find(({ kind }) => MARKER_FOLLOWING_CHILD_KINDS.has(kind));
437
+ if (firstFollowingChild) {
438
+ insertChildBefore(host.node, firstFollowingChild.node, "marker", marker);
439
+ }
440
+ else {
441
+ appendChild(host.node, "marker", marker);
442
+ }
443
+ }
395
444
  findClipEntry(spine, clipId, timelineId) {
396
445
  return timelineEntries(spine)
397
446
  .filter(({ kind }) => CLIP_KINDS.has(kind))
@@ -649,10 +698,13 @@ export class FcpxmlDocumentAdapter {
649
698
  throw new Error("INVALID_OPERATION: clip duration must fit the source");
650
699
  }
651
700
  }
652
- applyRippleDelete(spine, start, end) {
653
- if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || end <= start) {
701
+ applyRippleDelete(spine, start, end, sequenceDuration) {
702
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) {
654
703
  throw new Error("INVALID_OPERATION: ripple-delete range must be finite and increasing");
655
704
  }
705
+ if (start < 0 || end > sequenceDuration) {
706
+ throw new Error(`INVALID_OPERATION: ripple-delete range [${start}, ${end}) must fit timeline bounds [0, ${sequenceDuration})`);
707
+ }
656
708
  const direct = storyEntries(spine)
657
709
  .map(({ kind, node }) => timelineEntries(spine).find((entry) => entry.node === node && entry.kind === kind))
658
710
  .filter((entry) => entry !== undefined);
@@ -838,10 +890,13 @@ export class FcpxmlDocumentAdapter {
838
890
  const visual = pictureInPictureProperties(node);
839
891
  const fades = audioFadeProperties(node);
840
892
  const roleAttributeName = kind === "audio" ? "role" : kind === "asset-clip" ? "audioRole" : undefined;
841
- const roleAttribute = roleAttributeName === undefined ? undefined : attribute(node, roleAttributeName);
842
- const role = kind === "audio" || roleAttribute === "audio" || roleAttribute === "music"
893
+ const rawRoleAttribute = roleAttributeName === undefined ? undefined : attribute(node, roleAttributeName);
894
+ const roleAttribute = rawRoleAttribute === undefined ? undefined : String(rawRoleAttribute);
895
+ const audioRole = kind === "audio" || roleAttribute !== undefined
843
896
  ? audioRoleFromXml(node, roleAttributeName ?? "role")
844
897
  : undefined;
898
+ const isDialogue = roleAttribute === "dialogue" || roleAttribute?.startsWith("dialogue.");
899
+ const role = kind === "asset-clip" && isDialogue ? undefined : audioRole;
845
900
  const sourceStartValue = attribute(node, "start");
846
901
  const sourceStartTime = sourceStartValue === undefined ? undefined : parseRational(sourceStartValue);
847
902
  const sourceStart = sourceStartTime === undefined ? undefined : rationalSeconds(sourceStartTime);
@@ -856,6 +911,7 @@ export class FcpxmlDocumentAdapter {
856
911
  ...(sourceStart !== undefined ? { sourceStart, sourceStartTime } : {}),
857
912
  track: Number(attribute(node, "lane") ?? 0),
858
913
  ...(role !== undefined ? { role } : {}),
914
+ ...(isDialogue ? { nativeAudioRole: roleAttribute } : {}),
859
915
  ...(attribute(node, "framekit-attached-to") !== undefined ? { attachedTo: String(attribute(node, "framekit-attached-to")) } : {}),
860
916
  startTime,
861
917
  durationTime,
@@ -866,7 +922,10 @@ export class FcpxmlDocumentAdapter {
866
922
  };
867
923
  }
868
924
  instanceId(node, kind, path, timelineId) {
869
- const explicit = attribute(node, "id") ?? attribute(node, "uid");
925
+ const metadata = firstChild(node, "metadata");
926
+ const framekitId = metadata === undefined ? undefined : storyEntries(metadata)
927
+ .find(({ kind: childKind, node: child }) => childKind === "md" && attribute(child, "key") === "com.framekit.id")?.node;
928
+ const explicit = attribute(node, "id") ?? attribute(node, "uid") ?? (framekitId && attribute(framekitId, "value"));
870
929
  return String(explicit ?? `${timelineId}:spine:${path}:${kind}`);
871
930
  }
872
931
  findClipNode(spine, clipId, timelineId) {
@@ -890,7 +949,7 @@ export class FcpxmlDocumentAdapter {
890
949
  .filter(({ kind }) => kind === "marker")
891
950
  .map(({ node, startTime, durationTime }, index) => {
892
951
  return {
893
- id: String(attribute(node, "id") ?? `marker-${index + 1}`),
952
+ id: String(attribute(node, "id") ?? framekitNoteId(attribute(node, "note")) ?? `marker-${index + 1}`),
894
953
  start: rationalSeconds(startTime),
895
954
  duration: rationalSeconds(durationTime),
896
955
  startTime,
@@ -904,12 +963,12 @@ export class FcpxmlDocumentAdapter {
904
963
  .filter(({ kind }) => kind === "caption")
905
964
  .map(({ node, startTime, durationTime }, index) => {
906
965
  return {
907
- id: String(attribute(node, "id") ?? `caption-${index + 1}`),
966
+ id: String(attribute(node, "id") ?? framekitNoteId(textChildValue(node, "note")) ?? `caption-${index + 1}`),
908
967
  start: rationalSeconds(startTime),
909
968
  duration: rationalSeconds(durationTime),
910
969
  startTime,
911
970
  durationTime,
912
- text: String(attribute(node, "text") ?? attribute(node, "name") ?? ""),
971
+ text: String(textChildValue(node, "text") ?? attribute(node, "text") ?? attribute(node, "name") ?? ""),
913
972
  };
914
973
  });
915
974
  }
@@ -924,9 +983,11 @@ export class FcpxmlDocumentAdapter {
924
983
  const durationValue = attribute(node, "duration");
925
984
  const mediaKind = mediaKindFromResource(node);
926
985
  const originalMedia = storyEntries(node).find(({ kind, node: representation }) => kind === "media-rep" && attribute(representation, "kind") === "original-media")?.node;
986
+ const rawSource = attribute(node, "src") ?? (originalMedia && attribute(originalMedia, "src"));
987
+ const source = rawSource === undefined ? "" : String(rawSource);
927
988
  return {
928
989
  mediaId: String(attribute(node, "id") ?? ""),
929
- source: resolveMediaSource(String(attribute(node, "src") ?? (originalMedia && attribute(originalMedia, "src")) ?? attribute(node, "name") ?? attribute(node, "id") ?? ""), this.filePath),
990
+ source: source.trim() ? resolveMediaSource(source, this.filePath) : "",
930
991
  ...(mediaKind ? { mediaKind } : {}),
931
992
  ...(durationValue !== undefined ? { duration: parseSeconds(durationValue) } : {}),
932
993
  };
@@ -946,6 +1007,8 @@ export function resolveMediaSource(source, documentPath) {
946
1007
  return source;
947
1008
  }
948
1009
  }
1010
+ if (/^[a-z][a-z0-9+.-]*:/i.test(source))
1011
+ return source;
949
1012
  if (isAbsolute(source))
950
1013
  return source;
951
1014
  return resolve(dirname(documentPath), source);
@@ -1027,8 +1090,9 @@ function audioFadeProperties(node) {
1027
1090
  };
1028
1091
  }
1029
1092
  function audioRoleFromXml(node, attributeName = "role") {
1030
- const role = attribute(node, attributeName);
1031
- if (role === undefined || role === "audio")
1093
+ const value = attribute(node, attributeName);
1094
+ const role = value === undefined ? undefined : String(value);
1095
+ if (role === undefined || role === "audio" || /^dialogue(?:\.[^.]+)?$/.test(role))
1032
1096
  return "audio";
1033
1097
  if (role === "music")
1034
1098
  return "music";
@@ -1038,12 +1102,35 @@ function textChildValue(node, kind) {
1038
1102
  const text = firstChild(node, kind);
1039
1103
  if (!text)
1040
1104
  return undefined;
1041
- const value = Array.isArray(text[kind]) ? text[kind][0]?.["#text"] : undefined;
1042
- if (Array.isArray(value) && value.length > 0)
1043
- return String(value[0]);
1044
- if (typeof value === "string" || typeof value === "number")
1045
- return String(value);
1046
- return undefined;
1105
+ const value = xmlTextContent(text);
1106
+ return value.length > 0 ? value : undefined;
1107
+ }
1108
+ function xmlTextContent(node) {
1109
+ return Object.entries(node)
1110
+ .filter(([kind]) => kind !== ":@")
1111
+ .map(([kind, value]) => {
1112
+ if (kind === "#text") {
1113
+ const text = (Array.isArray(value) ? value : [value])
1114
+ .filter((part) => typeof part === "string" || typeof part === "number")
1115
+ .map(String)
1116
+ .filter((part) => part.trim().length > 0)
1117
+ .join("");
1118
+ return text;
1119
+ }
1120
+ if (!Array.isArray(value))
1121
+ return "";
1122
+ return value
1123
+ .filter((child) => typeof child === "object" && child !== null)
1124
+ .map(xmlTextContent)
1125
+ .join("");
1126
+ })
1127
+ .join("");
1128
+ }
1129
+ function framekitNoteId(value) {
1130
+ const prefix = "com.framekit.id:";
1131
+ return typeof value === "string" && value.startsWith(prefix) && value.length > prefix.length
1132
+ ? value.slice(prefix.length)
1133
+ : undefined;
1047
1134
  }
1048
1135
  function mediaKindCompatible(role, mediaKind) {
1049
1136
  if (mediaKind === undefined)
@@ -1058,8 +1145,13 @@ function timelineEntries(spine) {
1058
1145
  const localOffset = parseRational(attribute(child, "offset")
1059
1146
  ?? ((kind === "marker" || kind === "caption") ? attribute(child, "start") : undefined)
1060
1147
  ?? "0s");
1061
- const localStart = parentKind === "asset-clip"
1062
- && (kind === "title" || kind === "asset-clip" && attribute(child, "audioRole") === "music")
1148
+ const markerInHost = kind === "marker"
1149
+ && parentKind !== undefined
1150
+ && MARKER_HOST_KINDS.has(parentKind);
1151
+ const assetClipRelativeChild = parentKind === "asset-clip"
1152
+ && (kind === "title" || kind === "caption" || kind === "asset-clip" && attribute(child, "audioRole") === "music");
1153
+ const sourceRelativeChild = markerInHost || assetClipRelativeChild;
1154
+ const localStart = sourceRelativeChild
1063
1155
  ? subtractRational(localOffset, parseRational(attribute(node, "start") ?? "0s"))
1064
1156
  : localOffset;
1065
1157
  const durationTime = parseRational(attribute(child, "duration") ?? "0s");
@@ -1110,6 +1202,23 @@ function appendChild(node, kind, child) {
1110
1202
  node[kind] = [...(Array.isArray(node[kind]) ? node[kind] : []), wrapper];
1111
1203
  }
1112
1204
  }
1205
+ function insertChildBefore(parent, before, kind, child) {
1206
+ const elementKey = Object.keys(parent).find((key) => key !== ":@");
1207
+ if (!elementKey || !Array.isArray(parent[elementKey])) {
1208
+ appendChild(parent, kind, child);
1209
+ return;
1210
+ }
1211
+ const children = parent[elementKey];
1212
+ const index = children.indexOf(before);
1213
+ if (index < 0) {
1214
+ appendChild(parent, kind, child);
1215
+ return;
1216
+ }
1217
+ const wrapper = Object.prototype.hasOwnProperty.call(child, kind)
1218
+ ? child
1219
+ : { [kind]: [], ...child };
1220
+ children.splice(index, 0, wrapper);
1221
+ }
1113
1222
  function attributes(node) {
1114
1223
  return (node[":@"] ?? {});
1115
1224
  }
@@ -1241,7 +1350,7 @@ function mediaKindFromResource(node) {
1241
1350
  const hasAudio = attribute(node, "hasAudio");
1242
1351
  if (hasVideo === "1" || hasVideo === "true")
1243
1352
  return "video";
1244
- if ((hasVideo === "0" || hasVideo === "false") && (hasAudio === "1" || hasAudio === "true"))
1353
+ if (hasAudio === "1" || hasAudio === "true")
1245
1354
  return "audio";
1246
1355
  return undefined;
1247
1356
  }
@@ -1342,6 +1451,10 @@ function immutableUid(node, kind) {
1342
1451
  }
1343
1452
  return String(uid);
1344
1453
  }
1454
+ function optionalImmutableUid(node) {
1455
+ const uid = node ? attribute(node, "uid") : undefined;
1456
+ return uid === undefined || String(uid).trim().length === 0 ? undefined : String(uid);
1457
+ }
1345
1458
  function stableTimelineId(project, sequence) {
1346
1459
  stableProjectId(project);
1347
1460
  return stableSequenceId(sequence);
@@ -11,17 +11,12 @@ export * from "./media.js";
11
11
  export * from "./native.js";
12
12
  export * from "./disposable-native.js";
13
13
  export * from "./publisher.js";
14
+ export * from "./publish-readback.js";
14
15
  export * from "./export.js";
15
16
  export * from "./background-export.js";
16
17
  export * from "./background-materialization.js";
17
18
  export * from "./library-inspection.js";
18
- export * from "./sqlite-inspection.js";
19
- export * from "./sqlite-wal-observation.js";
20
- export * from "./sqlite-experiment.js";
21
- export * from "./shadow-mutation.js";
22
19
  export * from "./native-operation.js";
23
20
  export * from "./native-session.js";
24
21
  export * from "./timeline-ir-fcpxml.js";
25
- export * from "./fcpxml-console-experiment.js";
26
- export * from "./unattended-editing.js";
27
- export * from "./pasteboard-snapshot.js";
22
+ export * from "./canonical-recovery-guard.js";
@@ -1,5 +1,8 @@
1
1
  import { execFile as execFileCallback } from "node:child_process";
2
+ import { realpathSync } from "node:fs";
3
+ import { resolve } from "node:path";
2
4
  import { promisify } from "node:util";
5
+ import { fileURLToPath } from "node:url";
3
6
  import { validateProjectCatalog } from "../../../../packages/runtime/src/index.js";
4
7
  export const FINAL_CUT_LIBRARY_INSPECTION_BACKEND = "final-cut-background-library";
5
8
  export const FINAL_CUT_LIBRARY_INSPECTION_TIMEOUT_MS = 30_000;
@@ -62,6 +65,43 @@ export class FinalCutLibraryInspectionProvider {
62
65
  }
63
66
  return catalog;
64
67
  }
68
+ /** Bind a newly imported project to the exact library location requested by its FCPXML. */
69
+ async resolveProjectBinding(libraryPath, identity) {
70
+ const result = await this.inspect();
71
+ if (result.status === "unavailable" || result.status === "error") {
72
+ throw new Error(`${result.error.code}: ${result.error.message}`);
73
+ }
74
+ const expectedPath = normalizeLibraryPath(libraryPath);
75
+ const libraries = result.catalog.libraries.filter((library) => library.path
76
+ && normalizeLibraryPath(library.path) === expectedPath);
77
+ if (libraries.length === 0) {
78
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_PENDING: library has not appeared at ${expectedPath}`);
79
+ }
80
+ if (libraries.length !== 1) {
81
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_MISMATCH: multiple Final Cut libraries report path ${expectedPath}`);
82
+ }
83
+ const library = libraries[0];
84
+ const matches = library.events.flatMap((event) => event.projects.flatMap((project) => {
85
+ if (project.name !== identity.projectName)
86
+ return [];
87
+ const sequences = project.sequences.filter((sequence) => sequence.name === identity.sequenceName);
88
+ return sequences.map((sequence) => ({ event, project, sequence }));
89
+ }));
90
+ if (matches.length === 0) {
91
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_PENDING: project ${identity.projectName} / sequence ${identity.sequenceName} has not appeared in ${expectedPath}`);
92
+ }
93
+ if (matches.length !== 1) {
94
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_MISMATCH: expected one project and sequence in ${expectedPath}, found ${matches.length}`);
95
+ }
96
+ const match = matches[0];
97
+ return {
98
+ projectId: match.project.id,
99
+ sequenceId: match.sequence.id,
100
+ libraryId: library.id,
101
+ eventId: match.event.id,
102
+ libraryPath: expectedPath,
103
+ };
104
+ }
65
105
  }
66
106
  /** Build the JXA program used for direct, read-only Final Cut Apple Events. */
67
107
  export function buildFinalCutLibraryInspectionScript(applicationIdentifier = "com.apple.FinalCut") {
@@ -136,6 +176,7 @@ function libraryValue(library) {
136
176
  return {
137
177
  id: textValue(library, "id"),
138
178
  name: textValue(library, "name"),
179
+ path: textValue(library, "file"),
139
180
  events: events === null ? null : events.map(eventValue)
140
181
  };
141
182
  }
@@ -251,7 +292,8 @@ function parseLibrary(value, path, issues) {
251
292
  const events = parseChildren(record.events, `${path}.events`, "event", parseEvent, issues);
252
293
  if (!id || !name)
253
294
  return undefined;
254
- return { id, name, events };
295
+ const libraryPath = optionalText(record.path);
296
+ return { id, name, ...(libraryPath ? { path: libraryPath } : {}), events };
255
297
  }
256
298
  function parseEvent(value, path, issues) {
257
299
  const record = asRecord(value);
@@ -358,6 +400,23 @@ function normalizeInteger(value) {
358
400
  return String(value);
359
401
  return undefined;
360
402
  }
403
+ function optionalText(value) {
404
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
405
+ }
406
+ function normalizeLibraryPath(path) {
407
+ try {
408
+ const resolved = resolve(path.startsWith("file:") ? fileURLToPath(path) : path);
409
+ try {
410
+ return realpathSync(resolved);
411
+ }
412
+ catch {
413
+ return resolved;
414
+ }
415
+ }
416
+ catch {
417
+ return resolve(path);
418
+ }
419
+ }
361
420
  function parseTopLevelError(value, fallback) {
362
421
  const record = asRecord(value);
363
422
  const message = typeof record?.message === "string" && record.message.trim() ? record.message : fallback;
@@ -13,6 +13,8 @@ const READ_ONLY_LIVE_METHODS = new Set([
13
13
  "projects",
14
14
  "snapshot",
15
15
  ]);
16
+ // The extension waits up to five seconds for NSWorkspace's completion handler.
17
+ const DOCUMENT_DELIVERY_TIMEOUT_MS = 7_000;
16
18
  /** Newline-delimited JSON transport for the local Workflow Extension socket. */
17
19
  export class UnixSocketFinalCutLiveTransport {
18
20
  socketPath;
@@ -52,7 +54,7 @@ export class UnixSocketFinalCutLiveTransport {
52
54
  };
53
55
  const timer = setTimeout(() => {
54
56
  finish(() => reject(new Error(`FINAL_CUT_LIVE_TIMEOUT: ${this.socketPath}`)));
55
- }, this.timeoutMs);
57
+ }, request.method === "deliver-fcpxml" ? Math.max(this.timeoutMs, DOCUMENT_DELIVERY_TIMEOUT_MS) : this.timeoutMs);
56
58
  socket = createConnection(this.socketPath);
57
59
  socket.setEncoding("utf8");
58
60
  socket.on("connect", () => {
@@ -90,6 +92,7 @@ export class UnixSocketFinalCutLiveTransport {
90
92
  export class FinalCutLiveAdapter {
91
93
  transport;
92
94
  socketPath;
95
+ selectedTarget;
93
96
  constructor(transport, socketPath = "configured-socket") {
94
97
  this.transport = transport;
95
98
  this.socketPath = socketPath;
@@ -125,6 +128,11 @@ export class FinalCutLiveAdapter {
125
128
  throw new Error("FINAL_CUT_LIVE_PROTOCOL: snapshot response was empty");
126
129
  validateCanonicalSnapshot(response.snapshot);
127
130
  validateSnapshotTarget(response.snapshot, await this.listProjects());
131
+ if (this.selectedTarget
132
+ && (response.snapshot.projectId !== this.selectedTarget.projectId
133
+ || response.snapshot.timeline.id !== this.selectedTarget.sequenceId)) {
134
+ throw new Error("TARGET_MISMATCH: live canonical snapshot differs from the explicitly selected project and sequence");
135
+ }
128
136
  return response.snapshot;
129
137
  }
130
138
  async apply(operation, expectedRevision) {
@@ -133,6 +141,7 @@ export class FinalCutLiveAdapter {
133
141
  if (capabilities.editor.canonicalTimelineMode !== "canonical-write") {
134
142
  throw new Error("CAPABILITY_UNAVAILABLE: live Final Cut canonical mutation");
135
143
  }
144
+ await this.assertSelectedTargetActive();
136
145
  const response = await this.request({ method: "apply", operation, expectedRevision });
137
146
  if (!response.revision)
138
147
  throw new Error("FINAL_CUT_LIVE_PROTOCOL: apply response revision was empty");
@@ -148,6 +157,10 @@ export class FinalCutLiveAdapter {
148
157
  if (capabilities.editor.canonicalTimelineMode !== "canonical-write") {
149
158
  throw new Error("CAPABILITY_UNAVAILABLE: live Final Cut canonical rollback");
150
159
  }
160
+ await this.assertSelectedTargetActive();
161
+ if (this.selectedTarget && (snapshot.projectId !== this.selectedTarget.projectId || snapshot.timeline.id !== this.selectedTarget.sequenceId)) {
162
+ throw new Error("TARGET_MISMATCH: rollback snapshot differs from the explicitly selected project and sequence");
163
+ }
151
164
  await this.request({ method: "restore", snapshot, expectedRevision });
152
165
  }
153
166
  async readLiveState() {
@@ -172,7 +185,7 @@ export class FinalCutLiveAdapter {
172
185
  const response = await this.request({
173
186
  method: "deliver-fcpxml",
174
187
  artifactPath: request.artifactPath,
175
- ...(request.targetLibraryUid ? { targetLibraryUid: request.targetLibraryUid } : {}),
188
+ ...(request.targetLibraryLocation ? { targetLibraryLocation: request.targetLibraryLocation } : {}),
176
189
  activates: request.activates,
177
190
  });
178
191
  if (!response.delivery)
@@ -204,7 +217,19 @@ export class FinalCutLiveAdapter {
204
217
  if (!response.revision)
205
218
  throw new Error("FINAL_CUT_LIVE_PROTOCOL: project selection response revision was empty");
206
219
  validateRevision(response.revision, "project selection response revision");
207
- return createProjectSelectionResult(response.catalog, selection, response.revision);
220
+ const result = createProjectSelectionResult(response.catalog, selection, response.revision);
221
+ this.selectedTarget = { ...result.observedActiveTarget };
222
+ return result;
223
+ }
224
+ async assertSelectedTargetActive() {
225
+ const selected = this.selectedTarget;
226
+ if (!selected)
227
+ return;
228
+ const catalog = await this.listProjects();
229
+ if (this.selectedTarget !== selected
230
+ || catalog.activeProjectId !== selected.projectId || catalog.activeSequenceId !== selected.sequenceId) {
231
+ throw new Error("TARGET_MISMATCH: active project and sequence differ from the explicitly selected target");
232
+ }
208
233
  }
209
234
  async request(input) {
210
235
  const response = await this.transport.request({
@@ -239,7 +264,7 @@ function validateFcpxmlDelivery(delivery, request) {
239
264
  if (delivery.status !== "dispatched" && (!delivery.error?.code?.trim() || !delivery.error.message.trim())) {
240
265
  throw new Error("FINAL_CUT_LIVE_PROTOCOL: blocked FCPXML delivery response is missing an error");
241
266
  }
242
- if (request.targetLibraryUid && delivery.target.requestedLibraryUid !== request.targetLibraryUid) {
267
+ if (request.targetLibraryLocation && delivery.target.requestedLibraryLocation !== request.targetLibraryLocation) {
243
268
  throw new Error("FINAL_CUT_LIVE_PROTOCOL: FCPXML delivery target does not match the request");
244
269
  }
245
270
  }