@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
@@ -0,0 +1,30 @@
1
+ const fullCommitPattern = /^[0-9a-f]{40}$/i;
2
+ export function createPackageBuildIdentity(version, commit) {
3
+ if (!version.trim() || !fullCommitPattern.test(commit)) {
4
+ throw new Error("FRAMEKIT_PACKAGE_BUILD_IDENTITY_INVALID: version and full commit are required");
5
+ }
6
+ return { schemaVersion: 1, version, commit: commit.toLowerCase() };
7
+ }
8
+ export function parsePackageBuildIdentity(value, expectedVersion) {
9
+ if (value === undefined || value === null)
10
+ return undefined;
11
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
12
+ throw new Error("FRAMEKIT_PACKAGE_BUILD_IDENTITY_INVALID: expected an object");
13
+ }
14
+ const identity = value;
15
+ const commit = identity.commit;
16
+ if (identity.schemaVersion !== 1
17
+ || typeof identity.version !== "string"
18
+ || typeof commit !== "string"
19
+ || !fullCommitPattern.test(commit)) {
20
+ throw new Error("FRAMEKIT_PACKAGE_BUILD_IDENTITY_INVALID: schema or commit is invalid");
21
+ }
22
+ if (identity.version !== expectedVersion) {
23
+ throw new Error("FRAMEKIT_PACKAGE_BUILD_IDENTITY_VERSION_MISMATCH");
24
+ }
25
+ return {
26
+ schemaVersion: 1,
27
+ version: identity.version,
28
+ commit: commit.toLowerCase(),
29
+ };
30
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "version": "0.1.18",
4
+ "commit": "cc0fc08ebc4ecf62897918d93a54dd35a7c73bf3"
5
+ }
@@ -0,0 +1,101 @@
1
+ /** Adapt the persisted headless Timeline IR to the runtime's analysis contract. */
2
+ export function projectSnapshotFromTimelineIr(timeline) {
3
+ const occurrences = timeline.sequence.occurrences;
4
+ const seconds = (time) => {
5
+ const value = Number(time.value) / Number(time.timescale);
6
+ if (!Number.isFinite(value))
7
+ throw new Error("HEADLESS_TIMELINE_INVALID: rational time is outside the supported range");
8
+ return value;
9
+ };
10
+ const stories = timeline.sequence.storyElements.map((element) => {
11
+ const occurrence = occurrences.find((candidate) => candidate.id === element.occurrenceId);
12
+ return {
13
+ id: element.id,
14
+ kind: element.kind,
15
+ start: seconds(element.startTime),
16
+ duration: seconds(element.durationTime),
17
+ startTime: structuredClone(element.startTime),
18
+ durationTime: structuredClone(element.durationTime),
19
+ ...(element.lane !== undefined ? { lane: element.lane } : {}),
20
+ ...(occurrence?.mediaId ? { mediaId: occurrence.mediaId } : {}),
21
+ ...(element.text !== undefined ? { text: element.text } : {}),
22
+ ...(element.attachedTo ? { attachedTo: element.attachedTo } : {}),
23
+ };
24
+ });
25
+ for (const title of timeline.sequence.titles ?? []) {
26
+ stories.push({
27
+ id: title.id,
28
+ kind: "title",
29
+ start: seconds(title.startTime),
30
+ duration: seconds(title.durationTime),
31
+ startTime: structuredClone(title.startTime),
32
+ durationTime: structuredClone(title.durationTime),
33
+ lane: title.lane,
34
+ text: title.text,
35
+ });
36
+ }
37
+ return {
38
+ projectId: timeline.project.id,
39
+ projectName: timeline.project.name,
40
+ timeline: {
41
+ id: timeline.sequence.id,
42
+ name: timeline.sequence.name,
43
+ duration: seconds(timeline.sequence.durationTime),
44
+ durationTime: structuredClone(timeline.sequence.durationTime),
45
+ frameDuration: structuredClone(timeline.sequence.frameDuration),
46
+ clips: occurrences.map((occurrence) => ({
47
+ id: occurrence.id,
48
+ ...(occurrence.mediaId ? { mediaId: occurrence.mediaId } : {}),
49
+ name: occurrence.name,
50
+ start: seconds(occurrence.startTime),
51
+ duration: seconds(occurrence.durationTime),
52
+ ...(occurrence.sourceStartTime ? {
53
+ sourceStart: seconds(occurrence.sourceStartTime),
54
+ sourceStartTime: structuredClone(occurrence.sourceStartTime),
55
+ } : {}),
56
+ track: occurrence.track,
57
+ ...(occurrence.gainDb !== undefined ? { gainDb: occurrence.gainDb } : {}),
58
+ ...(occurrence.fadeIn !== undefined ? { fadeIn: occurrence.fadeIn } : {}),
59
+ ...(occurrence.fadeOut !== undefined ? { fadeOut: occurrence.fadeOut } : {}),
60
+ ...(occurrence.enabled !== undefined ? { enabled: occurrence.enabled } : {}),
61
+ ...(occurrence.role ? { role: occurrence.role } : {}),
62
+ ...(occurrence.attachedTo ? { attachedTo: occurrence.attachedTo } : {}),
63
+ startTime: structuredClone(occurrence.startTime),
64
+ durationTime: structuredClone(occurrence.durationTime),
65
+ })),
66
+ storyElements: stories,
67
+ markers: timeline.sequence.markers.map((marker) => ({
68
+ id: marker.id,
69
+ name: marker.name,
70
+ start: seconds(marker.startTime),
71
+ duration: seconds(marker.durationTime),
72
+ startTime: structuredClone(marker.startTime),
73
+ durationTime: structuredClone(marker.durationTime),
74
+ })),
75
+ captions: timeline.sequence.captions.map((caption) => ({
76
+ id: caption.id,
77
+ text: caption.text,
78
+ start: seconds(caption.startTime),
79
+ duration: seconds(caption.durationTime),
80
+ startTime: structuredClone(caption.startTime),
81
+ durationTime: structuredClone(caption.durationTime),
82
+ })),
83
+ },
84
+ media: timeline.resources.flatMap((resource) => {
85
+ if (!resource.source)
86
+ return [];
87
+ const mediaKind = resource.mediaKind === "audio" || resource.mediaKind === "video"
88
+ ? resource.mediaKind
89
+ : undefined;
90
+ const durationTime = resource.metadata?.durationTime;
91
+ return [{
92
+ mediaId: resource.id,
93
+ source: resource.source,
94
+ ...(mediaKind ? { mediaKind } : {}),
95
+ ...(resource.sourceDigest ? { sourceDigest: resource.sourceDigest } : {}),
96
+ ...(durationTime ? { duration: seconds(durationTime) } : {}),
97
+ }];
98
+ }),
99
+ revision: structuredClone(timeline.revision),
100
+ };
101
+ }
@@ -1,8 +1,8 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { readdir, readFile, rename, writeFile, mkdir } from "node:fs/promises";
3
- import { dirname, join } from "node:path";
4
- import { FramekitProjectStore, LocalMediaRegistrar, ProjectTransactionService, createFramekitRenderRequest, renderAndVerifyFramekitProject, } from "../../../packages/runtime/src/index.js";
5
- import { compileTimelineIrToFcpxml, } from "../../../adapters/final-cut/typescript/src/index.js";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { FramekitProjectStore, LocalMediaRegistrar, ProjectTransactionService, createFramekitRenderRequest, renderAndVerifyFramekitProject, timelineIrDigest, } from "../../../packages/runtime/src/index.js";
5
+ import { FcpxmlDocumentAdapter, compileTimelineIrToFcpxml, resolveMediaSource, } from "../../../adapters/final-cut/typescript/src/index.js";
6
6
  export class HeadlessProjectService {
7
7
  directory;
8
8
  mediaProbe;
@@ -72,13 +72,23 @@ export class HeadlessProjectService {
72
72
  }
73
73
  async previewRoughCut(request) {
74
74
  const prepared = await this.prepareRoughCut(request);
75
- const transaction = new ProjectTransactionService(this.store(request.projectId), { clock: this.clock });
76
- const preview = await transaction.preview(prepared.command);
77
- const fcpxml = compileTimelineIrToFcpxml(preview.after.timeline, { target: request.fcpxml.target });
75
+ const timestamp = this.clock();
76
+ const { preview, fcpxml } = await this.previewPreparedRoughCut(request, prepared, timestamp);
77
+ const approval = createRoughCutApproval({
78
+ inputDigest: prepared.inputDigest,
79
+ projectId: request.projectId,
80
+ sequenceId: request.sequenceId,
81
+ sourceRevision: request.plan.revision,
82
+ canonicalRevision: preview.after.timeline.revision,
83
+ artifactPath: resolve(request.fcpxml.path),
84
+ artifactDigest: fcpxml.digest,
85
+ outputIntent: prepared.outputIntent,
86
+ });
87
+ await this.saveRoughCutApproval(approval);
78
88
  return {
79
89
  ...preview,
80
90
  plan: structuredClone(request.plan),
81
- planDigest: prepared.planDigest,
91
+ planDigest: approval.planDigest,
82
92
  provenance: prepared.provenance,
83
93
  outputIntent: prepared.outputIntent,
84
94
  fcpxml: selectFcpxmlMetadata(fcpxml),
@@ -89,12 +99,35 @@ export class HeadlessProjectService {
89
99
  throw new Error("HEADLESS_ROUGH_CUT_APPROVAL_REQUIRED: set approved=true after reviewing the preview");
90
100
  }
91
101
  const prepared = await this.prepareRoughCut(request);
92
- if (request.planDigest !== prepared.planDigest) {
102
+ if (!/^[a-f0-9]{64}$/.test(request.planDigest)) {
93
103
  throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: planDigest does not match the submitted rough-cut plan");
94
104
  }
95
- const transaction = new ProjectTransactionService(this.store(request.projectId), { clock: this.clock });
96
- const preview = await transaction.preview(prepared.command);
97
- const fcpxml = compileTimelineIrToFcpxml(preview.after.timeline, { target: request.fcpxml.target });
105
+ let approval;
106
+ try {
107
+ approval = await this.readRoughCutApproval(request.planDigest);
108
+ }
109
+ catch (error) {
110
+ if (error.code === "ENOENT") {
111
+ throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: planDigest has no persisted preview approval");
112
+ }
113
+ throw error;
114
+ }
115
+ if (approval.inputDigest !== prepared.inputDigest
116
+ || approval.projectId !== request.projectId
117
+ || approval.sequenceId !== request.sequenceId
118
+ || !sameRevision(approval.sourceRevision, request.plan.revision)
119
+ || approval.artifactPath !== resolve(request.fcpxml.path)
120
+ || stableJson(approval.outputIntent) !== stableJson(prepared.outputIntent)) {
121
+ throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: planDigest does not match the submitted rough-cut plan");
122
+ }
123
+ const transaction = new ProjectTransactionService(this.store(request.projectId), {
124
+ clock: () => approval.canonicalRevision.timestamp,
125
+ });
126
+ const { preview, fcpxml } = await this.previewPreparedRoughCut(request, prepared, approval.canonicalRevision.timestamp, transaction);
127
+ if (!sameRevision(preview.after.timeline.revision, approval.canonicalRevision)
128
+ || fcpxml.digest !== approval.artifactDigest) {
129
+ throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: replayed preview differs from the approved revision or FCPXML digest");
130
+ }
98
131
  const renderRequest = createFramekitRenderRequest({
99
132
  timeline: preview.after.timeline,
100
133
  target: { projectId: request.projectId, sequenceId: request.sequenceId },
@@ -121,19 +154,155 @@ export class HeadlessProjectService {
121
154
  }
122
155
  const fcpxmlArtifact = await writeVerifiedFcpxml(request.fcpxml.path, fcpxml.xml, fcpxml.digest, request.fcpxml.overwrite === true);
123
156
  const committed = await transaction.execute(prepared.command);
157
+ const executionId = `rough-cut-${randomUUID()}`;
158
+ await this.saveRoughCutExecution({
159
+ schemaVersion: 1,
160
+ executionId,
161
+ approved: true,
162
+ projectId: request.projectId,
163
+ sequenceId: request.sequenceId,
164
+ sourceRevision: structuredClone(request.plan.revision),
165
+ canonicalRevision: structuredClone(committed.after.timeline.revision),
166
+ plan: structuredClone(request.plan),
167
+ operations: structuredClone(request.operations ?? []),
168
+ outputIntent: structuredClone(prepared.outputIntent),
169
+ planDigest: approval.planDigest,
170
+ inputDigest: prepared.inputDigest,
171
+ renderId,
172
+ artifactPath: resolve(fcpxmlArtifact.path),
173
+ artifactDigest: fcpxmlArtifact.digest,
174
+ artifactBytes: fcpxmlArtifact.bytes,
175
+ fcpxml: selectFcpxmlMetadata(fcpxml),
176
+ provenance: structuredClone(prepared.provenance),
177
+ });
124
178
  return {
125
179
  ...preview,
180
+ after: committed.after,
126
181
  plan: structuredClone(request.plan),
127
- planDigest: prepared.planDigest,
182
+ planDigest: approval.planDigest,
128
183
  provenance: prepared.provenance,
129
184
  outputIntent: prepared.outputIntent,
130
185
  fcpxml: selectFcpxmlMetadata(fcpxml),
186
+ executionId,
131
187
  committed: true,
132
188
  render: { renderId, status: "passed", outcome },
133
189
  fcpxmlArtifact,
134
190
  transaction: committed,
135
191
  };
136
192
  }
193
+ async verifyPublishableRoughCut(executionId, artifactPath, artifactDigest) {
194
+ validateExecutionId(executionId);
195
+ let record;
196
+ try {
197
+ record = JSON.parse(await readFile(this.executionPath(executionId), "utf8"));
198
+ }
199
+ catch (error) {
200
+ if (error.code === "ENOENT") {
201
+ throw new Error(`HEADLESS_ROUGH_CUT_EXECUTION_NOT_FOUND: unknown approved rough-cut execution ${executionId}`);
202
+ }
203
+ throw error;
204
+ }
205
+ const { evidenceDigest, ...unsignedRecord } = record;
206
+ if (record.schemaVersion !== 1 || record.executionId !== executionId || record.approved !== true
207
+ || !evidenceDigest || hash(stableJson(unsignedRecord)) !== evidenceDigest) {
208
+ throw new Error(`HEADLESS_ROUGH_CUT_EXECUTION_INVALID: approved rough-cut provenance is invalid for ${executionId}`);
209
+ }
210
+ const expectedInputDigest = digestRoughCutPlan(record.plan, record.operations, record.outputIntent);
211
+ if (expectedInputDigest !== record.inputDigest) {
212
+ throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: persisted rough-cut input digest does not match its plan and output intent");
213
+ }
214
+ const approval = await this.readRoughCutApproval(record.planDigest);
215
+ if (approval.inputDigest !== record.inputDigest
216
+ || approval.projectId !== record.projectId
217
+ || approval.sequenceId !== record.sequenceId
218
+ || !sameRevision(approval.sourceRevision, record.sourceRevision)
219
+ || !sameRevision(approval.canonicalRevision, record.canonicalRevision)
220
+ || approval.artifactPath !== record.artifactPath
221
+ || approval.artifactDigest !== record.artifactDigest
222
+ || stableJson(approval.outputIntent) !== stableJson(record.outputIntent)) {
223
+ throw new Error("HEADLESS_ROUGH_CUT_EXECUTION_INVALID: persisted execution differs from its approved preview");
224
+ }
225
+ if (!sameRevision(record.sourceRevision, record.plan.revision)) {
226
+ throw new Error("HEADLESS_ROUGH_CUT_EXECUTION_INVALID: source revision differs from the approved plan revision");
227
+ }
228
+ if (!sameRevision(record.canonicalRevision, record.fcpxml.provenance.revision)) {
229
+ throw new Error("HEADLESS_ROUGH_CUT_REVISION_MISMATCH: FCPXML provenance differs from the committed canonical revision");
230
+ }
231
+ if (record.fcpxml.destination.mode !== "versioned") {
232
+ throw new Error("HEADLESS_ROUGH_CUT_TARGET_NOT_CREATE_ONLY: native delivery requires a versioned create-only project target");
233
+ }
234
+ if (resolve(artifactPath) !== record.artifactPath) {
235
+ throw new Error("HEADLESS_ROUGH_CUT_ARTIFACT_TARGET_MISMATCH: requested path differs from the approved artifact path");
236
+ }
237
+ if (artifactDigest !== undefined && artifactDigest !== record.artifactDigest) {
238
+ throw new Error("HEADLESS_ROUGH_CUT_ARTIFACT_CHANGED: requested digest differs from the approved artifact digest");
239
+ }
240
+ const project = await this.open(record.projectId);
241
+ if (project.timeline.sequence.id !== record.sequenceId
242
+ || !sameRevision(project.timeline.revision, record.canonicalRevision)) {
243
+ throw new Error("HEADLESS_ROUGH_CUT_STALE_REVISION: canonical project changed after the approved rough cut");
244
+ }
245
+ const approvedSnapshot = await new FcpxmlDocumentAdapter(record.artifactPath, undefined, {
246
+ allowMissingImmutableIdsForReadback: true,
247
+ }).readProject();
248
+ const referencedMediaIds = new Set([
249
+ ...approvedSnapshot.timeline.clips.map(({ mediaId }) => mediaId),
250
+ ...approvedSnapshot.timeline.storyElements.map(({ mediaId }) => mediaId),
251
+ ].filter((mediaId) => mediaId !== undefined));
252
+ const approvedSources = approvedSnapshot.media
253
+ .filter(({ mediaId }) => referencedMediaIds.has(mediaId))
254
+ .map(({ source }) => resolve(source));
255
+ const digestBySource = new Map(project.timeline.resources
256
+ .filter((resource) => resource.source && resource.sourceDigest)
257
+ .map((resource) => [resolveMediaSource(resource.source, record.artifactPath), resource.sourceDigest]));
258
+ const sourceMediaDigests = [...new Set(approvedSources)].sort().map((source) => {
259
+ const sha256 = digestBySource.get(source);
260
+ if (!sha256) {
261
+ throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_MEDIA_DIGEST_UNAVAILABLE: no approved source digest is bound to ${source}`);
262
+ }
263
+ return { source, sha256 };
264
+ });
265
+ const render = await this.inspectRender(record.renderId);
266
+ if (render.status !== "passed" || render.projectId !== record.projectId || render.sequenceId !== record.sequenceId
267
+ || !sameRevision(render.requestedRevision, record.canonicalRevision)) {
268
+ throw new Error("HEADLESS_ROUGH_CUT_RENDER_EVIDENCE_MISMATCH: render evidence does not match the approved revision");
269
+ }
270
+ const artifact = await readFile(record.artifactPath, "utf8");
271
+ if (hash(artifact) !== record.artifactDigest || Buffer.byteLength(artifact) !== record.artifactBytes) {
272
+ throw new Error("HEADLESS_ROUGH_CUT_ARTIFACT_CHANGED: approved FCPXML no longer matches its recorded digest");
273
+ }
274
+ if (!record.fcpxml.target.libraryUid?.trim()
275
+ || !record.fcpxml.destination.projectUid?.trim()
276
+ || !record.fcpxml.destination.sequenceUid?.trim()) {
277
+ throw new Error("HEADLESS_ROUGH_CUT_TARGET_INVALID: approved FCPXML has no explicit library, project, and sequence target");
278
+ }
279
+ return {
280
+ executionId,
281
+ sourceTransactionId: `headless-rough-cut:${executionId}`,
282
+ projectId: record.projectId,
283
+ sequenceId: record.sequenceId,
284
+ sourceRevision: structuredClone(record.sourceRevision),
285
+ canonicalRevision: structuredClone(record.canonicalRevision),
286
+ planDigest: record.planDigest,
287
+ renderId: record.renderId,
288
+ artifactPath: record.artifactPath,
289
+ artifactDigest: record.artifactDigest,
290
+ sourceAudioPolicy: record.outputIntent.sourceAudioPolicy,
291
+ target: structuredClone(record.fcpxml.target),
292
+ destination: structuredClone(record.fcpxml.destination),
293
+ coverage: structuredClone(record.fcpxml.coverage),
294
+ provenance: structuredClone(record.provenance),
295
+ targetLibraryUid: record.fcpxml.target.libraryUid,
296
+ sourceMediaDigests,
297
+ };
298
+ }
299
+ async verifyPublishableRoughCutTransaction(request) {
300
+ const prefix = "headless-rough-cut:";
301
+ if (!request.sourceTransactionId.startsWith(prefix)) {
302
+ throw new Error("HEADLESS_ROUGH_CUT_EXECUTION_INVALID: source transaction is not a rough-cut execution");
303
+ }
304
+ return this.verifyPublishableRoughCut(request.sourceTransactionId.slice(prefix.length), request.artifactPath, request.artifactDigest);
305
+ }
137
306
  async render(projectId, sequenceId, parameters, expectedRevision) {
138
307
  if (!this.renderer || !this.verifier)
139
308
  throw new Error("HEADLESS_RENDER_UNAVAILABLE: renderer and verifier are not configured");
@@ -176,6 +345,14 @@ export class HeadlessProjectService {
176
345
  validateProjectId(projectId);
177
346
  return join(this.directory, `${projectId}.json`);
178
347
  }
348
+ executionPath(executionId) {
349
+ validateExecutionId(executionId);
350
+ return join(this.directory, `${executionId}.json`);
351
+ }
352
+ approvalPath(planDigest) {
353
+ validatePlanDigest(planDigest);
354
+ return join(this.directory, `${planDigest}.approval.json`);
355
+ }
179
356
  async saveRender(record) {
180
357
  await mkdir(this.directory, { recursive: true });
181
358
  const path = join(this.directory, `${record.renderId}.json`);
@@ -183,6 +360,33 @@ export class HeadlessProjectService {
183
360
  await writeFile(temporary, `${JSON.stringify(record)}\n`, { encoding: "utf8", flag: "wx" });
184
361
  await rename(temporary, path);
185
362
  }
363
+ async saveRoughCutExecution(record) {
364
+ await mkdir(this.directory, { recursive: true });
365
+ const execution = { ...record, evidenceDigest: hash(stableJson(record)) };
366
+ const path = this.executionPath(record.executionId);
367
+ const temporary = `${path}.${randomUUID()}.tmp`;
368
+ await writeFile(temporary, `${JSON.stringify(execution)}\n`, { encoding: "utf8", flag: "wx" });
369
+ await rename(temporary, path);
370
+ }
371
+ async saveRoughCutApproval(record) {
372
+ await mkdir(this.directory, { recursive: true });
373
+ const approval = { ...record, evidenceDigest: hash(stableJson(record)) };
374
+ const path = this.approvalPath(record.planDigest);
375
+ const temporary = `${path}.${randomUUID()}.tmp`;
376
+ await writeFile(temporary, `${JSON.stringify(approval)}\n`, { encoding: "utf8", flag: "wx" });
377
+ await rename(temporary, path);
378
+ }
379
+ async readRoughCutApproval(planDigest) {
380
+ const approval = JSON.parse(await readFile(this.approvalPath(planDigest), "utf8"));
381
+ const { evidenceDigest, ...unsignedApproval } = approval;
382
+ const { planDigest: storedDigest, ...digestFields } = unsignedApproval;
383
+ if (approval.schemaVersion !== 1 || storedDigest !== planDigest
384
+ || !evidenceDigest || hash(stableJson(unsignedApproval)) !== evidenceDigest
385
+ || hash(stableJson(digestFields)) !== planDigest) {
386
+ throw new Error(`HEADLESS_ROUGH_CUT_APPROVAL_INVALID: persisted approval is invalid for ${planDigest}`);
387
+ }
388
+ return approval;
389
+ }
186
390
  async prepareRoughCut(request) {
187
391
  await this.open(request.projectId);
188
392
  const project = await this.store(request.projectId).load();
@@ -205,9 +409,11 @@ export class HeadlessProjectService {
205
409
  overwrite: request.fcpxml.overwrite === true,
206
410
  },
207
411
  };
208
- const planDigest = digestRoughCutPlan(request.plan, operations, outputIntent);
412
+ const inputDigest = digestRoughCutPlan(request.plan, operations, outputIntent);
209
413
  const existingOccurrenceIds = new Set(project.timeline.sequence.occurrences.map(({ id }) => id));
210
414
  const resourceByMediaId = new Map(project.timeline.resources.map((resource) => [resource.id, resource]));
415
+ const hasPrimaryStoryContent = project.timeline.sequence.occurrences.some(({ track }) => track === 0)
416
+ || project.timeline.sequence.storyElements.length > 0;
211
417
  const provenance = [];
212
418
  const planOperations = [];
213
419
  for (const shot of request.plan.shots) {
@@ -224,9 +430,10 @@ export class HeadlessProjectService {
224
430
  const sourceStartTime = shot.range.startTime ?? secondsToRational(shot.range.start);
225
431
  const durationTime = shot.range.durationTime ?? secondsToRational(shot.range.end - shot.range.start);
226
432
  assertSourceRange(resource, shot.range, sourceStartTime, durationTime);
433
+ const appendToPrimaryStoryline = hasPrimaryStoryContent || planOperations.length > 0;
227
434
  planOperations.push({
228
435
  type: "insert-occurrence",
229
- placement: "append",
436
+ ...(appendToPrimaryStoryline ? { placement: "append" } : {}),
230
437
  occurrence: {
231
438
  id: occurrenceId,
232
439
  name: `Rough cut ${shot.order}: ${shot.rationale}`,
@@ -236,7 +443,7 @@ export class HeadlessProjectService {
236
443
  track: 0,
237
444
  role: "video",
238
445
  mediaId: resource.id,
239
- binding: { provider: "framekit.rough-cut", kind: "occurrence", identity: `${planDigest}:${shot.order}` },
446
+ binding: { provider: "framekit.rough-cut", kind: "occurrence", identity: `${inputDigest}:${shot.order}` },
240
447
  },
241
448
  });
242
449
  provenance.push({
@@ -258,9 +465,30 @@ export class HeadlessProjectService {
258
465
  expectedRevision: structuredClone(request.plan.revision),
259
466
  operations: editOperations,
260
467
  };
261
- return { command, planDigest, provenance, outputIntent };
468
+ return { command, inputDigest, provenance, outputIntent };
469
+ }
470
+ async previewPreparedRoughCut(request, prepared, timestamp, transaction = new ProjectTransactionService(this.store(request.projectId), { clock: () => timestamp })) {
471
+ const rawPreview = await transaction.preview(prepared.command);
472
+ const canonicalRevision = {
473
+ id: `ir:${timelineIrDigest(rawPreview.after.timeline)}`,
474
+ sequence: rawPreview.before.timeline.revision.sequence + 1,
475
+ timestamp,
476
+ };
477
+ const canonicalTimeline = structuredClone(rawPreview.after.timeline);
478
+ canonicalTimeline.revision = canonicalRevision;
479
+ const preview = {
480
+ ...rawPreview,
481
+ after: { ...rawPreview.after, timeline: canonicalTimeline },
482
+ };
483
+ const fcpxml = compileTimelineIrToFcpxml(canonicalTimeline, { target: request.fcpxml.target });
484
+ return { preview, fcpxml };
262
485
  }
263
486
  }
487
+ function createRoughCutApproval(fields) {
488
+ const digestFields = { schemaVersion: 1, ...fields };
489
+ const planDigest = hash(stableJson(digestFields));
490
+ return { ...digestFields, planDigest };
491
+ }
264
492
  function digestRoughCutPlan(plan, operations, outputIntent) {
265
493
  return createHash("sha256").update(stableJson({ plan, operations, outputIntent })).digest("hex");
266
494
  }
@@ -368,3 +596,14 @@ function validateRenderId(renderId) {
368
596
  if (!/^render-[0-9a-f-]{36}$/.test(renderId))
369
597
  throw new Error("HEADLESS_RENDER_INVALID: renderId is invalid");
370
598
  }
599
+ function validateExecutionId(executionId) {
600
+ if (!/^rough-cut-[0-9a-f-]{36}$/.test(executionId))
601
+ throw new Error("HEADLESS_ROUGH_CUT_EXECUTION_INVALID: executionId is invalid");
602
+ }
603
+ function validatePlanDigest(planDigest) {
604
+ if (!/^[a-f0-9]{64}$/.test(planDigest))
605
+ throw new Error("HEADLESS_ROUGH_CUT_APPROVAL_INVALID: planDigest is invalid");
606
+ }
607
+ function hash(value) {
608
+ return createHash("sha256").update(value).digest("hex");
609
+ }
@@ -2,7 +2,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
2
2
  import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { InMemoryEditorAdapter } from "../../../packages/testkit/src/index.js";
5
- import { createCommandAnalyzers, createFinalCutLiveAdapter, FcpxmlDocumentAdapter, FinalCutAssetRegistry, FinalCutMediaRegistry, FinalCutConnectionManager, assertCanonicalProviderConfiguration, FinalCutCanonicalNativeProvider, FinalCutCanonicalSnapshotSource, FinalCutLibraryInspectionProvider, FinalCutNativeAutomationAdapter, createFinalCutNativeTargetResolver, DisposableNativeEditWorkflow, FinalCutBackgroundMaterializationPublisher, FinalCutProjectPublisher, FinalCutSqliteInspectionProvider, FinalCutVideoExporter, FinalCutSessionAdapter, createNativeOperationLease, createDisposableNativeOperationSession, isFinalCutVideoProbeAvailable, } from "../../../adapters/final-cut/typescript/src/index.js";
5
+ import { createCommandAnalyzers, createFinalCutLiveAdapter, FcpxmlDocumentAdapter, FinalCutAssetRegistry, FinalCutMediaRegistry, FinalCutConnectionManager, assertCanonicalProviderConfiguration, FinalCutCanonicalNativeProvider, FinalCutCanonicalSnapshotSource, FinalCutLibraryInspectionProvider, FinalCutNativeAutomationAdapter, createFinalCutNativeTargetResolver, DisposableNativeEditWorkflow, FinalCutBackgroundMaterializationPublisher, FinalCutProjectPublisher, parseFinalCutProjectPublishRoute, FinalCutSqliteInspectionProvider, FinalCutVideoExporter, FinalCutSessionAdapter, createNativeOperationLease, createDisposableNativeOperationSession, isFinalCutVideoProbeAvailable, } from "../../../adapters/final-cut/typescript/src/index.js";
6
6
  import { FixtureAudioAnalyzer, FixtureMetadataAnalyzer, FixtureSpeechAnalyzer, FixtureVisualAnalyzer } from "../../../packages/testkit/src/index.js";
7
7
  import { AgentVideoRuntime, JsonSemanticMediaIndexStore } from "../../../packages/runtime/src/index.js";
8
8
  import { createMcpServer } from "./server.js";
@@ -212,10 +212,30 @@ const projectPublisher = liveMode && fcpxmlPath
212
212
  ? new FinalCutProjectPublisher({
213
213
  enabled: !headlessFinalCut && process.env.FRAMEKIT_FINAL_CUT_NATIVE_WRITES === "1",
214
214
  sourcePath: fcpxmlPath,
215
+ publishJobsDirectory: join(framekitStateDirectory, "publish-jobs"),
215
216
  documentDelivery: liveAdapter,
216
- targetLibraryUid: process.env.FRAMEKIT_FINAL_CUT_LIBRARY_UID,
217
- allowHeadedFallback: process.env.FRAMEKIT_FINAL_CUT_ALLOW_HEADED_IMPORT === "1",
217
+ publishRoute: parseFinalCutProjectPublishRoute(process.env.FRAMEKIT_FINAL_CUT_PUBLISH_ROUTE, Boolean(liveAdapter)),
218
218
  liveState: () => liveAdapter.readLiveState(),
219
+ readCanonicalSnapshot: (targetBinding, identity) => new FinalCutCanonicalSnapshotSource({
220
+ readbackTarget: { ...targetBinding, ...identity },
221
+ }).readSnapshot(),
222
+ targetBinding: (targetLibraryPath, identity) => {
223
+ if (!targetLibraryPath || !backgroundLibraryProvider) {
224
+ throw new Error("FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE: a target library path and Final Cut library catalog are required");
225
+ }
226
+ return backgroundLibraryProvider.resolveProjectBinding(targetLibraryPath, identity);
227
+ },
228
+ headlessSourceVerifier: async (request) => {
229
+ const proof = await headlessProjects.verifyPublishableRoughCutTransaction({
230
+ sourceTransactionId: request.sourceTransactionId,
231
+ artifactPath: request.artifactPath,
232
+ artifactDigest: request.artifactDigest,
233
+ });
234
+ return {
235
+ targetLibraryUid: proof.targetLibraryUid,
236
+ sourceMediaDigests: proof.sourceMediaDigests,
237
+ };
238
+ },
219
239
  })
220
240
  : undefined;
221
241
  const backgroundMaterializationCommand = liveMode
@@ -244,6 +264,10 @@ const server = createMcpServer(runtime, {
244
264
  projectPublisher,
245
265
  ...(sessionMaterializationPublisher?.isAvailable() ? { sessionMaterializationPublisher } : {}),
246
266
  videoExporter,
267
+ requireBuildAlignment: process.env.FRAMEKIT_REQUIRE_BUILD_ALIGNMENT === "1",
268
+ ...(process.env.FRAMEKIT_VALIDATION_COMMIT?.trim()
269
+ ? { validationCommit: process.env.FRAMEKIT_VALIDATION_COMMIT.trim() }
270
+ : {}),
247
271
  sessionDirectory: join(framekitStateDirectory, "sessions"),
248
272
  sessionChangeSource: createCanonicalSessionChangeSource(() => runtime.inspectProject()),
249
273
  materializationDirectory: join(framekitStateDirectory, "materializations"),