@morshoto/framekit 0.1.17 → 0.1.18

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 (26) hide show
  1. package/README.md +10 -4
  2. package/dist-package/adapters/final-cut/typescript/src/canonical.js +19 -7
  3. package/dist-package/adapters/final-cut/typescript/src/connection.js +5 -3
  4. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +128 -29
  5. package/dist-package/adapters/final-cut/typescript/src/index.js +1 -0
  6. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +60 -1
  7. package/dist-package/adapters/final-cut/typescript/src/live.js +2 -2
  8. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +213 -0
  9. package/dist-package/adapters/final-cut/typescript/src/publisher.js +762 -238
  10. package/dist-package/adapters/final-cut/typescript/src/session.js +6 -1
  11. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +200 -48
  12. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +17 -7
  13. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +2 -2
  14. package/dist-package/apps/cli/src/main.js +34 -19
  15. package/dist-package/apps/mcp-server/src/build-alignment.js +59 -0
  16. package/dist-package/apps/mcp-server/src/build-identity.js +30 -0
  17. package/dist-package/apps/mcp-server/src/build-identity.json +5 -0
  18. package/dist-package/apps/mcp-server/src/headless-project-snapshot.js +101 -0
  19. package/dist-package/apps/mcp-server/src/headless-projects.js +255 -16
  20. package/dist-package/apps/mcp-server/src/main.js +27 -3
  21. package/dist-package/apps/mcp-server/src/server.js +270 -49
  22. package/dist-package/apps/mcp-server/src/version.js +21 -2
  23. package/dist-package/packages/runtime/src/application/media-analysis-service.js +15 -5
  24. package/dist-package/packages/runtime/src/runtime.js +6 -0
  25. package/dist-package/packages/runtime/src/timeline/editing-session.js +7 -2
  26. package/package.json +9 -9
@@ -1,10 +1,22 @@
1
1
  import { execFile as execFileCallback } from "node:child_process";
2
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { chmodSync, constants, createReadStream, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { access, lstat, mkdtemp, open, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
3
4
  import { createHash, randomUUID } from "node:crypto";
4
- import { basename, join } from "node:path";
5
+ import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
5
6
  import { tmpdir } from "node:os";
6
7
  import { promisify } from "node:util";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
+ import { FcpxmlDocumentAdapter } from "./fcpxml.js";
10
+ import { verifyFinalCutPublishReadback } from "./publish-readback.js";
7
11
  const execFile = promisify(execFileCallback);
12
+ export function parseFinalCutProjectPublishRoute(value, backgroundDeliveryAvailable) {
13
+ if (value === undefined || value === "") {
14
+ return backgroundDeliveryAvailable ? "background-document-open" : "headed-apple-event";
15
+ }
16
+ if (value === "background-document-open" || value === "headed-apple-event")
17
+ return value;
18
+ throw new Error(`FRAMEKIT_FINAL_CUT_PUBLISH_ROUTE_INVALID: unsupported route ${value}`);
19
+ }
8
20
  /** Imports a validated FCPXML artifact as a new Final Cut project. */
9
21
  export class FinalCutProjectPublisher {
10
22
  enabled;
@@ -12,9 +24,11 @@ export class FinalCutProjectPublisher {
12
24
  executor;
13
25
  liveState;
14
26
  targetBinding;
27
+ readCanonicalSnapshot;
28
+ headlessSourceVerifier;
15
29
  documentDelivery;
16
- targetLibraryUid;
17
- allowHeadedFallback;
30
+ publishRoute;
31
+ publishJobsDirectory;
18
32
  verificationTimeoutMs;
19
33
  pollIntervalMs;
20
34
  publishJobs = new Map();
@@ -25,42 +39,82 @@ export class FinalCutProjectPublisher {
25
39
  this.executor = options.executor ?? runAppleScript;
26
40
  this.liveState = options.liveState;
27
41
  this.targetBinding = options.targetBinding;
42
+ this.readCanonicalSnapshot = options.readCanonicalSnapshot;
43
+ this.headlessSourceVerifier = options.headlessSourceVerifier;
28
44
  this.documentDelivery = options.documentDelivery;
29
- this.targetLibraryUid = options.targetLibraryUid;
30
- this.allowHeadedFallback = options.allowHeadedFallback ?? false;
45
+ this.publishRoute = options.publishRoute ?? (this.documentDelivery ? "background-document-open" : "headed-apple-event");
46
+ this.publishJobsDirectory = options.publishJobsDirectory;
31
47
  this.verificationTimeoutMs = Math.max(0, options.verificationTimeoutMs ?? 15_000);
32
48
  this.pollIntervalMs = Math.max(0, options.pollIntervalMs ?? options.waitMs ?? 100);
49
+ this.loadPersistedPublishJobs();
33
50
  }
34
51
  isAvailable() {
35
- return this.enabled;
52
+ return this.inspectReadiness().available;
53
+ }
54
+ /** Describe configured handoff providers without querying or changing Final Cut. */
55
+ inspectReadiness() {
56
+ const reasons = [];
57
+ if (!this.enabled) {
58
+ reasons.push({
59
+ code: "FINAL_CUT_PUBLISH_DISABLED",
60
+ message: "Final Cut project publishing is disabled",
61
+ });
62
+ }
63
+ if (!this.liveState) {
64
+ reasons.push({
65
+ code: "FINAL_CUT_PUBLISH_VERIFICATION_UNAVAILABLE",
66
+ message: "Live Final Cut project and sequence verification is unavailable",
67
+ });
68
+ }
69
+ if (!this.targetBinding) {
70
+ reasons.push({
71
+ code: "FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE",
72
+ message: "No native provider can bind the imported artifact to a created target",
73
+ });
74
+ }
75
+ if (!this.readCanonicalSnapshot) {
76
+ reasons.push({
77
+ code: "FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE",
78
+ message: "Headed canonical timeline readback is unavailable",
79
+ });
80
+ }
81
+ return {
82
+ available: reasons.length === 0,
83
+ targetBindingAvailable: Boolean(this.targetBinding),
84
+ reasons,
85
+ };
36
86
  }
37
87
  executionMode() {
38
- return this.documentDelivery ? "background-capable" : "headed-only";
88
+ // Dispatch may be background-capable, but native semantic readback uses
89
+ // Final Cut's headed File > Export XML command.
90
+ return "headed-only";
39
91
  }
40
92
  async preparePublish(request) {
41
- const { identity } = await this.readValidatedSource(request);
93
+ const validated = await this.readValidatedSource(request);
94
+ const targetLibraryPath = await validateTargetLibraryPath(request.targetLibraryPath, Boolean(this.documentDelivery)
95
+ || request.sourceTransactionId.startsWith("headless-rough-cut:"));
42
96
  const job = {
43
97
  jobId: `publish-job-${randomUUID()}`,
44
98
  state: "awaiting-confirmation",
45
99
  nextAction: "confirm",
46
100
  retryable: false,
47
- executionMode: this.documentDelivery ? "background-capable" : "headed-only",
101
+ executionMode: "headed-only",
48
102
  sourceTransactionId: request.sourceTransactionId,
49
- sourcePath: this.sourcePath,
50
- sourceTarget: { kind: "artifact", artifactPath: this.sourcePath },
103
+ sourcePath: request.artifactPath,
104
+ sourceTarget: { kind: "artifact", artifactPath: request.artifactPath },
51
105
  artifactDigest: request.artifactDigest,
52
- projectName: identity.projectName,
53
- sequenceName: identity.sequenceName,
106
+ ...(targetLibraryPath ? { targetLibraryPath } : {}),
107
+ projectName: validated.identity.projectName,
108
+ sequenceName: validated.identity.sequenceName,
54
109
  confirmationRequired: true,
55
110
  handoff: {
56
- mode: this.documentDelivery ? "background-document-open" : "headed-only",
57
- backgroundSupported: Boolean(this.documentDelivery),
58
- reason: this.documentDelivery
59
- ? "Uses the native FCPXML document-open bridge with activates=false; Final Cut may still return an explicit user-interaction-required boundary when target selection cannot be guaranteed."
60
- : "Final Cut has no supported non-UI project publishing contract; use the explicit headed handoff and verify the created target.",
111
+ mode: this.publishRoute === "background-document-open" ? "background-document-open" : "headed-only",
112
+ route: this.publishRoute,
113
+ backgroundSupported: this.publishRoute === "background-document-open",
114
+ reason: publishHandoffReason(this.publishRoute),
61
115
  },
62
116
  };
63
- this.publishJobs.set(job.jobId, job);
117
+ this.persistPublishJob(job);
64
118
  return clonePublishJob(job);
65
119
  }
66
120
  getPublishJob(jobId) {
@@ -70,9 +124,10 @@ export class FinalCutProjectPublisher {
70
124
  return clonePublishJob(job);
71
125
  }
72
126
  async executePublishJob(jobId, confirm) {
73
- const job = this.publishJobs.get(jobId);
74
- if (!job)
127
+ const storedJob = this.publishJobs.get(jobId);
128
+ if (!storedJob)
75
129
  throw new Error(`PUBLISH_JOB_NOT_FOUND: unknown publish job ${jobId}`);
130
+ const job = clonePublishJob(storedJob);
76
131
  if (job.state === "verified")
77
132
  return clonePublishJob(job);
78
133
  if (job.state === "failed" && !job.retryable)
@@ -87,10 +142,14 @@ export class FinalCutProjectPublisher {
87
142
  code: "CAPABILITY_UNAVAILABLE",
88
143
  message: "Final Cut project publishing is unavailable; bring Final Cut Pro to the front and retry this job",
89
144
  };
145
+ this.persistPublishJob(job);
90
146
  return clonePublishJob(job);
91
147
  }
92
148
  if (!this.liveState)
93
149
  return this.markAwaitingFinalCut(job, "FINAL_CUT_PUBLISH_VERIFICATION_UNAVAILABLE", "Final Cut project state verification is unavailable; retry this job when the live provider is ready");
150
+ if (!this.readCanonicalSnapshot) {
151
+ return this.markFailed(job, new Error("FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE: headed canonical timeline readback is not configured; no import was attempted"));
152
+ }
94
153
  if (job.state === "verification-pending")
95
154
  return this.resumePublishVerification(job);
96
155
  let validated;
@@ -99,23 +158,15 @@ export class FinalCutProjectPublisher {
99
158
  sourceTransactionId: job.sourceTransactionId,
100
159
  artifactPath: job.sourcePath,
101
160
  artifactDigest: job.artifactDigest,
161
+ ...(job.targetLibraryPath ? { targetLibraryPath: job.targetLibraryPath } : {}),
102
162
  });
163
+ await validateTargetLibraryPath(job.targetLibraryPath, Boolean(this.documentDelivery) || job.sourceTransactionId.startsWith("headless-rough-cut:"));
103
164
  }
104
165
  catch (error) {
105
166
  return this.markFailed(job, error);
106
167
  }
107
- let targetBinding;
108
- try {
109
- if (!this.targetBinding) {
110
- throw new Error("FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE: no native provider can bind the imported artifact to a created target; no import was attempted");
111
- }
112
- targetBinding = await this.targetBinding();
113
- if (!targetBinding.projectId.trim() || !targetBinding.sequenceId.trim()) {
114
- throw new Error("FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE: native target binding did not return project and sequence identities; no import was attempted");
115
- }
116
- }
117
- catch (error) {
118
- return this.markFailed(job, error);
168
+ if (!this.targetBinding) {
169
+ return this.markFailed(job, new Error("FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE: no native provider can bind the imported artifact to a created target; no import was attempted"));
119
170
  }
120
171
  let beforeLive;
121
172
  try {
@@ -125,25 +176,51 @@ export class FinalCutProjectPublisher {
125
176
  const normalized = publishError(error);
126
177
  return this.markAwaitingFinalCut(job, normalized.code, normalized.message);
127
178
  }
128
- const runtime = { beforeLive, identity: validated.identity, targetBinding };
179
+ const runtime = {
180
+ beforeLive,
181
+ identity: validated.identity,
182
+ ...(job.targetLibraryPath ? { targetLibraryPath: job.targetLibraryPath } : {}),
183
+ ...(validated.sourceProof ? { targetLibraryUid: validated.sourceProof.targetLibraryUid } : {}),
184
+ ...(validated.sourceProof ? { approvedSourceMediaDigests: structuredClone(validated.sourceProof.sourceMediaDigests) } : {}),
185
+ };
186
+ const previousRuntime = this.publishJobRuntime.get(job.jobId);
129
187
  this.publishJobRuntime.set(job.jobId, runtime);
130
188
  job.state = "verification-pending";
131
189
  job.nextAction = "status";
132
190
  job.retryable = false;
191
+ try {
192
+ this.persistPublishJob(job);
193
+ }
194
+ catch (error) {
195
+ if (previousRuntime)
196
+ this.publishJobRuntime.set(job.jobId, previousRuntime);
197
+ else
198
+ this.publishJobRuntime.delete(job.jobId);
199
+ throw error;
200
+ }
133
201
  try {
134
202
  const result = await this.importAndVerify({
135
203
  sourceTransactionId: job.sourceTransactionId,
136
204
  artifactPath: job.sourcePath,
137
205
  artifactDigest: job.artifactDigest,
206
+ ...(job.targetLibraryPath ? { targetLibraryPath: job.targetLibraryPath } : {}),
138
207
  confirm: true,
139
- }, validated.source, validated.identity, beforeLive, runtime);
208
+ }, validated.source, validated.identity, beforeLive, runtime, job);
140
209
  return this.markVerified(job, result);
141
210
  }
142
211
  catch (error) {
212
+ const normalized = publishError(error);
213
+ if (normalized.code === "PUBLISH_TARGET_LIBRARY_RESERVED")
214
+ return this.markFailed(job, error);
215
+ if (!runtime.importAttempted) {
216
+ await releaseTargetLibraryReservation(runtime);
217
+ return this.markAwaitingFinalCut(job, normalized.code, normalized.message);
218
+ }
143
219
  job.state = "verification-pending";
144
220
  job.nextAction = "retry";
145
221
  job.retryable = true;
146
- job.error = publishError(error);
222
+ job.error = normalized;
223
+ this.persistPublishJob(job);
147
224
  return clonePublishJob(job);
148
225
  }
149
226
  }
@@ -152,93 +229,198 @@ export class FinalCutProjectPublisher {
152
229
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing is disabled; configure FRAMEKIT_EDITOR=final-cut-live and FRAMEKIT_FCPXML_PATH, and ensure Final Cut is reachable through FRAMEKIT_FINAL_CUT_SOCKET");
153
230
  if (!request.confirm)
154
231
  throw new Error("PUBLISH_CONFIRMATION_REQUIRED: set confirm=true to create a new Final Cut project");
232
+ if (request.sourceTransactionId.startsWith("headless-rough-cut:")) {
233
+ throw new Error("HEADLESS_ROUGH_CUT_PUBLISH_JOB_REQUIRED: use artifact.publish.preview and artifact.publish.execute to preserve the approved target binding");
234
+ }
235
+ if (!this.readCanonicalSnapshot) {
236
+ throw new Error("FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE: headed canonical timeline readback is not configured; no import was attempted");
237
+ }
155
238
  const { source, identity } = await this.readValidatedSource(request);
156
239
  if (!this.liveState) {
157
240
  throw new Error("FINAL_CUT_PUBLISH_VERIFICATION_UNAVAILABLE: live project and sequence state is required");
158
241
  }
242
+ if (!this.targetBinding) {
243
+ throw new Error("FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE: no native provider can bind the imported artifact to a created target; no import was attempted");
244
+ }
245
+ const targetLibraryPath = await validateTargetLibraryPath(request.targetLibraryPath, Boolean(this.documentDelivery) || request.sourceTransactionId.startsWith("headless-rough-cut:"));
159
246
  const beforeLive = await readLiveState(this.liveState, "before import");
160
- return this.importAndVerify(request, source, identity, beforeLive);
247
+ const runtime = {
248
+ beforeLive,
249
+ identity,
250
+ ...(targetLibraryPath ? { targetLibraryPath } : {}),
251
+ };
252
+ try {
253
+ return await this.importAndVerify({ ...request, ...(targetLibraryPath ? { targetLibraryPath } : {}) }, source, identity, beforeLive, runtime);
254
+ }
255
+ catch (error) {
256
+ if (!runtime.importAttempted)
257
+ throw error;
258
+ const normalized = publishError(error);
259
+ const job = {
260
+ jobId: `publish-job-${randomUUID()}`,
261
+ state: "verification-pending",
262
+ nextAction: "retry",
263
+ retryable: true,
264
+ executionMode: "headed-only",
265
+ sourceTransactionId: request.sourceTransactionId,
266
+ sourcePath: this.sourcePath,
267
+ sourceTarget: { kind: "artifact", artifactPath: this.sourcePath },
268
+ artifactDigest: request.artifactDigest,
269
+ ...(targetLibraryPath ? { targetLibraryPath } : {}),
270
+ projectName: identity.projectName,
271
+ sequenceName: identity.sequenceName,
272
+ confirmationRequired: false,
273
+ handoff: {
274
+ mode: "headed-only",
275
+ route: this.publishRoute,
276
+ backgroundSupported: false,
277
+ reason: "A direct publish may have reached Final Cut; verify this job before another import so its target reservation remains protected.",
278
+ },
279
+ error: normalized,
280
+ };
281
+ this.publishJobRuntime.set(job.jobId, runtime);
282
+ this.persistPublishJob(job);
283
+ throw new Error(`FINAL_CUT_PUBLISH_VERIFICATION_PENDING: publish job ${job.jobId} retained the target reservation; inspect with artifact.publish.status and resume with artifact.publish.execute (${normalized.message})`);
284
+ }
161
285
  }
162
286
  async readValidatedSource(request) {
163
287
  if (!request.sourceTransactionId.trim())
164
288
  throw new Error("INVALID_PUBLISH_REQUEST: sourceTransactionId is required");
165
289
  if (!request.artifactDigest.trim())
166
290
  throw new Error("INVALID_PUBLISH_REQUEST: artifactDigest is required");
167
- if (request.artifactPath !== this.sourcePath) {
291
+ let sourceProof;
292
+ if (request.sourceTransactionId.startsWith("headless-rough-cut:")) {
293
+ if (!this.headlessSourceVerifier) {
294
+ throw new Error("HEADLESS_ROUGH_CUT_VERIFICATION_UNAVAILABLE: no approved headless source verifier is configured");
295
+ }
296
+ sourceProof = await this.headlessSourceVerifier(request);
297
+ if (!sourceProof.targetLibraryUid.trim()) {
298
+ throw new Error("HEADLESS_ROUGH_CUT_TARGET_INVALID: approved FCPXML has no explicit target library identity");
299
+ }
300
+ validateApprovedSourceMediaDigests(sourceProof.sourceMediaDigests);
301
+ }
302
+ else if (request.artifactPath !== this.sourcePath) {
168
303
  throw new Error(`PUBLISH_TARGET_MISMATCH: requested artifact ${request.artifactPath} is not managed by this publisher`);
169
304
  }
170
- const source = await readFile(this.sourcePath, "utf8");
305
+ const source = await readFile(request.artifactPath, "utf8");
171
306
  if (hash(source) !== request.artifactDigest) {
172
- throw new Error("PUBLISH_SOURCE_CHANGED: managed FCPXML artifact changed after transaction verification");
307
+ throw new Error(sourceProof
308
+ ? "HEADLESS_ROUGH_CUT_ARTIFACT_CHANGED: approved FCPXML changed after execution verification"
309
+ : "PUBLISH_SOURCE_CHANGED: managed FCPXML artifact changed after transaction verification");
173
310
  }
174
311
  if (!source.includes("<fcpxml") || !source.includes("<project")) {
175
312
  throw new Error("FINAL_CUT_PUBLISH_VALIDATION_FAILED: source is not a valid FCPXML project artifact");
176
313
  }
177
- return { source, identity: projectIdentityFromXml(source) };
314
+ return {
315
+ source,
316
+ identity: projectIdentityFromXml(source),
317
+ ...(sourceProof ? { sourceProof } : {}),
318
+ };
178
319
  }
179
- async importAndVerify(request, source, identity, beforeLive, runtime) {
320
+ async importAndVerify(request, source, identity, beforeLive, runtime, publishJob) {
180
321
  if (!this.liveState)
181
322
  throw new Error("FINAL_CUT_PUBLISH_VERIFICATION_UNAVAILABLE: live project and sequence state is required");
182
- if (runtime && !runtime.targetBinding) {
183
- throw new Error("FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE: no stable created-target identity was retained across verification; no publish success was reported");
323
+ if (!this.targetBinding)
324
+ throw new Error("FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE: no native provider can bind the imported artifact to a created target; no import was attempted");
325
+ if (!this.readCanonicalSnapshot)
326
+ throw new Error("FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE: headed canonical timeline readback is not configured; no import was attempted");
327
+ const route = publishJob?.handoff.route ?? this.publishRoute;
328
+ const targetLibraryPath = await validateTargetLibraryPath(request.targetLibraryPath, Boolean(this.documentDelivery) || request.sourceTransactionId.startsWith("headless-rough-cut:"));
329
+ const expectedSnapshot = await new FcpxmlDocumentAdapter(request.artifactPath, undefined, {
330
+ allowMissingImmutableIdsForReadback: true,
331
+ }).readProject();
332
+ const sourceMediaDigests = await captureSourceMediaDigests(expectedSnapshot);
333
+ if (runtime?.approvedSourceMediaDigests) {
334
+ assertSourceMediaMatchesApproval(sourceMediaDigests, runtime.approvedSourceMediaDigests);
335
+ }
336
+ if (hash(await readFile(request.artifactPath, "utf8")) !== request.artifactDigest) {
337
+ throw new Error("PUBLISH_SOURCE_CHANGED: managed FCPXML artifact changed before import");
338
+ }
339
+ if (runtime) {
340
+ runtime.expectedSnapshot = structuredClone(expectedSnapshot);
341
+ runtime.sourceMediaDigests = structuredClone(sourceMediaDigests);
184
342
  }
185
343
  const directory = await mkdtemp(join(tmpdir(), "framekit-finalcut-publish-"));
186
- const importedPath = join(directory, basename(this.sourcePath));
344
+ const importedPath = join(directory, basename(request.artifactPath));
187
345
  if (runtime)
188
346
  runtime.importedPath = importedPath;
189
- await writeFile(importedPath, source, "utf8");
347
+ const importedSource = targetLibraryPath ? withLibraryLocationImportOption(source, targetLibraryPath) : source;
348
+ const importedDigest = hash(importedSource);
349
+ if (runtime)
350
+ runtime.importedDigest = importedDigest;
190
351
  let delivery;
191
352
  try {
192
- if (this.documentDelivery) {
353
+ await writeFile(importedPath, importedSource, "utf8");
354
+ await validateTargetLibraryPath(targetLibraryPath, Boolean(this.documentDelivery));
355
+ const reservation = targetLibraryPath ? await reserveTargetLibraryPath(targetLibraryPath) : undefined;
356
+ if (runtime && reservation) {
357
+ runtime.reservationPath = reservation.path;
358
+ runtime.reservationId = reservation.id;
359
+ }
360
+ await validateTargetLibraryPath(targetLibraryPath, Boolean(this.documentDelivery));
361
+ if (route === "headed-apple-event") {
362
+ this.persistImportAttemptBeforeDispatch(publishJob, runtime);
363
+ await this.executor(importXmlScript(importedPath));
364
+ delivery = {
365
+ status: "dispatched",
366
+ route: "headed-apple-event",
367
+ requestedActivates: true,
368
+ activation: "activated",
369
+ ui: "displayed",
370
+ target: targetLibraryPath
371
+ ? { requestedLibraryLocation: targetLibraryPath, guarantee: "requested-unverified" }
372
+ : { guarantee: "unavailable" },
373
+ };
374
+ }
375
+ else if (this.documentDelivery) {
376
+ this.persistImportAttemptBeforeDispatch(publishJob, runtime);
193
377
  const dispatched = await this.documentDelivery.deliverFcpxml({
194
378
  artifactPath: importedPath,
195
- ...(this.targetLibraryUid ? { targetLibraryUid: this.targetLibraryUid } : {}),
379
+ ...(targetLibraryPath ? { targetLibraryLocation: targetLibraryPath } : {}),
196
380
  activates: false,
197
381
  });
198
- if (dispatched.status !== "dispatched" && !this.allowHeadedFallback) {
382
+ if (runtime && dispatched.status !== "dispatched" && !dispatched.attempted) {
383
+ runtime.importAttempted = false;
384
+ this.persistRuntimeForJob(publishJob, runtime);
385
+ }
386
+ if (dispatched.status !== "dispatched") {
199
387
  const error = dispatched.error ?? {
200
388
  code: "FINAL_CUT_DELIVERY_USER_INTERACTION_REQUIRED",
201
389
  message: "Final Cut did not accept the background document-open request",
202
390
  };
203
391
  throw new Error(`${error.code}: ${error.message}`);
204
392
  }
205
- if (dispatched.status === "dispatched") {
206
- delivery = {
207
- status: "verified",
208
- route: dispatched.route,
209
- requestedActivates: dispatched.requestedActivates,
210
- activation: dispatched.activation,
211
- ui: dispatched.ui,
212
- target: dispatched.target,
213
- };
214
- }
215
- else {
216
- await this.executor(importXmlScript(importedPath));
217
- delivery = {
218
- status: "verified",
219
- route: "headed-accessibility",
220
- requestedActivates: true,
221
- activation: "activated",
222
- ui: "displayed",
223
- target: dispatched.target,
224
- };
225
- }
226
- }
227
- else {
228
- await this.executor(importXmlScript(importedPath));
229
393
  delivery = {
230
- status: "verified",
231
- route: "headed-accessibility",
232
- requestedActivates: true,
233
- activation: "activated",
234
- ui: "displayed",
235
- target: { guarantee: "unavailable" },
394
+ status: "dispatched",
395
+ route: dispatched.route,
396
+ requestedActivates: dispatched.requestedActivates,
397
+ activation: dispatched.activation,
398
+ ui: dispatched.ui,
399
+ target: dispatched.target,
236
400
  };
237
401
  }
402
+ else {
403
+ throw new Error("FINAL_CUT_DELIVERY_UNAVAILABLE: selected background document-open route is not configured; no import was attempted");
404
+ }
238
405
  if (runtime)
239
406
  runtime.delivery = delivery;
240
- const live = await waitForImportedProject(this.liveState, identity, beforeLive, runtime?.targetBinding, this.verificationTimeoutMs, this.pollIntervalMs);
241
- return publishResult(request, importedPath, identity, beforeLive, live, delivery);
407
+ this.persistRuntimeForJob(publishJob, runtime);
408
+ const verifiedTarget = await waitForImportedProject(this.liveState, async (targetPath, targetIdentity) => {
409
+ return this.targetBinding(targetPath, targetIdentity);
410
+ }, targetLibraryPath, identity, beforeLive, this.verificationTimeoutMs, this.pollIntervalMs);
411
+ await assertSourceMediaUnchanged(sourceMediaDigests);
412
+ const semanticReadback = await this.readAndVerifyCanonicalTarget(expectedSnapshot, sourceMediaDigests, verifiedTarget.targetBinding, identity);
413
+ const result = publishResult(request, importedPath, importedDigest, identity, beforeLive, verifiedTarget.live, verifiedTarget.targetBinding, delivery, semanticReadback, sourceMediaDigests);
414
+ if (runtime)
415
+ await releaseTargetLibraryReservation(runtime);
416
+ return result;
417
+ }
418
+ catch (error) {
419
+ if (!runtime?.importAttempted) {
420
+ if (runtime)
421
+ await releaseTargetLibraryReservation(runtime);
422
+ }
423
+ throw error;
242
424
  }
243
425
  finally {
244
426
  await rm(directory, { recursive: true, force: true });
@@ -249,17 +431,24 @@ export class FinalCutProjectPublisher {
249
431
  if (!runtime || !this.liveState) {
250
432
  return this.markAwaitingFinalCut(job, "FINAL_CUT_PUBLISH_VERIFICATION_UNAVAILABLE", "Final Cut project state verification is unavailable; retry this job when the live provider is ready");
251
433
  }
252
- if (!runtime.targetBinding) {
253
- return this.markFailed(job, new Error("FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE: no stable created-target identity was retained across verification; no publish success was reported"));
434
+ if (!this.targetBinding) {
435
+ return this.markFailed(job, new Error("FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE: no native provider can bind the imported artifact to a created target; no publish success was reported"));
436
+ }
437
+ if (!this.readCanonicalSnapshot || !runtime.expectedSnapshot || !runtime.sourceMediaDigests) {
438
+ return this.markFailed(job, new Error("FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE: retained canonical readback evidence is missing; no publish success was reported"));
254
439
  }
255
440
  try {
256
- const live = await waitForImportedProject(this.liveState, runtime.identity, runtime.beforeLive, runtime.targetBinding, this.verificationTimeoutMs, this.pollIntervalMs);
441
+ const verifiedTarget = await waitForImportedProject(this.liveState, (targetPath, identity) => this.targetBinding(targetPath, identity), runtime.targetLibraryPath, runtime.identity, runtime.beforeLive, this.verificationTimeoutMs, this.pollIntervalMs);
442
+ await assertSourceMediaUnchanged(runtime.sourceMediaDigests);
443
+ const semanticReadback = await this.readAndVerifyCanonicalTarget(runtime.expectedSnapshot, runtime.sourceMediaDigests, verifiedTarget.targetBinding, runtime.identity);
257
444
  const result = publishResult({
258
445
  sourceTransactionId: job.sourceTransactionId,
259
446
  artifactPath: job.sourcePath,
260
447
  artifactDigest: job.artifactDigest,
448
+ ...(runtime.targetLibraryPath ? { targetLibraryPath: runtime.targetLibraryPath } : {}),
261
449
  confirm: true,
262
- }, runtime.importedPath ?? job.sourcePath, runtime.identity, runtime.beforeLive, live, runtime.delivery);
450
+ }, runtime.importedPath ?? job.sourcePath, runtime.importedDigest ?? job.artifactDigest, runtime.identity, runtime.beforeLive, verifiedTarget.live, verifiedTarget.targetBinding, runtime.delivery, semanticReadback, runtime.sourceMediaDigests);
451
+ await releaseTargetLibraryReservation(runtime);
263
452
  return this.markVerified(job, result);
264
453
  }
265
454
  catch (error) {
@@ -267,6 +456,7 @@ export class FinalCutProjectPublisher {
267
456
  job.nextAction = "retry";
268
457
  job.retryable = true;
269
458
  job.error = publishError(error);
459
+ this.persistPublishJob(job);
270
460
  return clonePublishJob(job);
271
461
  }
272
462
  }
@@ -277,13 +467,39 @@ export class FinalCutProjectPublisher {
277
467
  job.createdTarget = structuredClone(result.createdTarget);
278
468
  job.result = structuredClone(result);
279
469
  delete job.error;
470
+ this.persistPublishJob(job);
280
471
  return clonePublishJob(job);
281
472
  }
473
+ async readAndVerifyCanonicalTarget(expected, expectedMediaDigests, targetBinding, identity) {
474
+ if (!this.liveState || !this.readCanonicalSnapshot) {
475
+ throw new Error("FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE: headed canonical timeline readback is not configured");
476
+ }
477
+ const assertActiveTarget = async (phase) => {
478
+ const live = await readLiveState(this.liveState, phase);
479
+ if (live.project?.id !== targetBinding.projectId
480
+ || live.sequence?.id !== targetBinding.sequenceId
481
+ || live.project.name !== identity.projectName
482
+ || live.sequence.name !== identity.sequenceName) {
483
+ throw new Error(`FINAL_CUT_PUBLISH_READBACK_TARGET_MISMATCH: exact created project and sequence are not active ${phase}`);
484
+ }
485
+ };
486
+ await assertActiveTarget("before canonical export");
487
+ const actual = await this.readCanonicalSnapshot(targetBinding, identity);
488
+ await assertActiveTarget("after canonical export");
489
+ const actualMediaDigests = await captureSourceMediaDigests(actual);
490
+ assertPublishedMediaBindings(expectedMediaDigests, actualMediaDigests);
491
+ const semanticReadback = verifyFinalCutPublishReadback(expected, actual, {
492
+ expectedSourceMediaDigests: expectedMediaDigests,
493
+ actualSourceMediaDigests: actualMediaDigests,
494
+ });
495
+ return semanticReadback;
496
+ }
282
497
  markAwaitingFinalCut(job, code, message) {
283
498
  job.state = "awaiting-final-cut";
284
499
  job.nextAction = "retry";
285
500
  job.retryable = true;
286
501
  job.error = { code, message };
502
+ this.persistPublishJob(job);
287
503
  return clonePublishJob(job);
288
504
  }
289
505
  markFailed(job, error) {
@@ -291,8 +507,95 @@ export class FinalCutProjectPublisher {
291
507
  job.nextAction = "none";
292
508
  job.retryable = false;
293
509
  job.error = publishError(error);
510
+ this.persistPublishJob(job);
294
511
  return clonePublishJob(job);
295
512
  }
513
+ loadPersistedPublishJobs() {
514
+ if (!this.publishJobsDirectory)
515
+ return;
516
+ mkdirSync(this.publishJobsDirectory, { recursive: true, mode: 0o700 });
517
+ chmodSync(this.publishJobsDirectory, 0o700);
518
+ for (const name of readdirSync(this.publishJobsDirectory)) {
519
+ if (!name.endsWith(".json"))
520
+ continue;
521
+ const path = join(this.publishJobsDirectory, name);
522
+ let persisted;
523
+ try {
524
+ persisted = JSON.parse(readFileSync(path, "utf8"));
525
+ }
526
+ catch (error) {
527
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: could not read ${path}`, { cause: error });
528
+ }
529
+ const job = persisted?.job;
530
+ const validStates = [
531
+ "awaiting-confirmation",
532
+ "awaiting-final-cut",
533
+ "verification-pending",
534
+ "verified",
535
+ "failed",
536
+ ];
537
+ if (!persisted || persisted.version !== 1 || !job || typeof job.jobId !== "string"
538
+ || !/^publish-job-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(job.jobId)
539
+ || !validStates.includes(job.state) || name !== `${job.jobId}.json`) {
540
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: invalid publish job record ${path}`);
541
+ }
542
+ if (job.state === "verification-pending" && !persisted.runtime) {
543
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: pending job is missing recovery state ${path}`);
544
+ }
545
+ job.handoff.route ??= "background-document-open";
546
+ if (job.handoff.route !== "background-document-open" && job.handoff.route !== "headed-apple-event") {
547
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: invalid publish route in ${path}`);
548
+ }
549
+ this.publishJobs.set(job.jobId, job);
550
+ if (persisted.runtime)
551
+ this.publishJobRuntime.set(job.jobId, persisted.runtime);
552
+ }
553
+ }
554
+ persistRuntimeForJob(job, runtime) {
555
+ if (!job || !runtime)
556
+ return;
557
+ this.persistPublishJob(job);
558
+ }
559
+ persistImportAttemptBeforeDispatch(job, runtime) {
560
+ if (!runtime)
561
+ return;
562
+ runtime.importAttempted = true;
563
+ try {
564
+ this.persistRuntimeForJob(job, runtime);
565
+ }
566
+ catch (error) {
567
+ runtime.importAttempted = false;
568
+ throw error;
569
+ }
570
+ }
571
+ persistPublishJob(job) {
572
+ if (!this.publishJobsDirectory) {
573
+ this.publishJobs.set(job.jobId, clonePublishJob(job));
574
+ return;
575
+ }
576
+ if (!/^publish-job-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(job.jobId)) {
577
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: invalid publish job ID ${job.jobId}`);
578
+ }
579
+ mkdirSync(this.publishJobsDirectory, { recursive: true, mode: 0o700 });
580
+ chmodSync(this.publishJobsDirectory, 0o700);
581
+ const path = join(this.publishJobsDirectory, `${job.jobId}.json`);
582
+ const temporary = `${path}.${randomUUID()}.tmp`;
583
+ const record = {
584
+ version: 1,
585
+ job: structuredClone(job),
586
+ ...(this.publishJobRuntime.has(job.jobId)
587
+ ? { runtime: structuredClone(this.publishJobRuntime.get(job.jobId)) }
588
+ : {}),
589
+ };
590
+ try {
591
+ writeFileSync(temporary, `${JSON.stringify(record)}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
592
+ renameSync(temporary, path);
593
+ }
594
+ finally {
595
+ rmSync(temporary, { force: true });
596
+ }
597
+ this.publishJobs.set(job.jobId, clonePublishJob(job));
598
+ }
296
599
  }
297
600
  async function runAppleScript(script) {
298
601
  try {
@@ -309,150 +612,17 @@ async function runAppleScript(script) {
309
612
  }
310
613
  function importXmlScript(path) {
311
614
  return `
312
- using terms from application "System Events"
313
-
314
- on waitForMenuItem(container, expectedNames, timeoutSeconds, timeoutMessage)
315
- set deadline to (current date) + timeoutSeconds
316
- repeat
317
- repeat with candidate in (menu items of container)
318
- try
319
- set candidateName to name of candidate as text
320
- repeat with expectedName in expectedNames
321
- if candidateName is (expectedName as text) then return candidate
322
- end repeat
323
- end try
324
- end repeat
325
- if (current date) > deadline then error timeoutMessage
326
- delay 0.1
327
- end repeat
328
- end waitForMenuItem
329
-
330
- on waitForSubmenu(menuItem, submenuName, timeoutSeconds, timeoutMessage)
331
- set deadline to (current date) + timeoutSeconds
332
- repeat
333
- try
334
- if exists menu submenuName of menuItem then return menu submenuName of menuItem
335
- end try
336
- if (current date) > deadline then error timeoutMessage
337
- delay 0.1
338
- end repeat
339
- end waitForSubmenu
340
-
341
- on waitForWindow(finalCut, windowName, timeoutSeconds, timeoutMessage)
342
- set deadline to (current date) + timeoutSeconds
343
- repeat
344
- try
345
- if exists window windowName of finalCut then return window windowName of finalCut
346
- end try
347
- if (current date) > deadline then error timeoutMessage
348
- delay 0.1
349
- end repeat
350
- end waitForWindow
351
-
352
- on waitForImportSheet(importWindow, timeoutSeconds)
353
- set deadline to (current date) + timeoutSeconds
354
- repeat
355
- try
356
- if exists sheet 1 of importWindow then return sheet 1 of importWindow
357
- end try
358
- if (current date) > deadline then error "FINAL_CUT_PUBLISH_IMPORT_SHEET_TIMEOUT: Import XML sheet did not appear"
359
- delay 0.1
360
- end repeat
361
- end waitForImportSheet
362
-
363
- on matchesImportPathField(candidate)
364
- set candidateIdentifier to ""
365
- set candidateDescription to ""
366
- try
367
- set candidateIdentifier to value of attribute "AXIdentifier" of candidate as text
368
- end try
369
- try
370
- set candidateDescription to description of candidate as text
371
- end try
372
- if candidateIdentifier is "path" or candidateIdentifier is "location" then return true
373
- if candidateDescription contains "Go to the folder" then return true
374
- if candidateDescription contains "path" or candidateDescription contains "location" then return true
375
- return false
376
- end matchesImportPathField
377
-
378
- on locateImportPathField(pathSheet)
379
- set matchingFields to {}
380
- repeat with candidate in (text fields of pathSheet)
381
- if matchesImportPathField(candidate) then set end of matchingFields to candidate
382
- end repeat
383
- if (count of matchingFields) is 0 then error "FINAL_CUT_PUBLISH_PATH_CONTROL_UNAVAILABLE: Import XML path control had no accessibility identifier or description"
384
- if (count of matchingFields) is not 1 then error "FINAL_CUT_PUBLISH_PATH_CONTROL_AMBIGUOUS: Import XML path control was not unique"
385
- return item 1 of matchingFields
386
- end locateImportPathField
387
-
388
- on waitForImportSheetDismissal(importWindow, timeoutSeconds)
389
- set deadline to (current date) + timeoutSeconds
390
- repeat
391
- try
392
- if not (exists sheet 1 of importWindow) then return
393
- end try
394
- if (current date) > deadline then error "FINAL_CUT_PUBLISH_IMPORT_SHEET_DISMISS_TIMEOUT: Import XML sheet did not disappear"
395
- delay 0.1
396
- end repeat
397
- end waitForImportSheetDismissal
398
-
399
- on waitForImportWindowDismissal(finalCut, timeoutSeconds)
400
- set deadline to (current date) + timeoutSeconds
401
- repeat
402
- try
403
- if not (exists window "Import XML" of finalCut) then return
404
- end try
405
- if (current date) > deadline then error "FINAL_CUT_PUBLISH_IMPORT_TIMEOUT: Import XML window did not close"
406
- delay 0.1
407
- end repeat
408
- end waitForImportWindowDismissal
409
-
410
- on cancelImportIfOpen(finalCut)
411
- try
412
- if exists window "Import XML" of finalCut then
413
- set importWindow to window "Import XML" of finalCut
414
- repeat with candidate in (buttons of importWindow)
415
- try
416
- if (name of candidate as text) is "Cancel" then
417
- perform action "AXPress" of candidate
418
- exit repeat
419
- end if
420
- end try
421
- end repeat
422
- end if
423
- end try
424
- end cancelImportIfOpen
425
-
426
- end using terms from
427
-
428
- tell application "System Events"
429
- tell process "Final Cut Pro"
430
- set finalCut to it
431
- set importWindow to missing value
432
- try
433
- if not frontmost then error number -1719
434
- set fileMenu to menu "File" of menu bar 1
435
- set importMenuItem to my waitForMenuItem(fileMenu, {"Import"}, 10, "FINAL_CUT_PUBLISH_IMPORT_MENU_TIMEOUT: File > Import was not exposed")
436
- perform action "AXPress" of importMenuItem
437
- set importMenu to my waitForSubmenu(importMenuItem, "Import", 10, "FINAL_CUT_PUBLISH_IMPORT_MENU_TIMEOUT: Import submenu was not exposed")
438
- set xmlMenuItem to my waitForMenuItem(importMenu, {"XML…", "XML..."}, 10, "FINAL_CUT_PUBLISH_IMPORT_MENU_TIMEOUT: Import XML command was not exposed")
439
- perform action "AXPress" of xmlMenuItem
440
- set importWindow to my waitForWindow(finalCut, "Import XML", 10, "FINAL_CUT_PUBLISH_IMPORT_SHEET_TIMEOUT: Import XML sheet did not appear")
441
- keystroke "g" using {command down, shift down}
442
- set pathSheet to my waitForImportSheet(importWindow, 10)
443
- set pathField to my locateImportPathField(pathSheet)
444
- set value of pathField to ${appleScriptString(path)}
445
- key code 36
446
- my waitForImportSheetDismissal(importWindow, 10)
447
- key code 36
448
- my waitForImportWindowDismissal(finalCut, 60)
449
- on error errorMessage number errorNumber
450
- my cancelImportIfOpen(finalCut)
451
- error errorMessage number errorNumber
452
- end try
453
- end tell
615
+ tell application "Final Cut Pro"
616
+ activate
617
+ open POSIX file ${appleScriptString(path)}
454
618
  end tell`;
455
619
  }
620
+ function publishHandoffReason(route) {
621
+ const verification = "After dispatch, Final Cut must expose the new project as the active target. The publisher verifies its native IDs, exports the active timeline through File > Export XML, and compares timeline semantics and source media digests before reporting success.";
622
+ return route === "headed-apple-event"
623
+ ? `The preview selects the headed AppleEvent route. It activates Final Cut Pro and opens the staged FCPXML with the approved library location. ${verification}`
624
+ : `The preview selects the background document-open route and does not request activation. ${verification}`;
625
+ }
456
626
  function projectIdentityFromXml(source) {
457
627
  const projectMatch = source.match(/<project\b[^>]*\bname="([^"]+)"/);
458
628
  if (!projectMatch?.[1])
@@ -481,16 +651,35 @@ async function readLiveState(liveState, phase) {
481
651
  throw new Error(`FINAL_CUT_PUBLISH_STATE_UNAVAILABLE: ${phase}: ${detail}`);
482
652
  }
483
653
  }
484
- async function waitForImportedProject(liveState, identity, before, targetBinding, timeoutMs, pollIntervalMs) {
654
+ async function waitForImportedProject(liveState, resolveTargetBinding, targetLibraryPath, identity, before, timeoutMs, pollIntervalMs) {
485
655
  const deadline = Date.now() + timeoutMs;
486
656
  let latest;
487
657
  let lastError;
658
+ let latestBinding;
488
659
  do {
489
660
  try {
490
661
  latest = await readLiveState(liveState, "after import");
491
662
  lastError = undefined;
492
- if (isImportedProject(latest, identity, before, targetBinding))
493
- return latest;
663
+ }
664
+ catch (error) {
665
+ lastError = error;
666
+ }
667
+ try {
668
+ latestBinding = await resolveTargetBinding(targetLibraryPath, identity);
669
+ if (!latestBinding.projectId.trim() || !latestBinding.sequenceId.trim()) {
670
+ throw new Error("FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE: native target binding did not return project and sequence identities");
671
+ }
672
+ if (targetLibraryPath) {
673
+ if (!latestBinding.libraryPath || normalizeLibraryPath(latestBinding.libraryPath) !== normalizeLibraryPath(targetLibraryPath)) {
674
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_MISMATCH: expected library ${targetLibraryPath}, observed ${latestBinding.libraryPath ?? "unavailable"}`);
675
+ }
676
+ if (latest && isImportedProject(latest, identity, before, latestBinding)) {
677
+ return { live: latest, targetBinding: latestBinding };
678
+ }
679
+ }
680
+ else if (latest && isImportedProject(latest, identity, before, latestBinding)) {
681
+ return { live: latest, targetBinding: latestBinding };
682
+ }
494
683
  }
495
684
  catch (error) {
496
685
  lastError = error;
@@ -503,9 +692,9 @@ async function waitForImportedProject(liveState, identity, before, targetBinding
503
692
  throw lastError;
504
693
  const observedProject = latest?.project?.name ?? "none";
505
694
  const observedSequence = latest?.sequence?.name ?? "none";
506
- if (targetBinding && latest?.project && latest.sequence
507
- && (latest.project.id !== targetBinding.projectId || latest.sequence.id !== targetBinding.sequenceId)) {
508
- throw new Error(`FINAL_CUT_PUBLISH_TARGET_MISMATCH: expected bound target ${targetBinding.projectId}/${targetBinding.sequenceId}, observed ${latest.project.id}/${latest.sequence.id}`);
695
+ if (latestBinding && latest?.project && latest.sequence
696
+ && (latest.project.id !== latestBinding.projectId || latest.sequence.id !== latestBinding.sequenceId)) {
697
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_MISMATCH: expected bound target ${latestBinding.projectId}/${latestBinding.sequenceId}, observed ${latest.project.id}/${latest.sequence.id}`);
509
698
  }
510
699
  throw new Error(`FINAL_CUT_PUBLISH_VERIFICATION_FAILED: expected new project ${identity.projectName} / sequence ${identity.sequenceName}, observed ${observedProject} / ${observedSequence}`);
511
700
  }
@@ -529,22 +718,275 @@ function delay(milliseconds) {
529
718
  function hash(content) {
530
719
  return createHash("sha256").update(content).digest("hex");
531
720
  }
721
+ async function reserveTargetLibraryPath(targetLibraryPath) {
722
+ const requestedTarget = resolve(targetLibraryPath);
723
+ const parent = await realpath(dirname(requestedTarget));
724
+ const targetName = basename(requestedTarget).normalize("NFC");
725
+ const canonicalTarget = join(parent, basename(requestedTarget));
726
+ const reservationKey = join(parent, targetName);
727
+ const normalizedKey = process.platform === "darwin" ? reservationKey.toLowerCase() : reservationKey;
728
+ const reservationPath = join(parent, `.framekit-publish-${hash(normalizedKey)}.lock`);
729
+ const reservationId = randomUUID();
730
+ const reservationContents = JSON.stringify({
731
+ reservationId,
732
+ targetLibraryPath: canonicalTarget,
733
+ pid: process.pid,
734
+ createdAt: new Date().toISOString(),
735
+ });
736
+ try {
737
+ await writeFile(reservationPath, reservationContents, { encoding: "utf8", flag: "wx", mode: 0o600 });
738
+ }
739
+ catch (error) {
740
+ if (error?.code === "EEXIST") {
741
+ const recovered = await recoverAbandonedTargetLibraryReservation(reservationPath, canonicalTarget, reservationContents);
742
+ if (recovered)
743
+ return { path: reservationPath, id: reservationId };
744
+ throw new Error(`PUBLISH_TARGET_LIBRARY_RESERVED: another publisher is creating ${requestedTarget}`);
745
+ }
746
+ throw error;
747
+ }
748
+ return { path: reservationPath, id: reservationId };
749
+ }
750
+ async function recoverAbandonedTargetLibraryReservation(reservationPath, requestedTarget, nextReservationContents) {
751
+ const recoveryPath = `${reservationPath}.recovery`;
752
+ const recoveryId = randomUUID();
753
+ const darwinExclusiveLock = process.platform === "darwin";
754
+ // Darwin's O_EXLOCK is 0x20; the descriptor lock is released by the kernel if a publisher exits.
755
+ const recoveryFlags = darwinExclusiveLock
756
+ ? constants.O_CREAT | constants.O_RDWR | constants.O_NONBLOCK | constants.O_NOFOLLOW | 0x20
757
+ : "wx";
758
+ let recoveryHandle;
759
+ try {
760
+ recoveryHandle = await open(recoveryPath, recoveryFlags, 0o600);
761
+ }
762
+ catch (error) {
763
+ const code = error?.code;
764
+ if (code === "EEXIST" || code === "EAGAIN" || code === "EWOULDBLOCK")
765
+ return false;
766
+ throw error;
767
+ }
768
+ if (!recoveryHandle)
769
+ return false;
770
+ try {
771
+ if (!darwinExclusiveLock) {
772
+ await recoveryHandle.writeFile(JSON.stringify({ recoveryId, pid: process.pid }));
773
+ }
774
+ return await reclaimAbandonedTargetLibraryReservation(reservationPath, requestedTarget, nextReservationContents);
775
+ }
776
+ finally {
777
+ await recoveryHandle.close();
778
+ if (!darwinExclusiveLock) {
779
+ try {
780
+ const current = JSON.parse(await readFile(recoveryPath, "utf8"));
781
+ if (current.recoveryId === recoveryId)
782
+ await rm(recoveryPath);
783
+ }
784
+ catch (error) {
785
+ if (error?.code !== "ENOENT")
786
+ throw error;
787
+ }
788
+ }
789
+ }
790
+ }
791
+ async function reclaimAbandonedTargetLibraryReservation(reservationPath, requestedTarget, nextReservationContents) {
792
+ let reservationStat;
793
+ let reservationContents;
794
+ try {
795
+ reservationStat = await lstat(reservationPath);
796
+ if (!reservationStat.isFile())
797
+ return false;
798
+ reservationContents = await readFile(reservationPath, "utf8");
799
+ }
800
+ catch {
801
+ return false;
802
+ }
803
+ let reservation;
804
+ try {
805
+ reservation = JSON.parse(reservationContents);
806
+ }
807
+ catch {
808
+ return false;
809
+ }
810
+ if (typeof reservation.reservationId !== "string" || !reservation.reservationId
811
+ || typeof reservation.targetLibraryPath !== "string"
812
+ || resolve(reservation.targetLibraryPath) !== requestedTarget
813
+ || !Number.isSafeInteger(reservation.pid) || reservation.pid <= 0
814
+ || processIsRunning(reservation.pid))
815
+ return false;
816
+ try {
817
+ await lstat(requestedTarget);
818
+ return false;
819
+ }
820
+ catch (error) {
821
+ if (error?.code !== "ENOENT")
822
+ return false;
823
+ }
824
+ let currentStat;
825
+ let currentContents;
826
+ try {
827
+ currentStat = await lstat(reservationPath);
828
+ currentContents = await readFile(reservationPath, "utf8");
829
+ }
830
+ catch {
831
+ return false;
832
+ }
833
+ if (currentStat.dev !== reservationStat.dev || currentStat.ino !== reservationStat.ino || currentContents !== reservationContents)
834
+ return false;
835
+ try {
836
+ await rm(reservationPath);
837
+ }
838
+ catch {
839
+ return false;
840
+ }
841
+ try {
842
+ await writeFile(reservationPath, nextReservationContents, { encoding: "utf8", flag: "wx", mode: 0o600 });
843
+ return true;
844
+ }
845
+ catch (error) {
846
+ if (error?.code === "EEXIST")
847
+ return false;
848
+ throw error;
849
+ }
850
+ }
851
+ function processIsRunning(pid) {
852
+ try {
853
+ process.kill(pid, 0);
854
+ return true;
855
+ }
856
+ catch (error) {
857
+ return error?.code !== "ESRCH";
858
+ }
859
+ }
860
+ async function releaseTargetLibraryReservation(runtime) {
861
+ if (!runtime.reservationPath || !runtime.reservationId)
862
+ return;
863
+ const reservationPath = runtime.reservationPath;
864
+ try {
865
+ const contents = JSON.parse(await readFile(reservationPath, "utf8"));
866
+ if (contents.reservationId === runtime.reservationId) {
867
+ await rm(reservationPath, { force: true });
868
+ }
869
+ }
870
+ catch (error) {
871
+ if (error?.code !== "ENOENT") {
872
+ throw new Error(`PUBLISH_TARGET_RESERVATION_RELEASE_FAILED: could not release ${reservationPath}`);
873
+ }
874
+ }
875
+ delete runtime.reservationPath;
876
+ delete runtime.reservationId;
877
+ }
878
+ async function validateTargetLibraryPath(path, required) {
879
+ if (!path?.trim()) {
880
+ if (required)
881
+ throw new Error("PUBLISH_TARGET_LIBRARY_REQUIRED: provide a new absolute .fcpbundle path for the imported project");
882
+ return undefined;
883
+ }
884
+ if (!isAbsolute(path) || extname(path).toLowerCase() !== ".fcpbundle") {
885
+ throw new Error("PUBLISH_TARGET_LIBRARY_INVALID: targetLibraryPath must be an absolute path ending in .fcpbundle");
886
+ }
887
+ const requestedTarget = resolve(path);
888
+ try {
889
+ await lstat(requestedTarget);
890
+ throw new Error(`PUBLISH_TARGET_LIBRARY_EXISTS: target library already exists at ${requestedTarget}`);
891
+ }
892
+ catch (error) {
893
+ if (error instanceof Error && error.message.startsWith("PUBLISH_TARGET_LIBRARY_EXISTS:"))
894
+ throw error;
895
+ if (error?.code !== "ENOENT")
896
+ throw error;
897
+ }
898
+ let parent;
899
+ try {
900
+ parent = await realpath(dirname(requestedTarget));
901
+ await access(parent, constants.W_OK);
902
+ }
903
+ catch {
904
+ throw new Error(`PUBLISH_TARGET_LIBRARY_PARENT_UNAVAILABLE: target library parent must exist and be writable: ${dirname(requestedTarget)}`);
905
+ }
906
+ const canonicalTarget = join(parent, basename(requestedTarget));
907
+ try {
908
+ await lstat(canonicalTarget);
909
+ throw new Error(`PUBLISH_TARGET_LIBRARY_EXISTS: target library already exists at ${requestedTarget}`);
910
+ }
911
+ catch (error) {
912
+ if (error instanceof Error && error.message.startsWith("PUBLISH_TARGET_LIBRARY_EXISTS:"))
913
+ throw error;
914
+ if (error?.code !== "ENOENT")
915
+ throw error;
916
+ }
917
+ return requestedTarget;
918
+ }
919
+ function withLibraryLocationImportOption(source, targetLibraryPath) {
920
+ const opening = /<fcpxml\b[^>]*>/i.exec(source);
921
+ const closing = /<\/fcpxml\s*>/ig;
922
+ const closings = [...source.matchAll(closing)];
923
+ if (!opening || closings.length !== 1 || (closings[0]?.index ?? -1) < opening.index + opening[0].length) {
924
+ throw new Error("FINAL_CUT_PUBLISH_VALIDATION_FAILED: source FCPXML must have one complete fcpxml root");
925
+ }
926
+ const bodyStart = opening.index + opening[0].length;
927
+ const bodyEnd = closings[0].index;
928
+ const option = `<import-options><option key="library location" value="${escapeXmlAttribute(pathToFileURL(targetLibraryPath).href)}"/></import-options>`;
929
+ const body = source.slice(bodyStart, bodyEnd);
930
+ const existing = /<import-options\b([^>]*)>([\s\S]*?)<\/import-options\s*>/i;
931
+ const selfClosing = /<import-options\b([^>]*)\/>/i;
932
+ const existingMatch = existing.exec(body);
933
+ const selfClosingMatch = existingMatch ? undefined : selfClosing.exec(body);
934
+ let updatedBody;
935
+ if (existingMatch) {
936
+ const options = existingMatch[2] ?? "";
937
+ const locationOption = /<option\b(?=[^>]*\bkey=(["'])library location\1)[^>]*(?:\/>|>[\s\S]*?<\/option\s*>)/i;
938
+ const innerOption = option.slice("<import-options>".length, -"</import-options>".length);
939
+ const updatedOptions = locationOption.test(options)
940
+ ? options.replace(locationOption, () => innerOption)
941
+ : `${innerOption}${options}`;
942
+ updatedBody = body.replace(existing, () => `<import-options${existingMatch[1] ?? ""}>${updatedOptions}</import-options>`);
943
+ }
944
+ else if (selfClosingMatch) {
945
+ updatedBody = body.replace(selfClosing, () => `<import-options${selfClosingMatch[1] ?? ""}>${option.slice("<import-options>".length, -"</import-options>".length)}</import-options>`);
946
+ }
947
+ else {
948
+ updatedBody = `${option}${body}`;
949
+ }
950
+ return `${source.slice(0, bodyStart)}${updatedBody}${source.slice(bodyEnd)}`;
951
+ }
952
+ function escapeXmlAttribute(value) {
953
+ return value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
954
+ }
955
+ function normalizeLibraryPath(path) {
956
+ try {
957
+ const resolved = resolve(path.startsWith("file:") ? fileURLToPath(path) : path);
958
+ try {
959
+ return realpathSync(resolved);
960
+ }
961
+ catch {
962
+ return resolved;
963
+ }
964
+ }
965
+ catch {
966
+ return resolve(path);
967
+ }
968
+ }
532
969
  function clonePublishJob(job) {
533
970
  return structuredClone(job);
534
971
  }
535
- function publishResult(request, importedPath, identity, beforeLive, live, delivery) {
972
+ function publishResult(request, importedPath, importedDigest, identity, beforeLive, live, targetBinding, delivery, semanticReadback, sourceMediaDigests = []) {
536
973
  return {
537
974
  sourceTransactionId: request.sourceTransactionId,
538
975
  sourcePath: request.artifactPath,
539
976
  sourceTarget: { kind: "artifact", artifactPath: request.artifactPath },
540
977
  importedPath,
978
+ importedDigest,
979
+ ...(request.targetLibraryPath ? { targetLibraryPath: request.targetLibraryPath } : {}),
541
980
  projectName: identity.projectName,
542
981
  createdTarget: {
543
982
  kind: "editor.project",
544
- ...(live.project?.id ? { projectId: live.project.id } : {}),
545
- ...(live.sequence?.id ? { sequenceId: live.sequence.id } : {}),
983
+ projectId: targetBinding.projectId,
984
+ sequenceId: targetBinding.sequenceId,
985
+ ...(targetBinding.libraryId ? { libraryId: targetBinding.libraryId } : {}),
986
+ ...(targetBinding.eventId ? { eventId: targetBinding.eventId } : {}),
987
+ ...(targetBinding.libraryPath ? { libraryPath: targetBinding.libraryPath } : {}),
546
988
  projectName: identity.projectName,
547
- ...(live.sequence?.name ? { sequenceName: live.sequence.name } : {}),
989
+ sequenceName: identity.sequenceName,
548
990
  },
549
991
  activeProject: {
550
992
  ...(beforeLive.project ? { before: beforeLive.project } : {}),
@@ -555,10 +997,92 @@ function publishResult(request, importedPath, identity, beforeLive, live, delive
555
997
  },
556
998
  verified: true,
557
999
  ...(delivery ? { delivery } : {}),
1000
+ semanticReadback,
1001
+ sourceMediaIntegrity: {
1002
+ unchanged: true,
1003
+ digests: structuredClone(sourceMediaDigests),
1004
+ },
558
1005
  ...(live.project?.name ? { liveProject: live.project.name } : {}),
559
1006
  ...(live.sequence?.name ? { liveSequence: live.sequence.name } : {}),
560
1007
  };
561
1008
  }
1009
+ async function captureSourceMediaDigests(snapshot) {
1010
+ const referencedMediaIds = new Set([
1011
+ ...snapshot.timeline.clips.map(({ mediaId }) => mediaId),
1012
+ ...snapshot.timeline.storyElements.map(({ mediaId }) => mediaId),
1013
+ ].filter((mediaId) => mediaId !== undefined));
1014
+ const sources = snapshot.media
1015
+ .filter(({ mediaId }) => referencedMediaIds.has(mediaId))
1016
+ .map(({ source }) => source);
1017
+ return captureSourceMediaPaths(sources);
1018
+ }
1019
+ async function captureSourceMediaPaths(sources) {
1020
+ const normalizedSources = [...new Set(sources.map((source) => resolve(source)))].sort();
1021
+ const digests = [];
1022
+ for (const source of normalizedSources) {
1023
+ try {
1024
+ const details = await stat(source);
1025
+ if (!details.isFile()) {
1026
+ throw new Error("source is not a regular file");
1027
+ }
1028
+ const hashStream = createHash("sha256");
1029
+ for await (const chunk of createReadStream(source))
1030
+ hashStream.update(chunk);
1031
+ digests.push({ source, sha256: hashStream.digest("hex") });
1032
+ }
1033
+ catch (error) {
1034
+ const detail = error instanceof Error ? error.message : String(error);
1035
+ throw new Error(`FINAL_CUT_PUBLISH_SOURCE_MEDIA_UNAVAILABLE: cannot verify ${source}: ${detail}`);
1036
+ }
1037
+ }
1038
+ return digests;
1039
+ }
1040
+ function validateApprovedSourceMediaDigests(digests) {
1041
+ if (!Array.isArray(digests)) {
1042
+ throw new Error("HEADLESS_ROUGH_CUT_SOURCE_MEDIA_DIGEST_UNAVAILABLE: approved source media digests are missing");
1043
+ }
1044
+ const seenSources = new Set();
1045
+ for (const item of digests) {
1046
+ if (!item || !isAbsolute(item.source) || !/^[a-f0-9]{64}$/.test(item.sha256)) {
1047
+ throw new Error("HEADLESS_ROUGH_CUT_SOURCE_MEDIA_DIGEST_INVALID: approved source media digest is malformed");
1048
+ }
1049
+ const source = resolve(item.source);
1050
+ if (seenSources.has(source)) {
1051
+ throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_MEDIA_DIGEST_INVALID: duplicate source ${source}`);
1052
+ }
1053
+ seenSources.add(source);
1054
+ }
1055
+ }
1056
+ function assertSourceMediaMatchesApproval(observed, approved) {
1057
+ const normalized = (digests) => digests
1058
+ .map(({ source, sha256 }) => ({ source: resolve(source), sha256 }))
1059
+ .sort((left, right) => left.source < right.source ? -1 : left.source > right.source ? 1 : 0);
1060
+ if (JSON.stringify(normalized(observed)) !== JSON.stringify(normalized(approved))) {
1061
+ throw new Error("HEADLESS_ROUGH_CUT_SOURCE_MEDIA_CHANGED: current source media do not match the approved rough-cut digests");
1062
+ }
1063
+ }
1064
+ async function assertSourceMediaUnchanged(expected) {
1065
+ let observed;
1066
+ try {
1067
+ observed = await captureSourceMediaPaths(expected.map(({ source }) => source));
1068
+ }
1069
+ catch (error) {
1070
+ const detail = error instanceof Error ? error.message : String(error);
1071
+ throw new Error(`FINAL_CUT_PUBLISH_SOURCE_MEDIA_CHANGED: ${detail}`);
1072
+ }
1073
+ if (JSON.stringify(observed) !== JSON.stringify(expected)) {
1074
+ throw new Error("FINAL_CUT_PUBLISH_SOURCE_MEDIA_CHANGED: one or more source media digests changed during native publishing");
1075
+ }
1076
+ }
1077
+ function assertPublishedMediaBindings(expected, actual) {
1078
+ const signature = (digests) => digests
1079
+ .map(({ source, sha256 }) => ({ name: basename(resolve(source)).normalize("NFC"), sha256 }))
1080
+ .sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1
1081
+ : left.sha256 < right.sha256 ? -1 : left.sha256 > right.sha256 ? 1 : 0);
1082
+ if (JSON.stringify(signature(expected)) !== JSON.stringify(signature(actual))) {
1083
+ throw new Error("FINAL_CUT_PUBLISH_SOURCE_MEDIA_BINDING_MISMATCH: native library media do not match the approved source files");
1084
+ }
1085
+ }
562
1086
  function publishError(error) {
563
1087
  const message = error instanceof Error ? error.message : String(error);
564
1088
  const separator = message.indexOf(":");