@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
@@ -0,0 +1,942 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { readdir, readFile, rename, writeFile, mkdir, link, unlink, realpath, stat } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { FramekitProjectStore, LocalMediaRegistrar, ProjectTransactionService, createFramekitRenderRequest, renderAndVerifyFramekitProject, timelineIrDigest, } from "../../runtime/src/index.js";
5
+ import { FcpxmlDocumentAdapter, compileTimelineIrToFcpxml, resolveMediaSource, } from "../../../adapters/final-cut/typescript/src/index.js";
6
+ export class HeadlessProjectService {
7
+ directory;
8
+ protectedStateDirectory;
9
+ mediaProbe;
10
+ renderer;
11
+ verifier;
12
+ clock;
13
+ constructor(options) {
14
+ this.directory = options.directory;
15
+ this.protectedStateDirectory = options.protectedStateDirectory ?? options.directory;
16
+ this.mediaProbe = options.mediaProbe;
17
+ this.renderer = options.renderer;
18
+ this.verifier = options.verifier;
19
+ this.clock = options.clock ?? (() => new Date().toISOString());
20
+ }
21
+ async create(timeline) {
22
+ const store = this.store(timeline.project.id);
23
+ const timestamp = this.clock();
24
+ return store.create({
25
+ schemaVersion: 1,
26
+ metadata: { createdAt: timestamp, updatedAt: timestamp },
27
+ timeline,
28
+ });
29
+ }
30
+ async list() {
31
+ await mkdir(this.directory, { recursive: true });
32
+ const entries = await readdir(this.directory, { withFileTypes: true });
33
+ const summaries = [];
34
+ for (const entry of entries.filter((candidate) => (candidate.isFile() || candidate.isSymbolicLink()) && candidate.name.endsWith(".json"))) {
35
+ const projectId = entry.name.slice(0, -".json".length);
36
+ if (await this.isInternalRecord(entry.name))
37
+ continue;
38
+ const project = await this.store(projectId).load();
39
+ if (project.timeline.project.id !== projectId) {
40
+ throw new Error("HEADLESS_PROJECT_IDENTITY_MISMATCH: stored project ID differs from its filename");
41
+ }
42
+ summaries.push(toSummary(project, this.projectPath(projectId)));
43
+ }
44
+ return summaries.sort((left, right) => left.projectId.localeCompare(right.projectId));
45
+ }
46
+ async isInternalRecord(name) {
47
+ let value;
48
+ try {
49
+ value = JSON.parse(await readFile(join(this.directory, name), "utf8"));
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ if (!value || typeof value !== "object" || Array.isArray(value))
55
+ return false;
56
+ const record = value;
57
+ // A document-shaped file remains a project even when its ID resembles an
58
+ // internal record. Unknown or corrupt files still fail through the store.
59
+ if ("timeline" in record || "metadata" in record)
60
+ return false;
61
+ const render = /^(render-[0-9a-f-]{36})\.json$/.exec(name);
62
+ if (render && record.renderId === render[1])
63
+ return true;
64
+ const execution = /^(rough-cut-[0-9a-f-]{36})\.json$/.exec(name);
65
+ if (execution && record.schemaVersion === 1 && record.executionId === execution[1])
66
+ return true;
67
+ const approval = /^([0-9a-f]{64})\.approval\.json$/.exec(name);
68
+ return Boolean(approval && record.schemaVersion === 1 && record.planDigest === approval[1]);
69
+ }
70
+ async open(projectId) {
71
+ const project = await this.store(projectId).load();
72
+ const hasLocalMedia = project.timeline.resources.some((resource) => resource.sourceKind === "local-file");
73
+ if (hasLocalMedia && !this.mediaProbe) {
74
+ throw new Error("HEADLESS_MEDIA_PROBE_UNAVAILABLE: local-file resources require a configured media probe");
75
+ }
76
+ if (this.mediaProbe)
77
+ return new LocalMediaRegistrar(this.store(projectId), this.mediaProbe).reopen();
78
+ return project;
79
+ }
80
+ async inspect(projectId) {
81
+ return this.open(projectId);
82
+ }
83
+ async registerMedia(projectId, sourcePath, expectedRevision) {
84
+ if (!this.mediaProbe)
85
+ throw new Error("HEADLESS_MEDIA_PROBE_UNAVAILABLE: no local media metadata probe is configured");
86
+ return new LocalMediaRegistrar(this.store(projectId), this.mediaProbe, { clock: this.clock }).register(sourcePath, expectedRevision);
87
+ }
88
+ async searchMedia(projectId, query) {
89
+ const project = await this.open(projectId);
90
+ const needle = query.toLowerCase();
91
+ return {
92
+ revision: structuredClone(project.timeline.revision),
93
+ media: project.timeline.resources.filter((resource) => [resource.id, resource.name, resource.source].some((value) => value?.toLowerCase().includes(needle))).map((resource) => structuredClone(resource)),
94
+ };
95
+ }
96
+ async previewEdit(projectId, command, sequenceId) {
97
+ const project = await this.open(projectId);
98
+ const transaction = new ProjectTransactionService(this.snapshotStore(projectId, project), { clock: this.clock });
99
+ return transaction.preview({
100
+ ...command,
101
+ target: command.target ?? { projectId, sequenceId },
102
+ });
103
+ }
104
+ async executeEdit(projectId, command, sequenceId) {
105
+ const project = await this.open(projectId);
106
+ const timestamp = this.clock();
107
+ const transaction = new ProjectTransactionService(this.snapshotStore(projectId, project), { clock: () => timestamp });
108
+ const editCommand = {
109
+ ...command,
110
+ target: command.target ?? { projectId, sequenceId },
111
+ };
112
+ const preview = await transaction.preview(editCommand);
113
+ const recordId = `undo-${randomUUID()}`;
114
+ const afterDigest = timelineIrDigest(preview.after.timeline);
115
+ const record = {
116
+ version: 1, undoId: recordId, projectId, sequenceId,
117
+ before: preview.before,
118
+ beforeDigest: timelineIrDigest(preview.before.timeline),
119
+ afterDigest,
120
+ afterRevision: { id: `ir:${afterDigest}`, sequence: preview.before.timeline.revision.sequence + 1, timestamp },
121
+ };
122
+ const directory = join(this.directory, "undo");
123
+ await mkdir(directory, { recursive: true });
124
+ const serialized = JSON.stringify({ ...record, checksum: hash(stableJson(record)) });
125
+ // The client retains this commitment independently of the stored record.
126
+ const undoId = `${recordId}-${hash(serialized)}`;
127
+ await writeFile(join(directory, `${recordId}.json`), serialized, { encoding: "utf8", flag: "wx" });
128
+ const result = await transaction.execute(editCommand);
129
+ if (!sameRevision(result.after.timeline.revision, record.afterRevision) || timelineIrDigest(result.after.timeline) !== afterDigest) {
130
+ throw new Error("HEADLESS_EDIT_UNCERTAIN: committed edit differs from the recorded Undo state");
131
+ }
132
+ return { ...result, undoId };
133
+ }
134
+ async undoEdit(projectId, sequenceId, undoId, expectedRevision) {
135
+ const handle = /^(undo-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})-([0-9a-f]{64})$/.exec(undoId);
136
+ if (!handle) {
137
+ throw new Error("HEADLESS_UNDO_INVALID: invalid Undo identifier");
138
+ }
139
+ let record;
140
+ try {
141
+ const serialized = await readFile(join(this.directory, "undo", `${handle[1]}.json`), "utf8");
142
+ if (hash(serialized) !== handle[2])
143
+ throw new Error("record does not match client commitment");
144
+ record = JSON.parse(serialized);
145
+ const { checksum, ...content } = record;
146
+ if (record.version !== 1 || record.undoId !== handle[1] || checksum !== hash(stableJson(content))
147
+ || record.projectId !== projectId || record.sequenceId !== sequenceId
148
+ || record.before.timeline.project.id !== projectId || record.before.timeline.sequence.id !== sequenceId
149
+ || timelineIrDigest(record.before.timeline) !== record.beforeDigest)
150
+ throw new Error("invalid record");
151
+ }
152
+ catch {
153
+ throw new Error("HEADLESS_UNDO_INVALID: Undo record is missing or invalid");
154
+ }
155
+ const current = await this.open(projectId);
156
+ if (current.timeline.sequence.id !== sequenceId || !sameRevision(current.timeline.revision, expectedRevision)
157
+ || !sameRevision(current.timeline.revision, record.afterRevision) || timelineIrDigest(current.timeline) !== record.afterDigest) {
158
+ throw new Error("HEADLESS_UNDO_STALE: current target or revision differs from the recorded edit");
159
+ }
160
+ const restored = structuredClone(record.before);
161
+ const timestamp = this.clock();
162
+ restored.metadata.updatedAt = timestamp;
163
+ restored.timeline.revision = { id: `ir:${record.beforeDigest}`, sequence: current.timeline.revision.sequence + 1, timestamp };
164
+ await this.store(projectId).save(restored, current.timeline.revision);
165
+ const observed = await this.open(projectId);
166
+ const observedDigest = timelineIrDigest(observed.timeline);
167
+ if (!sameRevision(observed.timeline.revision, restored.timeline.revision) || observedDigest !== record.beforeDigest) {
168
+ throw new Error("HEADLESS_UNDO_UNVERIFIED: restored project could not be independently verified");
169
+ }
170
+ return { project: observed, verification: { verified: true, expectedDigest: record.beforeDigest, observedDigest } };
171
+ }
172
+ async exportFcpxml(projectId, sequenceId, expectedRevision, outputPath, target) {
173
+ const project = await this.open(projectId);
174
+ if (project.timeline.sequence.id !== sequenceId || !sameRevision(project.timeline.revision, expectedRevision)) {
175
+ throw new Error("HEADLESS_FCPXML_STALE: project target or revision does not match the requested export");
176
+ }
177
+ await this.assertOutputSeparation(project, [outputPath]);
178
+ const compiled = compileTimelineIrToFcpxml(project.timeline, { target });
179
+ const artifact = await writeVerifiedFcpxml(resolve(outputPath), compiled.xml, compiled.digest, false);
180
+ return { artifact, provenance: compiled.provenance, coverage: compiled.coverage };
181
+ }
182
+ async previewRoughCut(request) {
183
+ const prepared = await this.prepareRoughCut(request);
184
+ const timestamp = this.clock();
185
+ const { preview, fcpxml } = await this.previewPreparedRoughCut(request, prepared, timestamp);
186
+ const approval = createRoughCutApproval({
187
+ inputDigest: prepared.inputDigest,
188
+ projectId: request.projectId,
189
+ sequenceId: request.sequenceId,
190
+ sourceRevision: request.plan.revision,
191
+ canonicalRevision: preview.after.timeline.revision,
192
+ artifactPath: resolve(request.fcpxml.path),
193
+ artifactDigest: fcpxml.digest,
194
+ outputIntent: prepared.outputIntent,
195
+ });
196
+ await this.saveRoughCutApproval(approval);
197
+ return {
198
+ ...preview,
199
+ plan: structuredClone(request.plan),
200
+ planDigest: approval.planDigest,
201
+ provenance: prepared.provenance,
202
+ outputIntent: prepared.outputIntent,
203
+ fcpxml: selectFcpxmlMetadata(fcpxml),
204
+ };
205
+ }
206
+ async executeRoughCut(request) {
207
+ if (request.approved !== true) {
208
+ throw new Error("HEADLESS_ROUGH_CUT_APPROVAL_REQUIRED: set approved=true after reviewing the preview");
209
+ }
210
+ const prepared = await this.prepareRoughCut(request);
211
+ if (!/^[a-f0-9]{64}$/.test(request.planDigest)) {
212
+ throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: planDigest does not match the submitted rough-cut plan");
213
+ }
214
+ let approval;
215
+ try {
216
+ approval = await this.readRoughCutApproval(request.planDigest);
217
+ }
218
+ catch (error) {
219
+ if (error.code === "ENOENT") {
220
+ throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: planDigest has no persisted preview approval");
221
+ }
222
+ throw error;
223
+ }
224
+ if (approval.inputDigest !== prepared.inputDigest
225
+ || approval.projectId !== request.projectId
226
+ || approval.sequenceId !== request.sequenceId
227
+ || !sameRevision(approval.sourceRevision, request.plan.revision)
228
+ || approval.artifactPath !== resolve(request.fcpxml.path)
229
+ || stableJson(approval.outputIntent) !== stableJson(prepared.outputIntent)) {
230
+ throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: planDigest does not match the submitted rough-cut plan");
231
+ }
232
+ const transaction = new ProjectTransactionService(this.snapshotStore(request.projectId, prepared.project), {
233
+ clock: () => approval.canonicalRevision.timestamp,
234
+ });
235
+ const { preview, fcpxml } = await this.previewPreparedRoughCut(request, prepared, approval.canonicalRevision.timestamp, transaction);
236
+ if (!sameRevision(preview.after.timeline.revision, approval.canonicalRevision)
237
+ || fcpxml.digest !== approval.artifactDigest) {
238
+ throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: replayed preview differs from the approved revision or FCPXML digest");
239
+ }
240
+ await this.assertOutputSeparation(prepared.project, [request.render.outputPath, request.fcpxml.path]);
241
+ const renderRequest = createFramekitRenderRequest({
242
+ timeline: preview.after.timeline,
243
+ target: { projectId: request.projectId, sequenceId: request.sequenceId },
244
+ revision: preview.after.timeline.revision,
245
+ parameters: request.render,
246
+ });
247
+ if (!this.renderer || !this.verifier) {
248
+ throw new Error("HEADLESS_ROUGH_CUT_RENDER_UNAVAILABLE: renderer and verifier are not configured");
249
+ }
250
+ const outcome = await renderAndVerifyFramekitProject(renderRequest, this.renderer, this.verifier);
251
+ const renderId = `render-${randomUUID()}`;
252
+ const renderRecord = {
253
+ renderId,
254
+ projectId: request.projectId,
255
+ sequenceId: request.sequenceId,
256
+ requestedRevision: renderRequest.projectRevision,
257
+ createdAt: this.clock(),
258
+ status: outcome.status,
259
+ outcome,
260
+ };
261
+ await this.saveRender(renderRecord);
262
+ if (outcome.status !== "passed") {
263
+ throw new Error(`HEADLESS_ROUGH_CUT_RENDER_FAILED: render verification status was ${outcome.status}; inspect ${renderId}`);
264
+ }
265
+ await this.assertOutputSeparation(prepared.project, [request.render.outputPath, request.fcpxml.path]);
266
+ const fcpxmlArtifact = await writeVerifiedFcpxml(request.fcpxml.path, fcpxml.xml, fcpxml.digest, request.fcpxml.overwrite === true);
267
+ const committed = await transaction.execute(prepared.command);
268
+ const executionId = `rough-cut-${randomUUID()}`;
269
+ try {
270
+ await this.saveRoughCutExecution({
271
+ schemaVersion: 1,
272
+ executionId,
273
+ approved: true,
274
+ projectId: request.projectId,
275
+ sequenceId: request.sequenceId,
276
+ sourceRevision: structuredClone(request.plan.revision),
277
+ canonicalRevision: structuredClone(committed.after.timeline.revision),
278
+ plan: structuredClone(request.plan),
279
+ operations: structuredClone(request.operations ?? []),
280
+ outputIntent: structuredClone(prepared.outputIntent),
281
+ planDigest: approval.planDigest,
282
+ inputDigest: prepared.inputDigest,
283
+ renderId,
284
+ artifactPath: resolve(fcpxmlArtifact.path),
285
+ artifactDigest: fcpxmlArtifact.digest,
286
+ artifactBytes: fcpxmlArtifact.bytes,
287
+ fcpxml: selectFcpxmlMetadata(fcpxml),
288
+ provenance: structuredClone(prepared.provenance),
289
+ });
290
+ }
291
+ catch (error) {
292
+ const details = { projectId: request.projectId, sequenceId: request.sequenceId, executionId, committedRevision: committed.after.timeline.revision };
293
+ throw new Error(`HEADLESS_ROUGH_CUT_HISTORY_UNCONFIRMED: project already committed; no execution or publish proof was returned; reinspect project before retry: ${JSON.stringify(details)}`, { cause: error });
294
+ }
295
+ return {
296
+ ...preview,
297
+ after: committed.after,
298
+ plan: structuredClone(request.plan),
299
+ planDigest: approval.planDigest,
300
+ provenance: prepared.provenance,
301
+ outputIntent: prepared.outputIntent,
302
+ fcpxml: selectFcpxmlMetadata(fcpxml),
303
+ executionId,
304
+ committed: true,
305
+ render: { renderId, status: "passed", outcome },
306
+ fcpxmlArtifact,
307
+ transaction: committed,
308
+ };
309
+ }
310
+ async verifyPublishableRoughCut(executionId, artifactPath, artifactDigest) {
311
+ validateExecutionId(executionId);
312
+ let record;
313
+ try {
314
+ record = JSON.parse(await readFile(this.executionPath(executionId), "utf8"));
315
+ }
316
+ catch (error) {
317
+ if (error.code === "ENOENT") {
318
+ throw new Error(`HEADLESS_ROUGH_CUT_EXECUTION_NOT_FOUND: unknown approved rough-cut execution ${executionId}`);
319
+ }
320
+ throw error;
321
+ }
322
+ const { evidenceDigest, ...unsignedRecord } = record;
323
+ if (record.schemaVersion !== 1 || record.executionId !== executionId || record.approved !== true
324
+ || !evidenceDigest || hash(stableJson(unsignedRecord)) !== evidenceDigest) {
325
+ throw new Error(`HEADLESS_ROUGH_CUT_EXECUTION_INVALID: approved rough-cut provenance is invalid for ${executionId}`);
326
+ }
327
+ const expectedInputDigest = digestRoughCutPlan(record.plan, record.operations, record.outputIntent);
328
+ if (expectedInputDigest !== record.inputDigest) {
329
+ throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: persisted rough-cut input digest does not match its plan and output intent");
330
+ }
331
+ const approval = await this.readRoughCutApproval(record.planDigest);
332
+ if (approval.inputDigest !== record.inputDigest
333
+ || approval.projectId !== record.projectId
334
+ || approval.sequenceId !== record.sequenceId
335
+ || !sameRevision(approval.sourceRevision, record.sourceRevision)
336
+ || !sameRevision(approval.canonicalRevision, record.canonicalRevision)
337
+ || approval.artifactPath !== record.artifactPath
338
+ || approval.artifactDigest !== record.artifactDigest
339
+ || stableJson(approval.outputIntent) !== stableJson(record.outputIntent)) {
340
+ throw new Error("HEADLESS_ROUGH_CUT_EXECUTION_INVALID: persisted execution differs from its approved preview");
341
+ }
342
+ if (!sameRevision(record.sourceRevision, record.plan.revision)) {
343
+ throw new Error("HEADLESS_ROUGH_CUT_EXECUTION_INVALID: source revision differs from the approved plan revision");
344
+ }
345
+ if (!sameRevision(record.canonicalRevision, record.fcpxml.provenance.revision)) {
346
+ throw new Error("HEADLESS_ROUGH_CUT_REVISION_MISMATCH: FCPXML provenance differs from the committed canonical revision");
347
+ }
348
+ if (record.fcpxml.destination.mode !== "versioned") {
349
+ throw new Error("HEADLESS_ROUGH_CUT_TARGET_NOT_CREATE_ONLY: native delivery requires a versioned create-only project target");
350
+ }
351
+ if (resolve(artifactPath) !== record.artifactPath) {
352
+ throw new Error("HEADLESS_ROUGH_CUT_ARTIFACT_TARGET_MISMATCH: requested path differs from the approved artifact path");
353
+ }
354
+ if (artifactDigest !== undefined && artifactDigest !== record.artifactDigest) {
355
+ throw new Error("HEADLESS_ROUGH_CUT_ARTIFACT_CHANGED: requested digest differs from the approved artifact digest");
356
+ }
357
+ const project = await this.open(record.projectId);
358
+ if (project.timeline.sequence.id !== record.sequenceId
359
+ || !sameRevision(project.timeline.revision, record.canonicalRevision)) {
360
+ throw new Error("HEADLESS_ROUGH_CUT_STALE_REVISION: canonical project changed after the approved rough cut");
361
+ }
362
+ const approvedSnapshot = await new FcpxmlDocumentAdapter(record.artifactPath, undefined, {
363
+ allowMissingImmutableIdsForReadback: true,
364
+ }).readProject();
365
+ const referencedMediaIds = new Set([
366
+ ...approvedSnapshot.timeline.clips.map(({ mediaId }) => mediaId),
367
+ ...approvedSnapshot.timeline.storyElements.map(({ mediaId }) => mediaId),
368
+ ].filter((mediaId) => mediaId !== undefined));
369
+ const approvedSources = approvedSnapshot.media
370
+ .filter(({ mediaId }) => referencedMediaIds.has(mediaId))
371
+ .map(({ source }) => resolve(source));
372
+ const digestBySource = new Map(project.timeline.resources
373
+ .filter((resource) => resource.source && resource.sourceDigest)
374
+ .map((resource) => [resolveMediaSource(resource.source, record.artifactPath), resource.sourceDigest]));
375
+ const sourceMediaDigests = [...new Set(approvedSources)].sort().map((source) => {
376
+ const sha256 = digestBySource.get(source);
377
+ if (!sha256) {
378
+ throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_MEDIA_DIGEST_UNAVAILABLE: no approved source digest is bound to ${source}`);
379
+ }
380
+ return { source, sha256 };
381
+ });
382
+ const render = await this.inspectRender(record.renderId);
383
+ if (render.status !== "passed" || render.projectId !== record.projectId || render.sequenceId !== record.sequenceId
384
+ || !sameRevision(render.requestedRevision, record.canonicalRevision)) {
385
+ throw new Error("HEADLESS_ROUGH_CUT_RENDER_EVIDENCE_MISMATCH: render evidence does not match the approved revision");
386
+ }
387
+ const artifact = await readFile(record.artifactPath, "utf8");
388
+ if (hash(artifact) !== record.artifactDigest || Buffer.byteLength(artifact) !== record.artifactBytes) {
389
+ throw new Error("HEADLESS_ROUGH_CUT_ARTIFACT_CHANGED: approved FCPXML no longer matches its recorded digest");
390
+ }
391
+ if (!record.fcpxml.target.libraryUid?.trim()
392
+ || !record.fcpxml.destination.projectUid?.trim()
393
+ || !record.fcpxml.destination.sequenceUid?.trim()) {
394
+ throw new Error("HEADLESS_ROUGH_CUT_TARGET_INVALID: approved FCPXML has no explicit library, project, and sequence target");
395
+ }
396
+ return {
397
+ executionId,
398
+ sourceTransactionId: `headless-rough-cut:${executionId}`,
399
+ projectId: record.projectId,
400
+ sequenceId: record.sequenceId,
401
+ sourceRevision: structuredClone(record.sourceRevision),
402
+ canonicalRevision: structuredClone(record.canonicalRevision),
403
+ planDigest: record.planDigest,
404
+ renderId: record.renderId,
405
+ artifactPath: record.artifactPath,
406
+ artifactDigest: record.artifactDigest,
407
+ sourceAudioPolicy: record.outputIntent.sourceAudioPolicy,
408
+ target: structuredClone(record.fcpxml.target),
409
+ destination: structuredClone(record.fcpxml.destination),
410
+ coverage: structuredClone(record.fcpxml.coverage),
411
+ provenance: structuredClone(record.provenance),
412
+ targetLibraryUid: record.fcpxml.target.libraryUid,
413
+ sourceMediaDigests,
414
+ };
415
+ }
416
+ async verifyPublishableRoughCutTransaction(request) {
417
+ const prefix = "headless-rough-cut:";
418
+ if (!request.sourceTransactionId.startsWith(prefix)) {
419
+ throw new Error("HEADLESS_ROUGH_CUT_EXECUTION_INVALID: source transaction is not a rough-cut execution");
420
+ }
421
+ return this.verifyPublishableRoughCut(request.sourceTransactionId.slice(prefix.length), request.artifactPath, request.artifactDigest);
422
+ }
423
+ async render(projectId, sequenceId, parameters, expectedRevision) {
424
+ if (!this.renderer || !this.verifier)
425
+ throw new Error("HEADLESS_RENDER_UNAVAILABLE: renderer and verifier are not configured");
426
+ const project = await this.open(projectId);
427
+ await this.assertOutputSeparation(project, [parameters.outputPath]);
428
+ const request = createFramekitRenderRequest({
429
+ timeline: project.timeline,
430
+ target: { projectId, sequenceId },
431
+ ...(expectedRevision ? { revision: expectedRevision } : {}),
432
+ parameters,
433
+ });
434
+ const outcome = await renderAndVerifyFramekitProject(request, this.renderer, this.verifier);
435
+ const renderId = `render-${randomUUID()}`;
436
+ const record = {
437
+ renderId,
438
+ projectId,
439
+ sequenceId,
440
+ requestedRevision: request.projectRevision,
441
+ createdAt: this.clock(),
442
+ status: outcome.status,
443
+ outcome,
444
+ };
445
+ await this.saveRender(record);
446
+ return record;
447
+ }
448
+ async inspectRender(renderId) {
449
+ validateRenderId(renderId);
450
+ try {
451
+ return JSON.parse(await readFile(join(this.directory, `${renderId}.json`), "utf8"));
452
+ }
453
+ catch (error) {
454
+ if (error.code === "ENOENT")
455
+ throw new Error(`HEADLESS_RENDER_NOT_FOUND: render record does not exist: ${renderId}`);
456
+ throw error;
457
+ }
458
+ }
459
+ async assertOutputSeparation(project, paths) {
460
+ const summaries = await this.list();
461
+ const projects = await Promise.all(summaries.map((summary) => new FramekitProjectStore(summary.path).load()));
462
+ // Keep the already validated snapshot even if the project changed during enumeration.
463
+ await assertOutputSeparation([project, ...projects], this.protectedStateDirectory, paths);
464
+ }
465
+ store(projectId) {
466
+ return new FramekitProjectStore(this.projectPath(projectId));
467
+ }
468
+ snapshotStore(projectId, project) {
469
+ const store = this.store(projectId);
470
+ return {
471
+ create: (value) => store.create(value),
472
+ load: async () => {
473
+ const current = await store.load();
474
+ if (!sameRevision(current.timeline.revision, project.timeline.revision)
475
+ || timelineIrDigest(current.timeline) !== timelineIrDigest(project.timeline)) {
476
+ throw new Error("HEADLESS_PROJECT_STALE: project changed after media validation");
477
+ }
478
+ return current;
479
+ },
480
+ save: (value, expectedRevision) => store.save(value, expectedRevision),
481
+ };
482
+ }
483
+ projectPath(projectId) {
484
+ validateProjectId(projectId);
485
+ return join(this.directory, `${projectId}.json`);
486
+ }
487
+ executionPath(executionId) {
488
+ validateExecutionId(executionId);
489
+ return join(this.directory, `${executionId}.json`);
490
+ }
491
+ approvalPath(planDigest) {
492
+ validatePlanDigest(planDigest);
493
+ return join(this.directory, `${planDigest}.approval.json`);
494
+ }
495
+ async saveRender(record) {
496
+ await mkdir(this.directory, { recursive: true });
497
+ const path = join(this.directory, `${record.renderId}.json`);
498
+ await publishHistory(path, `${JSON.stringify(record)}\n`);
499
+ }
500
+ async saveRoughCutExecution(record) {
501
+ await mkdir(this.directory, { recursive: true });
502
+ const execution = { ...record, evidenceDigest: hash(stableJson(record)) };
503
+ const path = this.executionPath(record.executionId);
504
+ await publishHistory(path, `${JSON.stringify(execution)}\n`);
505
+ }
506
+ async saveRoughCutApproval(record) {
507
+ await mkdir(this.directory, { recursive: true });
508
+ const approval = { ...record, evidenceDigest: hash(stableJson(record)) };
509
+ const path = this.approvalPath(record.planDigest);
510
+ await publishHistory(path, `${JSON.stringify(approval)}\n`, true);
511
+ }
512
+ async readRoughCutApproval(planDigest) {
513
+ const approval = JSON.parse(await readFile(this.approvalPath(planDigest), "utf8"));
514
+ const { evidenceDigest, ...unsignedApproval } = approval;
515
+ const { planDigest: storedDigest, ...digestFields } = unsignedApproval;
516
+ if (approval.schemaVersion !== 1 || storedDigest !== planDigest
517
+ || !evidenceDigest || hash(stableJson(unsignedApproval)) !== evidenceDigest
518
+ || hash(stableJson(digestFields)) !== planDigest) {
519
+ throw new Error(`HEADLESS_ROUGH_CUT_APPROVAL_INVALID: persisted approval is invalid for ${planDigest}`);
520
+ }
521
+ return approval;
522
+ }
523
+ async prepareRoughCut(request) {
524
+ const project = await this.open(request.projectId);
525
+ if (project.timeline.sequence.id !== request.sequenceId) {
526
+ throw new Error("HEADLESS_ROUGH_CUT_TARGET_MISMATCH: sequenceId does not match the persisted project");
527
+ }
528
+ if (!sameRevision(project.timeline.revision, request.plan.revision)) {
529
+ throw new Error("HEADLESS_ROUGH_CUT_STALE_REVISION: rough-cut plan revision does not match the persisted project");
530
+ }
531
+ await this.assertOutputSeparation(project, [request.render.outputPath, request.fcpxml.path]);
532
+ if (!request.plan.shots.length)
533
+ throw new Error("HEADLESS_ROUGH_CUT_EMPTY_PLAN: rough-cut plan must contain at least one shot");
534
+ const operations = structuredClone(request.operations ?? []);
535
+ const sourceAudioPolicy = request.sourceAudioPolicy ?? "preserve-and-mix";
536
+ const outputIntent = {
537
+ sourceAudioPolicy,
538
+ render: structuredClone(request.render),
539
+ fcpxml: {
540
+ path: request.fcpxml.path,
541
+ target: structuredClone(request.fcpxml.target),
542
+ overwrite: request.fcpxml.overwrite === true,
543
+ },
544
+ };
545
+ const inputDigest = digestRoughCutPlan(request.plan, operations, outputIntent);
546
+ const existingOccurrenceIds = new Set(project.timeline.sequence.occurrences.map(({ id }) => id));
547
+ const resourceByMediaId = new Map(project.timeline.resources.map((resource) => [resource.id, resource]));
548
+ const hasPrimaryStoryContent = project.timeline.sequence.occurrences.some(({ track }) => track === 0)
549
+ || project.timeline.sequence.storyElements.length > 0;
550
+ const provenance = [];
551
+ const planOperations = [];
552
+ for (const shot of request.plan.shots) {
553
+ const shotWithEvidence = shot;
554
+ const occurrenceId = `rough-cut-${shot.order}`;
555
+ if (existingOccurrenceIds.has(occurrenceId)) {
556
+ throw new Error(`HEADLESS_ROUGH_CUT_OCCURRENCE_COLLISION: ${occurrenceId} already exists`);
557
+ }
558
+ existingOccurrenceIds.add(occurrenceId);
559
+ const resource = resourceByMediaId.get(shot.sourceIdentity.mediaId);
560
+ if (!resource)
561
+ throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_NOT_FOUND: ${shot.sourceIdentity.mediaId}`);
562
+ assertSourceIdentity(resource, shot.sourceIdentity);
563
+ assertSourceRange(resource, shot.range);
564
+ const sourceRange = alignInferredRoughCutRange(resource, shot.range, project.timeline.sequence.frameDuration);
565
+ assertSourceRange(resource, sourceRange);
566
+ const sourceStartTime = sourceRange.startTime ?? secondsToRational(sourceRange.start);
567
+ const durationTime = sourceRange.durationTime ?? secondsToRational(sourceRange.end - sourceRange.start);
568
+ const appendToPrimaryStoryline = hasPrimaryStoryContent || planOperations.length > 0;
569
+ planOperations.push({
570
+ type: "insert-occurrence",
571
+ ...(appendToPrimaryStoryline ? { placement: "append" } : {}),
572
+ occurrence: {
573
+ id: occurrenceId,
574
+ name: `Rough cut ${shot.order}: ${shot.rationale}`,
575
+ startTime: { value: "0", timescale: "1" },
576
+ durationTime,
577
+ sourceStartTime,
578
+ track: 0,
579
+ role: "video",
580
+ mediaId: resource.id,
581
+ binding: { provider: "framekit.rough-cut", kind: "occurrence", identity: `${inputDigest}:${shot.order}` },
582
+ },
583
+ });
584
+ provenance.push({
585
+ order: shot.order,
586
+ occurrenceId,
587
+ mediaId: resource.id,
588
+ sourceIdentity: structuredClone(shot.sourceIdentity),
589
+ sourceRange: structuredClone(sourceRange),
590
+ confidence: shot.confidence,
591
+ matchedProperties: [...shot.matchedProperties],
592
+ rationale: shot.rationale,
593
+ ...(shotWithEvidence.evidence ? { evidence: structuredClone(shotWithEvidence.evidence) } : {}),
594
+ });
595
+ }
596
+ const editOperations = [...planOperations, ...operations];
597
+ const command = {
598
+ schemaVersion: 1,
599
+ target: { projectId: request.projectId, sequenceId: request.sequenceId },
600
+ expectedRevision: structuredClone(request.plan.revision),
601
+ operations: editOperations,
602
+ };
603
+ return { command, inputDigest, provenance, outputIntent, project };
604
+ }
605
+ async previewPreparedRoughCut(request, prepared, timestamp, transaction = new ProjectTransactionService(this.snapshotStore(request.projectId, prepared.project), { clock: () => timestamp })) {
606
+ const rawPreview = await transaction.preview(prepared.command);
607
+ const canonicalRevision = {
608
+ id: `ir:${timelineIrDigest(rawPreview.after.timeline)}`,
609
+ sequence: rawPreview.before.timeline.revision.sequence + 1,
610
+ timestamp,
611
+ };
612
+ const canonicalTimeline = structuredClone(rawPreview.after.timeline);
613
+ canonicalTimeline.revision = canonicalRevision;
614
+ const preview = {
615
+ ...rawPreview,
616
+ after: { ...rawPreview.after, timeline: canonicalTimeline },
617
+ };
618
+ const fcpxml = compileTimelineIrToFcpxml(canonicalTimeline, { target: request.fcpxml.target });
619
+ return { preview, fcpxml };
620
+ }
621
+ }
622
+ async function publishHistory(path, contents, allowIdentical = false) {
623
+ const temporary = `${path}.${randomUUID()}.tmp`;
624
+ try {
625
+ await writeFile(temporary, contents, { encoding: "utf8", flag: "wx" });
626
+ try {
627
+ // Linking a fully written file fails atomically if the destination exists.
628
+ await link(temporary, path);
629
+ }
630
+ catch (error) {
631
+ if (error.code !== "EEXIST")
632
+ throw error;
633
+ if (allowIdentical && await readFile(path, "utf8") === contents)
634
+ return;
635
+ throw new Error("HEADLESS_HISTORY_COLLISION: history destination already exists", { cause: error });
636
+ }
637
+ }
638
+ finally {
639
+ try {
640
+ await unlink(temporary);
641
+ }
642
+ catch (error) {
643
+ if (error.code !== "ENOENT")
644
+ throw error;
645
+ }
646
+ }
647
+ }
648
+ function createRoughCutApproval(fields) {
649
+ const digestFields = { schemaVersion: 1, ...fields };
650
+ const planDigest = hash(stableJson(digestFields));
651
+ return { ...digestFields, planDigest };
652
+ }
653
+ function digestRoughCutPlan(plan, operations, outputIntent) {
654
+ return createHash("sha256").update(stableJson({ plan, operations, outputIntent })).digest("hex");
655
+ }
656
+ function stableJson(value) {
657
+ if (value === null || typeof value !== "object")
658
+ return JSON.stringify(value);
659
+ if (Array.isArray(value))
660
+ return `[${value.map(stableJson).join(",")}]`;
661
+ return `{${Object.entries(value).filter(([, child]) => child !== undefined).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => `${JSON.stringify(key)}:${stableJson(child)}`).join(",")}}`;
662
+ }
663
+ function assertSourceIdentity(resource, source) {
664
+ if (resource.source !== source.source)
665
+ throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_MISMATCH: source path differs for ${source.mediaId}`);
666
+ if (source.sourceDigest !== undefined && resource.sourceDigest !== source.sourceDigest) {
667
+ throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_MISMATCH: source digest differs for ${source.mediaId}`);
668
+ }
669
+ if (source.mediaKind !== undefined && resource.mediaKind !== source.mediaKind) {
670
+ throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_MISMATCH: media kind differs for ${source.mediaId}`);
671
+ }
672
+ if (resource.mediaKind !== "video")
673
+ throw new Error(`HEADLESS_ROUGH_CUT_VIDEO_REQUIRED: ${source.mediaId}`);
674
+ if (source.duration !== undefined && resource.metadata?.durationTime !== undefined
675
+ && Math.abs(source.duration - rationalSeconds(resource.metadata.durationTime)) > 0.01) {
676
+ throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_MISMATCH: source duration differs for ${source.mediaId}`);
677
+ }
678
+ }
679
+ function assertSourceRange(resource, range) {
680
+ if (!Number.isFinite(range.start) || !Number.isFinite(range.end) || range.start < 0 || range.end <= range.start) {
681
+ throw new Error("HEADLESS_ROUGH_CUT_RANGE_INVALID: source range must be finite and non-empty");
682
+ }
683
+ if (resource.metadata?.durationTime !== undefined && range.end > rationalSeconds(resource.metadata.durationTime) + 0.001) {
684
+ throw new Error(`HEADLESS_ROUGH_CUT_RANGE_INVALID: source range exceeds ${resource.id}`);
685
+ }
686
+ const sourceStartTime = range.startTime ?? secondsToRational(range.start);
687
+ const durationTime = range.durationTime ?? secondsToRational(range.end - range.start);
688
+ if (rationalSeconds(sourceStartTime) < 0 || rationalSeconds(durationTime) <= 0
689
+ || Math.abs(rationalSeconds(sourceStartTime) - range.start) > 0.001
690
+ || Math.abs(rationalSeconds(durationTime) - (range.end - range.start)) > 0.001) {
691
+ throw new Error("HEADLESS_ROUGH_CUT_RANGE_INVALID: rational source range must be non-negative and non-empty");
692
+ }
693
+ }
694
+ function alignInferredRoughCutRange(resource, range, sequenceFrameDuration) {
695
+ if (range.startTime !== undefined || range.durationTime !== undefined
696
+ || !Number.isFinite(range.start) || !Number.isFinite(range.end) || range.end <= range.start) {
697
+ return structuredClone(range);
698
+ }
699
+ const frameRate = resource.metadata?.streams.find((stream) => stream.kind === "video" && stream.frameRate)?.frameRate;
700
+ if (!frameRate || BigInt(frameRate.value) <= 0n || BigInt(frameRate.timescale) <= 0n
701
+ || BigInt(sequenceFrameDuration.value) <= 0n || BigInt(sequenceFrameDuration.timescale) <= 0n) {
702
+ return structuredClone(range);
703
+ }
704
+ const sourceFrameDuration = { value: frameRate.timescale, timescale: frameRate.value };
705
+ const startTime = nearestFrameTime(secondsToRational(range.start), sourceFrameDuration);
706
+ const sourceEndTime = nearestFrameTime(secondsToRational(range.end), sourceFrameDuration);
707
+ let durationTime = nearestFrameTime(subtractRationalTimes(sourceEndTime, startTime), sequenceFrameDuration);
708
+ if (resource.metadata?.durationTime !== undefined) {
709
+ // The FCPXML compiler rounds source starts to the sequence grid. Bound
710
+ // both the canonical and exported ranges when that rounding moves later.
711
+ const exportedStartTime = nearestFrameTime(startTime, sequenceFrameDuration);
712
+ const latestStartTime = compareRationalTimes(startTime, exportedStartTime) >= 0 ? startTime : exportedStartTime;
713
+ const available = subtractRationalTimes(resource.metadata.durationTime, latestStartTime);
714
+ const maxDuration = floorFrameTime(available, sequenceFrameDuration);
715
+ if (compareRationalTimes(durationTime, maxDuration) > 0)
716
+ durationTime = maxDuration;
717
+ }
718
+ if (BigInt(durationTime.value) <= 0n) {
719
+ throw new Error("HEADLESS_ROUGH_CUT_RANGE_INVALID: frame alignment produced an empty source range");
720
+ }
721
+ const endTime = addRationalTimes(startTime, durationTime);
722
+ return {
723
+ ...structuredClone(range),
724
+ start: rationalSeconds(startTime),
725
+ end: rationalSeconds(endTime),
726
+ startTime,
727
+ durationTime,
728
+ };
729
+ }
730
+ function floorFrameTime(time, frameDuration) {
731
+ const numerator = BigInt(time.value) * BigInt(frameDuration.timescale);
732
+ const denominator = BigInt(time.timescale) * BigInt(frameDuration.value);
733
+ const frames = numerator > 0n ? numerator / denominator : 0n;
734
+ return normalizeRationalTime(frames * BigInt(frameDuration.value), BigInt(frameDuration.timescale));
735
+ }
736
+ function nearestFrameTime(time, frameDuration) {
737
+ const timeValue = BigInt(time.value);
738
+ const timeScale = BigInt(time.timescale);
739
+ const frameValue = BigInt(frameDuration.value);
740
+ const frameScale = BigInt(frameDuration.timescale);
741
+ const numerator = timeValue * frameScale;
742
+ const denominator = timeScale * frameValue;
743
+ const frameCount = (numerator * 2n + denominator) / (denominator * 2n);
744
+ return normalizeRationalTime(frameCount * frameValue, frameScale);
745
+ }
746
+ function compareRationalTimes(left, right) {
747
+ const difference = BigInt(left.value) * BigInt(right.timescale) - BigInt(right.value) * BigInt(left.timescale);
748
+ return difference < 0n ? -1 : difference > 0n ? 1 : 0;
749
+ }
750
+ function subtractRationalTimes(left, right) {
751
+ const leftValue = BigInt(left.value);
752
+ const leftScale = BigInt(left.timescale);
753
+ const rightValue = BigInt(right.value);
754
+ const rightScale = BigInt(right.timescale);
755
+ return normalizeRationalTime(leftValue * rightScale - rightValue * leftScale, leftScale * rightScale);
756
+ }
757
+ function addRationalTimes(left, right) {
758
+ const leftValue = BigInt(left.value);
759
+ const leftScale = BigInt(left.timescale);
760
+ const rightValue = BigInt(right.value);
761
+ const rightScale = BigInt(right.timescale);
762
+ return normalizeRationalTime(leftValue * rightScale + rightValue * leftScale, leftScale * rightScale);
763
+ }
764
+ function normalizeRationalTime(value, timescale) {
765
+ const divisor = greatestCommonDivisorBigInt(value < 0n ? -value : value, timescale);
766
+ return { value: String(value / divisor), timescale: String(timescale / divisor) };
767
+ }
768
+ function greatestCommonDivisorBigInt(left, right) {
769
+ let a = left;
770
+ let b = right;
771
+ while (b !== 0n) {
772
+ const remainder = a % b;
773
+ a = b;
774
+ b = remainder;
775
+ }
776
+ return a || 1n;
777
+ }
778
+ function secondsToRational(seconds) {
779
+ const timescale = 1_000_000;
780
+ const value = Math.round(seconds * timescale);
781
+ const divisor = greatestCommonDivisor(Math.abs(value), timescale);
782
+ return { value: String(value / divisor), timescale: String(timescale / divisor) };
783
+ }
784
+ function rationalSeconds(time) {
785
+ return Number(time.value) / Number(time.timescale);
786
+ }
787
+ function greatestCommonDivisor(left, right) {
788
+ while (right !== 0) {
789
+ const remainder = left % right;
790
+ left = right;
791
+ right = remainder;
792
+ }
793
+ return left || 1;
794
+ }
795
+ function sameRevision(left, right) {
796
+ return left.id === right.id && left.sequence === right.sequence && left.timestamp === right.timestamp;
797
+ }
798
+ function selectFcpxmlMetadata(result) {
799
+ return {
800
+ digest: result.digest,
801
+ target: structuredClone(result.target),
802
+ destination: structuredClone(result.destination),
803
+ coverage: structuredClone(result.coverage),
804
+ provenance: structuredClone(result.provenance),
805
+ };
806
+ }
807
+ // Resolve symlinked ancestors even for a destination that does not exist yet.
808
+ async function canonicalOutputPath(path) {
809
+ const absolute = resolve(path);
810
+ try {
811
+ return await realpath(absolute);
812
+ }
813
+ catch (error) {
814
+ if (error.code !== "ENOENT")
815
+ throw error;
816
+ const parent = dirname(absolute);
817
+ if (parent === absolute)
818
+ throw error;
819
+ return join(await canonicalOutputPath(parent), basename(absolute));
820
+ }
821
+ }
822
+ async function sameExistingFile(left, right) {
823
+ try {
824
+ const [a, b] = await Promise.all([stat(left), stat(right)]);
825
+ return a.dev === b.dev && a.ino === b.ino;
826
+ }
827
+ catch (error) {
828
+ if (error.code === "ENOENT")
829
+ return false;
830
+ throw error;
831
+ }
832
+ }
833
+ async function stateTree(directory) {
834
+ const directories = [];
835
+ const files = [];
836
+ const visited = new Set();
837
+ async function visit(path, root = false) {
838
+ let canonical;
839
+ try {
840
+ canonical = await realpath(path);
841
+ }
842
+ catch (error) {
843
+ if (root && error.code === "ENOENT")
844
+ return;
845
+ throw error;
846
+ }
847
+ const info = await stat(canonical);
848
+ if (!info.isDirectory()) {
849
+ files.push(canonical);
850
+ return;
851
+ }
852
+ directories.push(canonical);
853
+ if (visited.has(canonical))
854
+ return;
855
+ visited.add(canonical);
856
+ for (const entry of await readdir(canonical, { withFileTypes: true })) {
857
+ await visit(join(canonical, entry.name));
858
+ }
859
+ }
860
+ await visit(directory, true);
861
+ return { directories, files };
862
+ }
863
+ function isInside(directory, path) {
864
+ const fromDirectory = relative(directory, path);
865
+ return !fromDirectory || (!isAbsolute(fromDirectory) && fromDirectory !== ".." && !fromDirectory.startsWith(`..${sep}`));
866
+ }
867
+ async function assertOutputSeparation(projects, stateDirectory, paths) {
868
+ const state = await canonicalOutputPath(stateDirectory);
869
+ const outputs = await Promise.all(paths.map(canonicalOutputPath));
870
+ const sources = await Promise.all(projects.flatMap((project) => project.timeline.resources)
871
+ .filter((resource) => resource.sourceKind === "local-file" && resource.source)
872
+ .map((resource) => canonicalOutputPath(resource.source)));
873
+ const protectedState = await stateTree(state);
874
+ const lexicalState = resolve(stateDirectory);
875
+ const collides = async (a, b) => a === b || await sameExistingFile(a, b);
876
+ for (let index = 0; index < outputs.length; index++) {
877
+ const output = outputs[index];
878
+ if (isInside(lexicalState, resolve(paths[index])) || isInside(state, output)
879
+ || protectedState.directories.some((directory) => isInside(directory, output))) {
880
+ throw new Error("HEADLESS_OUTPUT_COLLISION: output is inside Framekit state");
881
+ }
882
+ for (const protectedFile of [...sources, ...protectedState.files]) {
883
+ if (await collides(output, protectedFile))
884
+ throw new Error("HEADLESS_OUTPUT_COLLISION: output aliases protected state or registered media");
885
+ }
886
+ }
887
+ for (let i = 0; i < outputs.length; i++) {
888
+ for (let j = i + 1; j < outputs.length; j++) {
889
+ if (await collides(outputs[i], outputs[j]))
890
+ throw new Error("HEADLESS_OUTPUT_COLLISION: outputs alias each other");
891
+ }
892
+ }
893
+ }
894
+ async function writeVerifiedFcpxml(path, xml, digest, overwrite) {
895
+ await mkdir(dirname(path), { recursive: true });
896
+ const temporary = `${path}.${randomUUID()}.tmp`;
897
+ await writeFile(temporary, xml, { encoding: "utf8", flag: "wx" });
898
+ try {
899
+ if (overwrite)
900
+ await rename(temporary, path);
901
+ else
902
+ await link(temporary, path);
903
+ }
904
+ finally {
905
+ if (!overwrite)
906
+ await unlink(temporary).catch(() => { });
907
+ }
908
+ const persisted = await readFile(path, "utf8");
909
+ const persistedDigest = createHash("sha256").update(persisted).digest("hex");
910
+ if (persistedDigest !== digest)
911
+ throw new Error("HEADLESS_ROUGH_CUT_FCPXML_VERIFY_FAILED: persisted XML digest differs from the compiled artifact");
912
+ return { path, digest, bytes: Buffer.byteLength(persisted), verified: true };
913
+ }
914
+ function toSummary(project, path) {
915
+ return {
916
+ projectId: project.timeline.project.id,
917
+ projectName: project.timeline.project.name,
918
+ sequenceId: project.timeline.sequence.id,
919
+ sequenceName: project.timeline.sequence.name,
920
+ revision: project.timeline.revision,
921
+ path,
922
+ };
923
+ }
924
+ function validateProjectId(projectId) {
925
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(projectId))
926
+ throw new Error("HEADLESS_PROJECT_INVALID: projectId must be a safe logical identifier");
927
+ }
928
+ function validateRenderId(renderId) {
929
+ if (!/^render-[0-9a-f-]{36}$/.test(renderId))
930
+ throw new Error("HEADLESS_RENDER_INVALID: renderId is invalid");
931
+ }
932
+ function validateExecutionId(executionId) {
933
+ if (!/^rough-cut-[0-9a-f-]{36}$/.test(executionId))
934
+ throw new Error("HEADLESS_ROUGH_CUT_EXECUTION_INVALID: executionId is invalid");
935
+ }
936
+ function validatePlanDigest(planDigest) {
937
+ if (!/^[a-f0-9]{64}$/.test(planDigest))
938
+ throw new Error("HEADLESS_ROUGH_CUT_APPROVAL_INVALID: planDigest is invalid");
939
+ }
940
+ function hash(value) {
941
+ return createHash("sha256").update(value).digest("hex");
942
+ }