@morshoto/framekit 0.1.11 → 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.
@@ -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
+ }
@@ -85,6 +85,7 @@ const nativeEditor = liveMode
85
85
  const canonicalNativeMutationEditor = canonicalNativeProviderEnabled
86
86
  ? new FinalCutNativeAutomationAdapter({
87
87
  enabled: true,
88
+ liveState: () => liveAdapter.readLiveState(),
88
89
  nativeOperationLease,
89
90
  })
90
91
  : nativeEditor;
@@ -96,6 +97,23 @@ const canonicalNativeProvider = canonicalNativeProviderEnabled
96
97
  const result = await canonicalNativeMutationEditor.edit({ type: "rename-selected-clip", name });
97
98
  return { operationId: result.operationId, undoAvailable: result.undoAvailable };
98
99
  },
100
+ trimSelectedClipToRange: async (range) => {
101
+ const result = await canonicalNativeMutationEditor.trimSelectedClipToRange(range);
102
+ return { operationId: result.operationId, undoAvailable: result.undoAvailable };
103
+ },
104
+ addMarkerAtTime: async (marker) => {
105
+ const result = await canonicalNativeMutationEditor.addMarkerAtTime(marker);
106
+ return { operationId: result.operationId, undoAvailable: result.undoAvailable };
107
+ },
108
+ rippleDeleteRange: async (range) => {
109
+ const preview = await canonicalNativeMutationEditor.previewDeleteRange(range);
110
+ const result = await canonicalNativeMutationEditor.executeDeleteRange(preview.previewToken);
111
+ return { operationId: result.operationId, undoAvailable: result.undoAvailable };
112
+ },
113
+ setSelectedClipGain: async (gainDb) => {
114
+ const result = await canonicalNativeMutationEditor.edit({ type: "set-selected-clip-gain", gainDb });
115
+ return { operationId: result.operationId, undoAvailable: result.undoAvailable };
116
+ },
99
117
  undo: async (operationId) => {
100
118
  const result = await canonicalNativeMutationEditor.undo(operationId);
101
119
  return { undone: result.undone, verification: result.verification };
@@ -133,6 +151,8 @@ const editor = liveMode
133
151
  const analyzers = liveMode
134
152
  ? createCommandAnalyzers({
135
153
  speechCommand: process.env.FRAMEKIT_SPEECH_ANALYZER,
154
+ speechProviderVersion: process.env.FRAMEKIT_SPEECH_ANALYZER_VERSION,
155
+ speechRequireVad: process.env.FRAMEKIT_SPEECH_REQUIRE_VAD === "1",
136
156
  audioCommand: process.env.FRAMEKIT_AUDIO_ANALYZER,
137
157
  visualCommand: process.env.FRAMEKIT_VISUAL_ANALYZER,
138
158
  metadataCommand: process.env.FRAMEKIT_METADATA_ANALYZER,
@@ -99,6 +99,7 @@ export function resolveEditingRoute(request, context) {
99
99
  const missingRequirements = requirements.filter((requirement) => !requirement.satisfied(context));
100
100
  const missingCapabilities = missingRequirements.map((requirement) => requirement.label);
101
101
  const editor = context.editor?.identity;
102
+ const readiness = routingReadiness(context);
102
103
  const workflow = request.operation === "artifact.edit"
103
104
  ? BACKGROUND_ARTIFACT_WORKFLOW
104
105
  : request.operation === "project.list"
@@ -113,6 +114,7 @@ export function resolveEditingRoute(request, context) {
113
114
  requiredCapabilities,
114
115
  missingCapabilities,
115
116
  ...(editor ? { editor } : {}),
117
+ ...(readiness ? { readiness } : {}),
116
118
  workflow: [...workflow],
117
119
  reason: {
118
120
  code: "EXTERNAL_FALLBACK_SELECTED",
@@ -133,6 +135,7 @@ export function resolveEditingRoute(request, context) {
133
135
  requiredCapabilities,
134
136
  missingCapabilities,
135
137
  ...(editor ? { editor } : {}),
138
+ ...(readiness ? { readiness } : {}),
136
139
  workflow: [...workflow],
137
140
  reason: editorUnavailableReason(context, missingRequirements),
138
141
  };
@@ -145,6 +148,7 @@ export function resolveEditingRoute(request, context) {
145
148
  requiredCapabilities,
146
149
  missingCapabilities,
147
150
  ...(editor ? { editor } : {}),
151
+ ...(readiness ? { readiness } : {}),
148
152
  workflow: [...workflow],
149
153
  reason: capabilityUnavailableReason(context, missingRequirements, request.operation),
150
154
  };
@@ -157,6 +161,7 @@ export function resolveEditingRoute(request, context) {
157
161
  requiredCapabilities,
158
162
  missingCapabilities: [],
159
163
  ...(provider ? { provider } : {}),
164
+ ...(readiness ? { readiness } : {}),
160
165
  editor,
161
166
  workflow: [...workflow],
162
167
  reason: {
@@ -166,6 +171,18 @@ export function resolveEditingRoute(request, context) {
166
171
  },
167
172
  };
168
173
  }
174
+ function routingReadiness(context) {
175
+ const readiness = context.nativeReadiness;
176
+ if (!readiness)
177
+ return undefined;
178
+ return {
179
+ state: readiness.state,
180
+ nextAction: readiness.nextAction,
181
+ retryable: readiness.retryable,
182
+ ...(readiness.firstMissing ? { firstMissing: readiness.firstMissing } : {}),
183
+ guidance: readiness.guidance,
184
+ };
185
+ }
169
186
  function canonicalRequirement() {
170
187
  return {
171
188
  name: "canonicalDocument.read",
@@ -3,7 +3,7 @@ import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
3
3
  import { resolve as resolvePath } from "node:path";
4
4
  import { z } from "zod";
5
5
  import { createCapabilityPreflight, resolveEditingIntent, serializeCapabilityUnavailableError, withCanonicalTimelineMode, withCapabilityFamilies, } from "../../../packages/runtime/src/index.js";
6
- import { NATIVE_MEDIA_IMPORT_DIRECTORY_ERROR_CODE, serializeFinalCutLibraryInspectionError, serializeNativeFinalCutMediaImportError, } from "../../../adapters/final-cut/typescript/src/index.js";
6
+ import { NATIVE_MEDIA_IMPORT_DIRECTORY_ERROR_CODE, serializeFinalCutLibraryInspectionError, serializeNativeFinalCutMediaImportError, serializeNativeFinalCutPartialMutationError, } from "../../../adapters/final-cut/typescript/src/index.js";
7
7
  import { BACKGROUND_ARTIFACT_WORKFLOW, EDITOR_FIRST_MCP_INSTRUCTIONS, resolveEditingRoute, } from "./routing.js";
8
8
  import { FRAMEKIT_BUILD_FINGERPRINT, FRAMEKIT_VERSION, } from "./version.js";
9
9
  import { EditingSessionRepository } from "./headless-sessions.js";
@@ -702,6 +702,20 @@ function nativeMediaImportErrorResult(error) {
702
702
  }],
703
703
  };
704
704
  }
705
+ async function nativeMutationResult(action) {
706
+ try {
707
+ return jsonResult(await action());
708
+ }
709
+ catch (error) {
710
+ const serialized = serializeNativeFinalCutPartialMutationError(error);
711
+ if (!serialized)
712
+ throw error;
713
+ return {
714
+ isError: true,
715
+ content: [{ type: "text", text: JSON.stringify(serialized) }],
716
+ };
717
+ }
718
+ }
705
719
  function capabilityUnavailableErrorResult(error) {
706
720
  const serialized = serializeCapabilityUnavailableError(error);
707
721
  if (!serialized)
@@ -1110,7 +1124,7 @@ export function createMcpServer(runtime, options = {}) {
1110
1124
  if (!options.nativeEditor)
1111
1125
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native writes are not configured");
1112
1126
  const operation = nativeEditSchema.parse(input);
1113
- return jsonResult(await options.nativeEditor.edit(operation, { signal: extra.signal }));
1127
+ return nativeMutationResult(() => options.nativeEditor.edit(operation, { signal: extra.signal }));
1114
1128
  });
1115
1129
  server.registerTool("editor.native.disposable.preview", {
1116
1130
  description: "Preview a disposable native Final Cut rename after canonical target, revision, and native preflight checks.",
@@ -1183,7 +1197,7 @@ export function createMcpServer(runtime, options = {}) {
1183
1197
  }, async ({ previewToken }, extra) => {
1184
1198
  if (!options.nativeEditor)
1185
1199
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native title placement is not configured");
1186
- return jsonResult(await options.nativeEditor.executeTitleAdd(previewToken, { signal: extra.signal }));
1200
+ return nativeMutationResult(() => options.nativeEditor.executeTitleAdd(previewToken, { signal: extra.signal }));
1187
1201
  });
1188
1202
  server.registerTool("editor.native.picture-in-picture.preview", {
1189
1203
  description: "Preview connecting selected Final Cut Browser video to a stable timeline occurrence with verified transform properties.",
@@ -1201,7 +1215,7 @@ export function createMcpServer(runtime, options = {}) {
1201
1215
  if (!options.nativeEditor)
1202
1216
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native picture-in-picture placement is not configured");
1203
1217
  await requireEditingRoute(runtime, options, "editor.native.picture-in-picture");
1204
- return jsonResult(await options.nativeEditor.executePictureInPicture(previewToken, { signal: extra.signal }));
1218
+ return nativeMutationResult(() => options.nativeEditor.executePictureInPicture(previewToken, { signal: extra.signal }));
1205
1219
  });
1206
1220
  server.registerTool("editor.native.transition.search", {
1207
1221
  description: "Search the visible Final Cut Transitions browser and return only transitions with stable native identities.",
@@ -1236,7 +1250,7 @@ export function createMcpServer(runtime, options = {}) {
1236
1250
  }, async ({ previewToken }, extra) => {
1237
1251
  if (!options.nativeEditor)
1238
1252
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native transition placement is not configured");
1239
- return jsonResult(await options.nativeEditor.executeTransitionAdd(previewToken, { signal: extra.signal }));
1253
+ return nativeMutationResult(() => options.nativeEditor.executeTransitionAdd(previewToken, { signal: extra.signal }));
1240
1254
  });
1241
1255
  server.registerTool("editor.native.mask.preview", {
1242
1256
  description: "Preview adding a bounded native Final Cut Draw Mask to one located occurrence without mutating the timeline.",
@@ -1252,7 +1266,7 @@ export function createMcpServer(runtime, options = {}) {
1252
1266
  }, async ({ previewToken }, extra) => {
1253
1267
  if (!options.nativeEditor)
1254
1268
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native masking is not configured");
1255
- return jsonResult(await options.nativeEditor.executeMask(previewToken, { signal: extra.signal }));
1269
+ return nativeMutationResult(() => options.nativeEditor.executeMask(previewToken, { signal: extra.signal }));
1256
1270
  });
1257
1271
  server.registerTool("editor.native.undo", {
1258
1272
  description: "Undo a previously accepted native Final Cut UI edit using Final Cut's native Undo command.",
@@ -1292,7 +1306,7 @@ export function createMcpServer(runtime, options = {}) {
1292
1306
  }, async ({ previewToken }, extra) => {
1293
1307
  if (!options.nativeEditor)
1294
1308
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native media append is not configured");
1295
- return jsonResult(await options.nativeEditor.executeAppendMedia(previewToken, { signal: extra.signal }));
1309
+ return nativeMutationResult(() => options.nativeEditor.executeAppendMedia(previewToken, { signal: extra.signal }));
1296
1310
  });
1297
1311
  server.registerTool("editor.native.media.append.selected.preview", {
1298
1312
  description: "Preview appending the currently selected Final Cut Browser media to the end of the active timeline.",
@@ -1308,7 +1322,7 @@ export function createMcpServer(runtime, options = {}) {
1308
1322
  }, async ({ previewToken }, extra) => {
1309
1323
  if (!options.nativeEditor)
1310
1324
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native selected-media append is not configured");
1311
- return jsonResult(await options.nativeEditor.executeAppendSelectedMedia(previewToken, { signal: extra.signal }));
1325
+ return nativeMutationResult(() => options.nativeEditor.executeAppendSelectedMedia(previewToken, { signal: extra.signal }));
1312
1326
  });
1313
1327
  server.registerTool("editor.native.media.insert.preview", {
1314
1328
  description: "Preview inserting the selected Final Cut Browser media at the current playhead.",
@@ -1324,7 +1338,7 @@ export function createMcpServer(runtime, options = {}) {
1324
1338
  }, async ({ previewToken }, extra) => {
1325
1339
  if (!options.nativeEditor)
1326
1340
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native media insert is not configured");
1327
- return jsonResult(await options.nativeEditor.executeInsertMedia(previewToken, { signal: extra.signal }));
1341
+ return nativeMutationResult(() => options.nativeEditor.executeInsertMedia(previewToken, { signal: extra.signal }));
1328
1342
  });
1329
1343
  server.registerTool("editor.native.timeline.locate", {
1330
1344
  description: "Locate matching occurrences of a live Browser media result in the active Final Cut timeline.",
@@ -1356,7 +1370,7 @@ export function createMcpServer(runtime, options = {}) {
1356
1370
  }, async ({ previewToken }, extra) => {
1357
1371
  if (!options.nativeEditor)
1358
1372
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native Blade is not configured");
1359
- return jsonResult(await options.nativeEditor.executeBlade(previewToken, { signal: extra.signal }));
1373
+ return nativeMutationResult(() => options.nativeEditor.executeBlade(previewToken, { signal: extra.signal }));
1360
1374
  });
1361
1375
  server.registerTool("editor.native.delete-range.preview", {
1362
1376
  description: "Preview a destructive ripple-delete of an explicit rational time range from the Final Cut primary storyline.",
@@ -1372,7 +1386,7 @@ export function createMcpServer(runtime, options = {}) {
1372
1386
  }, async ({ previewToken }, extra) => {
1373
1387
  if (!options.nativeEditor)
1374
1388
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native range deletion is not configured");
1375
- return jsonResult(await options.nativeEditor.executeDeleteRange(previewToken, { signal: extra.signal }));
1389
+ return nativeMutationResult(() => options.nativeEditor.executeDeleteRange(previewToken, { signal: extra.signal }));
1376
1390
  });
1377
1391
  server.registerTool("editor.native.trim-to-duration.preview", {
1378
1392
  description: "Preview a destructive operation that preserves the beginning of the Final Cut sequence and removes everything after the requested rational duration.",
@@ -1388,7 +1402,7 @@ export function createMcpServer(runtime, options = {}) {
1388
1402
  }, async ({ previewToken }, extra) => {
1389
1403
  if (!options.nativeEditor)
1390
1404
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native duration trimming is not configured");
1391
- return jsonResult(await options.nativeEditor.executeTrimToDuration(previewToken, { signal: extra.signal }));
1405
+ return nativeMutationResult(() => options.nativeEditor.executeTrimToDuration(previewToken, { signal: extra.signal }));
1392
1406
  });
1393
1407
  server.registerTool("artifact.publish.preview", {
1394
1408
  description: "Prepare a headed-only publish handoff for a verified FCPXML artifact without opening Final Cut.",
@@ -2115,6 +2129,15 @@ async function requireEditingRoute(runtime, options, operation) {
2115
2129
  }
2116
2130
  async function editingRouteContext(runtime, options) {
2117
2131
  const connection = await effectiveConnectionStatus(runtime, options);
2132
+ let nativeReadiness;
2133
+ if (options.nativeEditor && typeof options.nativeEditor.inspect === "function") {
2134
+ try {
2135
+ nativeReadiness = (await options.nativeEditor.inspect()).readiness;
2136
+ }
2137
+ catch {
2138
+ nativeReadiness = undefined;
2139
+ }
2140
+ }
2118
2141
  let editor;
2119
2142
  try {
2120
2143
  editor = await inspectMcpEditor(runtime, options);
@@ -2126,5 +2149,6 @@ async function editingRouteContext(runtime, options) {
2126
2149
  connection,
2127
2150
  ...(editor ? { editor } : {}),
2128
2151
  ...(options.nativeEditor ? { native: { ...options.nativeEditor.capabilities() } } : {}),
2152
+ ...(nativeReadiness ? { nativeReadiness } : {}),
2129
2153
  };
2130
2154
  }
@@ -1,3 +1,4 @@
1
+ import { sameMediaSourceIdentity } from "../domain/media.js";
1
2
  import { planRoughCut } from "../planning/rough-cut.js";
2
3
  import { bindSpeechAnalysis } from "../speech/analysis.js";
3
4
  import { parseRational } from "../timeline/rational-time.js";
@@ -45,7 +46,22 @@ export class MediaAnalysisService {
45
46
  const sourceStart = clip.sourceStart ?? 0;
46
47
  const requestedRange = { start: sourceStart, end: sourceStart + clip.duration };
47
48
  const analysis = await this.options.audioAnalyzer.analyze({ project, media }, requestedRange);
48
- const analyzedDurationSeconds = analysis.analyzedDurationSeconds ?? clip.duration;
49
+ validateAudioProvenance(analysis, {
50
+ media,
51
+ mediaId,
52
+ project,
53
+ provider: this.options.audioAnalyzer.descriptor,
54
+ requestedRange,
55
+ });
56
+ const measuredRange = analysis.measuredRange ?? {
57
+ start: requestedRange.start,
58
+ end: requestedRange.start + (analysis.analyzedDurationSeconds ?? clip.duration),
59
+ };
60
+ validateAudioRange(measuredRange, requestedRange, "measured audio range");
61
+ const analyzedDurationSeconds = analysis.analyzedDurationSeconds ?? measuredRange.end - measuredRange.start;
62
+ if (Math.abs(analyzedDurationSeconds - (measuredRange.end - measuredRange.start)) > 0.000001) {
63
+ throw new Error("ANALYSIS_INVALID: audio measured duration does not match its measured range");
64
+ }
49
65
  const valid = analysis.valid !== false
50
66
  && Number.isFinite(analysis.integratedLufs)
51
67
  && Number.isFinite(analysis.truePeakDb)
@@ -56,12 +72,9 @@ export class MediaAnalysisService {
56
72
  mediaId,
57
73
  occurrenceId,
58
74
  requestedRange,
59
- measuredRange: {
60
- start: 0,
61
- end: Number.isFinite(analyzedDurationSeconds) ? analyzedDurationSeconds : clip.duration,
62
- },
75
+ measuredRange,
63
76
  revision: project.revision,
64
- provider: this.options.audioAnalyzer.descriptor ?? { id: "framekit.audio", provider: "unknown" },
77
+ provider: analysis.provider ?? this.options.audioAnalyzer.descriptor ?? { id: "framekit.audio", provider: "unknown" },
65
78
  dialoguePresent: analysis.dialoguePresent
66
79
  ?? Boolean(media.speech?.words.some((word) => word.filler !== true)),
67
80
  integratedLufs: analysis.integratedLufs,
@@ -470,3 +483,36 @@ function findMedia(project, mediaId) {
470
483
  throw new Error(`MEDIA_NOT_FOUND: ${mediaId}`);
471
484
  return media;
472
485
  }
486
+ function validateAudioProvenance(analysis, expected) {
487
+ if (analysis.schemaVersion !== undefined && analysis.schemaVersion !== 1) {
488
+ throw new Error("ANALYSIS_INVALID: unsupported audio analysis schema version");
489
+ }
490
+ if (analysis.mediaId !== undefined && analysis.mediaId !== expected.mediaId) {
491
+ throw new Error("TARGET_MISMATCH: audio analysis media identity does not match the requested media");
492
+ }
493
+ if (analysis.sourceIdentity !== undefined
494
+ && !sameMediaSourceIdentity(analysis.sourceIdentity, sourceIdentityOf(expected.media))) {
495
+ throw new Error("TARGET_MISMATCH: audio analysis source identity does not match the requested media");
496
+ }
497
+ if (analysis.requestedRange !== undefined && !sameRange(analysis.requestedRange, expected.requestedRange)) {
498
+ throw new Error("ANALYSIS_INVALID: audio requested range does not match the runtime request");
499
+ }
500
+ if (analysis.revision !== undefined
501
+ && (analysis.revision.id !== expected.project.revision.id || analysis.revision.sequence !== expected.project.revision.sequence)) {
502
+ throw new Error("ANALYSIS_STALE: audio analysis revision does not match the inspected project");
503
+ }
504
+ if (analysis.provider !== undefined && expected.provider !== undefined
505
+ && !sameDescriptor(analysis.provider, expected.provider)) {
506
+ throw new Error("ANALYSIS_INVALID: audio provider identity does not match the configured analyzer");
507
+ }
508
+ }
509
+ function validateAudioRange(range, requested, label) {
510
+ if (!Number.isFinite(range.start) || !Number.isFinite(range.end)
511
+ || range.start < requested.start || range.end > requested.end || range.end <= range.start) {
512
+ throw new Error(`ANALYSIS_INVALID: ${label} must fit inside the requested occurrence range`);
513
+ }
514
+ }
515
+ function sameRange(left, right) {
516
+ return Math.abs(left.start - right.start) <= 0.000001
517
+ && Math.abs(left.end - right.end) <= 0.000001;
518
+ }
@@ -17,11 +17,21 @@ export function reconcileProjectCatalog(catalog, options) {
17
17
  const sequence = state?.sequence && projectDescriptor
18
18
  ? matchIdentity(projectDescriptor.sequences, state.sequence.id, state.sequence.name, (candidate) => candidate.id, (candidate) => candidate.name)
19
19
  : unresolvedIdentity(state?.sequence?.id);
20
+ const diagnostics = [
21
+ identityDiagnostic("project", project, state?.project?.name),
22
+ ...(state?.sequence && projectDescriptor
23
+ ? [identityDiagnostic("sequence", sequence, state.sequence.name)]
24
+ : []),
25
+ ].filter((diagnostic) => diagnostic !== undefined);
20
26
  let status = project.method === "stable-id"
21
27
  && sequence.method === "stable-id"
22
28
  ? "matched"
23
29
  : "unresolved";
24
- let reason = status === "unresolved" ? "stable project and sequence IDs could not be reconciled" : undefined;
30
+ let reason = diagnostics.length > 0
31
+ ? diagnostics.map(formatDiagnostic).join("; ")
32
+ : status === "unresolved"
33
+ ? "stable project and sequence IDs could not be reconciled"
34
+ : undefined;
25
35
  if (status === "matched"
26
36
  && ((catalog.activeProjectId !== undefined && catalog.activeProjectId !== project.catalogId)
27
37
  || (catalog.activeSequenceId !== undefined && catalog.activeSequenceId !== sequence.catalogId))) {
@@ -61,6 +71,7 @@ export function reconcileProjectCatalog(catalog, options) {
61
71
  sequence,
62
72
  ...(beforeRevision ? { beforeRevision: { ...beforeRevision } } : {}),
63
73
  ...(afterRevision ? { afterRevision: { ...afterRevision } } : {}),
74
+ ...(diagnostics.length > 0 ? { diagnostics } : {}),
64
75
  ...(reason ? { reason } : {}),
65
76
  },
66
77
  selection: { ...options.provenance.selection },
@@ -74,6 +85,13 @@ function matchIdentity(values, liveId, liveName, id, name) {
74
85
  const named = values.filter((value) => name(value) === liveName);
75
86
  if (named.length === 1)
76
87
  return { method: "name-only", catalogId: id(named[0]), liveId };
88
+ if (named.length > 1) {
89
+ return {
90
+ method: "ambiguous-name",
91
+ liveId,
92
+ candidateCatalogIds: named.map((value) => id(value)),
93
+ };
94
+ }
77
95
  return unresolvedIdentity(liveId);
78
96
  }
79
97
  function unresolvedIdentity(liveId) {
@@ -86,6 +104,33 @@ function sameTarget(left, right) {
86
104
  function sameRevision(left, right) {
87
105
  return left.id === right.id && left.sequence === right.sequence;
88
106
  }
107
+ function identityDiagnostic(scope, match, liveName) {
108
+ if (match.method === "stable-id")
109
+ return undefined;
110
+ const diagnostic = {
111
+ scope,
112
+ code: match.method === "ambiguous-name"
113
+ ? "ambiguous-name"
114
+ : match.liveId
115
+ ? "stable-id-mismatch"
116
+ : "identity-unresolved",
117
+ ...(match.liveId ? { liveId: match.liveId } : {}),
118
+ ...(liveName ? { liveName } : {}),
119
+ ...(match.catalogId ? { catalogId: match.catalogId } : {}),
120
+ ...(match.candidateCatalogIds ? { candidateCatalogIds: [...match.candidateCatalogIds] } : {}),
121
+ };
122
+ return diagnostic;
123
+ }
124
+ function formatDiagnostic(diagnostic) {
125
+ const label = diagnostic.scope;
126
+ if (diagnostic.code === "ambiguous-name") {
127
+ return `${label} name is ambiguous across catalog IDs ${diagnostic.candidateCatalogIds?.join(", ") ?? "<none>"}`;
128
+ }
129
+ if (diagnostic.code === "stable-id-mismatch") {
130
+ return `${label} stable ID ${diagnostic.liveId ?? "<unavailable>"} did not match catalog ID ${diagnostic.catalogId ?? "<none>"}; name-only evidence is not canonical`;
131
+ }
132
+ return `${label} stable identity is unavailable for reconciliation`;
133
+ }
89
134
  export function validateProjectCatalog(catalog) {
90
135
  if (!Array.isArray(catalog.projects))
91
136
  throw new Error("PROJECT_CATALOG_INVALID: projects must be an array");