@morshoto/framekit 0.1.6 → 0.1.11

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 (43) hide show
  1. package/bin/framekit.mjs +2 -1
  2. package/dist-package/adapters/final-cut/typescript/src/assets.js +157 -35
  3. package/dist-package/adapters/final-cut/typescript/src/background-export.js +384 -0
  4. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +175 -0
  5. package/dist-package/adapters/final-cut/typescript/src/canonical.js +189 -32
  6. package/dist-package/adapters/final-cut/typescript/src/connection.js +55 -17
  7. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +33 -7
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml-console-experiment.js +74 -0
  9. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +615 -49
  10. package/dist-package/adapters/final-cut/typescript/src/index.js +10 -0
  11. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +390 -0
  12. package/dist-package/adapters/final-cut/typescript/src/live.js +16 -6
  13. package/dist-package/adapters/final-cut/typescript/src/media.js +151 -0
  14. package/dist-package/adapters/final-cut/typescript/src/native-session.js +412 -0
  15. package/dist-package/adapters/final-cut/typescript/src/native.js +1192 -364
  16. package/dist-package/adapters/final-cut/typescript/src/publisher.js +225 -32
  17. package/dist-package/adapters/final-cut/typescript/src/session.js +163 -17
  18. package/dist-package/adapters/final-cut/typescript/src/shadow-mutation.js +120 -0
  19. package/dist-package/adapters/final-cut/typescript/src/sqlite-inspection.js +433 -0
  20. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +372 -0
  21. package/dist-package/adapters/final-cut/typescript/src/unattended-editing.js +66 -0
  22. package/dist-package/apps/mcp-server/src/headless-sessions.js +112 -0
  23. package/dist-package/apps/mcp-server/src/main.js +41 -8
  24. package/dist-package/apps/mcp-server/src/materialization-jobs.js +326 -0
  25. package/dist-package/apps/mcp-server/src/routing.js +227 -39
  26. package/dist-package/apps/mcp-server/src/server.js +642 -97
  27. package/dist-package/apps/mcp-server/src/version.js +109 -1
  28. package/dist-package/packages/runtime/src/application/media-analysis-service.js +1 -3
  29. package/dist-package/packages/runtime/src/application/project-service.js +46 -7
  30. package/dist-package/packages/runtime/src/capabilities.js +55 -7
  31. package/dist-package/packages/runtime/src/context/project-catalog.js +159 -0
  32. package/dist-package/packages/runtime/src/domain/capabilities.js +33 -0
  33. package/dist-package/packages/runtime/src/domain/context.js +14 -1
  34. package/dist-package/packages/runtime/src/domain/index.js +1 -0
  35. package/dist-package/packages/runtime/src/domain/timeline-target.js +217 -0
  36. package/dist-package/packages/runtime/src/editing/edit-service.js +15 -1
  37. package/dist-package/packages/runtime/src/editing/intent.js +178 -2
  38. package/dist-package/packages/runtime/src/index.js +3 -0
  39. package/dist-package/packages/runtime/src/runtime.js +2 -2
  40. package/dist-package/packages/runtime/src/timeline/drift-reconciliation.js +295 -0
  41. package/dist-package/packages/runtime/src/timeline/editing-session.js +490 -0
  42. package/dist-package/packages/testkit/src/in-memory-editor.js +5 -4
  43. package/package.json +12 -6
@@ -0,0 +1,175 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import { readFile } from "node:fs/promises";
4
+ import { timelineIrDigest, validateTimelineIr } from "../../../../packages/runtime/src/index.js";
5
+ const DEFAULT_COMMAND_TIMEOUT_MS = 30_000;
6
+ /**
7
+ * Publishes an immutable FCPXML artifact through an explicit non-UI Final Cut
8
+ * capability. The command owns Final Cut import and target-bound canonical
9
+ * readback; this adapter never activates Final Cut or falls back to UI calls.
10
+ */
11
+ export class FinalCutBackgroundMaterializationPublisher {
12
+ options;
13
+ commandTimeoutMs;
14
+ constructor(options = {}) {
15
+ this.options = options;
16
+ if (options.commandTimeoutMs !== undefined && (!Number.isFinite(options.commandTimeoutMs) || options.commandTimeoutMs <= 0)) {
17
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_TIMEOUT_INVALID: command timeout must be greater than zero");
18
+ }
19
+ this.commandTimeoutMs = options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
20
+ }
21
+ isAvailable() {
22
+ return this.options.executor !== undefined || Boolean(this.options.command?.trim());
23
+ }
24
+ async publish(request) {
25
+ validateRequest(request);
26
+ const executor = this.options.executor ?? (this.options.command?.trim()
27
+ ? commandExecutor(this.options.command.trim(), this.commandTimeoutMs)
28
+ : undefined);
29
+ if (!executor) {
30
+ return {
31
+ state: "blocked",
32
+ code: "FINAL_CUT_BACKGROUND_MATERIALIZATION_UNAVAILABLE",
33
+ message: "No explicit non-UI Final Cut materialization capability is configured",
34
+ retryable: true,
35
+ };
36
+ }
37
+ const artifact = await readFile(request.artifactPath, "utf8");
38
+ if (createHash("sha256").update(artifact).digest("hex") !== request.artifactDigest) {
39
+ throw new Error("MATERIALIZATION_ARTIFACT_CHANGED: the staged FCPXML artifact no longer matches its immutable digest");
40
+ }
41
+ if (timelineIrDigest(request.desired) !== request.desiredDigest) {
42
+ throw new Error("MATERIALIZATION_DESIRED_SNAPSHOT_INVALID: the staged desired Timeline IR digest is invalid");
43
+ }
44
+ const result = await executor({ ...request, desired: structuredClone(request.desired) });
45
+ return validateResult(result);
46
+ }
47
+ }
48
+ function validateRequest(request) {
49
+ if (!request.jobId.trim())
50
+ throw new Error("MATERIALIZATION_REQUEST_INVALID: jobId is required");
51
+ if (!request.artifactPath.trim() || !request.artifactDigest.trim()) {
52
+ throw new Error("MATERIALIZATION_REQUEST_INVALID: immutable artifact path and digest are required");
53
+ }
54
+ if (!request.desiredDigest.trim())
55
+ throw new Error("MATERIALIZATION_REQUEST_INVALID: desired digest is required");
56
+ if (request.collisionPolicy !== "create-only")
57
+ throw new Error("MATERIALIZATION_REQUEST_INVALID: publication must be create-only");
58
+ const { target } = request;
59
+ if (target.provider !== "final-cut" || !target.libraryUid.trim() || !target.eventUid.trim() || !target.projectUid.trim() || !target.sequenceUid.trim()) {
60
+ throw new Error("FCPXML_TARGET_BINDING_INVALID: library, event, project, and sequence identities are required");
61
+ }
62
+ if (request.destination.mode !== "versioned") {
63
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_REUSE_FORBIDDEN: background publication cannot overwrite an existing project");
64
+ }
65
+ if (!request.destination.projectUid.trim() || !request.destination.sequenceUid.trim()) {
66
+ throw new Error("MATERIALIZATION_DESTINATION_INVALID: versioned project and sequence identities are required");
67
+ }
68
+ validateTimelineIr(request.desired);
69
+ }
70
+ function validateResult(result) {
71
+ if (!result || (result.state !== "completed" && result.state !== "blocked")) {
72
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_RESPONSE_INVALID: capability returned an invalid result");
73
+ }
74
+ if (result.state === "blocked") {
75
+ if (typeof result.code !== "string" || typeof result.message !== "string" || !result.code.trim() || !result.message.trim()) {
76
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_RESPONSE_INVALID: blocked result is missing code or message");
77
+ }
78
+ return result;
79
+ }
80
+ validateTimelineIr(result.canonicalReadback);
81
+ validateTargetIdentity(result.canonicalTarget);
82
+ if (result.headedNativeVerified !== false) {
83
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_RESPONSE_INVALID: background publisher cannot claim headed-native verification");
84
+ }
85
+ return result;
86
+ }
87
+ function validateTargetIdentity(target) {
88
+ if (!target || !target.libraryUid?.trim() || !target.eventUid?.trim() || !target.projectUid?.trim() || !target.sequenceUid?.trim()) {
89
+ throw new Error("FINAL_CUT_BACKGROUND_MATERIALIZATION_RESPONSE_INVALID: canonical target identity is incomplete");
90
+ }
91
+ }
92
+ function commandExecutor(command, timeoutMs) {
93
+ return async (request) => {
94
+ let output;
95
+ try {
96
+ output = await runCommand(command, request, timeoutMs);
97
+ }
98
+ catch (error) {
99
+ const detail = error instanceof Error ? error.message : String(error);
100
+ const timedOut = detail.startsWith("FINAL_CUT_BACKGROUND_MATERIALIZATION_COMMAND_TIMEOUT");
101
+ return {
102
+ state: "blocked",
103
+ code: timedOut
104
+ ? "FINAL_CUT_BACKGROUND_MATERIALIZATION_COMMAND_TIMEOUT"
105
+ : "FINAL_CUT_BACKGROUND_MATERIALIZATION_COMMAND_UNAVAILABLE",
106
+ message: detail,
107
+ retryable: true,
108
+ };
109
+ }
110
+ let parsed;
111
+ try {
112
+ parsed = JSON.parse(output);
113
+ }
114
+ catch (error) {
115
+ throw new Error(`FINAL_CUT_BACKGROUND_MATERIALIZATION_RESPONSE_INVALID: ${error instanceof Error ? error.message : String(error)}`);
116
+ }
117
+ return validateResult(parsed);
118
+ };
119
+ }
120
+ function runCommand(command, request, timeoutMs) {
121
+ return new Promise((resolve, reject) => {
122
+ const child = spawn(command, [], { stdio: ["pipe", "pipe", "pipe"] });
123
+ let stdout = "";
124
+ let stderr = "";
125
+ let settled = false;
126
+ let closed = false;
127
+ let timeoutHandle;
128
+ let forceKillHandle;
129
+ const cleanup = () => {
130
+ if (timeoutHandle !== undefined)
131
+ clearTimeout(timeoutHandle);
132
+ if (forceKillHandle !== undefined)
133
+ clearTimeout(forceKillHandle);
134
+ };
135
+ const settle = (callback) => {
136
+ if (settled)
137
+ return;
138
+ settled = true;
139
+ cleanup();
140
+ callback();
141
+ };
142
+ child.stdout.setEncoding("utf8");
143
+ child.stderr.setEncoding("utf8");
144
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
145
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
146
+ child.once("error", (error) => settle(() => reject(error)));
147
+ child.once("close", (code) => {
148
+ closed = true;
149
+ if (settled) {
150
+ cleanup();
151
+ return;
152
+ }
153
+ if (code === 0) {
154
+ settle(() => resolve(stdout));
155
+ }
156
+ else {
157
+ settle(() => reject(new Error(`FINAL_CUT_BACKGROUND_MATERIALIZATION_COMMAND_FAILED: command exited ${code}: ${stderr.trim()}`)));
158
+ }
159
+ });
160
+ timeoutHandle = setTimeout(() => {
161
+ if (settled)
162
+ return;
163
+ child.kill("SIGTERM");
164
+ forceKillHandle = setTimeout(() => {
165
+ if (!closed)
166
+ child.kill("SIGKILL");
167
+ }, 1_000);
168
+ settled = true;
169
+ if (timeoutHandle !== undefined)
170
+ clearTimeout(timeoutHandle);
171
+ reject(new Error(`FINAL_CUT_BACKGROUND_MATERIALIZATION_COMMAND_TIMEOUT: command exceeded ${timeoutMs}ms`));
172
+ }, timeoutMs);
173
+ child.stdin.end(`${JSON.stringify(request)}\n`);
174
+ });
175
+ }
@@ -3,7 +3,7 @@ import { mkdtemp, rm, stat } from "node:fs/promises";
3
3
  import { basename, join } from "node:path";
4
4
  import { tmpdir } from "node:os";
5
5
  import { promisify } from "node:util";
6
- import { canonicalSnapshotDigest, withCapabilityFamilies, } from "../../../../packages/runtime/src/index.js";
6
+ import { canonicalSnapshotDigest, assertTimelineTargetReadAfterWrite, createTimelineTarget, resolveTimelineTarget, reconcileProjectCatalog, validateProjectCatalog, withCapabilityFamilies, CapabilityUnavailableError, } from "../../../../packages/runtime/src/index.js";
7
7
  import { FcpxmlDocumentAdapter } from "./fcpxml.js";
8
8
  const execFile = promisify(execFileCallback);
9
9
  /** Reads the active Final Cut project through its headed Export XML command. */
@@ -86,6 +86,8 @@ end using terms from
86
86
 
87
87
  tell application "System Events"
88
88
  tell process "Final Cut Pro"
89
+ set frontmost to true
90
+ delay 0.1
89
91
  if not frontmost then error "FINAL_CUT_CANONICAL_NOT_FRONTMOST: Final Cut Pro must be frontmost"
90
92
  set finalCut to it
91
93
  set fileMenu to menu "File" of menu bar 1
@@ -159,6 +161,16 @@ export function createFinalCutNativeTargetResolver(native) {
159
161
  throw new Error(`AMBIGUOUS_PROJECT_TARGET: Final Cut timeline has multiple occurrences for ${query}`);
160
162
  }
161
163
  const occurrence = located.occurrences[0];
164
+ const occurrenceIdentity = occurrence.identity ?? occurrence.nativeIdentity;
165
+ if (!occurrenceIdentity) {
166
+ throw new Error(`TARGET_MISMATCH: native occurrence has no stable identity for ${clip.id}`);
167
+ }
168
+ if (!occurrence.sequenceId) {
169
+ throw new Error(`TARGET_MISMATCH: native occurrence has no stable sequence identity for ${clip.id}`);
170
+ }
171
+ if (occurrence.sequenceId !== snapshot.timeline.id) {
172
+ throw new Error(`TARGET_MISMATCH: native occurrence sequence changed for ${clip.id}`);
173
+ }
162
174
  if (occurrence.sourceIdentity && occurrence.sourceIdentity !== match.sourceIdentity) {
163
175
  throw new Error(`TARGET_MISMATCH: native occurrence source identity changed for ${clip.id}`);
164
176
  }
@@ -183,6 +195,7 @@ export class FinalCutCanonicalNativeProvider {
183
195
  native;
184
196
  readSnapshotSource;
185
197
  resolveTarget;
198
+ backgroundCatalog;
186
199
  lastDigest;
187
200
  lastSnapshot;
188
201
  revisionSequence = 0;
@@ -193,28 +206,44 @@ export class FinalCutCanonicalNativeProvider {
193
206
  this.native = options.native;
194
207
  this.readSnapshotSource = options.readSnapshot;
195
208
  this.resolveTarget = options.resolveTarget;
209
+ this.backgroundCatalog = options.backgroundCatalog;
196
210
  }
197
211
  async getIdentity() {
198
212
  const identity = await this.live.getIdentity();
199
213
  return { ...identity, backend: "final-cut-native-canonical" };
200
214
  }
201
- async getCapabilities() {
215
+ async getCapabilities(options = {}) {
216
+ const backgroundCatalog = await this.resolveBackgroundCatalog();
217
+ const snapshotProbe = backgroundCatalog && options.probeCanonicalSnapshot !== false
218
+ ? await this.probeCanonicalSnapshot()
219
+ : {
220
+ available: false,
221
+ reason: backgroundCatalog
222
+ ? "canonical snapshot availability was not checked"
223
+ : "canonical timeline snapshot requires a background project catalog",
224
+ };
225
+ const canonicalSnapshotCapability = snapshotProbe.available
226
+ ? true
227
+ : unavailableCanonicalSnapshot(snapshotProbe.reason);
202
228
  return withCapabilityFamilies({
203
229
  editor: {
204
- projectRead: true,
205
- timelineSnapshotRead: true,
206
- timelineWrite: true,
230
+ projectRead: snapshotProbe.available,
231
+ timelineSnapshotRead: snapshotProbe.available,
232
+ timelineWrite: snapshotProbe.available,
207
233
  timelineArtifactWrite: false,
208
- readAfterWrite: true,
234
+ readAfterWrite: snapshotProbe.available,
209
235
  incrementalChanges: true,
210
- rollback: true,
236
+ rollback: snapshotProbe.available,
211
237
  assetDiscovery: false,
212
238
  liveStateRead: true,
213
239
  playheadWrite: false,
214
240
  frameCapture: false,
215
241
  playbackControl: false,
216
- projectCatalogRead: true,
217
- projectSelection: true,
242
+ projectCatalogRead: Boolean(backgroundCatalog),
243
+ projectSelection: false,
244
+ projectSelectionMode: "unavailable",
245
+ backgroundLibraryInspection: Boolean(backgroundCatalog),
246
+ compositeTransactions: snapshotProbe.available,
218
247
  },
219
248
  analyzers: {
220
249
  speechTranscribe: false,
@@ -225,9 +254,35 @@ export class FinalCutCanonicalNativeProvider {
225
254
  }, {
226
255
  backend: "final-cut-native-canonical",
227
256
  connectionBackend: "workflow-extension-ipc",
228
- canonicalDocument: { read: true, write: true, artifactWrite: false },
257
+ canonicalDocument: {
258
+ read: canonicalSnapshotCapability,
259
+ write: canonicalSnapshotCapability,
260
+ artifactWrite: false,
261
+ },
262
+ observation: {
263
+ library: this.backgroundCatalog
264
+ ? {
265
+ available: true,
266
+ backend: this.backgroundCatalog.backend ?? "final-cut-background-library",
267
+ guarantee: "observed",
268
+ }
269
+ : false,
270
+ },
229
271
  });
230
272
  }
273
+ async probeCanonicalSnapshot() {
274
+ try {
275
+ await this.readSnapshotSource();
276
+ return { available: true };
277
+ }
278
+ catch (error) {
279
+ const detail = error instanceof Error ? error.message : String(error);
280
+ return {
281
+ available: false,
282
+ reason: `canonical snapshot provider unavailable: ${detail}`,
283
+ };
284
+ }
285
+ }
231
286
  async read() {
232
287
  return this.readProject();
233
288
  }
@@ -247,15 +302,37 @@ export class FinalCutCanonicalNativeProvider {
247
302
  this.lastSnapshot = { ...snapshot, revision: this.revision };
248
303
  return structuredClone(this.lastSnapshot);
249
304
  }
305
+ async previewTransaction(operations, expectedRevision) {
306
+ const before = await this.readProject();
307
+ assertSameRevision(expectedRevision, before.revision);
308
+ 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));
314
+ preview.revision = previewRevision(preview, before.revision);
315
+ return preview;
316
+ }
317
+ async applyTransaction(operations, expectedRevision) {
318
+ const operation = supportedCanonicalOperation(operations);
319
+ await this.apply(operation, expectedRevision);
320
+ }
250
321
  async apply(operation, expectedRevision) {
251
322
  const before = await this.readProject();
252
323
  assertSameRevision(expectedRevision, before.revision);
253
324
  if (operation.type !== "rename-clip") {
254
325
  throw new Error(`CAPABILITY_UNAVAILABLE: final-cut native canonical provider does not support ${operation.type}`);
255
326
  }
327
+ validateCanonicalRename(operation);
256
328
  const clip = before.timeline.clips.find(({ id }) => id === operation.clipId);
257
329
  if (!clip)
258
330
  throw new Error(`CLIP_NOT_FOUND: ${operation.clipId}`);
331
+ const timelineTarget = createTimelineTarget(before, {
332
+ occurrenceId: clip.id,
333
+ mediaId: clip.mediaId,
334
+ });
335
+ resolveTimelineTarget(before, timelineTarget);
259
336
  await this.resolveTarget(clip, before);
260
337
  const nativeResult = await this.native.renameSelectedClip(operation.name);
261
338
  if (!nativeResult.operationId || !nativeResult.undoAvailable) {
@@ -276,6 +353,7 @@ export class FinalCutCanonicalNativeProvider {
276
353
  if (canonicalSnapshotDigest(after) === this.pending.beforeDigest) {
277
354
  throw new Error("FINAL_CUT_CANONICAL_READBACK_FAILED: native edit did not change the canonical digest");
278
355
  }
356
+ assertTimelineTargetReadAfterWrite(timelineTarget, before, after);
279
357
  this.pending.afterRevision = after.revision;
280
358
  return after.revision;
281
359
  }
@@ -322,28 +400,19 @@ export class FinalCutCanonicalNativeProvider {
322
400
  this.pending = undefined;
323
401
  }
324
402
  async listProjects() {
325
- const snapshot = await this.readProject();
326
- return {
327
- projects: [{
328
- id: snapshot.projectId,
329
- name: snapshot.projectName,
330
- sequences: [{ id: snapshot.timeline.id, name: snapshot.timeline.name }],
331
- }],
332
- activeProjectId: snapshot.projectId,
333
- activeSequenceId: snapshot.timeline.id,
334
- };
403
+ const backgroundCatalog = await this.resolveBackgroundCatalog();
404
+ if (!backgroundCatalog) {
405
+ throw new CapabilityUnavailableError("project.list", "editor.projectCatalogRead", {
406
+ available: false,
407
+ backend: "final-cut-native-canonical",
408
+ guarantee: "none",
409
+ unavailableReason: "background project catalog is unavailable; canonical timeline snapshot export (File > Export XML) requires a headed Final Cut UI",
410
+ });
411
+ }
412
+ return this.readBackgroundCatalog(backgroundCatalog);
335
413
  }
336
414
  async selectProject(selection) {
337
- const catalog = await this.listProjects();
338
- const project = catalog.projects.find(({ id }) => id === selection.projectId);
339
- if (!project)
340
- throw new Error(`TARGET_MISMATCH: active project is not ${selection.projectId}`);
341
- const sequenceId = selection.sequenceId ?? (project.sequences.length === 1 ? project.sequences[0]?.id : undefined);
342
- if (!sequenceId)
343
- throw new Error(`AMBIGUOUS_PROJECT_TARGET: sequenceId is required for ${selection.projectId}`);
344
- if (sequenceId !== catalog.activeSequenceId)
345
- throw new Error(`TARGET_MISMATCH: active sequence is not ${sequenceId}`);
346
- return catalog;
415
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project selection is not exposed by the background provider");
347
416
  }
348
417
  async readLiveState() {
349
418
  return this.live.readLiveState();
@@ -353,13 +422,101 @@ export class FinalCutCanonicalNativeProvider {
353
422
  }
354
423
  async assertActiveTarget(snapshot) {
355
424
  const live = await this.live.readLiveState();
356
- if (live.project && live.project.name !== snapshot.projectName) {
425
+ if (!live.project || live.project.id !== snapshot.projectId) {
426
+ throw new Error(`TARGET_MISMATCH: active project identity ${live.project?.id ?? "<unavailable>"} does not match exported project ${snapshot.projectId}`);
427
+ }
428
+ if (live.project.name !== snapshot.projectName) {
357
429
  throw new Error(`TARGET_MISMATCH: exported project ${snapshot.projectName} is not active Final Cut project ${live.project.name}`);
358
430
  }
359
- if (live.sequence && live.sequence.name !== snapshot.timeline.name) {
431
+ if (!live.sequence || live.sequence.id !== snapshot.timeline.id) {
432
+ throw new Error(`TARGET_MISMATCH: active sequence identity ${live.sequence?.id ?? "<unavailable>"} does not match exported sequence ${snapshot.timeline.id}`);
433
+ }
434
+ if (live.sequence.name !== snapshot.timeline.name) {
360
435
  throw new Error(`TARGET_MISMATCH: exported sequence ${snapshot.timeline.name} is not active Final Cut sequence ${live.sequence.name}`);
361
436
  }
362
437
  }
438
+ async resolveBackgroundCatalog() {
439
+ if (this.backgroundCatalog)
440
+ return this.backgroundCatalog;
441
+ if (!this.live.listProjects || !this.live.getCapabilities)
442
+ return undefined;
443
+ try {
444
+ const capabilities = await this.live.getCapabilities();
445
+ if (!capabilities.editor.projectCatalogRead)
446
+ return undefined;
447
+ const identity = await this.live.getIdentity();
448
+ return {
449
+ backend: identity.backend,
450
+ listProjects: () => this.live.listProjects(),
451
+ };
452
+ }
453
+ catch {
454
+ return undefined;
455
+ }
456
+ }
457
+ async readBackgroundCatalog(provider) {
458
+ const before = await this.readLiveStateSafely();
459
+ const catalog = await provider.listProjects();
460
+ validateProjectCatalog(catalog);
461
+ const after = await this.readLiveStateSafely();
462
+ const liveIdentity = before && after ? await this.live.getIdentity() : undefined;
463
+ return reconcileProjectCatalog(catalog, {
464
+ ...(before && after ? { before, after } : {}),
465
+ provenance: {
466
+ catalog: {
467
+ source: "background-library",
468
+ backend: provider.backend ?? "final-cut-background-library",
469
+ guarantee: "observed",
470
+ },
471
+ ...(liveIdentity ? {
472
+ live: {
473
+ source: "live-socket",
474
+ backend: liveIdentity.backend,
475
+ guarantee: "observed",
476
+ },
477
+ } : {}),
478
+ selection: {
479
+ available: false,
480
+ mode: "unavailable",
481
+ unavailableReason: "project selection is not exposed by the background provider",
482
+ },
483
+ },
484
+ });
485
+ }
486
+ async readLiveStateSafely() {
487
+ try {
488
+ return await this.live.readLiveState();
489
+ }
490
+ catch {
491
+ return undefined;
492
+ }
493
+ }
494
+ }
495
+ 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");
498
+ }
499
+ return validateCanonicalRename(operations[0]);
500
+ }
501
+ function validateCanonicalRename(operation) {
502
+ if (!operation.name.trim())
503
+ throw new Error("INVALID_OPERATION: clip name cannot be empty");
504
+ return operation;
505
+ }
506
+ function unavailableCanonicalSnapshot(reason) {
507
+ return {
508
+ available: false,
509
+ backend: "final-cut-native-canonical",
510
+ guarantee: "none",
511
+ unavailableReason: reason,
512
+ };
513
+ }
514
+ function previewRevision(snapshot, before) {
515
+ return {
516
+ id: `canonical:${canonicalSnapshotDigest(snapshot)}`,
517
+ sequence: before.sequence + 1,
518
+ timestamp: new Date().toISOString(),
519
+ };
363
520
  }
364
521
  function assertSameRevision(expected, actual) {
365
522
  if (!sameRevision(expected, actual))
@@ -4,7 +4,7 @@ import { existsSync } from "node:fs";
4
4
  import { promisify } from "node:util";
5
5
  import { homedir } from "node:os";
6
6
  import { dirname, join, resolve } from "node:path";
7
- import { withCapabilityFamilies } from "../../../../packages/runtime/src/index.js";
7
+ import { withCanonicalTimelineMode, withCapabilityFamilies } from "../../../../packages/runtime/src/index.js";
8
8
  import { createFinalCutLiveAdapter, DEFAULT_FINAL_CUT_LIVE_SOCKET } from "./live.js";
9
9
  const execFile = promisify(execFileCallback);
10
10
  export function assertCanonicalProviderConfiguration(options) {
@@ -104,13 +104,19 @@ export class FinalCutConnectionManager {
104
104
  try {
105
105
  this.update({ state: "detecting", lastError: undefined });
106
106
  const existing = await this.tryProbe();
107
- if (existing)
108
- return this.ready(existing);
107
+ this.update({ extensionInstalled: await pathExists(this.extensionInstallPath) });
108
+ if (existing.result)
109
+ return this.ready(existing.result);
109
110
  if (this.canonicalProviderRequired) {
110
111
  return this.fail("FINAL_CUT_CANONICAL_PROVIDER_UNAVAILABLE", `Canonical live provider is unavailable at ${this.socketPath}; metadata-only fallback is disabled`, "needs-user-action");
111
112
  }
112
113
  if (this.headless) {
113
- return this.fail("FINAL_CUT_HEADLESS_SOCKET_UNAVAILABLE", `Headless mode only probes the existing Workflow Extension socket at ${this.socketPath}; it does not launch or activate Final Cut Pro`, "unavailable");
114
+ this.update({ state: "waiting-for-socket" });
115
+ const waiting = await this.waitForHeadlessBridge(existing.error);
116
+ if (waiting.result)
117
+ return this.ready(waiting.result);
118
+ const failure = headlessProbeFailure(waiting.error, this.socketPath);
119
+ return this.fail(failure.code, failure.message, "unavailable");
114
120
  }
115
121
  const editorDetected = await this.detectFinalCut();
116
122
  this.update({ editorDetected });
@@ -157,8 +163,8 @@ export class FinalCutConnectionManager {
157
163
  let nextActivationAt = Date.now() + this.activationRetryIntervalMs;
158
164
  while (Date.now() < deadline) {
159
165
  const result = await this.tryProbe();
160
- if (result)
161
- return this.ready(result);
166
+ if (result.result)
167
+ return this.ready(result.result);
162
168
  if (Date.now() >= nextActivationAt) {
163
169
  try {
164
170
  await this.activateWithDeadline(deadline);
@@ -186,24 +192,36 @@ export class FinalCutConnectionManager {
186
192
  }
187
193
  async tryProbe() {
188
194
  try {
189
- return await this.probe();
195
+ return { result: await this.probe() };
190
196
  }
191
- catch {
192
- return undefined;
197
+ catch (error) {
198
+ return { error };
199
+ }
200
+ }
201
+ async waitForHeadlessBridge(initialError) {
202
+ const deadline = Date.now() + this.startupTimeoutMs;
203
+ let attempt = { error: initialError };
204
+ while (Date.now() < deadline) {
205
+ if (isIncompatibleProbeError(attempt.error))
206
+ return attempt;
207
+ await this.sleep(Math.min(this.pollIntervalMs, Math.max(1, deadline - Date.now())));
208
+ attempt = await this.tryProbe();
209
+ if (attempt.result)
210
+ return attempt;
193
211
  }
212
+ return attempt;
194
213
  }
195
214
  ready(result) {
196
- const capabilities = withCapabilityFamilies(result.capabilities, {
215
+ const capabilities = withCanonicalTimelineMode(withCapabilityFamilies(result.capabilities, {
197
216
  backend: result.identity.backend,
198
217
  connectionBackend: result.identity.backend,
199
- });
218
+ }));
200
219
  if (this.canonicalProviderRequired && capabilities.editor.canonicalTimelineMode !== "canonical-write") {
201
220
  return this.fail("FINAL_CUT_CANONICAL_PROVIDER_REQUIRED", `Canonical live provider at ${this.socketPath} reports ${capabilities.editor.canonicalTimelineMode}; canonical-write is required`, "needs-user-action");
202
221
  }
203
222
  this.update({
204
223
  state: "ready",
205
224
  editorDetected: true,
206
- extensionInstalled: true,
207
225
  identity: result.identity,
208
226
  capabilities,
209
227
  lastError: undefined,
@@ -211,7 +229,12 @@ export class FinalCutConnectionManager {
211
229
  return this.getStatus();
212
230
  }
213
231
  fail(code, message, state) {
214
- this.update({ state, lastError: { code, message } });
232
+ this.update({
233
+ state,
234
+ identity: undefined,
235
+ capabilities: undefined,
236
+ lastError: { code, message },
237
+ });
215
238
  return this.getStatus();
216
239
  }
217
240
  update(patch) {
@@ -304,10 +327,7 @@ export class FinalCutConnectionManager {
304
327
  }
305
328
  function defaultProbe(socketPath) {
306
329
  const adapter = createFinalCutLiveAdapter(socketPath);
307
- return async () => ({
308
- identity: await adapter.getIdentity(),
309
- capabilities: await adapter.getCapabilities(),
310
- });
330
+ return () => adapter.inspect();
311
331
  }
312
332
  async function defaultDetectFinalCut(appPath) {
313
333
  try {
@@ -396,3 +416,21 @@ function isActivationTimeout(error) {
396
416
  const message = String(error);
397
417
  return message.includes("-1712") || message.includes("ETIMEDOUT") || message.includes("timed out");
398
418
  }
419
+ function isIncompatibleProbeError(error) {
420
+ return String(error).includes("FINAL_CUT_LIVE_PROTOCOL")
421
+ || String(error).includes("UNSUPPORTED_METHOD")
422
+ || String(error).includes("CAPABILITY_UNAVAILABLE");
423
+ }
424
+ function headlessProbeFailure(error, socketPath) {
425
+ const detail = error instanceof Error ? error.message : String(error ?? "unknown probe failure");
426
+ if (isIncompatibleProbeError(error)) {
427
+ return {
428
+ code: "FINAL_CUT_HEADLESS_PROTOCOL_INCOMPATIBLE",
429
+ message: `The Workflow Extension endpoint at ${socketPath} is incompatible with Framekit's live protocol: ${detail}`,
430
+ };
431
+ }
432
+ return {
433
+ code: "FINAL_CUT_HEADLESS_SOCKET_UNAVAILABLE",
434
+ message: `Headless mode could not connect to the Workflow Extension socket at ${socketPath}: ${detail}. It does not launch or activate Final Cut Pro`,
435
+ };
436
+ }