@morshoto/framekit 0.1.10 → 0.1.12

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 (31) hide show
  1. package/README.md +1 -0
  2. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +68 -5
  3. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +175 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery.js +31 -0
  5. package/dist-package/adapters/final-cut/typescript/src/canonical-verification.js +16 -0
  6. package/dist-package/adapters/final-cut/typescript/src/canonical.js +600 -56
  7. package/dist-package/adapters/final-cut/typescript/src/connection.js +52 -14
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml-console-experiment.js +74 -0
  9. package/dist-package/adapters/final-cut/typescript/src/index.js +9 -0
  10. package/dist-package/adapters/final-cut/typescript/src/live.js +11 -4
  11. package/dist-package/adapters/final-cut/typescript/src/native.js +321 -19
  12. package/dist-package/adapters/final-cut/typescript/src/session.js +19 -1
  13. package/dist-package/adapters/final-cut/typescript/src/shadow-mutation.js +174 -0
  14. package/dist-package/adapters/final-cut/typescript/src/sqlite-experiment.js +472 -0
  15. package/dist-package/adapters/final-cut/typescript/src/sqlite-inspection.js +433 -0
  16. package/dist-package/adapters/final-cut/typescript/src/sqlite-materialization.js +230 -0
  17. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +372 -0
  18. package/dist-package/adapters/final-cut/typescript/src/unattended-editing.js +66 -0
  19. package/dist-package/apps/mcp-server/src/headless-sessions.js +112 -0
  20. package/dist-package/apps/mcp-server/src/main.js +36 -2
  21. package/dist-package/apps/mcp-server/src/materialization-jobs.js +326 -0
  22. package/dist-package/apps/mcp-server/src/routing.js +17 -0
  23. package/dist-package/apps/mcp-server/src/server.js +146 -12
  24. package/dist-package/packages/runtime/src/application/media-analysis-service.js +52 -6
  25. package/dist-package/packages/runtime/src/context/project-catalog.js +46 -1
  26. package/dist-package/packages/runtime/src/index.js +2 -0
  27. package/dist-package/packages/runtime/src/skills/builtin.js +99 -8
  28. package/dist-package/packages/runtime/src/skills/runtime.js +1 -0
  29. package/dist-package/packages/runtime/src/timeline/drift-reconciliation.js +295 -0
  30. package/dist-package/packages/runtime/src/timeline/editing-session.js +490 -0
  31. package/package.json +10 -6
@@ -0,0 +1,433 @@
1
+ import { createHash } from "node:crypto";
2
+ import { execFile as execFileCallback } from "node:child_process";
3
+ import { readFile } from "node:fs/promises";
4
+ import { basename } from "node:path";
5
+ import { promisify } from "node:util";
6
+ export const FINAL_CUT_SQLITE_INSPECTION_BACKEND = "final-cut-sqlite-read-only";
7
+ export const FINAL_CUT_SQLITE_INSPECTION_TIMEOUT_MS = 30_000;
8
+ const execFile = promisify(execFileCallback);
9
+ export class FinalCutSqliteInspectionProviderError extends Error {
10
+ failure;
11
+ code;
12
+ retryable;
13
+ constructor(failure) {
14
+ super(`${failure.code}: ${failure.message}`);
15
+ this.failure = failure;
16
+ this.name = "FinalCutSqliteInspectionProviderError";
17
+ this.code = failure.code;
18
+ this.retryable = failure.retryable;
19
+ }
20
+ toJSON() {
21
+ return { ...this.failure };
22
+ }
23
+ }
24
+ /**
25
+ * Read-only inspection of Final Cut's Core Data SQLite stores.
26
+ *
27
+ * The provider intentionally returns an observation rather than ProjectSnapshot:
28
+ * the current schema exposes useful object/type/version hints, while the
29
+ * timeline payload lives in undocumented archived BLOBs.
30
+ */
31
+ export class FinalCutSqliteInspectionProvider {
32
+ backend = FINAL_CUT_SQLITE_INSPECTION_BACKEND;
33
+ executor;
34
+ digest;
35
+ timestamp;
36
+ constructor(options = {}) {
37
+ const sqliteCommand = options.sqliteCommand ?? "sqlite3";
38
+ this.executor = options.executor ?? ((databasePath, query, timeoutMs) => executeSqliteInspection(sqliteCommand, databasePath, query, timeoutMs));
39
+ this.digest = options.digest ?? hashSqliteFile;
40
+ this.timestamp = options.timestamp ?? (() => new Date().toISOString());
41
+ }
42
+ async inspect(databasePath) {
43
+ try {
44
+ const [response, digest] = await Promise.all([
45
+ this.executor(databasePath, buildFinalCutSqliteInspectionQuery(), FINAL_CUT_SQLITE_INSPECTION_TIMEOUT_MS),
46
+ this.digest(databasePath),
47
+ ]);
48
+ const parsed = parseFinalCutSqliteInspectionResponse(response);
49
+ if (parsed.status === "error")
50
+ return parsed;
51
+ const sequence = parsed.payload.collectionRows.reduce((maximum, row) => Math.max(maximum, row.optimisticVersion ?? 0), 0);
52
+ const observation = {
53
+ ...parsed.payload,
54
+ backend: this.backend,
55
+ sourcePath: databasePath,
56
+ databaseKind: databaseKindForPath(databasePath),
57
+ digest,
58
+ revision: { id: digest, sequence, timestamp: this.timestamp() },
59
+ canonical: false,
60
+ coverage: coverageFor(parsed.payload),
61
+ };
62
+ return { status: "partial", observation, issues: parsed.issues };
63
+ }
64
+ catch (error) {
65
+ return {
66
+ status: "unavailable",
67
+ error: unavailableError(error),
68
+ };
69
+ }
70
+ }
71
+ async readObservation(databasePath) {
72
+ const result = await this.inspect(databasePath);
73
+ if (result.status === "partial")
74
+ return result.observation;
75
+ throw new FinalCutSqliteInspectionProviderError(result.error);
76
+ }
77
+ }
78
+ /** Build the only SQL sent to a Final Cut store; it is schema/data read-only. */
79
+ export function buildFinalCutSqliteInspectionQuery() {
80
+ return `
81
+ PRAGMA query_only=ON;
82
+ SELECT json_object(
83
+ 'version', 1,
84
+ 'schemaVersion', (SELECT schema_version FROM pragma_schema_version LIMIT 1),
85
+ 'userVersion', (SELECT user_version FROM pragma_user_version LIMIT 1),
86
+ 'tables', COALESCE((SELECT json_group_array(json_object(
87
+ 'name', name,
88
+ 'sql', sql,
89
+ 'columns', (SELECT COALESCE(json_group_array(json_object(
90
+ 'name', p.name,
91
+ 'type', p.type,
92
+ 'primaryKey', p.pk
93
+ )), json('[]')) FROM pragma_table_info(m.name) AS p)
94
+ )) FROM (SELECT name, sql FROM sqlite_master WHERE type = 'table' ORDER BY name) AS m), json('[]')),
95
+ 'rowCounts', json_object(
96
+ 'ZCATALOGROOT', (SELECT COUNT(*) FROM ZCATALOGROOT),
97
+ 'ZCATALOGROOTMD', (SELECT COUNT(*) FROM ZCATALOGROOTMD),
98
+ 'ZCOLLECTION', (SELECT COUNT(*) FROM ZCOLLECTION),
99
+ 'ZCOLLECTIONMD', (SELECT COUNT(*) FROM ZCOLLECTIONMD),
100
+ 'Z_3CHILDCOLLECTIONS', (SELECT COUNT(*) FROM Z_3CHILDCOLLECTIONS),
101
+ 'Z_METADATA', (SELECT COUNT(*) FROM Z_METADATA),
102
+ 'Z_MODELCACHE', (SELECT COUNT(*) FROM Z_MODELCACHE),
103
+ 'Z_PRIMARYKEY', (SELECT COUNT(*) FROM Z_PRIMARYKEY)
104
+ ),
105
+ 'collectionTypes', COALESCE((SELECT json_group_array(json_object(
106
+ 'type', type,
107
+ 'count', count
108
+ )) FROM (
109
+ SELECT COALESCE(ZTYPE, '') AS type, COUNT(*) AS count
110
+ FROM ZCOLLECTION
111
+ GROUP BY ZTYPE
112
+ ORDER BY type
113
+ )), json('[]')),
114
+ 'collectionRows', COALESCE((SELECT json_group_array(json_object(
115
+ 'primaryKey', Z_PK,
116
+ 'type', ZTYPE,
117
+ 'identifier', ZIDENTIFIER,
118
+ 'optimisticVersion', Z_OPT,
119
+ 'catalogId', ZCATALOG,
120
+ 'metadataId', ZMETADATA
121
+ )) FROM (
122
+ SELECT Z_PK, ZTYPE, ZIDENTIFIER, Z_OPT, ZCATALOG, ZMETADATA
123
+ FROM ZCOLLECTION
124
+ WHERE ZTYPE LIKE 'FFMediaEventProject%'
125
+ OR ZTYPE IN ('FFAnchoredSequence', 'FFAnchoredClip', 'FFAsset', 'FFMediaRep')
126
+ ORDER BY Z_PK
127
+ )), json('[]')),
128
+ 'metadataRows', COALESCE((SELECT json_group_array(json_object(
129
+ 'primaryKey', Z_PK,
130
+ 'collectionId', ZCOLLECTION,
131
+ 'identifier', ZIDENTIFIER,
132
+ 'bytes', length(ZDICTIONARYDATA),
133
+ 'archive', CASE
134
+ WHEN substr(ZDICTIONARYDATA, 1, 8) = x'62706c6973743030' THEN 'NSKeyedArchiver'
135
+ WHEN ZDICTIONARYDATA IS NULL THEN NULL
136
+ ELSE 'opaque'
137
+ END
138
+ )) FROM (
139
+ SELECT Z_PK, ZCOLLECTION, ZIDENTIFIER, ZDICTIONARYDATA
140
+ FROM ZCOLLECTIONMD
141
+ ORDER BY Z_PK
142
+ )), json('[]'))
143
+ ) AS inspection;`;
144
+ }
145
+ export function parseFinalCutSqliteInspectionResponse(input) {
146
+ let payload;
147
+ try {
148
+ payload = typeof input === "string" ? JSON.parse(input) : input;
149
+ }
150
+ catch (error) {
151
+ return invalidResponse(`response was not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
152
+ }
153
+ const record = asRecord(payload);
154
+ if (!record)
155
+ return invalidResponse("response must be an object");
156
+ if (record.version !== 1)
157
+ return invalidResponse("version must be 1");
158
+ const schemaVersion = integerField(record.schemaVersion, "schemaVersion");
159
+ const userVersion = integerField(record.userVersion, "userVersion");
160
+ const tables = parseTables(record.tables);
161
+ const rowCounts = parseNumberMap(record.rowCounts, "rowCounts");
162
+ const collectionTypes = parseCollectionTypes(record.collectionTypes);
163
+ const collectionRows = parseCollectionRows(record.collectionRows);
164
+ const metadataRows = parseMetadataRows(record.metadataRows);
165
+ const firstFailure = [schemaVersion, userVersion]
166
+ .find((value) => isParseFailure(value));
167
+ if (firstFailure || typeof tables === "string" || typeof rowCounts === "string"
168
+ || typeof collectionTypes === "string" || typeof collectionRows === "string" || typeof metadataRows === "string") {
169
+ return invalidResponse(firstFailure?.message
170
+ ?? [tables, rowCounts, collectionTypes, collectionRows, metadataRows]
171
+ .find((value) => typeof value === "string")
172
+ ?? "unknown validation failure");
173
+ }
174
+ return {
175
+ status: "partial",
176
+ payload: {
177
+ version: 1,
178
+ schemaVersion: schemaVersion,
179
+ userVersion: userVersion,
180
+ tables,
181
+ rowCounts,
182
+ collectionTypes,
183
+ collectionRows,
184
+ metadataRows,
185
+ },
186
+ issues: [
187
+ {
188
+ code: "FINAL_CUT_SQLITE_OPAQUE_PAYLOAD",
189
+ message: "ZCOLLECTIONMD.ZDICTIONARYDATA is an undocumented archived payload; timeline fields are not promoted to canonical state",
190
+ path: "ZCOLLECTIONMD.ZDICTIONARYDATA",
191
+ retryable: false,
192
+ },
193
+ {
194
+ code: "FINAL_CUT_SQLITE_REVISION_UNAVAILABLE",
195
+ message: "SQLite digest and Z_OPT provide storage-change evidence, not a target-bound Final Cut editor revision",
196
+ path: "revision",
197
+ retryable: false,
198
+ },
199
+ ],
200
+ };
201
+ }
202
+ export function compareFinalCutSqliteObservations(previous, current) {
203
+ const reasons = [];
204
+ if (previous.digest !== current.digest)
205
+ reasons.push("SQLite file digest changed");
206
+ if (previous.schemaVersion !== current.schemaVersion)
207
+ reasons.push("SQLite schema version changed");
208
+ if (previous.revision.sequence !== current.revision.sequence)
209
+ reasons.push("SQLite object version changed");
210
+ return {
211
+ status: reasons.length > 0 ? "changed" : "unchanged",
212
+ previousDigest: previous.digest,
213
+ currentDigest: current.digest,
214
+ reasons,
215
+ };
216
+ }
217
+ async function executeSqliteInspection(sqliteCommand, databasePath, query, timeoutMs) {
218
+ const result = await execFile(sqliteCommand, ["-readonly", "-batch", "-noheader", databasePath, query], {
219
+ maxBuffer: 8_000_000,
220
+ timeout: timeoutMs,
221
+ });
222
+ return result.stdout.trim();
223
+ }
224
+ async function hashSqliteFile(databasePath) {
225
+ const bytes = await readFile(databasePath);
226
+ return createHash("sha256").update(bytes).digest("hex");
227
+ }
228
+ function databaseKindForPath(databasePath) {
229
+ const fileName = basename(databasePath);
230
+ if (fileName === "CurrentVersion.flexolibrary")
231
+ return "flexolibrary";
232
+ if (fileName === "CurrentVersion.fcpevent")
233
+ return "fcpevent";
234
+ return "unknown";
235
+ }
236
+ function coverageFor(payload) {
237
+ const hasProject = payload.collectionTypes.some(({ type }) => type === "FFMediaEventProject");
238
+ const hasMedia = payload.collectionTypes.some(({ type }) => ["FFAsset", "FFMediaRep"].includes(type));
239
+ return {
240
+ complete: false,
241
+ projectIdentity: hasProject ? "partial" : "unknown",
242
+ sequenceIdentity: "unknown",
243
+ clipOccurrences: "unknown",
244
+ mediaIdentity: hasMedia ? "partial" : "unknown",
245
+ rationalTiming: "unknown",
246
+ roles: "unknown",
247
+ storylineRelationships: "unknown",
248
+ markersCaptions: "unknown",
249
+ revision: "partial",
250
+ };
251
+ }
252
+ function unavailableError(error) {
253
+ const message = error instanceof Error ? error.message : String(error);
254
+ return {
255
+ code: "FINAL_CUT_SQLITE_INSPECTION_UNAVAILABLE",
256
+ message: `Final Cut SQLite inspection is unavailable: ${message}`,
257
+ retryable: /busy|locked|timed out|timeout|temporar/i.test(message),
258
+ };
259
+ }
260
+ function invalidResponse(message) {
261
+ return {
262
+ status: "error",
263
+ error: {
264
+ code: "FINAL_CUT_SQLITE_RESPONSE_INVALID",
265
+ message: `Final Cut SQLite response is invalid: ${message}`,
266
+ retryable: false,
267
+ },
268
+ };
269
+ }
270
+ function parseTables(value) {
271
+ if (!Array.isArray(value))
272
+ return "tables must be an array";
273
+ const result = [];
274
+ for (const [index, item] of value.entries()) {
275
+ const record = asRecord(item);
276
+ if (!record)
277
+ return `tables[${index}] must be an object`;
278
+ const name = textField(record.name, `tables[${index}].name`);
279
+ const sql = textField(record.sql, `tables[${index}].sql`);
280
+ const columns = parseColumns(record.columns, `tables[${index}].columns`);
281
+ if (isParseFailure(name) || isParseFailure(sql) || typeof columns === "string") {
282
+ return isParseFailure(name) ? name.message
283
+ : isParseFailure(sql) ? sql.message : columns;
284
+ }
285
+ result.push({ name, sql, columns });
286
+ }
287
+ return result;
288
+ }
289
+ function parseColumns(value, path) {
290
+ if (!Array.isArray(value))
291
+ return `${path} must be an array`;
292
+ const result = [];
293
+ for (const [index, item] of value.entries()) {
294
+ const record = asRecord(item);
295
+ if (!record)
296
+ return `${path}[${index}] must be an object`;
297
+ const name = textField(record.name, `${path}[${index}].name`);
298
+ const type = textField(record.type, `${path}[${index}].type`);
299
+ const primaryKey = integerField(record.primaryKey, `${path}[${index}].primaryKey`);
300
+ if (isParseFailure(name) || isParseFailure(type) || isParseFailure(primaryKey)) {
301
+ return isParseFailure(name) ? name.message
302
+ : isParseFailure(type) ? type.message : primaryKey.message;
303
+ }
304
+ result.push({ name, type, primaryKey });
305
+ }
306
+ return result;
307
+ }
308
+ function parseNumberMap(value, path) {
309
+ const record = asRecord(value);
310
+ if (!record)
311
+ return `${path} must be an object`;
312
+ const result = {};
313
+ for (const [key, item] of Object.entries(record)) {
314
+ const number = integerField(item, `${path}.${key}`);
315
+ if (isParseFailure(number))
316
+ return number.message;
317
+ result[key] = number;
318
+ }
319
+ return result;
320
+ }
321
+ function parseCollectionTypes(value) {
322
+ if (!Array.isArray(value))
323
+ return "collectionTypes must be an array";
324
+ const result = [];
325
+ for (const [index, item] of value.entries()) {
326
+ const record = asRecord(item);
327
+ if (!record)
328
+ return `collectionTypes[${index}] must be an object`;
329
+ const type = textField(record.type, `collectionTypes[${index}].type`);
330
+ const count = integerField(record.count, `collectionTypes[${index}].count`);
331
+ if (isParseFailure(type) || isParseFailure(count)) {
332
+ return isParseFailure(type) ? type.message : count.message;
333
+ }
334
+ result.push({ type, count });
335
+ }
336
+ return result;
337
+ }
338
+ function parseCollectionRows(value) {
339
+ if (!Array.isArray(value))
340
+ return "collectionRows must be an array";
341
+ const result = [];
342
+ for (const [index, item] of value.entries()) {
343
+ const record = asRecord(item);
344
+ if (!record)
345
+ return `collectionRows[${index}] must be an object`;
346
+ const primaryKey = integerField(record.primaryKey, `collectionRows[${index}].primaryKey`);
347
+ const type = textField(record.type, `collectionRows[${index}].type`);
348
+ if (isParseFailure(primaryKey) || isParseFailure(type)) {
349
+ return isParseFailure(primaryKey) ? primaryKey.message : type.message;
350
+ }
351
+ const identifier = optionalText(record.identifier, `collectionRows[${index}].identifier`);
352
+ const optimisticVersion = optionalNumber(record.optimisticVersion, `collectionRows[${index}].optimisticVersion`);
353
+ const catalogId = optionalNumber(record.catalogId, `collectionRows[${index}].catalogId`);
354
+ const metadataId = optionalNumber(record.metadataId, `collectionRows[${index}].metadataId`);
355
+ if (isParseFailure(identifier))
356
+ return identifier.message;
357
+ if (isParseFailure(optimisticVersion))
358
+ return optimisticVersion.message;
359
+ if (isParseFailure(catalogId))
360
+ return catalogId.message;
361
+ if (isParseFailure(metadataId))
362
+ return metadataId.message;
363
+ result.push({
364
+ primaryKey,
365
+ type,
366
+ ...(typeof identifier === "string" ? { identifier } : {}),
367
+ ...(typeof optimisticVersion === "number" ? { optimisticVersion } : {}),
368
+ ...(typeof catalogId === "number" ? { catalogId } : {}),
369
+ ...(typeof metadataId === "number" ? { metadataId } : {}),
370
+ });
371
+ }
372
+ return result;
373
+ }
374
+ function parseMetadataRows(value) {
375
+ if (!Array.isArray(value))
376
+ return "metadataRows must be an array";
377
+ const result = [];
378
+ for (const [index, item] of value.entries()) {
379
+ const record = asRecord(item);
380
+ if (!record)
381
+ return `metadataRows[${index}] must be an object`;
382
+ const primaryKey = integerField(record.primaryKey, `metadataRows[${index}].primaryKey`);
383
+ const bytes = integerField(record.bytes, `metadataRows[${index}].bytes`);
384
+ if (isParseFailure(primaryKey) || isParseFailure(bytes)) {
385
+ return isParseFailure(primaryKey) ? primaryKey.message : bytes.message;
386
+ }
387
+ const collectionId = optionalNumber(record.collectionId, `metadataRows[${index}].collectionId`);
388
+ const identifier = optionalText(record.identifier, `metadataRows[${index}].identifier`);
389
+ const archive = optionalText(record.archive, `metadataRows[${index}].archive`);
390
+ if (isParseFailure(collectionId))
391
+ return collectionId.message;
392
+ if (isParseFailure(identifier))
393
+ return identifier.message;
394
+ if (isParseFailure(archive))
395
+ return archive.message;
396
+ result.push({
397
+ primaryKey,
398
+ bytes,
399
+ ...(typeof collectionId === "number" ? { collectionId } : {}),
400
+ ...(typeof identifier === "string" ? { identifier } : {}),
401
+ ...(typeof archive === "string" ? { archive } : {}),
402
+ });
403
+ }
404
+ return result;
405
+ }
406
+ function optionalText(value, path) {
407
+ if (value === undefined || value === null)
408
+ return undefined;
409
+ if (typeof value !== "string")
410
+ return failure(`${path} must be a string or null`);
411
+ return value;
412
+ }
413
+ function optionalNumber(value, path) {
414
+ if (value === undefined || value === null)
415
+ return undefined;
416
+ const number = integerField(value, path);
417
+ return isParseFailure(number) ? number : number;
418
+ }
419
+ function textField(value, path) {
420
+ return typeof value === "string" ? value : failure(`${path} must be a string`);
421
+ }
422
+ function integerField(value, path) {
423
+ return typeof value === "number" && Number.isSafeInteger(value) ? value : failure(`${path} must be a safe integer`);
424
+ }
425
+ function failure(message) {
426
+ return { parseFailure: true, message };
427
+ }
428
+ function isParseFailure(value) {
429
+ return Boolean(value && typeof value === "object" && value.parseFailure === true);
430
+ }
431
+ function asRecord(value) {
432
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
433
+ }
@@ -0,0 +1,230 @@
1
+ import { createHash } from "node:crypto";
2
+ import { timelineIrDigest, validateTimelineIr } from "../../../../packages/runtime/src/index.js";
3
+ import { decodeFinalCutKeyedArchive, } from "./sqlite-experiment.js";
4
+ /**
5
+ * Phase 5 gate. This never invents an NSKeyedArchiver encoder: the caller must
6
+ * provide one and the bytes must be exactly identical for this proof to pass.
7
+ */
8
+ export async function proveFinalCutArchiveByteRoundTrip(payload, decoder, encoder) {
9
+ const decoded = await decodeFinalCutKeyedArchive(payload, decoder);
10
+ const encoded = await encoder(decoded);
11
+ if (!Buffer.from(payload).equals(Buffer.from(encoded))) {
12
+ throw new Error("FINAL_CUT_SHADOW_ARCHIVE_ROUND_TRIP_UNPROVEN: decode/encode bytes are not identical");
13
+ }
14
+ return {
15
+ originalDigest: digest(payload),
16
+ encodedDigest: digest(encoded),
17
+ byteIdentical: true,
18
+ };
19
+ }
20
+ /**
21
+ * Phase 6 compiler. IDs are allocated from observed maxima and identifiers are
22
+ * deterministic, content-bound, and collision checked. Existing names are not
23
+ * update targets; every node is an insert into a new versioned graph.
24
+ */
25
+ export async function compileFinalCutVersionedGraphRecipe(request) {
26
+ validateTimelineIr(request.timeline);
27
+ requireText(request.projectUid, "projectUid");
28
+ requireText(request.sequenceUid, "sequenceUid");
29
+ validateAllocation(request.existing);
30
+ const timelineDigest = timelineIrDigest(request.timeline);
31
+ const digestPrefix = timelineDigest.slice(0, 16);
32
+ const usedCollection = new Set(request.existing.existingCollectionPrimaryKeys);
33
+ const usedMetadata = new Set(request.existing.existingMetadataPrimaryKeys);
34
+ const usedCatalog = new Set(request.existing.existingCatalogPrimaryKeys);
35
+ const usedIdentifiers = new Set(request.existing.existingIdentifiers);
36
+ const collectionNext = nextPositive(usedCollection);
37
+ const metadataNext = nextPositive(usedMetadata);
38
+ const catalogNext = nextPositive(usedCatalog);
39
+ let nextCollection = collectionNext;
40
+ let nextMetadata = metadataNext;
41
+ let nextCatalog = catalogNext;
42
+ const entityByType = new Map();
43
+ for (const entry of Object.values(request.existing.primaryKeyMaxByEntity))
44
+ entityByType.set(entry.entity, entry.max);
45
+ const descriptors = [
46
+ { logicalId: `project:${request.timeline.project.id}`, kind: "project", name: versionedName(request.timeline.project.name, digestPrefix) },
47
+ { logicalId: `sequence:${request.timeline.sequence.id}`, kind: "sequence", name: versionedName(request.timeline.sequence.name, digestPrefix) },
48
+ ...request.timeline.resources.map((resource) => ({ logicalId: `resource:${resource.id}`, kind: "resource", name: resource.name })),
49
+ ...request.timeline.sequence.occurrences.map((item) => ({ logicalId: `occurrence:${item.id}`, kind: "occurrence", name: item.name })),
50
+ ...request.timeline.sequence.storyElements.map((item) => ({ logicalId: `story-element:${item.id}`, kind: "story-element", name: item.kind })),
51
+ ...request.timeline.sequence.markers.map((item) => ({ logicalId: `marker:${item.id}`, kind: "marker", name: item.name })),
52
+ ...request.timeline.sequence.captions.map((item) => ({ logicalId: `caption:${item.id}`, kind: "caption", name: item.text })),
53
+ ];
54
+ const nodes = [];
55
+ const nodeByLogicalId = new Map();
56
+ for (const descriptor of descriptors) {
57
+ const entityEntry = entityForKind(descriptor.kind, request.existing.primaryKeyMaxByEntity);
58
+ if (!entityEntry)
59
+ throw new Error(`FINAL_CUT_SHADOW_RECIPE_UNPROVEN: entity allocation is missing for ${descriptor.kind}`);
60
+ const identifier = allocateIdentifier(`framekit-${descriptor.kind}`, descriptor.logicalId, digestPrefix, usedIdentifiers);
61
+ const catalogIdentifier = allocateIdentifier("framekit-catalog", descriptor.logicalId, digestPrefix, usedIdentifiers);
62
+ const node = {
63
+ logicalId: descriptor.logicalId,
64
+ kind: descriptor.kind,
65
+ entity: entityEntry.entity,
66
+ primaryKey: allocateNumber(usedCollection, () => nextCollection++),
67
+ optimisticVersion: 1,
68
+ identifier,
69
+ name: descriptor.name,
70
+ catalogPrimaryKey: allocateNumber(usedCatalog, () => nextCatalog++),
71
+ catalogIdentifier,
72
+ metadataPrimaryKey: allocateNumber(usedMetadata, () => nextMetadata++),
73
+ metadataIdentifier: `${identifier}-metadata`,
74
+ archive: await request.archiveEncoder(descriptor),
75
+ };
76
+ if (!Buffer.from(node.archive).subarray(0, 8).equals(Buffer.from("bplist00", "ascii"))) {
77
+ throw new Error(`FINAL_CUT_SHADOW_ARCHIVE_UNSUPPORTED: encoder returned a non-binary-plist archive for ${descriptor.logicalId}`);
78
+ }
79
+ nodes.push(node);
80
+ nodeByLogicalId.set(descriptor.logicalId, node);
81
+ entityByType.set(node.entity, (entityByType.get(node.entity) ?? entityEntry.max) + 1);
82
+ }
83
+ const edges = [];
84
+ const project = nodeByLogicalId.get(`project:${request.timeline.project.id}`);
85
+ const sequence = nodeByLogicalId.get(`sequence:${request.timeline.sequence.id}`);
86
+ edges.push({ parentPrimaryKey: project.primaryKey, childPrimaryKey: sequence.primaryKey });
87
+ for (const resource of request.timeline.resources)
88
+ edges.push({ parentPrimaryKey: sequence.primaryKey, childPrimaryKey: nodeByLogicalId.get(`resource:${resource.id}`).primaryKey });
89
+ for (const occurrence of request.timeline.sequence.occurrences)
90
+ edges.push({ parentPrimaryKey: sequence.primaryKey, childPrimaryKey: nodeByLogicalId.get(`occurrence:${occurrence.id}`).primaryKey });
91
+ for (const item of request.timeline.sequence.storyElements)
92
+ edges.push({ parentPrimaryKey: sequence.primaryKey, childPrimaryKey: nodeByLogicalId.get(`story-element:${item.id}`).primaryKey });
93
+ for (const marker of request.timeline.sequence.markers)
94
+ edges.push({ parentPrimaryKey: sequence.primaryKey, childPrimaryKey: nodeByLogicalId.get(`marker:${marker.id}`).primaryKey });
95
+ for (const caption of request.timeline.sequence.captions)
96
+ edges.push({ parentPrimaryKey: sequence.primaryKey, childPrimaryKey: nodeByLogicalId.get(`caption:${caption.id}`).primaryKey });
97
+ const primaryKeyUpdates = [...entityByType.entries()].map(([entity, nextMax]) => {
98
+ const original = Object.values(request.existing.primaryKeyMaxByEntity).find((entry) => entry.entity === entity);
99
+ return { entity, expectedMax: original.max, nextMax };
100
+ }).filter((entry) => entry.nextMax > entry.expectedMax).sort((left, right) => left.entity - right.entity);
101
+ return {
102
+ kind: "versioned-project-materialization",
103
+ fingerprint: request.fingerprint,
104
+ timelineDigest,
105
+ projectUid: request.projectUid,
106
+ sequenceUid: request.sequenceUid,
107
+ nodes,
108
+ edges,
109
+ primaryKeyUpdates,
110
+ catalogEntity: request.existing.catalogEntity,
111
+ metadataEntity: request.existing.metadataEntity,
112
+ };
113
+ }
114
+ /** Build the only SQL accepted for a versioned graph recipe. */
115
+ export function buildFinalCutVersionedGraphSql(recipe) {
116
+ if (recipe.kind !== "versioned-project-materialization" || recipe.nodes.length === 0) {
117
+ throw new Error("FINAL_CUT_SHADOW_RECIPE_INVALID: versioned graph is empty or unsupported");
118
+ }
119
+ const statements = ["BEGIN IMMEDIATE;"];
120
+ for (const update of recipe.primaryKeyUpdates) {
121
+ statements.push(`UPDATE Z_PRIMARYKEY SET Z_MAX = ${number(update.nextMax)} WHERE Z_ENT = ${number(update.entity)} AND Z_MAX = ${number(update.expectedMax)}; SELECT changes();`);
122
+ }
123
+ for (const node of recipe.nodes) {
124
+ statements.push(`INSERT INTO ZCATALOGROOT (Z_PK, Z_ENT, Z_OPT, ZIDENTIFIER, ZNAME) VALUES (${number(node.catalogPrimaryKey)}, ${number(recipe.catalogEntity)}, 1, '${sqlText(node.catalogIdentifier)}', '${sqlText(node.name)}');`);
125
+ }
126
+ for (const node of recipe.nodes) {
127
+ statements.push(`INSERT INTO ZCOLLECTION (Z_PK, Z_ENT, Z_OPT, ZCATALOG, ZMETADATA, ZIDENTIFIER, ZNAME, ZTYPE) VALUES (${number(node.primaryKey)}, ${number(node.entity)}, 1, ${number(node.catalogPrimaryKey)}, ${number(node.metadataPrimaryKey)}, '${sqlText(node.identifier)}', '${sqlText(node.name)}', '${sqlText(node.kind)}');`);
128
+ }
129
+ for (const node of recipe.nodes) {
130
+ statements.push(`INSERT INTO ZCOLLECTIONMD (Z_PK, Z_ENT, Z_OPT, ZCOLLECTION, ZIDENTIFIER, ZDICTIONARYDATA) VALUES (${number(node.metadataPrimaryKey)}, ${number(recipe.metadataEntity)}, 1, ${number(node.primaryKey)}, '${sqlText(node.metadataIdentifier)}', x'${hex(node.archive)}');`);
131
+ }
132
+ for (const edge of recipe.edges) {
133
+ statements.push(`INSERT INTO Z_3CHILDCOLLECTIONS (Z_3PARENTCOLLECTIONS, Z_3CHILDCOLLECTIONS) VALUES (${number(edge.parentPrimaryKey)}, ${number(edge.childPrimaryKey)});`);
134
+ }
135
+ statements.push("COMMIT;");
136
+ return { sql: statements.join(" "), expectedCasUpdates: recipe.primaryKeyUpdates.length };
137
+ }
138
+ /**
139
+ * Phase 8 gate. Reopen and export are injected headed operations; a digest or
140
+ * target mismatch can never be reported as native completion.
141
+ */
142
+ export async function verifyFinalCutNativeReopen(target, desired, reopen, exportTarget) {
143
+ try {
144
+ validateTimelineIr(desired);
145
+ requireText(target.projectUid, "target.projectUid");
146
+ requireText(target.sequenceUid, "target.sequenceUid");
147
+ await reopen();
148
+ const readback = await exportTarget(target);
149
+ if (readback.target.projectUid !== target.projectUid || readback.target.sequenceUid !== target.sequenceUid) {
150
+ return { status: "not_completed", reason: "FINAL_CUT_NATIVE_TARGET_MISMATCH" };
151
+ }
152
+ validateTimelineIr(readback.timeline);
153
+ const desiredDigest = timelineIrDigest(desired);
154
+ const readbackDigest = timelineIrDigest(readback.timeline);
155
+ if (desiredDigest !== readbackDigest)
156
+ return { status: "not_completed", reason: "FINAL_CUT_NATIVE_TIMELINE_MISMATCH" };
157
+ return { status: "native_completed", target: structuredClone(target), desiredDigest, readbackDigest };
158
+ }
159
+ catch (error) {
160
+ return { status: "not_completed", reason: error instanceof Error ? error.message : String(error) };
161
+ }
162
+ }
163
+ function validateAllocation(allocation) {
164
+ for (const key of ["existingCollectionPrimaryKeys", "existingMetadataPrimaryKeys", "existingCatalogPrimaryKeys", "existingIdentifiers"]) {
165
+ if (!Array.isArray(allocation[key]))
166
+ throw new Error(`FINAL_CUT_SHADOW_RECIPE_INVALID: ${key} is required`);
167
+ }
168
+ if (!Number.isSafeInteger(allocation.catalogEntity) || !Number.isSafeInteger(allocation.metadataEntity)) {
169
+ throw new Error("FINAL_CUT_SHADOW_RECIPE_INVALID: catalog and metadata entities are required");
170
+ }
171
+ }
172
+ function entityForKind(kind, values) {
173
+ const aliases = {
174
+ project: ["project", "FFMediaEventProject"],
175
+ sequence: ["sequence", "FFAnchoredSequence"],
176
+ resource: ["resource", "FFAsset", "FFMediaRep"],
177
+ occurrence: ["occurrence", "FFAnchoredClip"],
178
+ "story-element": ["story-element"],
179
+ marker: ["marker"],
180
+ caption: ["caption"],
181
+ };
182
+ for (const alias of aliases[kind])
183
+ if (values[alias])
184
+ return values[alias];
185
+ return undefined;
186
+ }
187
+ function allocateIdentifier(prefix, logicalId, digestPrefix, used) {
188
+ const base = `${prefix}-${shortHash(`${logicalId}:${digestPrefix}`)}`;
189
+ let value = base;
190
+ let suffix = 2;
191
+ while (used.has(value))
192
+ value = `${base}-${suffix++}`;
193
+ used.add(value);
194
+ return value;
195
+ }
196
+ function allocateNumber(used, next) {
197
+ let value = next();
198
+ while (used.has(value))
199
+ value = next();
200
+ used.add(value);
201
+ return value;
202
+ }
203
+ function nextPositive(values) {
204
+ return Math.max(0, ...values) + 1;
205
+ }
206
+ function versionedName(name, digestPrefix) {
207
+ return `${name} (Framekit ${digestPrefix})`;
208
+ }
209
+ function requireText(value, label) {
210
+ if (typeof value !== "string" || value.length === 0 || value.includes("\0"))
211
+ throw new Error(`FINAL_CUT_SHADOW_RECIPE_INVALID: ${label} must be non-empty text`);
212
+ }
213
+ function number(value) {
214
+ if (!Number.isSafeInteger(value) || value < 0)
215
+ throw new Error("FINAL_CUT_SHADOW_RECIPE_INVALID: numeric field is unsafe");
216
+ return String(value);
217
+ }
218
+ function sqlText(value) {
219
+ requireText(value, "SQL text");
220
+ return value.replaceAll("'", "''");
221
+ }
222
+ function hex(value) {
223
+ return Buffer.from(value).toString("hex");
224
+ }
225
+ function digest(value) {
226
+ return createHash("sha256").update(value).digest("hex");
227
+ }
228
+ function shortHash(value) {
229
+ return createHash("sha256").update(value).digest("hex").slice(0, 16);
230
+ }