@morshoto/framekit 0.1.17 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +25 -14
  2. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +8 -2
  3. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.js +275 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical.js +557 -84
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +10 -3
  6. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +6 -0
  7. package/dist-package/adapters/final-cut/typescript/src/experimental.js +8 -0
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +150 -37
  9. package/dist-package/adapters/final-cut/typescript/src/index.js +2 -7
  10. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +60 -1
  11. package/dist-package/adapters/final-cut/typescript/src/live.js +29 -4
  12. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.js +175 -0
  13. package/dist-package/adapters/final-cut/typescript/src/native-session.js +11 -6
  14. package/dist-package/adapters/final-cut/typescript/src/native.js +201 -82
  15. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +214 -0
  16. package/dist-package/adapters/final-cut/typescript/src/publisher.js +1008 -243
  17. package/dist-package/adapters/final-cut/typescript/src/session.js +49 -14
  18. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +203 -49
  19. package/dist-package/adapters/headless/typescript/src/audio-output.js +3 -0
  20. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +48 -20
  21. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +9 -4
  22. package/dist-package/apps/cli/src/dev-doctor.js +198 -0
  23. package/dist-package/apps/cli/src/headless-projects.js +5 -0
  24. package/dist-package/apps/cli/src/main.js +76 -19
  25. package/dist-package/apps/mcp-server/runtime/speech-analyzer-wrapper.mjs +54 -0
  26. package/dist-package/apps/mcp-server/runtime/whisper-speech-backend.py +181 -0
  27. package/dist-package/apps/mcp-server/src/build-alignment.js +59 -0
  28. package/dist-package/apps/mcp-server/src/build-identity.js +30 -0
  29. package/dist-package/apps/mcp-server/src/build-identity.json +5 -0
  30. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.js +18 -0
  31. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.js +3 -0
  32. package/dist-package/apps/mcp-server/src/headless-project-snapshot.js +101 -0
  33. package/dist-package/apps/mcp-server/src/main.js +50 -21
  34. package/dist-package/apps/mcp-server/src/materialization-jobs.js +143 -10
  35. package/dist-package/apps/mcp-server/src/routing.js +2 -0
  36. package/dist-package/apps/mcp-server/src/server.js +986 -180
  37. package/dist-package/apps/mcp-server/src/tools/skills/catalog.js +142 -0
  38. package/dist-package/apps/mcp-server/src/tools/skills/metadata.js +71 -0
  39. package/dist-package/apps/mcp-server/src/tools/skills/register.js +101 -0
  40. package/dist-package/apps/mcp-server/src/version.js +21 -2
  41. package/dist-package/packages/headless-application/src/headless-projects.js +942 -0
  42. package/dist-package/packages/headless-application/src/index.js +1 -0
  43. package/dist-package/packages/runtime/src/application/media-analysis-service.js +15 -5
  44. package/dist-package/packages/runtime/src/application/project-service.js +5 -1
  45. package/dist-package/packages/runtime/src/application/project-store.js +13 -36
  46. package/dist-package/packages/runtime/src/application/transaction-store.js +1 -1
  47. package/dist-package/packages/runtime/src/capabilities.js +1 -1
  48. package/dist-package/packages/runtime/src/context/context-engine.js +22 -16
  49. package/dist-package/packages/runtime/src/context/context-service.js +2 -2
  50. package/dist-package/packages/runtime/src/editing/edit-service.js +76 -10
  51. package/dist-package/packages/runtime/src/index.js +1 -0
  52. package/dist-package/packages/runtime/src/runtime.js +22 -7
  53. package/dist-package/packages/runtime/src/timeline/editing-session.js +23 -2
  54. package/dist-package/packages/testkit/src/in-memory-editor.js +3 -3
  55. package/dist-package/packages/testkit/src/index.js +1 -0
  56. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.js +192 -0
  57. package/package.json +36 -14
  58. package/dist-package/apps/mcp-server/src/headless-projects.js +0 -370
@@ -1,20 +1,37 @@
1
1
  import { execFile as execFileCallback } from "node:child_process";
2
- import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { chmodSync, closeSync, constants, createReadStream, fsyncSync, ftruncateSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs";
4
+ import { access, lstat, mkdir, mkdtemp, open, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
3
5
  import { createHash, randomUUID } from "node:crypto";
4
- import { basename, join } from "node:path";
6
+ import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
5
7
  import { tmpdir } from "node:os";
6
8
  import { promisify } from "node:util";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import { FcpxmlDocumentAdapter } from "./fcpxml.js";
11
+ import { verifyFinalCutPublishReadback } from "./publish-readback.js";
7
12
  const execFile = promisify(execFileCallback);
13
+ export function parseFinalCutProjectPublishRoute(value, backgroundDeliveryAvailable) {
14
+ if (value === undefined || value === "") {
15
+ return backgroundDeliveryAvailable ? "background-document-open" : "headed-apple-event";
16
+ }
17
+ if (value === "background-document-open" || value === "headed-apple-event")
18
+ return value;
19
+ throw new Error(`FRAMEKIT_FINAL_CUT_PUBLISH_ROUTE_INVALID: unsupported route ${value}`);
20
+ }
8
21
  /** Imports a validated FCPXML artifact as a new Final Cut project. */
9
22
  export class FinalCutProjectPublisher {
23
+ dispatchContext = new AsyncLocalStorage();
10
24
  enabled;
11
25
  sourcePath;
26
+ publishJobDirectory;
12
27
  executor;
13
28
  liveState;
14
29
  targetBinding;
30
+ readCanonicalSnapshot;
31
+ headlessSourceVerifier;
15
32
  documentDelivery;
16
- targetLibraryUid;
17
- allowHeadedFallback;
33
+ publishRoute;
34
+ publishJobsDirectory;
18
35
  verificationTimeoutMs;
19
36
  pollIntervalMs;
20
37
  publishJobs = new Map();
@@ -22,45 +39,89 @@ export class FinalCutProjectPublisher {
22
39
  constructor(options) {
23
40
  this.enabled = options.enabled ?? false;
24
41
  this.sourcePath = options.sourcePath;
42
+ this.publishJobDirectory = options.publishJobDirectory;
25
43
  this.executor = options.executor ?? runAppleScript;
26
44
  this.liveState = options.liveState;
27
45
  this.targetBinding = options.targetBinding;
46
+ this.readCanonicalSnapshot = options.readCanonicalSnapshot;
47
+ this.headlessSourceVerifier = options.headlessSourceVerifier;
28
48
  this.documentDelivery = options.documentDelivery;
29
- this.targetLibraryUid = options.targetLibraryUid;
30
- this.allowHeadedFallback = options.allowHeadedFallback ?? false;
49
+ this.publishRoute = options.publishRoute ?? (this.documentDelivery ? "background-document-open" : "headed-apple-event");
50
+ this.publishJobsDirectory = options.publishJobsDirectory;
31
51
  this.verificationTimeoutMs = Math.max(0, options.verificationTimeoutMs ?? 15_000);
32
52
  this.pollIntervalMs = Math.max(0, options.pollIntervalMs ?? options.waitMs ?? 100);
53
+ this.loadPersistedPublishJobs();
54
+ }
55
+ async trackNativeDispatch(operation, onDispatch) {
56
+ return this.dispatchContext.run(onDispatch, operation);
33
57
  }
34
58
  isAvailable() {
35
- return this.enabled;
59
+ return this.inspectReadiness().available;
60
+ }
61
+ /** Describe configured handoff providers without querying or changing Final Cut. */
62
+ inspectReadiness() {
63
+ const reasons = [];
64
+ if (!this.enabled) {
65
+ reasons.push({
66
+ code: "FINAL_CUT_PUBLISH_DISABLED",
67
+ message: "Final Cut project publishing is disabled",
68
+ });
69
+ }
70
+ if (!this.liveState) {
71
+ reasons.push({
72
+ code: "FINAL_CUT_PUBLISH_VERIFICATION_UNAVAILABLE",
73
+ message: "Live Final Cut project and sequence verification is unavailable",
74
+ });
75
+ }
76
+ if (!this.targetBinding) {
77
+ reasons.push({
78
+ code: "FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE",
79
+ message: "No native provider can bind the imported artifact to a created target",
80
+ });
81
+ }
82
+ if (!this.readCanonicalSnapshot) {
83
+ reasons.push({
84
+ code: "FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE",
85
+ message: "Headed canonical timeline readback is unavailable",
86
+ });
87
+ }
88
+ return {
89
+ available: reasons.length === 0,
90
+ targetBindingAvailable: Boolean(this.targetBinding),
91
+ reasons,
92
+ };
36
93
  }
37
94
  executionMode() {
38
- return this.documentDelivery ? "background-capable" : "headed-only";
95
+ // Dispatch may be background-capable, but native semantic readback uses
96
+ // Final Cut's headed File > Export XML command.
97
+ return "headed-only";
39
98
  }
40
99
  async preparePublish(request) {
41
- const { identity } = await this.readValidatedSource(request);
100
+ const validated = await this.readValidatedSource(request);
101
+ const targetLibraryPath = await validateTargetLibraryPath(request.targetLibraryPath, Boolean(this.documentDelivery)
102
+ || request.sourceTransactionId.startsWith("headless-rough-cut:"));
42
103
  const job = {
43
104
  jobId: `publish-job-${randomUUID()}`,
44
105
  state: "awaiting-confirmation",
45
106
  nextAction: "confirm",
46
107
  retryable: false,
47
- executionMode: this.documentDelivery ? "background-capable" : "headed-only",
108
+ executionMode: "headed-only",
48
109
  sourceTransactionId: request.sourceTransactionId,
49
- sourcePath: this.sourcePath,
50
- sourceTarget: { kind: "artifact", artifactPath: this.sourcePath },
110
+ sourcePath: request.artifactPath,
111
+ sourceTarget: { kind: "artifact", artifactPath: request.artifactPath },
51
112
  artifactDigest: request.artifactDigest,
52
- projectName: identity.projectName,
53
- sequenceName: identity.sequenceName,
113
+ ...(targetLibraryPath ? { targetLibraryPath } : {}),
114
+ projectName: validated.identity.projectName,
115
+ sequenceName: validated.identity.sequenceName,
54
116
  confirmationRequired: true,
55
117
  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.",
118
+ mode: this.publishRoute === "background-document-open" ? "background-document-open" : "headed-only",
119
+ route: this.publishRoute,
120
+ backgroundSupported: this.publishRoute === "background-document-open",
121
+ reason: publishHandoffReason(this.publishRoute),
61
122
  },
62
123
  };
63
- this.publishJobs.set(job.jobId, job);
124
+ this.persistPublishJob(job);
64
125
  return clonePublishJob(job);
65
126
  }
66
127
  getPublishJob(jobId) {
@@ -69,16 +130,95 @@ export class FinalCutProjectPublisher {
69
130
  throw new Error(`PUBLISH_JOB_NOT_FOUND: unknown publish job ${jobId}`);
70
131
  return clonePublishJob(job);
71
132
  }
72
- async executePublishJob(jobId, confirm) {
73
- const job = this.publishJobs.get(jobId);
74
- if (!job)
133
+ async loadPublishJob(jobId) {
134
+ const current = this.publishJobs.get(jobId);
135
+ if (current)
136
+ return clonePublishJob(current);
137
+ if (!this.publishJobDirectory) {
75
138
  throw new Error(`PUBLISH_JOB_NOT_FOUND: unknown publish job ${jobId}`);
139
+ }
140
+ let persisted;
141
+ try {
142
+ persisted = JSON.parse(await readFile(this.publishJobPath(jobId), "utf8"));
143
+ }
144
+ catch (error) {
145
+ if (error.code === "ENOENT") {
146
+ throw new Error(`PUBLISH_JOB_NOT_FOUND: unknown publish job ${jobId}`);
147
+ }
148
+ throw new Error(`PUBLISH_JOB_STATE_INVALID: could not read verified publish job ${jobId}`);
149
+ }
150
+ if (!isVerifiedPublishJob(persisted, jobId)) {
151
+ throw new Error(`PUBLISH_JOB_STATE_INVALID: verified publish job ${jobId} has incomplete target proof`);
152
+ }
153
+ const job = clonePublishJob(persisted);
154
+ this.publishJobs.set(jobId, job);
155
+ return clonePublishJob(job);
156
+ }
157
+ /** Revalidate a persisted native target against the live catalog and active project. */
158
+ async verifyCreatedTarget(jobId) {
159
+ const job = await this.loadPublishJob(jobId);
160
+ const createdTarget = job.result?.createdTarget;
161
+ if (job.state !== "verified" || !job.result?.verified || !createdTarget) {
162
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_UNVERIFIED: publish job ${jobId} has no verified native target`);
163
+ }
164
+ const libraryPath = job.targetLibraryPath ?? createdTarget.libraryPath;
165
+ if (!libraryPath || !createdTarget.libraryId || !createdTarget.eventId || !this.targetBinding) {
166
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_REBIND_UNAVAILABLE: publish job ${jobId} has no live library binding provider`);
167
+ }
168
+ if (!this.liveState) {
169
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_REBIND_UNAVAILABLE: publish job ${jobId} has no live active-target provider`);
170
+ }
171
+ const observed = await this.targetBinding(libraryPath, {
172
+ projectName: createdTarget.projectName,
173
+ sequenceName: createdTarget.sequenceName ?? job.sequenceName,
174
+ });
175
+ if (observed.projectId !== createdTarget.projectId
176
+ || observed.sequenceId !== createdTarget.sequenceId
177
+ || observed.libraryId !== createdTarget.libraryId
178
+ || observed.eventId !== createdTarget.eventId
179
+ || !observed.libraryPath
180
+ || normalizeLibraryPath(libraryPath) !== normalizeLibraryPath(observed.libraryPath)) {
181
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_REBIND_MISMATCH: catalog target ${observed.libraryId}/${observed.eventId}/${observed.projectId}/${observed.sequenceId} does not match persisted ${createdTarget.libraryId}/${createdTarget.eventId}/${createdTarget.projectId}/${createdTarget.sequenceId}`);
182
+ }
183
+ const live = await readLiveState(this.liveState, "after publisher restart");
184
+ if (live.project?.id !== createdTarget.projectId
185
+ || live.project?.name !== createdTarget.projectName
186
+ || live.sequence?.id !== createdTarget.sequenceId
187
+ || live.sequence?.name !== createdTarget.sequenceName) {
188
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_REBIND_MISMATCH: active target ${live.project?.id ?? "<unavailable>"}/${live.sequence?.id ?? "<unavailable>"} does not match persisted ${createdTarget.projectId}/${createdTarget.sequenceId}`);
189
+ }
190
+ return structuredClone(createdTarget);
191
+ }
192
+ async executePublishJob(jobId, confirm, confirmVerification = false) {
193
+ const storedJob = this.publishJobs.get(jobId) ?? await this.loadPublishJob(jobId);
194
+ const job = clonePublishJob(storedJob);
76
195
  if (job.state === "verified")
77
196
  return clonePublishJob(job);
78
197
  if (job.state === "failed" && !job.retryable)
79
198
  return clonePublishJob(job);
80
199
  if (!confirm)
81
200
  throw new Error("PUBLISH_CONFIRMATION_REQUIRED: set confirm=true to create a new Final Cut project");
201
+ // Once a dispatch may have occurred, unavailable providers must never
202
+ // transition the job back to a state that can dispatch again.
203
+ if (job.state === "verification-pending") {
204
+ if (!confirmVerification) {
205
+ job.nextAction = "confirm-verification";
206
+ job.retryable = false;
207
+ this.persistPublishJob(job);
208
+ return clonePublishJob(job);
209
+ }
210
+ if (!this.enabled || !this.liveState || !this.targetBinding || !this.readCanonicalSnapshot) {
211
+ job.nextAction = "retry";
212
+ job.retryable = true;
213
+ job.error = {
214
+ code: "FINAL_CUT_PUBLISH_VERIFICATION_UNAVAILABLE",
215
+ message: "Verification is unavailable; retain this job and resume verification without dispatching again",
216
+ };
217
+ this.persistPublishJob(job);
218
+ return clonePublishJob(job);
219
+ }
220
+ return this.resumePublishVerification(job);
221
+ }
82
222
  if (!this.enabled) {
83
223
  job.state = "awaiting-final-cut";
84
224
  job.nextAction = "retry";
@@ -87,35 +227,29 @@ export class FinalCutProjectPublisher {
87
227
  code: "CAPABILITY_UNAVAILABLE",
88
228
  message: "Final Cut project publishing is unavailable; bring Final Cut Pro to the front and retry this job",
89
229
  };
230
+ this.persistPublishJob(job);
90
231
  return clonePublishJob(job);
91
232
  }
92
233
  if (!this.liveState)
93
234
  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");
94
- if (job.state === "verification-pending")
95
- return this.resumePublishVerification(job);
235
+ if (!this.readCanonicalSnapshot) {
236
+ return this.markFailed(job, new Error("FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE: headed canonical timeline readback is not configured; no import was attempted"));
237
+ }
96
238
  let validated;
97
239
  try {
98
240
  validated = await this.readValidatedSource({
99
241
  sourceTransactionId: job.sourceTransactionId,
100
242
  artifactPath: job.sourcePath,
101
243
  artifactDigest: job.artifactDigest,
244
+ ...(job.targetLibraryPath ? { targetLibraryPath: job.targetLibraryPath } : {}),
102
245
  });
246
+ await validateTargetLibraryPath(job.targetLibraryPath, Boolean(this.documentDelivery) || job.sourceTransactionId.startsWith("headless-rough-cut:"));
103
247
  }
104
248
  catch (error) {
105
249
  return this.markFailed(job, error);
106
250
  }
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);
251
+ if (!this.targetBinding) {
252
+ 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
253
  }
120
254
  let beforeLive;
121
255
  try {
@@ -125,25 +259,60 @@ export class FinalCutProjectPublisher {
125
259
  const normalized = publishError(error);
126
260
  return this.markAwaitingFinalCut(job, normalized.code, normalized.message);
127
261
  }
128
- const runtime = { beforeLive, identity: validated.identity, targetBinding };
262
+ const runtime = {
263
+ beforeLive,
264
+ identity: validated.identity,
265
+ ...(job.targetLibraryPath ? { targetLibraryPath: job.targetLibraryPath } : {}),
266
+ ...(validated.sourceProof ? { targetLibraryUid: validated.sourceProof.targetLibraryUid } : {}),
267
+ ...(validated.sourceProof ? { approvedSourceMediaDigests: structuredClone(validated.sourceProof.sourceMediaDigests) } : {}),
268
+ };
269
+ const previousRuntime = this.publishJobRuntime.get(job.jobId);
129
270
  this.publishJobRuntime.set(job.jobId, runtime);
130
271
  job.state = "verification-pending";
131
272
  job.nextAction = "status";
132
273
  job.retryable = false;
274
+ try {
275
+ this.persistPublishJob(job);
276
+ }
277
+ catch (error) {
278
+ if (previousRuntime)
279
+ this.publishJobRuntime.set(job.jobId, previousRuntime);
280
+ else
281
+ this.publishJobRuntime.delete(job.jobId);
282
+ throw error;
283
+ }
133
284
  try {
134
285
  const result = await this.importAndVerify({
135
286
  sourceTransactionId: job.sourceTransactionId,
136
287
  artifactPath: job.sourcePath,
137
288
  artifactDigest: job.artifactDigest,
289
+ ...(job.targetLibraryPath ? { targetLibraryPath: job.targetLibraryPath } : {}),
138
290
  confirm: true,
139
- }, validated.source, validated.identity, beforeLive, runtime);
291
+ }, validated.source, validated.identity, beforeLive, runtime, job);
292
+ if (!result) {
293
+ job.state = "verification-pending";
294
+ job.nextAction = "confirm-verification";
295
+ job.retryable = false;
296
+ delete job.error;
297
+ this.persistPublishJob(job);
298
+ return clonePublishJob(job);
299
+ }
140
300
  return this.markVerified(job, result);
141
301
  }
142
302
  catch (error) {
303
+ const normalized = publishError(error);
304
+ if (normalized.code === "PUBLISH_TARGET_LIBRARY_RESERVED")
305
+ return this.markFailed(job, error);
306
+ if (!runtime.importAttempted) {
307
+ await releaseTargetLibraryReservation(runtime);
308
+ return this.markAwaitingFinalCut(job, normalized.code, normalized.message);
309
+ }
143
310
  job.state = "verification-pending";
144
311
  job.nextAction = "retry";
145
312
  job.retryable = true;
146
- job.error = publishError(error);
313
+ job.dispatchError = structuredClone(normalized);
314
+ job.error = normalized;
315
+ this.persistPublishJob(job);
147
316
  return clonePublishJob(job);
148
317
  }
149
318
  }
@@ -152,96 +321,221 @@ export class FinalCutProjectPublisher {
152
321
  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
322
  if (!request.confirm)
154
323
  throw new Error("PUBLISH_CONFIRMATION_REQUIRED: set confirm=true to create a new Final Cut project");
324
+ if (!request.confirmVerification)
325
+ throw new Error("PUBLISH_VERIFICATION_CONFIRMATION_REQUIRED: separately confirm headed semantic readback before direct publish");
326
+ if (request.sourceTransactionId.startsWith("headless-rough-cut:")) {
327
+ throw new Error("HEADLESS_ROUGH_CUT_PUBLISH_JOB_REQUIRED: use artifact.publish.preview and artifact.publish.execute to preserve the approved target binding");
328
+ }
329
+ if (!this.readCanonicalSnapshot) {
330
+ throw new Error("FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE: headed canonical timeline readback is not configured; no import was attempted");
331
+ }
155
332
  const { source, identity } = await this.readValidatedSource(request);
156
333
  if (!this.liveState) {
157
334
  throw new Error("FINAL_CUT_PUBLISH_VERIFICATION_UNAVAILABLE: live project and sequence state is required");
158
335
  }
336
+ if (!this.targetBinding) {
337
+ 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");
338
+ }
339
+ const targetLibraryPath = await validateTargetLibraryPath(request.targetLibraryPath, Boolean(this.documentDelivery) || request.sourceTransactionId.startsWith("headless-rough-cut:"));
159
340
  const beforeLive = await readLiveState(this.liveState, "before import");
160
- return this.importAndVerify(request, source, identity, beforeLive);
341
+ const runtime = {
342
+ beforeLive,
343
+ identity,
344
+ ...(targetLibraryPath ? { targetLibraryPath } : {}),
345
+ };
346
+ try {
347
+ const result = await this.importAndVerify({ ...request, ...(targetLibraryPath ? { targetLibraryPath } : {}) }, source, identity, beforeLive, runtime);
348
+ if (!result)
349
+ throw new Error("FINAL_CUT_PUBLISH_VERIFICATION_PENDING: separate verification is required");
350
+ return result;
351
+ }
352
+ catch (error) {
353
+ if (!runtime.importAttempted)
354
+ throw error;
355
+ const normalized = publishError(error);
356
+ const job = {
357
+ jobId: `publish-job-${randomUUID()}`,
358
+ state: "verification-pending",
359
+ nextAction: "retry",
360
+ retryable: true,
361
+ executionMode: "headed-only",
362
+ sourceTransactionId: request.sourceTransactionId,
363
+ sourcePath: this.sourcePath ?? request.artifactPath,
364
+ sourceTarget: { kind: "artifact", artifactPath: this.sourcePath ?? request.artifactPath },
365
+ artifactDigest: request.artifactDigest,
366
+ ...(targetLibraryPath ? { targetLibraryPath } : {}),
367
+ projectName: identity.projectName,
368
+ sequenceName: identity.sequenceName,
369
+ confirmationRequired: false,
370
+ ...(runtime.delivery ? { delivery: structuredClone(runtime.delivery) } : {}),
371
+ ...(!runtime.delivery ? { dispatchError: structuredClone(normalized) } : {}),
372
+ ...(runtime.observedTarget ? { observedTarget: structuredClone(runtime.observedTarget) } : {}),
373
+ handoff: {
374
+ mode: "headed-only",
375
+ route: this.publishRoute,
376
+ backgroundSupported: false,
377
+ reason: "A direct publish may have reached Final Cut; verify this job before another import so its target reservation remains protected.",
378
+ },
379
+ error: normalized,
380
+ };
381
+ this.publishJobRuntime.set(job.jobId, runtime);
382
+ this.persistPublishJob(job);
383
+ 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})`);
384
+ }
161
385
  }
162
386
  async readValidatedSource(request) {
163
387
  if (!request.sourceTransactionId.trim())
164
388
  throw new Error("INVALID_PUBLISH_REQUEST: sourceTransactionId is required");
165
389
  if (!request.artifactDigest.trim())
166
390
  throw new Error("INVALID_PUBLISH_REQUEST: artifactDigest is required");
167
- if (request.artifactPath !== this.sourcePath) {
391
+ let sourceProof;
392
+ if (request.sourceTransactionId.startsWith("headless-rough-cut:")) {
393
+ if (!this.headlessSourceVerifier) {
394
+ throw new Error("HEADLESS_ROUGH_CUT_VERIFICATION_UNAVAILABLE: no approved headless source verifier is configured");
395
+ }
396
+ sourceProof = await this.headlessSourceVerifier(request);
397
+ if (!sourceProof.targetLibraryUid.trim()) {
398
+ throw new Error("HEADLESS_ROUGH_CUT_TARGET_INVALID: approved FCPXML has no explicit target library identity");
399
+ }
400
+ validateApprovedSourceMediaDigests(sourceProof.sourceMediaDigests);
401
+ }
402
+ else if (!this.sourcePath) {
403
+ throw new Error("PUBLISH_SOURCE_UNAVAILABLE: a managed FCPXML path is required for non-headless publishing");
404
+ }
405
+ else if (request.artifactPath !== this.sourcePath) {
168
406
  throw new Error(`PUBLISH_TARGET_MISMATCH: requested artifact ${request.artifactPath} is not managed by this publisher`);
169
407
  }
170
- const source = await readFile(this.sourcePath, "utf8");
408
+ const source = await readFile(request.artifactPath, "utf8");
171
409
  if (hash(source) !== request.artifactDigest) {
172
- throw new Error("PUBLISH_SOURCE_CHANGED: managed FCPXML artifact changed after transaction verification");
410
+ throw new Error(sourceProof
411
+ ? "HEADLESS_ROUGH_CUT_ARTIFACT_CHANGED: approved FCPXML changed after execution verification"
412
+ : "PUBLISH_SOURCE_CHANGED: managed FCPXML artifact changed after transaction verification");
173
413
  }
174
414
  if (!source.includes("<fcpxml") || !source.includes("<project")) {
175
415
  throw new Error("FINAL_CUT_PUBLISH_VALIDATION_FAILED: source is not a valid FCPXML project artifact");
176
416
  }
177
- return { source, identity: projectIdentityFromXml(source) };
417
+ return {
418
+ source,
419
+ identity: projectIdentityFromXml(source),
420
+ ...(sourceProof ? { sourceProof } : {}),
421
+ };
178
422
  }
179
- async importAndVerify(request, source, identity, beforeLive, runtime) {
423
+ async importAndVerify(request, source, identity, beforeLive, runtime, publishJob) {
180
424
  if (!this.liveState)
181
425
  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");
426
+ if (!this.targetBinding)
427
+ 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");
428
+ if (!this.readCanonicalSnapshot)
429
+ throw new Error("FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE: headed canonical timeline readback is not configured; no import was attempted");
430
+ const route = publishJob?.handoff.route ?? this.publishRoute;
431
+ const targetLibraryPath = await validateTargetLibraryPath(request.targetLibraryPath, Boolean(this.documentDelivery) || request.sourceTransactionId.startsWith("headless-rough-cut:"));
432
+ const expectedSnapshot = await new FcpxmlDocumentAdapter(request.artifactPath, undefined, {
433
+ allowMissingImmutableIdsForReadback: true,
434
+ }).readProject();
435
+ const sourceMediaDigests = await captureSourceMediaDigests(expectedSnapshot);
436
+ if (runtime?.approvedSourceMediaDigests) {
437
+ assertSourceMediaMatchesApproval(sourceMediaDigests, runtime.approvedSourceMediaDigests);
438
+ }
439
+ if (hash(await readFile(request.artifactPath, "utf8")) !== request.artifactDigest) {
440
+ throw new Error("PUBLISH_SOURCE_CHANGED: managed FCPXML artifact changed before import");
441
+ }
442
+ if (runtime) {
443
+ runtime.expectedSnapshot = structuredClone(expectedSnapshot);
444
+ runtime.sourceMediaDigests = structuredClone(sourceMediaDigests);
184
445
  }
185
446
  const directory = await mkdtemp(join(tmpdir(), "framekit-finalcut-publish-"));
186
- const importedPath = join(directory, basename(this.sourcePath));
447
+ const importedPath = join(directory, basename(request.artifactPath));
187
448
  if (runtime)
188
449
  runtime.importedPath = importedPath;
189
- await writeFile(importedPath, source, "utf8");
450
+ const importedSource = targetLibraryPath ? withLibraryLocationImportOption(source, targetLibraryPath) : source;
451
+ const importedDigest = hash(importedSource);
452
+ if (runtime)
453
+ runtime.importedDigest = importedDigest;
190
454
  let delivery;
455
+ let completed = false;
191
456
  try {
192
- if (this.documentDelivery) {
457
+ await writeFile(importedPath, importedSource, "utf8");
458
+ await validateTargetLibraryPath(targetLibraryPath, Boolean(this.documentDelivery));
459
+ const reservation = targetLibraryPath ? await reserveTargetLibraryPath(targetLibraryPath) : undefined;
460
+ if (runtime && reservation) {
461
+ runtime.reservationPath = reservation.path;
462
+ runtime.reservationId = reservation.id;
463
+ }
464
+ await validateTargetLibraryPath(targetLibraryPath, Boolean(this.documentDelivery));
465
+ if (route === "headed-apple-event") {
466
+ this.persistImportAttemptBeforeDispatch(publishJob, runtime);
467
+ await this.executor(importXmlScript(importedPath));
468
+ delivery = {
469
+ status: "dispatched",
470
+ route: "headed-apple-event",
471
+ requestedActivates: true,
472
+ activation: "activated",
473
+ ui: "displayed",
474
+ target: targetLibraryPath
475
+ ? { requestedLibraryLocation: targetLibraryPath, guarantee: "requested-unverified" }
476
+ : { guarantee: "unavailable" },
477
+ };
478
+ }
479
+ else if (this.documentDelivery) {
480
+ this.persistImportAttemptBeforeDispatch(publishJob, runtime);
193
481
  const dispatched = await this.documentDelivery.deliverFcpxml({
194
482
  artifactPath: importedPath,
195
- ...(this.targetLibraryUid ? { targetLibraryUid: this.targetLibraryUid } : {}),
483
+ ...(targetLibraryPath ? { targetLibraryLocation: targetLibraryPath } : {}),
196
484
  activates: false,
197
485
  });
198
- if (dispatched.status !== "dispatched" && !this.allowHeadedFallback) {
486
+ if (runtime && dispatched.status !== "dispatched" && !dispatched.attempted) {
487
+ runtime.importAttempted = false;
488
+ this.persistRuntimeForJob(publishJob, runtime);
489
+ }
490
+ if (dispatched.status !== "dispatched") {
199
491
  const error = dispatched.error ?? {
200
492
  code: "FINAL_CUT_DELIVERY_USER_INTERACTION_REQUIRED",
201
493
  message: "Final Cut did not accept the background document-open request",
202
494
  };
203
495
  throw new Error(`${error.code}: ${error.message}`);
204
496
  }
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
497
  delivery = {
230
- status: "verified",
231
- route: "headed-accessibility",
232
- requestedActivates: true,
233
- activation: "activated",
234
- ui: "displayed",
235
- target: { guarantee: "unavailable" },
498
+ status: "dispatched",
499
+ route: dispatched.route,
500
+ requestedActivates: dispatched.requestedActivates,
501
+ activation: dispatched.activation,
502
+ ui: dispatched.ui,
503
+ target: dispatched.target,
236
504
  };
237
505
  }
506
+ else {
507
+ throw new Error("FINAL_CUT_DELIVERY_UNAVAILABLE: selected background document-open route is not configured; no import was attempted");
508
+ }
238
509
  if (runtime)
239
510
  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);
511
+ if (publishJob)
512
+ publishJob.delivery = structuredClone(delivery);
513
+ this.persistRuntimeForJob(publishJob, runtime);
514
+ if (publishJob)
515
+ return undefined;
516
+ const verifiedTarget = await waitForImportedProject(this.liveState, async (targetPath, targetIdentity) => {
517
+ return this.targetBinding(targetPath, targetIdentity);
518
+ }, targetLibraryPath, identity, beforeLive, this.verificationTimeoutMs, this.pollIntervalMs);
519
+ if (runtime)
520
+ runtime.observedTarget = structuredClone(verifiedTarget.targetBinding);
521
+ await assertSourceMediaUnchanged(sourceMediaDigests);
522
+ const semanticReadback = await this.readAndVerifyCanonicalTarget(expectedSnapshot, sourceMediaDigests, verifiedTarget.targetBinding, identity);
523
+ const result = publishResult(request, importedPath, importedDigest, identity, beforeLive, verifiedTarget.live, verifiedTarget.targetBinding, delivery, semanticReadback, sourceMediaDigests);
524
+ if (runtime)
525
+ await releaseTargetLibraryReservation(runtime);
526
+ completed = true;
527
+ return result;
528
+ }
529
+ catch (error) {
530
+ if (!runtime?.importAttempted) {
531
+ if (runtime)
532
+ await releaseTargetLibraryReservation(runtime);
533
+ }
534
+ throw error;
242
535
  }
243
536
  finally {
244
- await rm(directory, { recursive: true, force: true });
537
+ if (completed || !runtime?.importAttempted)
538
+ await rm(directory, { recursive: true, force: true });
245
539
  }
246
540
  }
247
541
  async resumePublishVerification(job) {
@@ -249,17 +543,27 @@ export class FinalCutProjectPublisher {
249
543
  if (!runtime || !this.liveState) {
250
544
  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
545
  }
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"));
546
+ if (!this.targetBinding) {
547
+ 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"));
548
+ }
549
+ if (!this.readCanonicalSnapshot || !runtime.expectedSnapshot || !runtime.sourceMediaDigests) {
550
+ return this.markFailed(job, new Error("FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE: retained canonical readback evidence is missing; no publish success was reported"));
254
551
  }
255
552
  try {
256
- const live = await waitForImportedProject(this.liveState, runtime.identity, runtime.beforeLive, runtime.targetBinding, this.verificationTimeoutMs, this.pollIntervalMs);
553
+ const verifiedTarget = await waitForImportedProject(this.liveState, (targetPath, identity) => this.targetBinding(targetPath, identity), runtime.targetLibraryPath, runtime.identity, runtime.beforeLive, this.verificationTimeoutMs, this.pollIntervalMs);
554
+ job.observedTarget = structuredClone(verifiedTarget.targetBinding);
555
+ this.persistPublishJob(job);
556
+ await assertSourceMediaUnchanged(runtime.sourceMediaDigests);
557
+ const semanticReadback = await this.readAndVerifyCanonicalTarget(runtime.expectedSnapshot, runtime.sourceMediaDigests, verifiedTarget.targetBinding, runtime.identity);
257
558
  const result = publishResult({
258
559
  sourceTransactionId: job.sourceTransactionId,
259
560
  artifactPath: job.sourcePath,
260
561
  artifactDigest: job.artifactDigest,
562
+ ...(runtime.targetLibraryPath ? { targetLibraryPath: runtime.targetLibraryPath } : {}),
261
563
  confirm: true,
262
- }, runtime.importedPath ?? job.sourcePath, runtime.identity, runtime.beforeLive, live, runtime.delivery);
564
+ }, runtime.importedPath ?? job.sourcePath, runtime.importedDigest ?? job.artifactDigest, runtime.identity, runtime.beforeLive, verifiedTarget.live, verifiedTarget.targetBinding, runtime.delivery, semanticReadback, runtime.sourceMediaDigests);
565
+ await releaseTargetLibraryReservation(runtime);
566
+ await removeCompletedImportArtifact(runtime);
263
567
  return this.markVerified(job, result);
264
568
  }
265
569
  catch (error) {
@@ -267,23 +571,88 @@ export class FinalCutProjectPublisher {
267
571
  job.nextAction = "retry";
268
572
  job.retryable = true;
269
573
  job.error = publishError(error);
574
+ this.persistPublishJob(job);
270
575
  return clonePublishJob(job);
271
576
  }
272
577
  }
273
- markVerified(job, result) {
578
+ async markVerified(job, result) {
274
579
  job.state = "verified";
275
580
  job.nextAction = "none";
276
581
  job.retryable = false;
277
582
  job.createdTarget = structuredClone(result.createdTarget);
278
583
  job.result = structuredClone(result);
279
584
  delete job.error;
585
+ try {
586
+ await this.persistVerifiedPublishJob(job);
587
+ this.persistPublishJob(job);
588
+ }
589
+ catch (error) {
590
+ job.state = "verification-pending";
591
+ job.nextAction = "retry";
592
+ job.retryable = true;
593
+ delete job.createdTarget;
594
+ delete job.result;
595
+ job.error = {
596
+ code: "FINAL_CUT_PUBLISH_JOB_PERSISTENCE_FAILED",
597
+ message: error instanceof Error ? error.message : String(error),
598
+ };
599
+ }
600
+ this.publishJobs.set(job.jobId, job);
280
601
  return clonePublishJob(job);
281
602
  }
603
+ async persistVerifiedPublishJob(job) {
604
+ if (!this.publishJobDirectory)
605
+ return;
606
+ const path = this.publishJobPath(job.jobId);
607
+ const temporaryPath = `${path}.${randomUUID()}.tmp`;
608
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
609
+ try {
610
+ await writeFile(temporaryPath, `${JSON.stringify(job)}\n`, {
611
+ encoding: "utf8",
612
+ flag: "wx",
613
+ mode: 0o600,
614
+ });
615
+ await rename(temporaryPath, path);
616
+ }
617
+ catch (error) {
618
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
619
+ throw error;
620
+ }
621
+ }
622
+ publishJobPath(jobId) {
623
+ const key = createHash("sha256").update(jobId).digest("hex");
624
+ return join(this.publishJobDirectory, `${key}.json`);
625
+ }
626
+ async readAndVerifyCanonicalTarget(expected, expectedMediaDigests, targetBinding, identity) {
627
+ if (!this.liveState || !this.readCanonicalSnapshot) {
628
+ throw new Error("FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE: headed canonical timeline readback is not configured");
629
+ }
630
+ const assertActiveTarget = async (phase) => {
631
+ const live = await readLiveState(this.liveState, phase);
632
+ if (live.project?.id !== targetBinding.projectId
633
+ || live.sequence?.id !== targetBinding.sequenceId
634
+ || live.project.name !== identity.projectName
635
+ || live.sequence.name !== identity.sequenceName) {
636
+ throw new Error(`FINAL_CUT_PUBLISH_READBACK_TARGET_MISMATCH: exact created project and sequence are not active ${phase}`);
637
+ }
638
+ };
639
+ await assertActiveTarget("before canonical export");
640
+ const actual = await this.readCanonicalSnapshot(targetBinding, identity);
641
+ await assertActiveTarget("after canonical export");
642
+ const actualMediaDigests = await captureSourceMediaDigests(actual);
643
+ assertPublishedMediaBindings(expectedMediaDigests, actualMediaDigests);
644
+ const semanticReadback = verifyFinalCutPublishReadback(expected, actual, {
645
+ expectedSourceMediaDigests: expectedMediaDigests,
646
+ actualSourceMediaDigests: actualMediaDigests,
647
+ });
648
+ return semanticReadback;
649
+ }
282
650
  markAwaitingFinalCut(job, code, message) {
283
651
  job.state = "awaiting-final-cut";
284
652
  job.nextAction = "retry";
285
653
  job.retryable = true;
286
654
  job.error = { code, message };
655
+ this.persistPublishJob(job);
287
656
  return clonePublishJob(job);
288
657
  }
289
658
  markFailed(job, error) {
@@ -291,8 +660,122 @@ export class FinalCutProjectPublisher {
291
660
  job.nextAction = "none";
292
661
  job.retryable = false;
293
662
  job.error = publishError(error);
663
+ this.persistPublishJob(job);
294
664
  return clonePublishJob(job);
295
665
  }
666
+ loadPersistedPublishJobs() {
667
+ if (!this.publishJobsDirectory)
668
+ return;
669
+ mkdirSync(this.publishJobsDirectory, { recursive: true, mode: 0o700 });
670
+ chmodSync(this.publishJobsDirectory, 0o700);
671
+ for (const name of readdirSync(this.publishJobsDirectory)) {
672
+ if (!name.endsWith(".json"))
673
+ continue;
674
+ const path = join(this.publishJobsDirectory, name);
675
+ if (/^[a-f0-9]{64}\.json$/i.test(name)) {
676
+ let legacyJob;
677
+ try {
678
+ legacyJob = JSON.parse(readFileSync(path, "utf8"));
679
+ }
680
+ catch (error) {
681
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: could not read ${path}`, { cause: error });
682
+ }
683
+ const jobId = legacyJob && typeof legacyJob === "object"
684
+ ? legacyJob.jobId
685
+ : undefined;
686
+ if (typeof jobId !== "string" || !isVerifiedPublishJob(legacyJob, jobId)
687
+ || name !== `${createHash("sha256").update(jobId).digest("hex")}.json`) {
688
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: invalid legacy verified publish job ${path}`);
689
+ }
690
+ continue;
691
+ }
692
+ let persisted;
693
+ try {
694
+ persisted = JSON.parse(readFileSync(path, "utf8"));
695
+ }
696
+ catch (error) {
697
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: could not read ${path}`, { cause: error });
698
+ }
699
+ const job = persisted?.job;
700
+ const validStates = [
701
+ "awaiting-confirmation",
702
+ "awaiting-final-cut",
703
+ "verification-pending",
704
+ "verified",
705
+ "failed",
706
+ ];
707
+ if (!persisted || persisted.version !== 1 || !job || typeof job.jobId !== "string"
708
+ || !/^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)
709
+ || !validStates.includes(job.state) || name !== `${job.jobId}.json`) {
710
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: invalid publish job record ${path}`);
711
+ }
712
+ if (job.state === "verification-pending" && !persisted.runtime) {
713
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: pending job is missing recovery state ${path}`);
714
+ }
715
+ if (persisted.runtime?.importAttempted === true && job.state !== "verification-pending" && job.state !== "verified") {
716
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: spent import has a re-dispatchable state ${path}`);
717
+ }
718
+ if (job.state === "verified" && !isVerifiedPublishJob(job, job.jobId)) {
719
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: verified job is missing consistent native target proof ${path}`);
720
+ }
721
+ job.handoff.route ??= "background-document-open";
722
+ if (job.handoff.route !== "background-document-open" && job.handoff.route !== "headed-apple-event") {
723
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: invalid publish route in ${path}`);
724
+ }
725
+ if (!job.delivery && persisted.runtime?.delivery)
726
+ job.delivery = structuredClone(persisted.runtime.delivery);
727
+ this.publishJobs.set(job.jobId, job);
728
+ if (persisted.runtime)
729
+ this.publishJobRuntime.set(job.jobId, persisted.runtime);
730
+ }
731
+ }
732
+ persistRuntimeForJob(job, runtime) {
733
+ if (!job || !runtime)
734
+ return;
735
+ this.persistPublishJob(job);
736
+ }
737
+ persistImportAttemptBeforeDispatch(job, runtime) {
738
+ if (!runtime)
739
+ return;
740
+ runtime.importAttempted = true;
741
+ try {
742
+ this.persistRuntimeForJob(job, runtime);
743
+ }
744
+ catch (error) {
745
+ runtime.importAttempted = false;
746
+ throw error;
747
+ }
748
+ this.dispatchContext.getStore()?.();
749
+ markReservationDispatchAttempt(runtime);
750
+ }
751
+ persistPublishJob(job) {
752
+ if (!this.publishJobsDirectory) {
753
+ this.publishJobs.set(job.jobId, clonePublishJob(job));
754
+ return;
755
+ }
756
+ 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)) {
757
+ throw new Error(`PUBLISH_JOB_STORE_INVALID: invalid publish job ID ${job.jobId}`);
758
+ }
759
+ mkdirSync(this.publishJobsDirectory, { recursive: true, mode: 0o700 });
760
+ chmodSync(this.publishJobsDirectory, 0o700);
761
+ const path = join(this.publishJobsDirectory, `${job.jobId}.json`);
762
+ const temporary = `${path}.${randomUUID()}.tmp`;
763
+ const record = {
764
+ version: 1,
765
+ job: structuredClone(job),
766
+ ...(this.publishJobRuntime.has(job.jobId)
767
+ ? { runtime: structuredClone(this.publishJobRuntime.get(job.jobId)) }
768
+ : {}),
769
+ };
770
+ try {
771
+ writeFileSync(temporary, `${JSON.stringify(record)}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
772
+ renameSync(temporary, path);
773
+ }
774
+ finally {
775
+ rmSync(temporary, { force: true });
776
+ }
777
+ this.publishJobs.set(job.jobId, clonePublishJob(job));
778
+ }
296
779
  }
297
780
  async function runAppleScript(script) {
298
781
  try {
@@ -309,150 +792,17 @@ async function runAppleScript(script) {
309
792
  }
310
793
  function importXmlScript(path) {
311
794
  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
795
+ tell application "Final Cut Pro"
796
+ activate
797
+ open POSIX file ${appleScriptString(path)}
454
798
  end tell`;
455
799
  }
800
+ function publishHandoffReason(route) {
801
+ 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.";
802
+ return route === "headed-apple-event"
803
+ ? `The preview selects the headed AppleEvent route. It activates Final Cut Pro and opens the staged FCPXML with the approved library location. ${verification}`
804
+ : `The preview selects the background document-open route and does not request activation. ${verification}`;
805
+ }
456
806
  function projectIdentityFromXml(source) {
457
807
  const projectMatch = source.match(/<project\b[^>]*\bname="([^"]+)"/);
458
808
  if (!projectMatch?.[1])
@@ -481,16 +831,35 @@ async function readLiveState(liveState, phase) {
481
831
  throw new Error(`FINAL_CUT_PUBLISH_STATE_UNAVAILABLE: ${phase}: ${detail}`);
482
832
  }
483
833
  }
484
- async function waitForImportedProject(liveState, identity, before, targetBinding, timeoutMs, pollIntervalMs) {
834
+ async function waitForImportedProject(liveState, resolveTargetBinding, targetLibraryPath, identity, before, timeoutMs, pollIntervalMs) {
485
835
  const deadline = Date.now() + timeoutMs;
486
836
  let latest;
487
837
  let lastError;
838
+ let latestBinding;
488
839
  do {
489
840
  try {
490
841
  latest = await readLiveState(liveState, "after import");
491
842
  lastError = undefined;
492
- if (isImportedProject(latest, identity, before, targetBinding))
493
- return latest;
843
+ }
844
+ catch (error) {
845
+ lastError = error;
846
+ }
847
+ try {
848
+ latestBinding = await resolveTargetBinding(targetLibraryPath, identity);
849
+ if (!latestBinding.projectId.trim() || !latestBinding.sequenceId.trim()) {
850
+ throw new Error("FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE: native target binding did not return project and sequence identities");
851
+ }
852
+ if (targetLibraryPath) {
853
+ if (!latestBinding.libraryPath || normalizeLibraryPath(latestBinding.libraryPath) !== normalizeLibraryPath(targetLibraryPath)) {
854
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_MISMATCH: expected library ${targetLibraryPath}, observed ${latestBinding.libraryPath ?? "unavailable"}`);
855
+ }
856
+ if (latest && isImportedProject(latest, identity, before, latestBinding)) {
857
+ return { live: latest, targetBinding: latestBinding };
858
+ }
859
+ }
860
+ else if (latest && isImportedProject(latest, identity, before, latestBinding)) {
861
+ return { live: latest, targetBinding: latestBinding };
862
+ }
494
863
  }
495
864
  catch (error) {
496
865
  lastError = error;
@@ -503,9 +872,9 @@ async function waitForImportedProject(liveState, identity, before, targetBinding
503
872
  throw lastError;
504
873
  const observedProject = latest?.project?.name ?? "none";
505
874
  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}`);
875
+ if (latestBinding && latest?.project && latest.sequence
876
+ && (latest.project.id !== latestBinding.projectId || latest.sequence.id !== latestBinding.sequenceId)) {
877
+ throw new Error(`FINAL_CUT_PUBLISH_TARGET_MISMATCH: expected bound target ${latestBinding.projectId}/${latestBinding.sequenceId}, observed ${latest.project.id}/${latest.sequence.id}`);
509
878
  }
510
879
  throw new Error(`FINAL_CUT_PUBLISH_VERIFICATION_FAILED: expected new project ${identity.projectName} / sequence ${identity.sequenceName}, observed ${observedProject} / ${observedSequence}`);
511
880
  }
@@ -529,22 +898,336 @@ function delay(milliseconds) {
529
898
  function hash(content) {
530
899
  return createHash("sha256").update(content).digest("hex");
531
900
  }
901
+ async function reserveTargetLibraryPath(targetLibraryPath) {
902
+ const requestedTarget = resolve(targetLibraryPath);
903
+ const parent = await realpath(dirname(requestedTarget));
904
+ const targetName = basename(requestedTarget).normalize("NFC");
905
+ const canonicalTarget = join(parent, basename(requestedTarget));
906
+ const reservationKey = join(parent, targetName);
907
+ const normalizedKey = process.platform === "darwin" ? reservationKey.toLowerCase() : reservationKey;
908
+ const reservationPath = join(parent, `.framekit-publish-${hash(normalizedKey)}.lock`);
909
+ const reservationId = randomUUID();
910
+ const reservationContents = JSON.stringify({
911
+ reservationId,
912
+ targetLibraryPath: canonicalTarget,
913
+ phase: "reserved",
914
+ pid: process.pid,
915
+ createdAt: new Date().toISOString(),
916
+ });
917
+ try {
918
+ await writeFile(reservationPath, reservationContents, { encoding: "utf8", flag: "wx", mode: 0o600 });
919
+ }
920
+ catch (error) {
921
+ if (error?.code === "EEXIST") {
922
+ const recovered = await recoverAbandonedTargetLibraryReservation(reservationPath, canonicalTarget, reservationContents);
923
+ if (recovered)
924
+ return { path: reservationPath, id: reservationId };
925
+ throw new Error(`PUBLISH_TARGET_LIBRARY_RESERVED: another publisher is creating ${requestedTarget}`);
926
+ }
927
+ throw error;
928
+ }
929
+ return { path: reservationPath, id: reservationId };
930
+ }
931
+ async function recoverAbandonedTargetLibraryReservation(reservationPath, requestedTarget, nextReservationContents) {
932
+ const recoveryPath = `${reservationPath}.recovery`;
933
+ const recoveryId = randomUUID();
934
+ const darwinExclusiveLock = process.platform === "darwin";
935
+ // Darwin's O_EXLOCK is 0x20; the descriptor lock is released by the kernel if a publisher exits.
936
+ const recoveryFlags = darwinExclusiveLock
937
+ ? constants.O_CREAT | constants.O_RDWR | constants.O_NONBLOCK | constants.O_NOFOLLOW | 0x20
938
+ : "wx";
939
+ let recoveryHandle;
940
+ try {
941
+ recoveryHandle = await open(recoveryPath, recoveryFlags, 0o600);
942
+ }
943
+ catch (error) {
944
+ const code = error?.code;
945
+ if (code === "EEXIST" || code === "EAGAIN" || code === "EWOULDBLOCK")
946
+ return false;
947
+ throw error;
948
+ }
949
+ if (!recoveryHandle)
950
+ return false;
951
+ try {
952
+ if (!darwinExclusiveLock) {
953
+ await recoveryHandle.writeFile(JSON.stringify({ recoveryId, pid: process.pid }));
954
+ }
955
+ return await reclaimAbandonedTargetLibraryReservation(reservationPath, requestedTarget, nextReservationContents);
956
+ }
957
+ finally {
958
+ await recoveryHandle.close();
959
+ if (!darwinExclusiveLock) {
960
+ try {
961
+ const current = JSON.parse(await readFile(recoveryPath, "utf8"));
962
+ if (current.recoveryId === recoveryId)
963
+ await rm(recoveryPath);
964
+ }
965
+ catch (error) {
966
+ if (error?.code !== "ENOENT")
967
+ throw error;
968
+ }
969
+ }
970
+ }
971
+ }
972
+ async function reclaimAbandonedTargetLibraryReservation(reservationPath, requestedTarget, nextReservationContents) {
973
+ let reservationStat;
974
+ let reservationContents;
975
+ try {
976
+ reservationStat = await lstat(reservationPath);
977
+ if (!reservationStat.isFile())
978
+ return false;
979
+ reservationContents = await readFile(reservationPath, "utf8");
980
+ }
981
+ catch {
982
+ return false;
983
+ }
984
+ let reservation;
985
+ try {
986
+ reservation = JSON.parse(reservationContents);
987
+ }
988
+ catch {
989
+ return false;
990
+ }
991
+ if (reservation.phase !== "reserved"
992
+ || typeof reservation.reservationId !== "string" || !reservation.reservationId
993
+ || typeof reservation.targetLibraryPath !== "string"
994
+ || resolve(reservation.targetLibraryPath) !== requestedTarget
995
+ || !Number.isSafeInteger(reservation.pid) || reservation.pid <= 0
996
+ || processIsRunning(reservation.pid))
997
+ return false;
998
+ try {
999
+ await lstat(requestedTarget);
1000
+ return false;
1001
+ }
1002
+ catch (error) {
1003
+ if (error?.code !== "ENOENT")
1004
+ return false;
1005
+ }
1006
+ let currentStat;
1007
+ let currentContents;
1008
+ try {
1009
+ currentStat = await lstat(reservationPath);
1010
+ currentContents = await readFile(reservationPath, "utf8");
1011
+ }
1012
+ catch {
1013
+ return false;
1014
+ }
1015
+ if (currentStat.dev !== reservationStat.dev || currentStat.ino !== reservationStat.ino || currentContents !== reservationContents)
1016
+ return false;
1017
+ try {
1018
+ await rm(reservationPath);
1019
+ }
1020
+ catch {
1021
+ return false;
1022
+ }
1023
+ try {
1024
+ await writeFile(reservationPath, nextReservationContents, { encoding: "utf8", flag: "wx", mode: 0o600 });
1025
+ return true;
1026
+ }
1027
+ catch (error) {
1028
+ if (error?.code === "EEXIST")
1029
+ return false;
1030
+ throw error;
1031
+ }
1032
+ }
1033
+ function processIsRunning(pid) {
1034
+ try {
1035
+ process.kill(pid, 0);
1036
+ return true;
1037
+ }
1038
+ catch (error) {
1039
+ return error?.code !== "ESRCH";
1040
+ }
1041
+ }
1042
+ function markReservationDispatchAttempt(runtime) {
1043
+ if (!runtime.reservationPath || !runtime.reservationId)
1044
+ return;
1045
+ const fd = openSync(runtime.reservationPath, constants.O_RDWR | constants.O_NOFOLLOW);
1046
+ try {
1047
+ const reservation = JSON.parse(readFileSync(fd, "utf8"));
1048
+ if (reservation.reservationId !== runtime.reservationId || reservation.phase !== "reserved") {
1049
+ throw new Error("PUBLISH_TARGET_LIBRARY_RESERVED: reservation changed before dispatch");
1050
+ }
1051
+ const content = Buffer.from(JSON.stringify({ ...reservation, phase: "dispatch-attempted" }));
1052
+ ftruncateSync(fd, 0);
1053
+ let written = 0;
1054
+ while (written < content.length) {
1055
+ const count = writeSync(fd, content, written, content.length - written, written);
1056
+ if (count <= 0)
1057
+ throw new Error("PUBLISH_TARGET_RESERVATION_WRITE_FAILED: unable to persist dispatch marker");
1058
+ written += count;
1059
+ }
1060
+ fsyncSync(fd);
1061
+ }
1062
+ finally {
1063
+ closeSync(fd);
1064
+ }
1065
+ }
1066
+ async function releaseTargetLibraryReservation(runtime) {
1067
+ if (!runtime.reservationPath || !runtime.reservationId)
1068
+ return;
1069
+ const reservationPath = runtime.reservationPath;
1070
+ try {
1071
+ const contents = JSON.parse(await readFile(reservationPath, "utf8"));
1072
+ if (contents.reservationId === runtime.reservationId) {
1073
+ await rm(reservationPath, { force: true });
1074
+ }
1075
+ }
1076
+ catch (error) {
1077
+ if (error?.code !== "ENOENT") {
1078
+ throw new Error(`PUBLISH_TARGET_RESERVATION_RELEASE_FAILED: could not release ${reservationPath}`);
1079
+ }
1080
+ }
1081
+ delete runtime.reservationPath;
1082
+ delete runtime.reservationId;
1083
+ }
1084
+ async function removeCompletedImportArtifact(runtime) {
1085
+ if (!runtime.importedPath)
1086
+ return;
1087
+ const directory = dirname(resolve(runtime.importedPath));
1088
+ if (dirname(directory) !== resolve(tmpdir()) || !basename(directory).startsWith("framekit-finalcut-publish-"))
1089
+ return;
1090
+ await rm(directory, { recursive: true, force: true }).catch(() => { });
1091
+ }
1092
+ async function validateTargetLibraryPath(path, required) {
1093
+ if (!path?.trim()) {
1094
+ if (required)
1095
+ throw new Error("PUBLISH_TARGET_LIBRARY_REQUIRED: provide a new absolute .fcpbundle path for the imported project");
1096
+ return undefined;
1097
+ }
1098
+ if (!isAbsolute(path) || extname(path).toLowerCase() !== ".fcpbundle") {
1099
+ throw new Error("PUBLISH_TARGET_LIBRARY_INVALID: targetLibraryPath must be an absolute path ending in .fcpbundle");
1100
+ }
1101
+ const requestedTarget = resolve(path);
1102
+ try {
1103
+ await lstat(requestedTarget);
1104
+ throw new Error(`PUBLISH_TARGET_LIBRARY_EXISTS: target library already exists at ${requestedTarget}`);
1105
+ }
1106
+ catch (error) {
1107
+ if (error instanceof Error && error.message.startsWith("PUBLISH_TARGET_LIBRARY_EXISTS:"))
1108
+ throw error;
1109
+ if (error?.code !== "ENOENT")
1110
+ throw error;
1111
+ }
1112
+ let parent;
1113
+ try {
1114
+ parent = await realpath(dirname(requestedTarget));
1115
+ await access(parent, constants.W_OK);
1116
+ }
1117
+ catch {
1118
+ throw new Error(`PUBLISH_TARGET_LIBRARY_PARENT_UNAVAILABLE: target library parent must exist and be writable: ${dirname(requestedTarget)}`);
1119
+ }
1120
+ const canonicalTarget = join(parent, basename(requestedTarget));
1121
+ try {
1122
+ await lstat(canonicalTarget);
1123
+ throw new Error(`PUBLISH_TARGET_LIBRARY_EXISTS: target library already exists at ${requestedTarget}`);
1124
+ }
1125
+ catch (error) {
1126
+ if (error instanceof Error && error.message.startsWith("PUBLISH_TARGET_LIBRARY_EXISTS:"))
1127
+ throw error;
1128
+ if (error?.code !== "ENOENT")
1129
+ throw error;
1130
+ }
1131
+ return requestedTarget;
1132
+ }
1133
+ function withLibraryLocationImportOption(source, targetLibraryPath) {
1134
+ const opening = /<fcpxml\b[^>]*>/i.exec(source);
1135
+ const closing = /<\/fcpxml\s*>/ig;
1136
+ const closings = [...source.matchAll(closing)];
1137
+ if (!opening || closings.length !== 1 || (closings[0]?.index ?? -1) < opening.index + opening[0].length) {
1138
+ throw new Error("FINAL_CUT_PUBLISH_VALIDATION_FAILED: source FCPXML must have one complete fcpxml root");
1139
+ }
1140
+ const bodyStart = opening.index + opening[0].length;
1141
+ const bodyEnd = closings[0].index;
1142
+ const option = `<import-options><option key="library location" value="${escapeXmlAttribute(pathToFileURL(targetLibraryPath).href)}"/></import-options>`;
1143
+ const body = source.slice(bodyStart, bodyEnd);
1144
+ const existing = /<import-options\b([^>]*)>([\s\S]*?)<\/import-options\s*>/i;
1145
+ const selfClosing = /<import-options\b([^>]*)\/>/i;
1146
+ const existingMatch = existing.exec(body);
1147
+ const selfClosingMatch = existingMatch ? undefined : selfClosing.exec(body);
1148
+ let updatedBody;
1149
+ if (existingMatch) {
1150
+ const options = existingMatch[2] ?? "";
1151
+ const locationOption = /<option\b(?=[^>]*\bkey=(["'])library location\1)[^>]*(?:\/>|>[\s\S]*?<\/option\s*>)/i;
1152
+ const innerOption = option.slice("<import-options>".length, -"</import-options>".length);
1153
+ const updatedOptions = locationOption.test(options)
1154
+ ? options.replace(locationOption, () => innerOption)
1155
+ : `${innerOption}${options}`;
1156
+ updatedBody = body.replace(existing, () => `<import-options${existingMatch[1] ?? ""}>${updatedOptions}</import-options>`);
1157
+ }
1158
+ else if (selfClosingMatch) {
1159
+ updatedBody = body.replace(selfClosing, () => `<import-options${selfClosingMatch[1] ?? ""}>${option.slice("<import-options>".length, -"</import-options>".length)}</import-options>`);
1160
+ }
1161
+ else {
1162
+ updatedBody = `${option}${body}`;
1163
+ }
1164
+ return `${source.slice(0, bodyStart)}${updatedBody}${source.slice(bodyEnd)}`;
1165
+ }
1166
+ function escapeXmlAttribute(value) {
1167
+ return value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
1168
+ }
1169
+ function normalizeLibraryPath(path) {
1170
+ try {
1171
+ const resolved = resolve(path.startsWith("file:") ? fileURLToPath(path) : path);
1172
+ try {
1173
+ return realpathSync(resolved);
1174
+ }
1175
+ catch {
1176
+ return resolved;
1177
+ }
1178
+ }
1179
+ catch {
1180
+ return resolve(path);
1181
+ }
1182
+ }
532
1183
  function clonePublishJob(job) {
533
1184
  return structuredClone(job);
534
1185
  }
535
- function publishResult(request, importedPath, identity, beforeLive, live, delivery) {
1186
+ function isVerifiedPublishJob(value, jobId) {
1187
+ if (!value || typeof value !== "object")
1188
+ return false;
1189
+ const job = value;
1190
+ return job.jobId === jobId
1191
+ && job.state === "verified"
1192
+ && job.result?.verified === true
1193
+ && sameNativeTargetIdentity(job.createdTarget, job.result.createdTarget);
1194
+ }
1195
+ function sameNativeTargetIdentity(left, right) {
1196
+ if (!hasStableNativeTargetIds(left) || !hasStableNativeTargetIds(right))
1197
+ return false;
1198
+ return left.kind === right.kind
1199
+ && left.projectId === right.projectId
1200
+ && left.sequenceId === right.sequenceId
1201
+ && left.libraryId === right.libraryId
1202
+ && left.eventId === right.eventId;
1203
+ }
1204
+ function hasStableNativeTargetIds(value) {
1205
+ return value?.kind === "editor.project"
1206
+ && typeof value.projectId === "string"
1207
+ && value.projectId.trim().length > 0
1208
+ && typeof value.sequenceId === "string"
1209
+ && value.sequenceId.trim().length > 0
1210
+ && (value.libraryId === undefined || (typeof value.libraryId === "string" && value.libraryId.trim().length > 0))
1211
+ && (value.eventId === undefined || (typeof value.eventId === "string" && value.eventId.trim().length > 0));
1212
+ }
1213
+ function publishResult(request, importedPath, importedDigest, identity, beforeLive, live, targetBinding, delivery, semanticReadback, sourceMediaDigests = []) {
536
1214
  return {
537
1215
  sourceTransactionId: request.sourceTransactionId,
538
1216
  sourcePath: request.artifactPath,
539
1217
  sourceTarget: { kind: "artifact", artifactPath: request.artifactPath },
540
1218
  importedPath,
1219
+ importedDigest,
1220
+ ...(request.targetLibraryPath ? { targetLibraryPath: request.targetLibraryPath } : {}),
541
1221
  projectName: identity.projectName,
542
1222
  createdTarget: {
543
1223
  kind: "editor.project",
544
- ...(live.project?.id ? { projectId: live.project.id } : {}),
545
- ...(live.sequence?.id ? { sequenceId: live.sequence.id } : {}),
1224
+ projectId: targetBinding.projectId,
1225
+ sequenceId: targetBinding.sequenceId,
1226
+ ...(targetBinding.libraryId ? { libraryId: targetBinding.libraryId } : {}),
1227
+ ...(targetBinding.eventId ? { eventId: targetBinding.eventId } : {}),
1228
+ ...(targetBinding.libraryPath ? { libraryPath: targetBinding.libraryPath } : {}),
546
1229
  projectName: identity.projectName,
547
- ...(live.sequence?.name ? { sequenceName: live.sequence.name } : {}),
1230
+ sequenceName: identity.sequenceName,
548
1231
  },
549
1232
  activeProject: {
550
1233
  ...(beforeLive.project ? { before: beforeLive.project } : {}),
@@ -555,10 +1238,92 @@ function publishResult(request, importedPath, identity, beforeLive, live, delive
555
1238
  },
556
1239
  verified: true,
557
1240
  ...(delivery ? { delivery } : {}),
1241
+ semanticReadback,
1242
+ sourceMediaIntegrity: {
1243
+ unchanged: true,
1244
+ digests: structuredClone(sourceMediaDigests),
1245
+ },
558
1246
  ...(live.project?.name ? { liveProject: live.project.name } : {}),
559
1247
  ...(live.sequence?.name ? { liveSequence: live.sequence.name } : {}),
560
1248
  };
561
1249
  }
1250
+ async function captureSourceMediaDigests(snapshot) {
1251
+ const referencedMediaIds = new Set([
1252
+ ...snapshot.timeline.clips.map(({ mediaId }) => mediaId),
1253
+ ...snapshot.timeline.storyElements.map(({ mediaId }) => mediaId),
1254
+ ].filter((mediaId) => mediaId !== undefined));
1255
+ const sources = snapshot.media
1256
+ .filter(({ mediaId }) => referencedMediaIds.has(mediaId))
1257
+ .map(({ source }) => source);
1258
+ return captureSourceMediaPaths(sources);
1259
+ }
1260
+ async function captureSourceMediaPaths(sources) {
1261
+ const normalizedSources = [...new Set(sources.map((source) => resolve(source)))].sort();
1262
+ const digests = [];
1263
+ for (const source of normalizedSources) {
1264
+ try {
1265
+ const details = await stat(source);
1266
+ if (!details.isFile()) {
1267
+ throw new Error("source is not a regular file");
1268
+ }
1269
+ const hashStream = createHash("sha256");
1270
+ for await (const chunk of createReadStream(source))
1271
+ hashStream.update(chunk);
1272
+ digests.push({ source, sha256: hashStream.digest("hex") });
1273
+ }
1274
+ catch (error) {
1275
+ const detail = error instanceof Error ? error.message : String(error);
1276
+ throw new Error(`FINAL_CUT_PUBLISH_SOURCE_MEDIA_UNAVAILABLE: cannot verify ${source}: ${detail}`);
1277
+ }
1278
+ }
1279
+ return digests;
1280
+ }
1281
+ function validateApprovedSourceMediaDigests(digests) {
1282
+ if (!Array.isArray(digests)) {
1283
+ throw new Error("HEADLESS_ROUGH_CUT_SOURCE_MEDIA_DIGEST_UNAVAILABLE: approved source media digests are missing");
1284
+ }
1285
+ const seenSources = new Set();
1286
+ for (const item of digests) {
1287
+ if (!item || !isAbsolute(item.source) || !/^[a-f0-9]{64}$/.test(item.sha256)) {
1288
+ throw new Error("HEADLESS_ROUGH_CUT_SOURCE_MEDIA_DIGEST_INVALID: approved source media digest is malformed");
1289
+ }
1290
+ const source = resolve(item.source);
1291
+ if (seenSources.has(source)) {
1292
+ throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_MEDIA_DIGEST_INVALID: duplicate source ${source}`);
1293
+ }
1294
+ seenSources.add(source);
1295
+ }
1296
+ }
1297
+ function assertSourceMediaMatchesApproval(observed, approved) {
1298
+ const normalized = (digests) => digests
1299
+ .map(({ source, sha256 }) => ({ source: resolve(source), sha256 }))
1300
+ .sort((left, right) => left.source < right.source ? -1 : left.source > right.source ? 1 : 0);
1301
+ if (JSON.stringify(normalized(observed)) !== JSON.stringify(normalized(approved))) {
1302
+ throw new Error("HEADLESS_ROUGH_CUT_SOURCE_MEDIA_CHANGED: current source media do not match the approved rough-cut digests");
1303
+ }
1304
+ }
1305
+ async function assertSourceMediaUnchanged(expected) {
1306
+ let observed;
1307
+ try {
1308
+ observed = await captureSourceMediaPaths(expected.map(({ source }) => source));
1309
+ }
1310
+ catch (error) {
1311
+ const detail = error instanceof Error ? error.message : String(error);
1312
+ throw new Error(`FINAL_CUT_PUBLISH_SOURCE_MEDIA_CHANGED: ${detail}`);
1313
+ }
1314
+ if (JSON.stringify(observed) !== JSON.stringify(expected)) {
1315
+ throw new Error("FINAL_CUT_PUBLISH_SOURCE_MEDIA_CHANGED: one or more source media digests changed during native publishing");
1316
+ }
1317
+ }
1318
+ function assertPublishedMediaBindings(expected, actual) {
1319
+ const signature = (digests) => digests
1320
+ .map(({ source, sha256 }) => ({ name: basename(resolve(source)).normalize("NFC"), sha256 }))
1321
+ .sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1
1322
+ : left.sha256 < right.sha256 ? -1 : left.sha256 > right.sha256 ? 1 : 0);
1323
+ if (JSON.stringify(signature(expected)) !== JSON.stringify(signature(actual))) {
1324
+ throw new Error("FINAL_CUT_PUBLISH_SOURCE_MEDIA_BINDING_MISMATCH: native library media do not match the approved source files");
1325
+ }
1326
+ }
562
1327
  function publishError(error) {
563
1328
  const message = error instanceof Error ? error.message : String(error);
564
1329
  const separator = message.indexOf(":");