@morshoto/framekit 0.1.18 → 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.
- package/README.md +17 -12
- package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +8 -2
- package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.js +275 -0
- package/dist-package/adapters/final-cut/typescript/src/canonical.js +538 -77
- package/dist-package/adapters/final-cut/typescript/src/connection.js +6 -1
- package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +6 -0
- package/dist-package/adapters/final-cut/typescript/src/experimental.js +8 -0
- package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +22 -8
- package/dist-package/adapters/final-cut/typescript/src/index.js +1 -7
- package/dist-package/adapters/final-cut/typescript/src/live.js +27 -2
- package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.js +175 -0
- package/dist-package/adapters/final-cut/typescript/src/native-session.js +11 -6
- package/dist-package/adapters/final-cut/typescript/src/native.js +201 -82
- package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +1 -0
- package/dist-package/adapters/final-cut/typescript/src/publisher.js +255 -14
- package/dist-package/adapters/final-cut/typescript/src/session.js +43 -13
- package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +3 -1
- package/dist-package/adapters/headless/typescript/src/audio-output.js +3 -0
- package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +32 -14
- package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +9 -4
- package/dist-package/apps/cli/src/dev-doctor.js +198 -0
- package/dist-package/apps/cli/src/headless-projects.js +5 -0
- package/dist-package/apps/cli/src/main.js +42 -0
- package/dist-package/apps/mcp-server/runtime/speech-analyzer-wrapper.mjs +54 -0
- package/dist-package/apps/mcp-server/runtime/whisper-speech-backend.py +181 -0
- package/dist-package/apps/mcp-server/src/build-identity.json +2 -2
- package/dist-package/apps/mcp-server/src/canonical-native-snapshot.js +18 -0
- package/dist-package/apps/mcp-server/src/final-cut-runtime-config.js +3 -0
- package/dist-package/apps/mcp-server/src/main.js +24 -19
- package/dist-package/apps/mcp-server/src/materialization-jobs.js +143 -10
- package/dist-package/apps/mcp-server/src/routing.js +2 -0
- package/dist-package/apps/mcp-server/src/server.js +737 -152
- package/dist-package/apps/mcp-server/src/tools/skills/catalog.js +142 -0
- package/dist-package/apps/mcp-server/src/tools/skills/metadata.js +71 -0
- package/dist-package/apps/mcp-server/src/tools/skills/register.js +101 -0
- package/dist-package/{apps/mcp-server → packages/headless-application}/src/headless-projects.js +391 -58
- package/dist-package/packages/headless-application/src/index.js +1 -0
- package/dist-package/packages/runtime/src/application/project-service.js +5 -1
- package/dist-package/packages/runtime/src/application/project-store.js +13 -36
- package/dist-package/packages/runtime/src/application/transaction-store.js +1 -1
- package/dist-package/packages/runtime/src/capabilities.js +1 -1
- package/dist-package/packages/runtime/src/context/context-engine.js +22 -16
- package/dist-package/packages/runtime/src/context/context-service.js +2 -2
- package/dist-package/packages/runtime/src/editing/edit-service.js +76 -10
- package/dist-package/packages/runtime/src/index.js +1 -0
- package/dist-package/packages/runtime/src/runtime.js +16 -7
- package/dist-package/packages/runtime/src/timeline/editing-session.js +16 -0
- package/dist-package/packages/testkit/src/in-memory-editor.js +3 -3
- package/dist-package/packages/testkit/src/index.js +1 -0
- package/dist-package/packages/testkit/src/sender-lifecycle-fixture.js +192 -0
- package/package.json +32 -10
package/dist-package/{apps/mcp-server → packages/headless-application}/src/headless-projects.js
RENAMED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { readdir, readFile, rename, writeFile, mkdir } from "node:fs/promises";
|
|
3
|
-
import { dirname, join, resolve } from "node:path";
|
|
4
|
-
import { FramekitProjectStore, LocalMediaRegistrar, ProjectTransactionService, createFramekitRenderRequest, renderAndVerifyFramekitProject, timelineIrDigest, } from "
|
|
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
5
|
import { FcpxmlDocumentAdapter, compileTimelineIrToFcpxml, resolveMediaSource, } from "../../../adapters/final-cut/typescript/src/index.js";
|
|
6
6
|
export class HeadlessProjectService {
|
|
7
7
|
directory;
|
|
8
|
+
protectedStateDirectory;
|
|
8
9
|
mediaProbe;
|
|
9
10
|
renderer;
|
|
10
11
|
verifier;
|
|
11
12
|
clock;
|
|
12
13
|
constructor(options) {
|
|
13
14
|
this.directory = options.directory;
|
|
15
|
+
this.protectedStateDirectory = options.protectedStateDirectory ?? options.directory;
|
|
14
16
|
this.mediaProbe = options.mediaProbe;
|
|
15
17
|
this.renderer = options.renderer;
|
|
16
18
|
this.verifier = options.verifier;
|
|
@@ -29,13 +31,42 @@ export class HeadlessProjectService {
|
|
|
29
31
|
await mkdir(this.directory, { recursive: true });
|
|
30
32
|
const entries = await readdir(this.directory, { withFileTypes: true });
|
|
31
33
|
const summaries = [];
|
|
32
|
-
for (const entry of entries.filter((candidate) => candidate.isFile()
|
|
34
|
+
for (const entry of entries.filter((candidate) => (candidate.isFile() || candidate.isSymbolicLink()) && candidate.name.endsWith(".json"))) {
|
|
33
35
|
const projectId = entry.name.slice(0, -".json".length);
|
|
36
|
+
if (await this.isInternalRecord(entry.name))
|
|
37
|
+
continue;
|
|
34
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
|
+
}
|
|
35
42
|
summaries.push(toSummary(project, this.projectPath(projectId)));
|
|
36
43
|
}
|
|
37
44
|
return summaries.sort((left, right) => left.projectId.localeCompare(right.projectId));
|
|
38
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
|
+
}
|
|
39
70
|
async open(projectId) {
|
|
40
71
|
const project = await this.store(projectId).load();
|
|
41
72
|
const hasLocalMedia = project.timeline.resources.some((resource) => resource.sourceKind === "local-file");
|
|
@@ -43,7 +74,7 @@ export class HeadlessProjectService {
|
|
|
43
74
|
throw new Error("HEADLESS_MEDIA_PROBE_UNAVAILABLE: local-file resources require a configured media probe");
|
|
44
75
|
}
|
|
45
76
|
if (this.mediaProbe)
|
|
46
|
-
|
|
77
|
+
return new LocalMediaRegistrar(this.store(projectId), this.mediaProbe).reopen();
|
|
47
78
|
return project;
|
|
48
79
|
}
|
|
49
80
|
async inspect(projectId) {
|
|
@@ -54,21 +85,99 @@ export class HeadlessProjectService {
|
|
|
54
85
|
throw new Error("HEADLESS_MEDIA_PROBE_UNAVAILABLE: no local media metadata probe is configured");
|
|
55
86
|
return new LocalMediaRegistrar(this.store(projectId), this.mediaProbe, { clock: this.clock }).register(sourcePath, expectedRevision);
|
|
56
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
|
+
}
|
|
57
96
|
async previewEdit(projectId, command, sequenceId) {
|
|
58
|
-
await this.open(projectId);
|
|
59
|
-
const transaction = new ProjectTransactionService(this.
|
|
97
|
+
const project = await this.open(projectId);
|
|
98
|
+
const transaction = new ProjectTransactionService(this.snapshotStore(projectId, project), { clock: this.clock });
|
|
60
99
|
return transaction.preview({
|
|
61
100
|
...command,
|
|
62
101
|
target: command.target ?? { projectId, sequenceId },
|
|
63
102
|
});
|
|
64
103
|
}
|
|
65
104
|
async executeEdit(projectId, command, sequenceId) {
|
|
66
|
-
await this.open(projectId);
|
|
67
|
-
const
|
|
68
|
-
|
|
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 = {
|
|
69
109
|
...command,
|
|
70
110
|
target: command.target ?? { projectId, sequenceId },
|
|
71
|
-
}
|
|
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 };
|
|
72
181
|
}
|
|
73
182
|
async previewRoughCut(request) {
|
|
74
183
|
const prepared = await this.prepareRoughCut(request);
|
|
@@ -120,7 +229,7 @@ export class HeadlessProjectService {
|
|
|
120
229
|
|| stableJson(approval.outputIntent) !== stableJson(prepared.outputIntent)) {
|
|
121
230
|
throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: planDigest does not match the submitted rough-cut plan");
|
|
122
231
|
}
|
|
123
|
-
const transaction = new ProjectTransactionService(this.
|
|
232
|
+
const transaction = new ProjectTransactionService(this.snapshotStore(request.projectId, prepared.project), {
|
|
124
233
|
clock: () => approval.canonicalRevision.timestamp,
|
|
125
234
|
});
|
|
126
235
|
const { preview, fcpxml } = await this.previewPreparedRoughCut(request, prepared, approval.canonicalRevision.timestamp, transaction);
|
|
@@ -128,6 +237,7 @@ export class HeadlessProjectService {
|
|
|
128
237
|
|| fcpxml.digest !== approval.artifactDigest) {
|
|
129
238
|
throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: replayed preview differs from the approved revision or FCPXML digest");
|
|
130
239
|
}
|
|
240
|
+
await this.assertOutputSeparation(prepared.project, [request.render.outputPath, request.fcpxml.path]);
|
|
131
241
|
const renderRequest = createFramekitRenderRequest({
|
|
132
242
|
timeline: preview.after.timeline,
|
|
133
243
|
target: { projectId: request.projectId, sequenceId: request.sequenceId },
|
|
@@ -152,29 +262,36 @@ export class HeadlessProjectService {
|
|
|
152
262
|
if (outcome.status !== "passed") {
|
|
153
263
|
throw new Error(`HEADLESS_ROUGH_CUT_RENDER_FAILED: render verification status was ${outcome.status}; inspect ${renderId}`);
|
|
154
264
|
}
|
|
265
|
+
await this.assertOutputSeparation(prepared.project, [request.render.outputPath, request.fcpxml.path]);
|
|
155
266
|
const fcpxmlArtifact = await writeVerifiedFcpxml(request.fcpxml.path, fcpxml.xml, fcpxml.digest, request.fcpxml.overwrite === true);
|
|
156
267
|
const committed = await transaction.execute(prepared.command);
|
|
157
268
|
const executionId = `rough-cut-${randomUUID()}`;
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
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
|
+
}
|
|
178
295
|
return {
|
|
179
296
|
...preview,
|
|
180
297
|
after: committed.after,
|
|
@@ -307,6 +424,7 @@ export class HeadlessProjectService {
|
|
|
307
424
|
if (!this.renderer || !this.verifier)
|
|
308
425
|
throw new Error("HEADLESS_RENDER_UNAVAILABLE: renderer and verifier are not configured");
|
|
309
426
|
const project = await this.open(projectId);
|
|
427
|
+
await this.assertOutputSeparation(project, [parameters.outputPath]);
|
|
310
428
|
const request = createFramekitRenderRequest({
|
|
311
429
|
timeline: project.timeline,
|
|
312
430
|
target: { projectId, sequenceId },
|
|
@@ -338,9 +456,30 @@ export class HeadlessProjectService {
|
|
|
338
456
|
throw error;
|
|
339
457
|
}
|
|
340
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
|
+
}
|
|
341
465
|
store(projectId) {
|
|
342
466
|
return new FramekitProjectStore(this.projectPath(projectId));
|
|
343
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
|
+
}
|
|
344
483
|
projectPath(projectId) {
|
|
345
484
|
validateProjectId(projectId);
|
|
346
485
|
return join(this.directory, `${projectId}.json`);
|
|
@@ -356,25 +495,19 @@ export class HeadlessProjectService {
|
|
|
356
495
|
async saveRender(record) {
|
|
357
496
|
await mkdir(this.directory, { recursive: true });
|
|
358
497
|
const path = join(this.directory, `${record.renderId}.json`);
|
|
359
|
-
|
|
360
|
-
await writeFile(temporary, `${JSON.stringify(record)}\n`, { encoding: "utf8", flag: "wx" });
|
|
361
|
-
await rename(temporary, path);
|
|
498
|
+
await publishHistory(path, `${JSON.stringify(record)}\n`);
|
|
362
499
|
}
|
|
363
500
|
async saveRoughCutExecution(record) {
|
|
364
501
|
await mkdir(this.directory, { recursive: true });
|
|
365
502
|
const execution = { ...record, evidenceDigest: hash(stableJson(record)) };
|
|
366
503
|
const path = this.executionPath(record.executionId);
|
|
367
|
-
|
|
368
|
-
await writeFile(temporary, `${JSON.stringify(execution)}\n`, { encoding: "utf8", flag: "wx" });
|
|
369
|
-
await rename(temporary, path);
|
|
504
|
+
await publishHistory(path, `${JSON.stringify(execution)}\n`);
|
|
370
505
|
}
|
|
371
506
|
async saveRoughCutApproval(record) {
|
|
372
507
|
await mkdir(this.directory, { recursive: true });
|
|
373
508
|
const approval = { ...record, evidenceDigest: hash(stableJson(record)) };
|
|
374
509
|
const path = this.approvalPath(record.planDigest);
|
|
375
|
-
|
|
376
|
-
await writeFile(temporary, `${JSON.stringify(approval)}\n`, { encoding: "utf8", flag: "wx" });
|
|
377
|
-
await rename(temporary, path);
|
|
510
|
+
await publishHistory(path, `${JSON.stringify(approval)}\n`, true);
|
|
378
511
|
}
|
|
379
512
|
async readRoughCutApproval(planDigest) {
|
|
380
513
|
const approval = JSON.parse(await readFile(this.approvalPath(planDigest), "utf8"));
|
|
@@ -388,14 +521,14 @@ export class HeadlessProjectService {
|
|
|
388
521
|
return approval;
|
|
389
522
|
}
|
|
390
523
|
async prepareRoughCut(request) {
|
|
391
|
-
await this.open(request.projectId);
|
|
392
|
-
const project = await this.store(request.projectId).load();
|
|
524
|
+
const project = await this.open(request.projectId);
|
|
393
525
|
if (project.timeline.sequence.id !== request.sequenceId) {
|
|
394
526
|
throw new Error("HEADLESS_ROUGH_CUT_TARGET_MISMATCH: sequenceId does not match the persisted project");
|
|
395
527
|
}
|
|
396
528
|
if (!sameRevision(project.timeline.revision, request.plan.revision)) {
|
|
397
529
|
throw new Error("HEADLESS_ROUGH_CUT_STALE_REVISION: rough-cut plan revision does not match the persisted project");
|
|
398
530
|
}
|
|
531
|
+
await this.assertOutputSeparation(project, [request.render.outputPath, request.fcpxml.path]);
|
|
399
532
|
if (!request.plan.shots.length)
|
|
400
533
|
throw new Error("HEADLESS_ROUGH_CUT_EMPTY_PLAN: rough-cut plan must contain at least one shot");
|
|
401
534
|
const operations = structuredClone(request.operations ?? []);
|
|
@@ -427,9 +560,11 @@ export class HeadlessProjectService {
|
|
|
427
560
|
if (!resource)
|
|
428
561
|
throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_NOT_FOUND: ${shot.sourceIdentity.mediaId}`);
|
|
429
562
|
assertSourceIdentity(resource, shot.sourceIdentity);
|
|
430
|
-
|
|
431
|
-
const
|
|
432
|
-
assertSourceRange(resource,
|
|
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);
|
|
433
568
|
const appendToPrimaryStoryline = hasPrimaryStoryContent || planOperations.length > 0;
|
|
434
569
|
planOperations.push({
|
|
435
570
|
type: "insert-occurrence",
|
|
@@ -451,7 +586,7 @@ export class HeadlessProjectService {
|
|
|
451
586
|
occurrenceId,
|
|
452
587
|
mediaId: resource.id,
|
|
453
588
|
sourceIdentity: structuredClone(shot.sourceIdentity),
|
|
454
|
-
sourceRange: structuredClone(
|
|
589
|
+
sourceRange: structuredClone(sourceRange),
|
|
455
590
|
confidence: shot.confidence,
|
|
456
591
|
matchedProperties: [...shot.matchedProperties],
|
|
457
592
|
rationale: shot.rationale,
|
|
@@ -465,9 +600,9 @@ export class HeadlessProjectService {
|
|
|
465
600
|
expectedRevision: structuredClone(request.plan.revision),
|
|
466
601
|
operations: editOperations,
|
|
467
602
|
};
|
|
468
|
-
return { command, inputDigest, provenance, outputIntent };
|
|
603
|
+
return { command, inputDigest, provenance, outputIntent, project };
|
|
469
604
|
}
|
|
470
|
-
async previewPreparedRoughCut(request, prepared, timestamp, transaction = new ProjectTransactionService(this.
|
|
605
|
+
async previewPreparedRoughCut(request, prepared, timestamp, transaction = new ProjectTransactionService(this.snapshotStore(request.projectId, prepared.project), { clock: () => timestamp })) {
|
|
471
606
|
const rawPreview = await transaction.preview(prepared.command);
|
|
472
607
|
const canonicalRevision = {
|
|
473
608
|
id: `ir:${timelineIrDigest(rawPreview.after.timeline)}`,
|
|
@@ -484,6 +619,32 @@ export class HeadlessProjectService {
|
|
|
484
619
|
return { preview, fcpxml };
|
|
485
620
|
}
|
|
486
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
|
+
}
|
|
487
648
|
function createRoughCutApproval(fields) {
|
|
488
649
|
const digestFields = { schemaVersion: 1, ...fields };
|
|
489
650
|
const planDigest = hash(stableJson(digestFields));
|
|
@@ -515,19 +676,105 @@ function assertSourceIdentity(resource, source) {
|
|
|
515
676
|
throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_MISMATCH: source duration differs for ${source.mediaId}`);
|
|
516
677
|
}
|
|
517
678
|
}
|
|
518
|
-
function assertSourceRange(resource, range
|
|
679
|
+
function assertSourceRange(resource, range) {
|
|
519
680
|
if (!Number.isFinite(range.start) || !Number.isFinite(range.end) || range.start < 0 || range.end <= range.start) {
|
|
520
681
|
throw new Error("HEADLESS_ROUGH_CUT_RANGE_INVALID: source range must be finite and non-empty");
|
|
521
682
|
}
|
|
522
683
|
if (resource.metadata?.durationTime !== undefined && range.end > rationalSeconds(resource.metadata.durationTime) + 0.001) {
|
|
523
684
|
throw new Error(`HEADLESS_ROUGH_CUT_RANGE_INVALID: source range exceeds ${resource.id}`);
|
|
524
685
|
}
|
|
686
|
+
const sourceStartTime = range.startTime ?? secondsToRational(range.start);
|
|
687
|
+
const durationTime = range.durationTime ?? secondsToRational(range.end - range.start);
|
|
525
688
|
if (rationalSeconds(sourceStartTime) < 0 || rationalSeconds(durationTime) <= 0
|
|
526
689
|
|| Math.abs(rationalSeconds(sourceStartTime) - range.start) > 0.001
|
|
527
690
|
|| Math.abs(rationalSeconds(durationTime) - (range.end - range.start)) > 0.001) {
|
|
528
691
|
throw new Error("HEADLESS_ROUGH_CUT_RANGE_INVALID: rational source range must be non-negative and non-empty");
|
|
529
692
|
}
|
|
530
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
|
+
}
|
|
531
778
|
function secondsToRational(seconds) {
|
|
532
779
|
const timescale = 1_000_000;
|
|
533
780
|
const value = Math.round(seconds * timescale);
|
|
@@ -557,21 +804,107 @@ function selectFcpxmlMetadata(result) {
|
|
|
557
804
|
provenance: structuredClone(result.provenance),
|
|
558
805
|
};
|
|
559
806
|
}
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
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;
|
|
563
839
|
try {
|
|
564
|
-
await
|
|
565
|
-
throw new Error(`HEADLESS_ROUGH_CUT_FCPXML_EXISTS: refusing to overwrite ${path}`);
|
|
840
|
+
canonical = await realpath(path);
|
|
566
841
|
}
|
|
567
842
|
catch (error) {
|
|
568
|
-
if (error.code
|
|
569
|
-
|
|
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");
|
|
570
891
|
}
|
|
571
892
|
}
|
|
893
|
+
}
|
|
894
|
+
async function writeVerifiedFcpxml(path, xml, digest, overwrite) {
|
|
895
|
+
await mkdir(dirname(path), { recursive: true });
|
|
572
896
|
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
573
897
|
await writeFile(temporary, xml, { encoding: "utf8", flag: "wx" });
|
|
574
|
-
|
|
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
|
+
}
|
|
575
908
|
const persisted = await readFile(path, "utf8");
|
|
576
909
|
const persistedDigest = createHash("sha256").update(persisted).digest("hex");
|
|
577
910
|
if (persistedDigest !== digest)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./headless-projects.js";
|
|
@@ -11,6 +11,10 @@ export class ProjectService {
|
|
|
11
11
|
this.options = options;
|
|
12
12
|
}
|
|
13
13
|
async inspectProject() {
|
|
14
|
+
const inspect = () => this.inspectProjectInScope();
|
|
15
|
+
return this.adapter.withCanonicalReadScope?.(inspect) ?? inspect();
|
|
16
|
+
}
|
|
17
|
+
async inspectProjectInScope() {
|
|
14
18
|
const identity = await this.adapter.getIdentity();
|
|
15
19
|
const capabilities = withCanonicalTimelineMode(withCapabilityFamilies(await this.adapter.getCapabilities(), {
|
|
16
20
|
backend: identity.backend,
|
|
@@ -91,7 +95,7 @@ export class ProjectService {
|
|
|
91
95
|
return this.adapter.listProjects();
|
|
92
96
|
}
|
|
93
97
|
async selectProject(selection) {
|
|
94
|
-
const capabilities = await this.adapter.getCapabilities();
|
|
98
|
+
const capabilities = await this.adapter.getCapabilities({ probeCanonicalSnapshot: false });
|
|
95
99
|
if (!capabilities.editor.projectSelection || !this.adapter.selectProject) {
|
|
96
100
|
const identity = await this.adapter.getIdentity();
|
|
97
101
|
throw new CapabilityUnavailableError("project.select", "editor.projectSelection", {
|