@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.
Files changed (51) hide show
  1. package/README.md +17 -12
  2. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +8 -2
  3. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.js +275 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical.js +538 -77
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +6 -1
  6. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +6 -0
  7. package/dist-package/adapters/final-cut/typescript/src/experimental.js +8 -0
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +22 -8
  9. package/dist-package/adapters/final-cut/typescript/src/index.js +1 -7
  10. package/dist-package/adapters/final-cut/typescript/src/live.js +27 -2
  11. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.js +175 -0
  12. package/dist-package/adapters/final-cut/typescript/src/native-session.js +11 -6
  13. package/dist-package/adapters/final-cut/typescript/src/native.js +201 -82
  14. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +1 -0
  15. package/dist-package/adapters/final-cut/typescript/src/publisher.js +255 -14
  16. package/dist-package/adapters/final-cut/typescript/src/session.js +43 -13
  17. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +3 -1
  18. package/dist-package/adapters/headless/typescript/src/audio-output.js +3 -0
  19. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +32 -14
  20. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +9 -4
  21. package/dist-package/apps/cli/src/dev-doctor.js +198 -0
  22. package/dist-package/apps/cli/src/headless-projects.js +5 -0
  23. package/dist-package/apps/cli/src/main.js +42 -0
  24. package/dist-package/apps/mcp-server/runtime/speech-analyzer-wrapper.mjs +54 -0
  25. package/dist-package/apps/mcp-server/runtime/whisper-speech-backend.py +181 -0
  26. package/dist-package/apps/mcp-server/src/build-identity.json +2 -2
  27. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.js +18 -0
  28. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.js +3 -0
  29. package/dist-package/apps/mcp-server/src/main.js +24 -19
  30. package/dist-package/apps/mcp-server/src/materialization-jobs.js +143 -10
  31. package/dist-package/apps/mcp-server/src/routing.js +2 -0
  32. package/dist-package/apps/mcp-server/src/server.js +737 -152
  33. package/dist-package/apps/mcp-server/src/tools/skills/catalog.js +142 -0
  34. package/dist-package/apps/mcp-server/src/tools/skills/metadata.js +71 -0
  35. package/dist-package/apps/mcp-server/src/tools/skills/register.js +101 -0
  36. package/dist-package/{apps/mcp-server → packages/headless-application}/src/headless-projects.js +391 -58
  37. package/dist-package/packages/headless-application/src/index.js +1 -0
  38. package/dist-package/packages/runtime/src/application/project-service.js +5 -1
  39. package/dist-package/packages/runtime/src/application/project-store.js +13 -36
  40. package/dist-package/packages/runtime/src/application/transaction-store.js +1 -1
  41. package/dist-package/packages/runtime/src/capabilities.js +1 -1
  42. package/dist-package/packages/runtime/src/context/context-engine.js +22 -16
  43. package/dist-package/packages/runtime/src/context/context-service.js +2 -2
  44. package/dist-package/packages/runtime/src/editing/edit-service.js +76 -10
  45. package/dist-package/packages/runtime/src/index.js +1 -0
  46. package/dist-package/packages/runtime/src/runtime.js +16 -7
  47. package/dist-package/packages/runtime/src/timeline/editing-session.js +16 -0
  48. package/dist-package/packages/testkit/src/in-memory-editor.js +3 -3
  49. package/dist-package/packages/testkit/src/index.js +1 -0
  50. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.js +192 -0
  51. package/package.json +32 -10
@@ -1,9 +1,12 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
3
- import { resolve as resolvePath } from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { closeSync, constants, fstatSync, openSync, readFileSync } from "node:fs";
5
+ import { types as utilTypes } from "node:util";
6
+ import { isAbsolute, resolve as resolvePath } from "node:path";
4
7
  import { z } from "zod/v3";
5
- import { createCapabilityPreflight, resolveEditingIntent, serializeCapabilityUnavailableError, withCanonicalTimelineMode, withCapabilityFamilies, createTimelineIrFromProjectSnapshot, } from "../../../packages/runtime/src/index.js";
6
- import { NATIVE_MEDIA_IMPORT_DIRECTORY_ERROR_CODE, serializeFinalCutLibraryInspectionError, serializeNativeFinalCutMediaImportError, serializeNativeFinalCutPartialMutationError, } from "../../../adapters/final-cut/typescript/src/index.js";
8
+ import { canonicalSnapshotDigest, createCapabilityPreflight, resolveEditingIntent, serializeCapabilityUnavailableError, withCanonicalTimelineMode, withCapabilityFamilies, createTimelineIrFromProjectSnapshot, } from "../../../packages/runtime/src/index.js";
9
+ import { NATIVE_MEDIA_IMPORT_DIRECTORY_ERROR_CODE, serializeFinalCutLibraryInspectionError, serializeNativeFinalCutMediaImportError, nativeMediaSearchQueryError, FinalCutProjectPublisher, FinalCutNativeAutomationAdapter, disabledNativeFocusContext, serializeNativeFinalCutPartialMutationError, } from "../../../adapters/final-cut/typescript/src/index.js";
7
10
  import { BACKGROUND_ARTIFACT_WORKFLOW, EDITING_ROUTE_EDIT_TYPES, EDITOR_FIRST_MCP_INSTRUCTIONS, HEADLESS_TIMELINE_EDIT_TYPES, HEADLESS_FIRST_MCP_INSTRUCTIONS, resolveEditingRoute, } from "./routing.js";
8
11
  import { assessBuildAlignment } from "./build-alignment.js";
9
12
  import { FRAMEKIT_BUILD_FINGERPRINT, FRAMEKIT_VERSION, } from "./version.js";
@@ -11,6 +14,16 @@ import { EditingSessionRepository } from "./headless-sessions.js";
11
14
  import { SessionMaterializationJobs, } from "./materialization-jobs.js";
12
15
  import { projectSnapshotFromTimelineIr } from "./headless-project-snapshot.js";
13
16
  import { chooseTimelineReadback } from "./readback-policy.js";
17
+ import { registerSkillTools, skillPreviewResult } from "./tools/skills/register.js";
18
+ const builtInPublishExecute = FinalCutProjectPublisher.prototype.executePublishJob;
19
+ const builtInPublishGetJob = FinalCutProjectPublisher.prototype.getPublishJob;
20
+ const builtInPublishTrack = FinalCutProjectPublisher.prototype.trackNativeDispatch;
21
+ const builtInPublishPersist = Reflect.get(FinalCutProjectPublisher.prototype, "persistPublishJob");
22
+ const builtInNativeMethods = new Map(Reflect.ownKeys(FinalCutNativeAutomationAdapter.prototype)
23
+ .map((key) => [key, Object.getOwnPropertyDescriptor(FinalCutNativeAutomationAdapter.prototype, key)?.value]));
24
+ const builtInMapGet = Map.prototype.get;
25
+ const builtInMapSet = Map.prototype.set;
26
+ const builtInMapHas = Map.prototype.has;
14
27
  const revisionValueSchema = z.object({
15
28
  id: z.string(),
16
29
  sequence: z.number().int().nonnegative(),
@@ -25,6 +38,8 @@ const timelineReadbackSchema = z.object({
25
38
  sessionId: z.string().min(1).optional(),
26
39
  requestedCanonical: z.boolean().optional().default(false),
27
40
  finalVerification: z.boolean().optional().default(false),
41
+ confirmHeadedRead: z.boolean().optional(),
42
+ expectedTarget: contextTargetSchema.optional(),
28
43
  }).strict();
29
44
  const contextCursorSchema = z.object({
30
45
  revision: revisionValueSchema,
@@ -55,6 +70,8 @@ const mediaIndexQuerySchema = z.object({
55
70
  const timelineSemanticContextQuerySchema = z.object({
56
71
  query: z.string().optional(),
57
72
  occurrenceIds: z.array(z.string().min(1)).optional(),
73
+ confirmHeadedRead: z.boolean().optional(),
74
+ expectedTarget: contextTargetSchema.optional(),
58
75
  }).strict();
59
76
  const roughCutPlanSchema = mediaIndexQuerySchema.extend({
60
77
  maxShots: z.number().int().positive().optional(),
@@ -149,7 +166,14 @@ const colorCorrectionSchema = z.object({
149
166
  }),
150
167
  baseRevision: revisionSchema,
151
168
  });
152
- const rippleDeleteSchema = z.object({ type: z.literal("ripple-delete"), timelineId: z.string().min(1), range: rangeSchema, reason: z.string().optional(), baseRevision: revisionSchema });
169
+ const rippleDeleteSchema = z.object({
170
+ type: z.literal("ripple-delete"),
171
+ timelineId: z.string().min(1),
172
+ // The editor validates this range against the active timeline and reports its actual bounds.
173
+ range: z.object({ start: z.number().finite(), end: z.number().finite() }),
174
+ reason: z.string().optional(),
175
+ baseRevision: revisionSchema,
176
+ });
153
177
  const addMarkerSchema = z.object({ type: z.literal("add-marker"), timelineId: z.string().min(1), marker: markerSchema, baseRevision: revisionSchema });
154
178
  const roughCutImportSchema = z.object({
155
179
  type: z.literal("media.import"),
@@ -325,6 +349,7 @@ const artifactPublishInputSchema = z.object({
325
349
  targetLibraryPath: z.string().trim().min(1),
326
350
  transactionId: z.string().min(1),
327
351
  confirm: z.boolean(),
352
+ confirmVerification: z.boolean().optional(),
328
353
  }).strict();
329
354
  const artifactTransactionInputSchema = z.object({
330
355
  artifactPath: z.string().trim().min(1),
@@ -760,32 +785,6 @@ function isDirectoryMediaImportError(error) {
760
785
  && typeof guidance.previewTool === "string"
761
786
  && typeof guidance.executeTool === "string";
762
787
  }
763
- function skillErrorResult(error) {
764
- const value = error && typeof error === "object" ? error : {};
765
- const message = error instanceof Error ? error.message : String(error);
766
- const code = error instanceof z.ZodError
767
- ? "SKILL_INPUT_INVALID"
768
- : typeof value.code === "string" ? value.code : message.split(":", 1)[0] || "SKILL_ERROR";
769
- return {
770
- isError: true,
771
- content: [{
772
- type: "text",
773
- text: JSON.stringify({
774
- code,
775
- message,
776
- ...(value.availability ? { availability: value.availability } : {}),
777
- }),
778
- }],
779
- };
780
- }
781
- function skillPreviewResult(preview) {
782
- const details = preview.plan.details ?? {};
783
- return jsonResult({
784
- ...preview,
785
- ...details,
786
- plan: { ...preview.plan, ...details },
787
- });
788
- }
789
788
  function normalizeConnectionStatus(value) {
790
789
  if (!value || typeof value !== "object")
791
790
  return value;
@@ -855,7 +854,7 @@ export function createMcpServer(runtime, options = {}) {
855
854
  : {}),
856
855
  ...(options.projectPublisher
857
856
  ? {
858
- projectPublisher: withBuildAlignmentGuard(options.projectPublisher, assertAlignment, ["isAvailable", "inspectReadiness", "executionMode", "getPublishJob"]),
857
+ projectPublisher: withBuildAlignmentGuard(options.projectPublisher, assertAlignment, ["isAvailable", "inspectReadiness", "executionMode", "getPublishJob", "loadPublishJob"]),
859
858
  }
860
859
  : {}),
861
860
  ...(options.videoExporter
@@ -863,13 +862,51 @@ export function createMcpServer(runtime, options = {}) {
863
862
  : {}),
864
863
  };
865
864
  }
865
+ const publishRouteIsGuarded = Boolean(options.canonicalRecovery && options.projectPublisher);
866
+ if (options.canonicalRecovery) {
867
+ const recovery = options.canonicalRecovery;
868
+ options = {
869
+ ...options,
870
+ ...(options.nativeEditor
871
+ ? { nativeEditor: withRecoveryCheckpointGuard(options.nativeEditor, recovery, ["capabilities", "inspect"], [
872
+ "edit", "undo", "executeBlade", "executeMask", "executeTitleAdd", "executeTransitionAdd",
873
+ "executeAppendMedia", "executeAppendSelectedMedia", "executeInsertMedia", "executeDeleteRange",
874
+ "executeTrimToDuration", "executePictureInPicture", "importMedia", "executeImportMediaDirectory",
875
+ "focusTimeline", "selectMedia", "selectOccurrence", "selectCanonicalOccurrence", "targetMedia",
876
+ "searchMedia", "searchMediaForCanonicalTarget", "searchTitles", "searchTransitions", "locateOccurrence", "locateOccurrenceForCanonicalTarget",
877
+ "previewBlade", "previewMask", "previewDeleteRange", "previewTrimToDuration", "previewAppendMedia",
878
+ "previewAppendSelectedMedia", "previewInsertMedia", "previewTitleAdd", "previewPictureInPicture", "previewTransitionAdd",
879
+ ]) }
880
+ : {}),
881
+ ...(options.disposableNative
882
+ ? { disposableNative: withRecoveryCheckpointGuard(options.disposableNative, recovery, [], ["preview", "execute", "undo"], "disposable") }
883
+ : {}),
884
+ ...(options.nativeOperationSession
885
+ ? { nativeOperationSession: withRecoveryCheckpointGuard(options.nativeOperationSession, recovery, ["status", "cancel"]) }
886
+ : {}),
887
+ ...(options.projectPublisher
888
+ ? { projectPublisher: withPublishRecoveryGuard(options.projectPublisher, recovery, async (publisher, property) => {
889
+ if (property === "executePublishJob") {
890
+ if (publisher.isAvailable() && requiresHeadedPublishingRoute(publisher))
891
+ await requireEditingRoute(runtime, options, "timeline.publish.new-project");
892
+ }
893
+ else {
894
+ if (!publisher.isAvailable())
895
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH, native writes, live project verification, and a target-binding provider");
896
+ if (requiresHeadedPublishingRoute(publisher))
897
+ await requireEditingRoute(runtime, options, "timeline.publish.new-project");
898
+ }
899
+ }) }
900
+ : {}),
901
+ };
902
+ }
866
903
  const server = new McpServer({ name: "framekit", version: FRAMEKIT_VERSION }, { instructions: options.headlessProjects ? HEADLESS_FIRST_MCP_INSTRUCTIONS : EDITOR_FIRST_MCP_INSTRUCTIONS });
867
904
  const nativeTransitionAssets = new Map();
868
905
  const sessions = options.sessionDirectory
869
906
  ? new EditingSessionRepository(options.sessionDirectory, options.sessionChangeSource)
870
907
  : undefined;
871
908
  const materializations = sessions && options.materializationDirectory
872
- ? new SessionMaterializationJobs(options.materializationDirectory, sessions, options.sessionMaterializationPublisher)
909
+ ? new SessionMaterializationJobs(options.materializationDirectory, sessions, options.sessionMaterializationPublisher, options.canonicalRecovery)
873
910
  : undefined;
874
911
  const requireSessions = () => {
875
912
  if (!sessions)
@@ -982,7 +1019,11 @@ export function createMcpServer(runtime, options = {}) {
982
1019
  server.registerTool("session.materialize.execute", {
983
1020
  description: "Confirm, stage, checkpoint, and request publication of a versioned FCPXML project.",
984
1021
  inputSchema: { sessionId: z.string().min(1), target: sessionMaterializationTargetSchema, confirm: z.boolean() },
985
- }, async ({ sessionId, target, confirm }) => sessionResult(async () => requireMaterializations().execute(sessionId, target, confirm)));
1022
+ }, async ({ sessionId, target, confirm }) => sessionResult(async () => {
1023
+ if (options.sessionMaterializationPublisher)
1024
+ await options.canonicalRecovery?.assertClear();
1025
+ return requireMaterializations().execute(sessionId, target, confirm);
1026
+ }));
986
1027
  server.registerTool("session.materialize.status", {
987
1028
  description: "Inspect a persisted materialization job after completion, blockage, or server restart.",
988
1029
  inputSchema: { jobId: z.string().min(1) },
@@ -990,7 +1031,11 @@ export function createMcpServer(runtime, options = {}) {
990
1031
  server.registerTool("session.materialize.retry", {
991
1032
  description: "Resume a retryable persisted materialization job with its verified immutable artifact.",
992
1033
  inputSchema: { jobId: z.string().min(1) },
993
- }, async ({ jobId }) => sessionResult(async () => requireMaterializations().retry(jobId)));
1034
+ }, async ({ jobId }) => sessionResult(async () => {
1035
+ if (options.sessionMaterializationPublisher)
1036
+ await options.canonicalRecovery?.assertClear();
1037
+ return requireMaterializations().retry(jobId);
1038
+ }));
994
1039
  server.registerTool("session.materialize.resync", {
995
1040
  description: "Read the completed versioned handoff target and create a fresh editing-session baseline for continuation.",
996
1041
  inputSchema: { jobId: z.string().min(1), sessionId: z.string().min(1) },
@@ -1003,71 +1048,107 @@ export function createMcpServer(runtime, options = {}) {
1003
1048
  description: "Read native Final Cut handoff readiness without launching, activating, importing, or mutating Final Cut.",
1004
1049
  inputSchema: { publishJobId: z.string().trim().min(1).optional() },
1005
1050
  }, async ({ publishJobId }) => jsonResult(await inspectNativeHandoffReadiness(runtime, options, publishJobId)));
1006
- server.registerTool("skill.list", {
1007
- description: "List registered versioned Framekit Skills with current capability availability.",
1051
+ server.registerTool("editor.native.recovery.evidence.inspect", {
1052
+ description: "Read point-in-time native reservation and sender evidence without changing state or proving receiver quiescence. Recovery eligibility is unavailable.",
1008
1053
  inputSchema: {},
1009
- }, async () => {
1010
- try {
1011
- return jsonResult((await runtime.listSkillAvailability()).map(({ manifest, availability }) => ({
1012
- ...manifest,
1013
- availability,
1014
- })));
1015
- }
1016
- catch (error) {
1017
- return skillErrorResult(error);
1018
- }
1019
- });
1020
- server.registerTool("skill.inspect", {
1021
- description: "Inspect one registered Framekit Skill version and its current capability availability.",
1022
- inputSchema: { skill: z.string().min(1), version: z.string().min(1).optional() },
1023
- }, async ({ skill, version }) => {
1054
+ }, async () => sessionResult(async () => {
1055
+ if (!options.canonicalRecovery?.inspectNativeRecoveryEvidence)
1056
+ throw new Error("CAPABILITY_UNAVAILABLE: native recovery evidence inspection is not configured");
1057
+ return options.canonicalRecovery.inspectNativeRecoveryEvidence();
1058
+ }));
1059
+ server.registerTool("editor.native.recovery.inspect", {
1060
+ description: "Inspect recovery checkpoint evidence in the configured state directory without contacting Final Cut or clearing the checkpoint.",
1061
+ inputSchema: {},
1062
+ }, async () => sessionResult(async () => {
1063
+ if (!options.canonicalRecovery)
1064
+ throw new Error("CAPABILITY_UNAVAILABLE: canonical recovery checkpoint inspection is not configured");
1065
+ let evidence;
1024
1066
  try {
1025
- const { manifest, availability } = await runtime.inspectSkillAvailability(skill, version);
1026
- return jsonResult({ ...manifest, availability });
1067
+ evidence = await options.canonicalRecovery.inspectVersioned();
1027
1068
  }
1028
1069
  catch (error) {
1029
- return skillErrorResult(error);
1070
+ const nativeReservation = await options.canonicalRecovery.inspectNativeReservation();
1071
+ if (!nativeReservation)
1072
+ throw error;
1073
+ return { status: "recovery-required", scope: "configured-state-directory", nativeReservation };
1030
1074
  }
1031
- });
1032
- server.registerTool("skill.preview", {
1033
- description: "Validate and preview a registered Skill without mutating the editor.",
1075
+ return evidence
1076
+ ? { status: "recovery-required", scope: "configured-state-directory", ...evidence }
1077
+ : { status: "clear", scope: "configured-state-directory" };
1078
+ }));
1079
+ server.registerTool("editor.native.recovery.preview", {
1080
+ description: "Compare a separately authorized headed canonical read with one target-bound checkpoint. Confirmation alone does not establish authorization. Never clears the checkpoint or proves native operation quiescence.",
1034
1081
  inputSchema: {
1035
- skill: z.string().min(1),
1036
- version: z.string().min(1).optional(),
1037
- arguments: z.record(z.unknown()),
1082
+ confirmHeadedRead: z.boolean().optional(),
1083
+ expectedTarget: contextTargetSchema.optional(),
1084
+ expectedCheckpointId: z.string().regex(/^[a-f0-9]{64}$/).optional(),
1038
1085
  },
1039
- }, async ({ skill, version, arguments: skillArguments }) => {
1086
+ }, async ({ confirmHeadedRead, expectedTarget, expectedCheckpointId }) => {
1087
+ const operation = "editor.native.recovery.preview";
1088
+ if (!confirmHeadedRead || !expectedTarget || !expectedCheckpointId) {
1089
+ return mcpReadErrorResult("HEADED_READ_CONFIRMATION_REQUIRED", "recovery preview requires confirmation, target IDs, and the inspected checkpoint ID", operation);
1090
+ }
1091
+ if (!options.canonicalRecovery)
1092
+ return mcpReadErrorResult("CAPABILITY_UNAVAILABLE", "canonical recovery checkpoint inspection is not configured", operation);
1093
+ let evidence;
1040
1094
  try {
1041
- const baseRevision = revisionValueSchema.parse(skillArguments.baseRevision);
1042
- const { baseRevision: _baseRevision, ...input } = skillArguments;
1043
- return skillPreviewResult(await runtime.previewSkill({
1044
- skillId: skill,
1045
- ...(version ? { version } : {}),
1046
- baseRevision,
1047
- input,
1048
- }));
1095
+ evidence = await options.canonicalRecovery.inspectVersioned();
1049
1096
  }
1050
1097
  catch (error) {
1051
- return skillErrorResult(error);
1098
+ return mcpReadErrorResult("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED", error instanceof Error ? error.message : String(error), operation);
1099
+ }
1100
+ if (!evidence || evidence.checkpointId !== expectedCheckpointId)
1101
+ return mcpReadErrorResult("CHECKPOINT_MISMATCH", "recovery checkpoint is missing or changed", operation);
1102
+ if (evidence.checkpoint.projectId !== expectedTarget.projectId || evidence.checkpoint.sequenceId !== expectedTarget.sequenceId) {
1103
+ return mcpReadErrorResult("TARGET_MISMATCH", "requested target differs from the checkpoint", operation);
1104
+ }
1105
+ const passive = await inspectMcpEditor(runtime, options);
1106
+ if (passive.identity.backend !== "final-cut-native-canonical") {
1107
+ return mcpReadErrorResult("CAPABILITY_UNAVAILABLE", "recovery preview requires the canonical native provider", operation);
1052
1108
  }
1053
- });
1054
- server.registerTool("skill.execute", {
1055
- description: "Execute only a runtime-issued Skill preview token and return verification/rollback evidence.",
1056
- inputSchema: {
1057
- previewToken: z.string().min(1),
1058
- },
1059
- }, async ({ previewToken }) => {
1060
1109
  try {
1061
- return jsonResult(await runtime.executeSkill(previewToken));
1110
+ return await inspectCanonicalReadForMcp(runtime, options, operation, true, expectedTarget, async () => {
1111
+ const beforeLive = await runtime.inspectLiveEditor();
1112
+ if (!liveTargetMatches(beforeLive, expectedTarget) || !beforeLive.revision?.id || !Number.isSafeInteger(beforeLive.revision.sequence)) {
1113
+ throw new Error("STALE_CONTEXT: live target or revision is unavailable before recovery read");
1114
+ }
1115
+ const snapshot = await runtime.inspectProject();
1116
+ const afterLive = await runtime.inspectLiveEditor();
1117
+ if (!liveTargetMatches(afterLive, expectedTarget) || afterLive.revision?.id !== beforeLive.revision.id
1118
+ || afterLive.revision?.sequence !== beforeLive.revision.sequence) {
1119
+ throw new Error("STALE_CONTEXT: live target or revision changed during recovery read");
1120
+ }
1121
+ if (snapshot.projectId !== expectedTarget.projectId || snapshot.timeline.id !== expectedTarget.sequenceId) {
1122
+ throw new Error("TARGET_MISMATCH: canonical snapshot differs from the checkpoint target");
1123
+ }
1124
+ const after = await options.canonicalRecovery.inspectVersioned();
1125
+ if (!after || after.checkpointId !== expectedCheckpointId)
1126
+ throw new Error("CHECKPOINT_MISMATCH: checkpoint changed during canonical read");
1127
+ const observedDigest = canonicalSnapshotDigest(snapshot);
1128
+ const comparison = evidence.checkpoint.expectedRestoreDigest === observedDigest
1129
+ ? "matches-expected-restoration"
1130
+ : evidence.checkpoint.beforeDigest === observedDigest ? "matches-before" : "different";
1131
+ return { checkpointId: expectedCheckpointId, target: expectedTarget, observedRevision: snapshot.revision, observedLiveRevision: afterLive.revision, observedDigest, comparison, pointInTime: true, quiescence: "unproven", checkpointCleared: false };
1132
+ }, (result) => result.target);
1062
1133
  }
1063
1134
  catch (error) {
1064
- return skillErrorResult(error);
1135
+ const message = error instanceof Error ? error.message : String(error);
1136
+ if (message.startsWith("STALE_CONTEXT:"))
1137
+ return mcpReadErrorResult("STALE_CONTEXT", message, operation);
1138
+ if (message.startsWith("TARGET_MISMATCH:"))
1139
+ return mcpReadErrorResult("TARGET_MISMATCH", message, operation);
1140
+ if (message.startsWith("CHECKPOINT_MISMATCH:"))
1141
+ return mcpReadErrorResult("CHECKPOINT_MISMATCH", message, operation);
1142
+ if (message.startsWith("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED:"))
1143
+ return mcpReadErrorResult("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED", message, operation);
1144
+ throw error;
1065
1145
  }
1066
1146
  });
1147
+ registerSkillTools(server, runtime);
1067
1148
  server.registerTool("project.inspect", {
1068
1149
  description: "Read a bound session baseline or perform an explicit canonical project resync before editing.route selects a capability-checked path.",
1069
1150
  inputSchema: timelineReadbackSchema,
1070
- }, async ({ sessionId, requestedCanonical, finalVerification }) => {
1151
+ }, async ({ sessionId, requestedCanonical, finalVerification, confirmHeadedRead, expectedTarget }) => {
1071
1152
  if (sessionId) {
1072
1153
  const { stored, decision } = await prepareSessionReadback(sessionId, requestedCanonical, finalVerification);
1073
1154
  if (decision.route === "session" || decision.route === "fast-observation") {
@@ -1078,20 +1159,9 @@ export function createMcpServer(runtime, options = {}) {
1078
1159
  snapshot: stored.document.base,
1079
1160
  });
1080
1161
  }
1081
- const resynced = await canonicalResyncSession(sessionId, stored.document.provider?.id);
1082
- return jsonResult({ sessionId, readback: decision, ...resynced });
1083
- }
1084
- const inspected = await inspectMcpEditor(runtime, options);
1085
- const capability = inspected.capabilities.families.canonicalDocument.read;
1086
- if (!capability.available) {
1087
- return capabilityErrorResult("project.inspect", "canonicalDocument.read", capability);
1088
- }
1089
- try {
1090
- return jsonResult(await runtime.inspectProject());
1091
- }
1092
- catch (error) {
1093
- return capabilityUnavailableErrorResult(error);
1162
+ return inspectCanonicalReadForMcp(runtime, options, "project.inspect", confirmHeadedRead, expectedTarget, async () => ({ sessionId, readback: decision, ...await canonicalResyncSession(sessionId, stored.document.provider?.id) }), (result) => ({ projectId: result.snapshot.projectId, sequenceId: result.snapshot.timeline.id }));
1094
1163
  }
1164
+ return inspectCanonicalReadForMcp(runtime, options, "project.inspect", confirmHeadedRead, expectedTarget, () => runtime.inspectProject(), (result) => ({ projectId: result.projectId, sequenceId: result.timeline.id }));
1095
1165
  });
1096
1166
  server.registerTool("artifact.inspect", {
1097
1167
  description: "Identify the managed FCPXML artifact used by the background artifact.edit and artifact.publish workflows.",
@@ -1153,6 +1223,10 @@ export function createMcpServer(runtime, options = {}) {
1153
1223
  expectedRevision: revisionValueSchema.optional(),
1154
1224
  },
1155
1225
  }, async ({ projectId, sourcePath, expectedRevision }) => sessionResult(() => requireHeadlessProjects().registerMedia(projectId, sourcePath, expectedRevision)));
1226
+ server.registerTool("headless.media.search", {
1227
+ description: "Search one Framekit-owned project's registered media by ID, name, or source path without contacting Final Cut.",
1228
+ inputSchema: { projectId: z.string().min(1), query: z.string() },
1229
+ }, async ({ projectId, query }) => sessionResult(() => requireHeadlessProjects().searchMedia(projectId, query)));
1156
1230
  server.registerTool("headless.edit.preview", {
1157
1231
  description: "Preview supported Framekit Timeline IR edits without persisting or mutating the project.",
1158
1232
  inputSchema: {
@@ -1179,6 +1253,10 @@ export function createMcpServer(runtime, options = {}) {
1179
1253
  expectedRevision,
1180
1254
  operations: operations,
1181
1255
  }, sequenceId)));
1256
+ server.registerTool("headless.edit.undo", {
1257
+ description: "Restore the prior Framekit-owned timeline at the expected revision and independently verify the persisted result.",
1258
+ inputSchema: { projectId: z.string().min(1), sequenceId: z.string().min(1), undoId: z.string().min(1), expectedRevision: revisionValueSchema },
1259
+ }, async ({ projectId, sequenceId, undoId, expectedRevision }) => sessionResult(() => requireHeadlessProjects().undoEdit(projectId, sequenceId, undoId, expectedRevision)));
1182
1260
  const headlessRenderParametersSchema = z.object({
1183
1261
  outputPath: z.string().min(1),
1184
1262
  format: z.enum(["mp4", "mov"]),
@@ -1236,6 +1314,10 @@ export function createMcpServer(runtime, options = {}) {
1236
1314
  eventName: z.string().min(1).optional(),
1237
1315
  materialization: z.enum(["versioned", "reuse-existing"]).optional(),
1238
1316
  }).strict();
1317
+ server.registerTool("headless.fcpxml.export", {
1318
+ description: "Compile an exact Framekit-owned project revision to a new FCPXML artifact without contacting Final Cut.",
1319
+ inputSchema: { projectId: z.string().min(1), sequenceId: z.string().min(1), expectedRevision: revisionValueSchema, outputPath: z.string().min(1), target: headlessFcpxmlTargetSchema },
1320
+ }, async ({ projectId, sequenceId, expectedRevision, outputPath, target }) => sessionResult(() => requireHeadlessProjects().exportFcpxml(projectId, sequenceId, expectedRevision, outputPath, target)));
1239
1321
  const headlessRoughCutRequestSchema = z.object({
1240
1322
  projectId: z.string().min(1),
1241
1323
  sequenceId: z.string().min(1),
@@ -1535,11 +1617,18 @@ export function createMcpServer(runtime, options = {}) {
1535
1617
  return jsonResult(await options.nativeEditor.undo(operationId, { signal: extra.signal }));
1536
1618
  });
1537
1619
  server.registerTool("editor.native.media.search", {
1538
- description: "Search the active Final Cut Browser for live media and return short-lived media handles.",
1620
+ description: "Search the active Final Cut Browser by literal text and return short-lived media handles; wildcard operators are unsupported.",
1539
1621
  inputSchema: { query: z.string().min(1) },
1540
1622
  }, async ({ query }, extra) => {
1541
1623
  if (!options.nativeEditor)
1542
1624
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native media search is not configured");
1625
+ const queryError = nativeMediaSearchQueryError(query);
1626
+ if (queryError) {
1627
+ return {
1628
+ isError: true,
1629
+ content: [{ type: "text", text: JSON.stringify(queryError) }],
1630
+ };
1631
+ }
1543
1632
  return jsonResult(await options.nativeEditor.searchMedia(query, { signal: extra.signal }));
1544
1633
  });
1545
1634
  server.registerTool("editor.native.media.select", {
@@ -1707,18 +1796,19 @@ export function createMcpServer(runtime, options = {}) {
1707
1796
  return jsonResult({ ...job, ...(sourceProof ? { sourceProof } : {}) });
1708
1797
  });
1709
1798
  server.registerTool("artifact.publish.execute", {
1710
- description: "Execute an experimental native handoff after explicit confirmation; dispatch alone is not project-creation proof, and success requires target readback.",
1799
+ description: "Dispatch a prepared native handoff with confirm=true; for a pending job separately authorize headed readback with confirmVerification=true. Dispatch does not prove project creation.",
1711
1800
  inputSchema: {
1712
1801
  jobId: z.string().trim().min(1),
1713
1802
  confirm: z.literal(true),
1803
+ confirmVerification: z.boolean().optional(),
1714
1804
  },
1715
- }, async ({ jobId, confirm }) => {
1805
+ }, async ({ jobId, confirm, confirmVerification }) => {
1716
1806
  if (!options.projectPublisher)
1717
1807
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH and native writes");
1718
- if (options.projectPublisher.isAvailable() && requiresHeadedPublishingRoute(options.projectPublisher)) {
1808
+ if (!publishRouteIsGuarded && options.projectPublisher.isAvailable() && requiresHeadedPublishingRoute(options.projectPublisher)) {
1719
1809
  await requireEditingRoute(runtime, options, "timeline.publish.new-project");
1720
1810
  }
1721
- return jsonResult(await options.projectPublisher.executePublishJob(jobId, confirm));
1811
+ return jsonResult(await options.projectPublisher.executePublishJob(jobId, confirm, confirmVerification));
1722
1812
  });
1723
1813
  server.registerTool("artifact.publish.status", {
1724
1814
  description: "Read the current state of a prepared artifact publish job without opening Final Cut or retrying it.",
@@ -1726,16 +1816,19 @@ export function createMcpServer(runtime, options = {}) {
1726
1816
  }, async ({ jobId }) => {
1727
1817
  if (!options.projectPublisher)
1728
1818
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH and native writes");
1729
- return jsonResult(options.projectPublisher.getPublishJob(jobId));
1819
+ return jsonResult(await options.projectPublisher.loadPublishJob(jobId));
1730
1820
  });
1731
1821
  server.registerTool("artifact.publish", {
1732
- description: "Experimental, opt-in native import of validated FCPXML. Dispatch alone does not prove project creation; success requires matching created-target readback and explicit confirmation.",
1822
+ description: "Experimental direct import; explicitly confirm both creation and headed readback for this artifact. Dispatch alone does not prove project creation.",
1733
1823
  inputSchema: artifactPublishInputSchema,
1734
- }, async ({ artifactPath, targetLibraryPath, transactionId, confirm }) => {
1735
- if (!options.projectPublisher?.isAvailable())
1824
+ }, async ({ artifactPath, targetLibraryPath, transactionId, confirm, confirmVerification }) => {
1825
+ if (!options.projectPublisher)
1736
1826
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH, native writes, live project verification, and a target-binding provider");
1737
- if (requiresHeadedPublishingRoute(options.projectPublisher)) {
1738
- await requireEditingRoute(runtime, options, "timeline.publish.new-project");
1827
+ if (!publishRouteIsGuarded) {
1828
+ if (!options.projectPublisher.isAvailable())
1829
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH, native writes, live project verification, and a target-binding provider");
1830
+ if (requiresHeadedPublishingRoute(options.projectPublisher))
1831
+ await requireEditingRoute(runtime, options, "timeline.publish.new-project");
1739
1832
  }
1740
1833
  const transaction = runtime.getTransaction(transactionId);
1741
1834
  if (transaction.target?.kind !== "artifact" || transaction.target.artifactPath !== artifactPath) {
@@ -1753,20 +1846,25 @@ export function createMcpServer(runtime, options = {}) {
1753
1846
  artifactDigest: transaction.artifactDigest,
1754
1847
  targetLibraryPath,
1755
1848
  confirm,
1849
+ confirmVerification,
1756
1850
  }));
1757
1851
  });
1758
1852
  server.registerTool("timeline.publish.new-project", {
1759
- description: "Experimental, opt-in native import of a verified artifact transaction; reports verified delivery only after matching created-target readback and explicit confirmation.",
1853
+ description: "Experimental direct import of a verified artifact; explicitly confirm creation and headed readback before verified delivery.",
1760
1854
  inputSchema: {
1761
1855
  transactionId: z.string().min(1),
1762
1856
  targetLibraryPath: z.string().trim().min(1),
1763
1857
  confirm: z.literal(true),
1858
+ confirmVerification: z.boolean().optional(),
1764
1859
  },
1765
- }, async ({ transactionId, targetLibraryPath, confirm }) => {
1766
- if (!options.projectPublisher?.isAvailable())
1860
+ }, async ({ transactionId, targetLibraryPath, confirm, confirmVerification }) => {
1861
+ if (!options.projectPublisher)
1767
1862
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH, native writes, live project verification, and a target-binding provider");
1768
- if (requiresHeadedPublishingRoute(options.projectPublisher)) {
1769
- await requireEditingRoute(runtime, options, "timeline.publish.new-project");
1863
+ if (!publishRouteIsGuarded) {
1864
+ if (!options.projectPublisher.isAvailable())
1865
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH, native writes, live project verification, and a target-binding provider");
1866
+ if (requiresHeadedPublishingRoute(options.projectPublisher))
1867
+ await requireEditingRoute(runtime, options, "timeline.publish.new-project");
1770
1868
  }
1771
1869
  const transaction = runtime.getTransaction(transactionId);
1772
1870
  if (transaction.target?.kind !== "artifact") {
@@ -1784,6 +1882,7 @@ export function createMcpServer(runtime, options = {}) {
1784
1882
  artifactDigest: transaction.artifactDigest,
1785
1883
  targetLibraryPath,
1786
1884
  confirm,
1885
+ confirmVerification,
1787
1886
  }));
1788
1887
  });
1789
1888
  server.registerTool("timeline.export", {
@@ -1848,9 +1947,28 @@ export function createMcpServer(runtime, options = {}) {
1848
1947
  });
1849
1948
  });
1850
1949
  server.registerTool("context.inspect", {
1851
- description: "Read the queryable agent editing context and its current revision.",
1852
- inputSchema: {},
1853
- }, async () => jsonResult(await runtime.inspectContext()));
1950
+ description: "Read editing context passively, or explicitly confirm a headed read for the expected project and sequence.",
1951
+ inputSchema: {
1952
+ confirmHeadedRead: z.boolean().optional(),
1953
+ expectedTarget: contextTargetSchema.optional(),
1954
+ },
1955
+ }, async ({ confirmHeadedRead, expectedTarget }) => sessionResult(async () => {
1956
+ if (!confirmHeadedRead)
1957
+ return runtime.inspectContext({ probeCanonicalSnapshot: false });
1958
+ if (!expectedTarget)
1959
+ throw new Error("EXPECTED_TARGET_REQUIRED: headed context read requires a project and sequence");
1960
+ const matches = (live) => live.project?.id === expectedTarget.projectId && live.sequence?.id === expectedTarget.sequenceId;
1961
+ if (!matches(await runtime.inspectLiveEditor()))
1962
+ throw new Error("TARGET_MISMATCH: active project or sequence differs from expected target");
1963
+ const context = await runtime.inspectContext({ probeCanonicalSnapshot: true });
1964
+ if (!context.project)
1965
+ throw new Error("CAPABILITY_UNAVAILABLE: headed canonical context could not be read");
1966
+ if (!matches(await runtime.inspectLiveEditor()) ||
1967
+ context.project.projectId !== expectedTarget.projectId || context.project.timeline.id !== expectedTarget.sequenceId) {
1968
+ throw new Error("TARGET_MISMATCH: context target changed during headed read");
1969
+ }
1970
+ return context;
1971
+ }));
1854
1972
  server.registerTool("context.changes", {
1855
1973
  description: "Read incremental timeline, live-state, and native-asset changes after a context revision.",
1856
1974
  inputSchema: {
@@ -1899,7 +2017,7 @@ export function createMcpServer(runtime, options = {}) {
1899
2017
  server.registerTool("timeline.inspect", {
1900
2018
  description: "Read a bound session baseline or perform an explicit canonical timeline resync after canonical capability checks.",
1901
2019
  inputSchema: timelineReadbackSchema,
1902
- }, async ({ sessionId, requestedCanonical, finalVerification }) => {
2020
+ }, async ({ sessionId, requestedCanonical, finalVerification, confirmHeadedRead, expectedTarget }) => {
1903
2021
  if (sessionId) {
1904
2022
  const { stored, decision } = await prepareSessionReadback(sessionId, requestedCanonical, finalVerification);
1905
2023
  if (decision.route === "session" || decision.route === "fast-observation") {
@@ -1910,41 +2028,19 @@ export function createMcpServer(runtime, options = {}) {
1910
2028
  timeline: stored.document.base,
1911
2029
  });
1912
2030
  }
1913
- const resynced = await canonicalResyncSession(sessionId, stored.document.provider?.id);
1914
- return jsonResult({
1915
- sessionId,
1916
- readback: decision,
1917
- snapshot: resynced.snapshot.timeline,
1918
- session: resynced.session,
1919
- });
1920
- }
1921
- const inspected = await inspectMcpEditor(runtime, options);
1922
- const capability = inspected.capabilities.families.canonicalDocument.read;
1923
- if (!capability.available) {
1924
- return capabilityErrorResult("timeline.inspect", "canonicalDocument.read", capability);
1925
- }
1926
- try {
1927
- return jsonResult(await runtime.inspectTimeline());
1928
- }
1929
- catch (error) {
1930
- return capabilityUnavailableErrorResult(error);
2031
+ return inspectCanonicalReadForMcp(runtime, options, "timeline.inspect", confirmHeadedRead, expectedTarget, async () => {
2032
+ const resynced = await canonicalResyncSession(sessionId, stored.document.provider?.id);
2033
+ return { sessionId, readback: decision, snapshot: resynced.snapshot.timeline, session: resynced.session };
2034
+ }, (result) => ({ sequenceId: result.snapshot.id }));
1931
2035
  }
2036
+ return inspectCanonicalReadForMcp(runtime, options, "timeline.inspect", confirmHeadedRead, expectedTarget, () => runtime.inspectTimeline(), (result) => ({ sequenceId: result.id }));
1932
2037
  });
1933
2038
  server.registerTool("timeline.semantic.inspect", {
1934
2039
  description: "Enrich timeline occurrences with source-range-bound semantic speech, visual, and metadata context without mutating the timeline.",
1935
2040
  inputSchema: timelineSemanticContextQuerySchema.shape,
1936
2041
  }, async (query) => {
1937
- const inspected = await inspectMcpEditor(runtime, options);
1938
- const capability = inspected.capabilities.families.canonicalDocument.read;
1939
- if (!capability.available) {
1940
- return capabilityErrorResult("timeline.semantic.inspect", "canonicalDocument.read", capability);
1941
- }
1942
- try {
1943
- return jsonResult(await runtime.inspectTimelineSemanticContext(query));
1944
- }
1945
- catch (error) {
1946
- return capabilityUnavailableErrorResult(error);
1947
- }
2042
+ const { confirmHeadedRead, expectedTarget, ...contextQuery } = query;
2043
+ return inspectCanonicalReadForMcp(runtime, options, "timeline.semantic.inspect", confirmHeadedRead, expectedTarget, () => runtime.inspectTimelineSemanticContext(contextQuery), (result) => ({ sequenceId: result.timelineId }));
1948
2044
  });
1949
2045
  server.registerTool("timeline.frame.capture", {
1950
2046
  description: "Capture an image at an exact timeline position with project, sequence, clip, and optional visual-analysis metadata.",
@@ -2026,6 +2122,18 @@ export function createMcpServer(runtime, options = {}) {
2026
2122
  sequence: z.number().int().nonnegative().optional(),
2027
2123
  },
2028
2124
  }, async ({ projectId, sequenceId, revision, sequence }) => {
2125
+ if (!(projectId && sequenceId && revision)) {
2126
+ const inspected = await inspectMcpEditor(runtime, options);
2127
+ const capability = inspected.capabilities.families.canonicalDocument.read;
2128
+ if (!capability.available)
2129
+ return capabilityErrorResult("timeline.changes", "canonicalDocument.read", capability);
2130
+ if (capability.evidenceTier === "headed-native") {
2131
+ return capabilityErrorResult("timeline.changes", "canonicalDocument.read", {
2132
+ available: false, backend: capability.backend, guarantee: "none",
2133
+ unavailableReason: "canonical timeline changes require an explicitly authorized headed read",
2134
+ });
2135
+ }
2136
+ }
2029
2137
  const project = projectId && sequenceId && revision
2030
2138
  ? undefined
2031
2139
  : await runtime.inspectProject();
@@ -2402,8 +2510,52 @@ async function effectiveConnectionStatus(runtime, options) {
2402
2510
  });
2403
2511
  }
2404
2512
  }
2405
- async function inspectMcpEditor(runtime, options) {
2406
- const inspected = await runtime.inspectEditor();
2513
+ async function inspectCanonicalReadForMcp(runtime, options, operation, confirmHeadedRead, expectedTarget, read, targetOf) {
2514
+ const passive = await inspectMcpEditor(runtime, options);
2515
+ const headed = passive.identity.backend === "final-cut-native-canonical";
2516
+ if (headed && (!confirmHeadedRead || !expectedTarget)) {
2517
+ return mcpReadErrorResult("HEADED_READ_CONFIRMATION_REQUIRED", `${operation} requires confirmHeadedRead and expectedTarget projectId and sequenceId before exporting a canonical snapshot`, operation);
2518
+ }
2519
+ if (headed && expectedTarget) {
2520
+ const before = await runtime.inspectLiveEditor();
2521
+ if (!liveTargetMatches(before, expectedTarget)) {
2522
+ return mcpReadErrorResult("TARGET_MISMATCH", `${operation} active project or sequence differs from expectedTarget`, operation);
2523
+ }
2524
+ }
2525
+ return runtime.withCanonicalReadScope(async () => {
2526
+ const inspected = await inspectMcpEditor(runtime, options, true);
2527
+ const capability = inspected.capabilities.families.canonicalDocument.read;
2528
+ if (!capability.available)
2529
+ return capabilityErrorResult(operation, "canonicalDocument.read", capability);
2530
+ try {
2531
+ const result = await read();
2532
+ if (headed && expectedTarget) {
2533
+ const live = await runtime.inspectLiveEditor();
2534
+ const returnedTarget = targetOf(result);
2535
+ if (!liveTargetMatches(live, expectedTarget)
2536
+ || (returnedTarget.projectId !== undefined && returnedTarget.projectId !== expectedTarget.projectId)
2537
+ || (returnedTarget.sequenceId !== undefined && returnedTarget.sequenceId !== expectedTarget.sequenceId)) {
2538
+ return mcpReadErrorResult("TARGET_MISMATCH", `${operation} result or active target changed during the headed read`, operation);
2539
+ }
2540
+ }
2541
+ return jsonResult(result);
2542
+ }
2543
+ catch (error) {
2544
+ return capabilityUnavailableErrorResult(error);
2545
+ }
2546
+ });
2547
+ }
2548
+ function liveTargetMatches(live, target) {
2549
+ return live.project?.id === target.projectId && live.sequence?.id === target.sequenceId;
2550
+ }
2551
+ function mcpReadErrorResult(code, message, operation) {
2552
+ return {
2553
+ isError: true,
2554
+ content: [{ type: "text", text: JSON.stringify({ code, message, operation }) }],
2555
+ };
2556
+ }
2557
+ async function inspectMcpEditor(runtime, options, probeCanonicalSnapshot = false) {
2558
+ const inspected = await runtime.inspectEditor({ probeCanonicalSnapshot });
2407
2559
  const fingerprint = options.buildFingerprint ?? FRAMEKIT_BUILD_FINGERPRINT;
2408
2560
  const buildAlignment = assessBuildAlignment(fingerprint, inspected.identity.buildFingerprint, options.validationCommit);
2409
2561
  if (options.requireBuildAlignment && buildAlignment.status !== "matched") {
@@ -2428,6 +2580,7 @@ async function inspectMcpEditor(runtime, options) {
2428
2580
  ...inspected.capabilities.editor,
2429
2581
  artifactPublish: publishingAvailable,
2430
2582
  artifactPublishMode: publishingMode,
2583
+ ...(publishingAvailable ? { artifactPublishDispatchGuarantee: "requested-unverified" } : {}),
2431
2584
  ...(publishingAvailable ? {} : { timelinePublishNewProject: false }),
2432
2585
  videoExport: exportAvailable,
2433
2586
  backgroundRender: backgroundExportAvailable,
@@ -2462,6 +2615,7 @@ async function inspectMcpEditor(runtime, options) {
2462
2615
  },
2463
2616
  publishing: publishingAvailable,
2464
2617
  publishingBackend: publishingMode === "background-capable" ? "fcpxml-document-open" : "fcpxml-publisher",
2618
+ publishingGuarantee: "native-verified",
2465
2619
  export: exportAvailable,
2466
2620
  exportBackend: "final-cut-native-export",
2467
2621
  backgroundExport: {
@@ -2497,7 +2651,7 @@ async function inspectMcpEditor(runtime, options) {
2497
2651
  }),
2498
2652
  fingerprint,
2499
2653
  buildAlignment,
2500
- nativeHandoffReadiness: createNativeHandoffReadiness(options.projectPublisher, buildAlignment),
2654
+ nativeHandoffReadiness: await createNativeHandoffReadiness(options.projectPublisher, buildAlignment),
2501
2655
  },
2502
2656
  ...(native ? { native } : {}),
2503
2657
  };
@@ -2506,7 +2660,7 @@ async function inspectNativeHandoffReadiness(runtime, options, publishJobId) {
2506
2660
  const fingerprint = options.buildFingerprint ?? FRAMEKIT_BUILD_FINGERPRINT;
2507
2661
  let extensionFingerprint;
2508
2662
  try {
2509
- extensionFingerprint = (await runtime.inspectEditor()).identity.buildFingerprint;
2663
+ extensionFingerprint = (await runtime.inspectEditor({ probeCanonicalSnapshot: false })).identity.buildFingerprint;
2510
2664
  }
2511
2665
  catch {
2512
2666
  const status = await connectionStatus(options).catch(() => undefined);
@@ -2515,7 +2669,7 @@ async function inspectNativeHandoffReadiness(runtime, options, publishJobId) {
2515
2669
  const buildAlignment = assessBuildAlignment(fingerprint, extensionFingerprint, options.validationCommit);
2516
2670
  return createNativeHandoffReadiness(options.projectPublisher, buildAlignment, publishJobId);
2517
2671
  }
2518
- function createNativeHandoffReadiness(publisher, buildAlignment, publishJobId) {
2672
+ async function createNativeHandoffReadiness(publisher, buildAlignment, publishJobId) {
2519
2673
  const publisherReadiness = inspectProjectPublisherReadiness(publisher);
2520
2674
  const reasons = [...publisherReadiness.reasons];
2521
2675
  if (buildAlignment.status !== "matched") {
@@ -2537,15 +2691,36 @@ function createNativeHandoffReadiness(publisher, buildAlignment, publishJobId) {
2537
2691
  }
2538
2692
  else {
2539
2693
  try {
2540
- const job = publisher.getPublishJob(publishJobId);
2694
+ const job = typeof publisher.loadPublishJob === "function"
2695
+ ? await publisher.loadPublishJob(publishJobId)
2696
+ : publisher.getPublishJob(publishJobId);
2541
2697
  publish = { jobId: job.jobId, state: job.state };
2542
2698
  const resultTarget = job.result?.createdTarget;
2543
2699
  const targetMatches = job.createdTarget
2544
2700
  && resultTarget
2545
- && job.createdTarget.projectId === resultTarget.projectId
2546
- && job.createdTarget.sequenceId === resultTarget.sequenceId;
2701
+ && nativeTargetIdentityMatches(job.createdTarget, resultTarget);
2547
2702
  if (job.state === "verified" && job.result?.verified === true && targetMatches) {
2548
- verifiedTarget = resultTarget;
2703
+ if (typeof publisher.verifyCreatedTarget === "function") {
2704
+ try {
2705
+ const reboundTarget = await publisher.verifyCreatedTarget(job.jobId);
2706
+ if (!nativeTargetIdentityMatches(resultTarget, reboundTarget)) {
2707
+ throw new Error("persisted target identity changed during live rebind");
2708
+ }
2709
+ verifiedTarget = reboundTarget;
2710
+ }
2711
+ catch (error) {
2712
+ reasons.push({
2713
+ code: "FINAL_CUT_PUBLISH_TARGET_REBIND_FAILED",
2714
+ message: `Publish job ${job.jobId} no longer matches the live native target: ${error instanceof Error ? error.message : String(error)}`,
2715
+ });
2716
+ }
2717
+ }
2718
+ else {
2719
+ reasons.push({
2720
+ code: "FINAL_CUT_PUBLISH_TARGET_REBIND_UNAVAILABLE",
2721
+ message: `Publish job ${job.jobId} cannot be rebound because the publisher cannot revalidate the native library and active target`,
2722
+ });
2723
+ }
2549
2724
  }
2550
2725
  else {
2551
2726
  reasons.push({
@@ -2578,6 +2753,13 @@ function createNativeHandoffReadiness(publisher, buildAlignment, publishJobId) {
2578
2753
  ...(ready && verifiedTarget ? { createdTarget: verifiedTarget } : {}),
2579
2754
  };
2580
2755
  }
2756
+ function nativeTargetIdentityMatches(left, right) {
2757
+ return left.kind === right.kind
2758
+ && left.projectId === right.projectId
2759
+ && left.sequenceId === right.sequenceId
2760
+ && left.libraryId === right.libraryId
2761
+ && left.eventId === right.eventId;
2762
+ }
2581
2763
  function inspectProjectPublisherReadiness(publisher) {
2582
2764
  if (!publisher) {
2583
2765
  return {
@@ -2603,13 +2785,416 @@ function inspectProjectPublisherReadiness(publisher) {
2603
2785
  };
2604
2786
  }
2605
2787
  async function assertRequiredBuildAlignment(runtime, options) {
2606
- const inspected = await runtime.inspectEditor();
2788
+ const inspected = await runtime.inspectEditor({ probeCanonicalSnapshot: false });
2607
2789
  const fingerprint = options.buildFingerprint ?? FRAMEKIT_BUILD_FINGERPRINT;
2608
2790
  const alignment = assessBuildAlignment(fingerprint, inspected.identity.buildFingerprint, options.validationCommit);
2609
2791
  if (alignment.status !== "matched") {
2610
2792
  throw new Error(`FRAMEKIT_BUILD_ALIGNMENT_MISMATCH: ${alignment.message}`);
2611
2793
  }
2612
2794
  }
2795
+ function withPublishRecoveryGuard(provider, recovery, validateRoute) {
2796
+ const allowed = new Set(["isAvailable", "inspectReadiness", "executionMode", "getPublishJob", "loadPublishJob", "preparePublish"]);
2797
+ let current;
2798
+ return new Proxy(provider, {
2799
+ get(target, property) {
2800
+ if (property !== "executePublishJob" && property !== "publishNewProject") {
2801
+ const value = Reflect.get(target, property, target);
2802
+ if (typeof value !== "function")
2803
+ return value;
2804
+ if (allowed.has(property))
2805
+ return value.bind(target);
2806
+ return async (...args) => {
2807
+ await recovery.assertClear();
2808
+ return Reflect.apply(value, target, args);
2809
+ };
2810
+ }
2811
+ return async (...args) => {
2812
+ const jobId = property === "executePublishJob" && typeof args[0] === "string" ? args[0] : undefined;
2813
+ let provenDisabled = false;
2814
+ let entry = current;
2815
+ const acquiringReservation = !entry;
2816
+ if (entry) {
2817
+ if (entry.active || !jobId || entry.jobId !== jobId || args[1] !== true || args[2] !== true) {
2818
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: publish reservation only permits verification of its settled pending job");
2819
+ }
2820
+ entry.active = true;
2821
+ try {
2822
+ const observed = await recovery.inspectNativeReservation();
2823
+ if (observed?.reservationId !== entry.reservation.reservationId) {
2824
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: publish reservation changed before verification");
2825
+ }
2826
+ const getJob = Reflect.get(target, "getPublishJob", target);
2827
+ const job = getJob.call(target, jobId);
2828
+ if (job?.state !== "verification-pending" || (job.jobId !== undefined && job.jobId !== jobId)) {
2829
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: publish job changed before verification");
2830
+ }
2831
+ }
2832
+ catch (error) {
2833
+ entry.active = false;
2834
+ throw error;
2835
+ }
2836
+ }
2837
+ else {
2838
+ // Never invoke caller-controlled job lookup before the reservation.
2839
+ const job = jobId ? inertBuiltInPublishJob(target, jobId) : undefined;
2840
+ if (job && job.jobId !== jobId)
2841
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: publish job identity mismatch");
2842
+ const pending = job?.state === "verification-pending";
2843
+ const operation = jobId
2844
+ ? `native.publish.${createHash("sha256").update(jobId).digest("hex")}`
2845
+ : "native.publish.direct";
2846
+ const path = job?.targetLibraryPath;
2847
+ const digest = job?.artifactDigest;
2848
+ const context = jobId && !pending && /^publish-job-[a-z0-9-]{1,80}$/.test(jobId)
2849
+ && typeof path === "string" && path.length <= 4096 && isAbsolute(path) && path.endsWith(".fcpbundle")
2850
+ && typeof digest === "string" && /^[a-f0-9]{64}$/.test(digest)
2851
+ ? Object.freeze({ kind: "publish", jobId, dispatchId: randomUUID(), requestedTarget: Object.freeze({ libraryPath: path }),
2852
+ artifactDigest: digest, executorIdentity: null, nativeQuiescence: "unproven" })
2853
+ : undefined;
2854
+ // Capture primitives and data descriptors before awaiting the guard;
2855
+ // its implementation must not rewrite the evidence used for rechecks.
2856
+ const configurationKeys = ["enabled", "liveState", "readCanonicalSnapshot", "sourcePath", "publishJobsDirectory"];
2857
+ const requestedConfiguration = job ? configurationKeys.map((key) => Object.getOwnPropertyDescriptor(target, key)) : undefined;
2858
+ const requestedIntent = context && job ? { libraryPath: context.requestedTarget.libraryPath,
2859
+ artifactDigest: context.artifactDigest, state: job.state } : undefined;
2860
+ const reservation = await recovery.beginNative(operation, context);
2861
+ entry = { jobId, reservation, active: true, dispatched: pending, needsBinding: !context,
2862
+ ...(requestedIntent ? { requestedIntent } : {}), ...(requestedConfiguration ? { requestedConfiguration } : {}) };
2863
+ current = entry;
2864
+ }
2865
+ try {
2866
+ if (acquiringReservation && jobId && entry.requestedIntent) {
2867
+ const currentJob = inertBuiltInPublishJob(target, jobId);
2868
+ const expected = entry.requestedIntent;
2869
+ if (!currentJob || currentJob.jobId !== jobId || currentJob.targetLibraryPath !== expected.libraryPath
2870
+ || currentJob.artifactDigest !== expected.artifactDigest || currentJob.state !== expected.state) {
2871
+ entry.dispatched = true;
2872
+ await entry.reservation.markDispatchPossible();
2873
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: publish intent changed during reservation acquisition");
2874
+ }
2875
+ }
2876
+ // Property getters on arbitrary providers may themselves dispatch.
2877
+ const trustedShape = !utilTypes.isProxy(target) && property === "executePublishJob"
2878
+ && Object.getPrototypeOf(target) === FinalCutProjectPublisher.prototype
2879
+ && [["executePublishJob", builtInPublishExecute], ["getPublishJob", builtInPublishGetJob],
2880
+ ["persistPublishJob", builtInPublishPersist], ["trackNativeDispatch", builtInPublishTrack]].every(([key, method]) => typeof key === "string" && !Object.getOwnPropertyDescriptor(target, key)
2881
+ && Object.getOwnPropertyDescriptor(FinalCutProjectPublisher.prototype, key)?.value === method);
2882
+ if (acquiringReservation && !trustedShape) {
2883
+ entry.dispatched = true;
2884
+ await entry.reservation.markDispatchPossible();
2885
+ // A custom lookup may execute arbitrary provider code. Run it only
2886
+ // after durable uncertainty, then bind any eligible requested intent.
2887
+ if (jobId && entry.needsBinding) {
2888
+ const lookup = Reflect.get(target, "getPublishJob", target);
2889
+ if (typeof lookup === "function") {
2890
+ const requested = Reflect.apply(lookup, target, [jobId]);
2891
+ if (requested?.jobId !== undefined && requested.jobId !== jobId) {
2892
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: publish job identity mismatch");
2893
+ }
2894
+ if (requested?.state === "verification-pending") {
2895
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: unowned pending publish cannot be invoked again");
2896
+ }
2897
+ const path = requested?.targetLibraryPath;
2898
+ const digest = requested?.artifactDigest;
2899
+ if (requested?.state !== "verification-pending" && /^publish-job-[a-z0-9-]{1,80}$/.test(jobId)
2900
+ && typeof path === "string" && path.length <= 4096 && isAbsolute(path) && path.endsWith(".fcpbundle")
2901
+ && typeof digest === "string" && /^[a-f0-9]{64}$/.test(digest)) {
2902
+ await entry.reservation.bindRecoveryContext({ kind: "publish", jobId, dispatchId: randomUUID(),
2903
+ requestedTarget: { libraryPath: path }, artifactDigest: digest,
2904
+ executorIdentity: null, nativeQuiescence: "unproven" });
2905
+ }
2906
+ }
2907
+ }
2908
+ }
2909
+ const value = trustedShape ? builtInPublishExecute : Reflect.get(target, property, target);
2910
+ const track = trustedShape ? builtInPublishTrack : Reflect.get(target, "trackNativeDispatch", target);
2911
+ if (typeof value !== "function")
2912
+ throw new Error("CAPABILITY_UNAVAILABLE: publisher operation is not available");
2913
+ if (acquiringReservation && jobId && property === "executePublishJob"
2914
+ && trustedShape) {
2915
+ const stores = ["publishJobs", "publishJobRuntime"].map((key) => Object.getOwnPropertyDescriptor(target, key)?.value);
2916
+ const ordinaryStores = stores.every((store) => !utilTypes.isProxy(store) && utilTypes.isMap(store)
2917
+ && Object.getPrototypeOf(store) === Map.prototype
2918
+ && !Object.getOwnPropertyDescriptor(store, "get") && !Object.getOwnPropertyDescriptor(store, "set") && !Object.getOwnPropertyDescriptor(store, "has")
2919
+ && Object.getOwnPropertyDescriptor(Map.prototype, "get")?.value === builtInMapGet
2920
+ && Object.getOwnPropertyDescriptor(Map.prototype, "set")?.value === builtInMapSet
2921
+ && Object.getOwnPropertyDescriptor(Map.prototype, "has")?.value === builtInMapHas);
2922
+ const job = ordinaryStores ? inertBuiltInPublishJob(target, jobId) : undefined;
2923
+ if (!ordinaryStores || (!job && builtInMapHas.call(stores[0], jobId))) {
2924
+ // A present but non-inert job may execute getters or identify a
2925
+ // different operation. Do not invoke it even after the marker.
2926
+ entry.dispatched = true;
2927
+ await entry.reservation.markDispatchPossible();
2928
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: publish job identity cannot be inspected safely");
2929
+ }
2930
+ if (job) {
2931
+ const enabled = Object.getOwnPropertyDescriptor(target, "enabled");
2932
+ const directory = Object.getOwnPropertyDescriptor(target, "publishJobsDirectory");
2933
+ const configurationKeys = ["enabled", "liveState", "readCanonicalSnapshot", "sourcePath", "publishJobsDirectory"];
2934
+ const configurationUnchanged = Boolean(entry.requestedConfiguration && configurationKeys.every((key, index) => {
2935
+ const before = entry.requestedConfiguration?.[index];
2936
+ const after = Object.getOwnPropertyDescriptor(target, key);
2937
+ return before && after && "value" in before && "value" in after && Object.is(before.value, after.value);
2938
+ }));
2939
+ const safePersistence = Boolean(configurationUnchanged && directory && "value" in directory
2940
+ && (directory.value === undefined
2941
+ || (typeof directory.value === "string" && !builtInMapHas.call(stores[1], jobId))));
2942
+ provenDisabled = (job.state === "awaiting-confirmation" || job.state === "awaiting-final-cut")
2943
+ && enabled?.value === false && safePersistence;
2944
+ const liveState = Object.getOwnPropertyDescriptor(target, "liveState");
2945
+ if (args[1] === true && enabled?.value === true && safePersistence
2946
+ && (job.state === "awaiting-confirmation" || job.state === "awaiting-final-cut")
2947
+ && liveState && "value" in liveState && liveState.value === undefined) {
2948
+ // This preflight uses only inert data and never invokes the
2949
+ // provider or its mutable dependencies.
2950
+ const blocked = { ...job, state: "awaiting-final-cut", nextAction: "retry", retryable: true,
2951
+ error: { code: "FINAL_CUT_PUBLISH_VERIFICATION_UNAVAILABLE", message: "Final Cut project state verification is unavailable; retry this job when the live provider is ready" } };
2952
+ builtInPublishPersist.call(target, blocked);
2953
+ return blocked;
2954
+ }
2955
+ const readback = Object.getOwnPropertyDescriptor(target, "readCanonicalSnapshot");
2956
+ if (args[1] === true && enabled?.value === true && safePersistence
2957
+ && (job.state === "awaiting-confirmation" || job.state === "awaiting-final-cut")
2958
+ && liveState && "value" in liveState && typeof liveState.value === "function"
2959
+ && readback && "value" in readback && readback.value === undefined) {
2960
+ const failed = { ...job, state: "failed", nextAction: "none", retryable: false,
2961
+ error: { code: "FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE", message: "FINAL_CUT_PUBLISH_READBACK_UNAVAILABLE: headed canonical timeline readback is not configured; no import was attempted" } };
2962
+ builtInPublishPersist.call(target, failed);
2963
+ return failed;
2964
+ }
2965
+ // A mismatching managed artifact can be rejected without invoking
2966
+ // the publisher or its tracker. Keep this synchronous so the
2967
+ // trusted store and publisher checks cannot race an await.
2968
+ const source = Object.getOwnPropertyDescriptor(target, "sourcePath");
2969
+ if (args[1] === true && enabled?.value === true && !provenDisabled
2970
+ && (job.state === "awaiting-confirmation" || job.state === "awaiting-final-cut")
2971
+ && !job.sourceTransactionId.startsWith("headless-rough-cut:")
2972
+ && typeof source?.value === "string" && source.value === job.sourcePath
2973
+ && safePersistence
2974
+ && managedArtifactChanged(job.sourcePath, job.artifactDigest)) {
2975
+ const failed = { ...job, state: "failed", nextAction: "none", retryable: false,
2976
+ error: { code: "PUBLISH_SOURCE_CHANGED", message: "Managed FCPXML artifact changed after transaction verification" } };
2977
+ builtInPublishPersist.call(target, failed);
2978
+ return failed;
2979
+ }
2980
+ }
2981
+ }
2982
+ const invoke = async () => {
2983
+ // Once the provider is invoked, a missing callback is not proof of non-dispatch.
2984
+ if (!provenDisabled)
2985
+ entry.dispatched = true;
2986
+ return Reflect.apply(value, target, args);
2987
+ };
2988
+ // Custom tracking code can defer invocation and return or throw first.
2989
+ if (!provenDisabled)
2990
+ entry.dispatched = true;
2991
+ // Record uncertainty before entering any untrusted tracker or provider.
2992
+ // Resumed verification reuses the already marked reservation.
2993
+ if (acquiringReservation && trustedShape && !provenDisabled)
2994
+ await entry.reservation.markDispatchPossible();
2995
+ if (!provenDisabled)
2996
+ await validateRoute(target, property);
2997
+ const result = typeof track === "function"
2998
+ ? await Reflect.apply(track, target, [invoke, () => { entry.dispatched = true; }])
2999
+ : await invoke();
3000
+ if (entry.dispatched && result && typeof result === "object" && !Array.isArray(result)) {
3001
+ return { ...result, recoveryReservation: { status: "recovery-required", reservationId: entry.reservation.reservationId, reason: "native-quiescence-unproven" } };
3002
+ }
3003
+ return result;
3004
+ }
3005
+ finally {
3006
+ entry.active = false;
3007
+ if (!entry.dispatched) {
3008
+ await entry.reservation.release();
3009
+ if (current === entry)
3010
+ current = undefined;
3011
+ }
3012
+ }
3013
+ };
3014
+ },
3015
+ });
3016
+ }
3017
+ function inertBuiltInPublishJob(target, jobId) {
3018
+ if (utilTypes.isProxy(target) || Object.getPrototypeOf(target) !== FinalCutProjectPublisher.prototype
3019
+ || Object.getOwnPropertyDescriptor(target, "getPublishJob")
3020
+ || Object.getOwnPropertyDescriptor(FinalCutProjectPublisher.prototype, "getPublishJob")?.value !== builtInPublishGetJob)
3021
+ return undefined;
3022
+ const store = Object.getOwnPropertyDescriptor(target, "publishJobs")?.value;
3023
+ if (utilTypes.isProxy(store) || !utilTypes.isMap(store) || Object.getPrototypeOf(store) !== Map.prototype
3024
+ || Object.getOwnPropertyDescriptor(Map.prototype, "get")?.value !== builtInMapGet)
3025
+ return undefined;
3026
+ const job = builtInMapGet.call(store, jobId);
3027
+ const seen = new Set();
3028
+ const inert = (value) => {
3029
+ if (value === null || ["string", "boolean", "number", "undefined"].includes(typeof value))
3030
+ return true;
3031
+ if (typeof value !== "object" || utilTypes.isProxy(value) || seen.has(value) || seen.size >= 10_000)
3032
+ return false;
3033
+ seen.add(value);
3034
+ const prototype = Object.getPrototypeOf(value);
3035
+ if (prototype !== Object.prototype && prototype !== Array.prototype && prototype !== null)
3036
+ return false;
3037
+ return Reflect.ownKeys(value).every((key) => {
3038
+ if (typeof key !== "string")
3039
+ return false;
3040
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
3041
+ return Boolean(descriptor && "value" in descriptor && inert(descriptor.value));
3042
+ });
3043
+ };
3044
+ return inert(job) && job && typeof job === "object" ? structuredClone(job) : undefined;
3045
+ }
3046
+ function managedArtifactChanged(path, digest) {
3047
+ let fd;
3048
+ try {
3049
+ fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
3050
+ const info = fstatSync(fd);
3051
+ if (!info.isFile() || info.size > 64 * 1024 * 1024)
3052
+ return false;
3053
+ return createHash("sha256").update(readFileSync(fd, "utf8")).digest("hex") !== digest;
3054
+ }
3055
+ catch {
3056
+ return false;
3057
+ }
3058
+ finally {
3059
+ if (fd !== undefined)
3060
+ closeSync(fd);
3061
+ }
3062
+ }
3063
+ function withRecoveryCheckpointGuard(provider, recovery, allowedMethods = [], reservedMethods = [], reservationKind = "native") {
3064
+ const allowed = new Set(allowedMethods);
3065
+ const reserved = new Set(reservedMethods);
3066
+ const contextMethods = new Set(["focusTimeline", "selectMedia", "selectOccurrence", "selectCanonicalOccurrence"]);
3067
+ const searchMethods = new Set(["searchMedia", "searchMediaForCanonicalTarget", "searchTitles", "searchTransitions"]);
3068
+ return new Proxy(provider, {
3069
+ get(target, property) {
3070
+ if (!reserved.has(property)) {
3071
+ const value = Reflect.get(target, property, target);
3072
+ if (typeof value !== "function")
3073
+ return value;
3074
+ if (allowed.has(property))
3075
+ return value.bind(target);
3076
+ return async (...args) => {
3077
+ await recovery.assertClear();
3078
+ return Reflect.apply(value, target, args);
3079
+ };
3080
+ }
3081
+ // Inspect descriptors without invoking provider accessors while another
3082
+ // native reservation may be held. Unknown proxy shapes stay guarded.
3083
+ if (!utilTypes.isProxy(target)) {
3084
+ let object = target;
3085
+ while (object && !utilTypes.isProxy(object)) {
3086
+ const descriptor = Object.getOwnPropertyDescriptor(object, property);
3087
+ if (descriptor) {
3088
+ if ("value" in descriptor && typeof descriptor.value !== "function")
3089
+ return descriptor.value;
3090
+ break;
3091
+ }
3092
+ object = Object.getPrototypeOf(object);
3093
+ }
3094
+ if (!object)
3095
+ return undefined;
3096
+ }
3097
+ return async (...args) => {
3098
+ if (reserved.has(property)) {
3099
+ const reservation = await recovery.beginNative(`native.${reservationKind === "disposable" ? "disposable." : ""}${String(property).toLowerCase()}`);
3100
+ // Reject a disabled operation without invoking any adapter code. For all
3101
+ // other cases, callbacks and mutable internals may schedule dispatch.
3102
+ const disabledPreflight = !utilTypes.isProxy(target)
3103
+ && Object.getPrototypeOf(target) === FinalCutNativeAutomationAdapter.prototype
3104
+ && Object.getOwnPropertyDescriptor(target, "enabled")?.value === false
3105
+ && Reflect.ownKeys(target).every((key) => {
3106
+ const descriptor = Object.getOwnPropertyDescriptor(target, key);
3107
+ return Boolean(descriptor && "value" in descriptor);
3108
+ })
3109
+ && [...builtInNativeMethods].every(([key, method]) => key === "constructor" || typeof method !== "function"
3110
+ || (!Object.getOwnPropertyDescriptor(target, key)
3111
+ && Object.getOwnPropertyDescriptor(FinalCutNativeAutomationAdapter.prototype, key)?.value === method));
3112
+ const untrustedProvider = !disabledPreflight;
3113
+ let dispatched = untrustedProvider;
3114
+ try {
3115
+ if (untrustedProvider)
3116
+ await reservation.markDispatchPossible();
3117
+ if (disabledPreflight) {
3118
+ if (property === "focusTimeline") {
3119
+ await reservation.release();
3120
+ return disabledNativeFocusContext();
3121
+ }
3122
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut native writes are disabled");
3123
+ }
3124
+ const value = Reflect.get(target, property, target);
3125
+ const track = Reflect.get(target, "trackNativeDispatch", target);
3126
+ if (typeof value !== "function")
3127
+ throw new Error("CAPABILITY_UNAVAILABLE: native operation is not available");
3128
+ const invoke = async () => Reflect.apply(value, target, args);
3129
+ const result = typeof track === "function"
3130
+ ? await Reflect.apply(track, target, [invoke, () => { dispatched = true; }])
3131
+ : await invoke();
3132
+ const evidence = result;
3133
+ const restored = typeof evidence?.beforeDigest === "string" && /^[a-f0-9]{64}$/.test(evidence.beforeDigest)
3134
+ && evidence.restoredDigest === evidence.beforeDigest;
3135
+ const media = (value) => {
3136
+ if (!value || typeof value !== "object")
3137
+ return false;
3138
+ const item = value;
3139
+ return typeof item.mediaHandle === "string" && item.mediaHandle.length > 0
3140
+ && item.verification?.verified === true && item.verification.stage === "post-import-browser-discovery";
3141
+ };
3142
+ const directory = result;
3143
+ const verifiedDirectory = () => {
3144
+ if (directory?.status !== "completed" || directory.partial !== false || directory.failedCount !== 0
3145
+ || !Array.isArray(directory.files) || directory.files.length === 0
3146
+ || directory.importedCount !== directory.files.length || !Array.isArray(directory.results)
3147
+ || directory.results.length !== directory.files.length)
3148
+ return false;
3149
+ const expected = new Set();
3150
+ for (const file of directory.files) {
3151
+ if (!file || typeof file.sourcePath !== "string" || !file.sourcePath || expected.has(file.sourcePath))
3152
+ return false;
3153
+ expected.add(file.sourcePath);
3154
+ }
3155
+ const handles = new Set();
3156
+ for (const entry of directory.results) {
3157
+ if (!entry || entry.status !== "imported" || typeof entry.sourcePath !== "string"
3158
+ || !expected.delete(entry.sourcePath) || !media(entry.media))
3159
+ return false;
3160
+ const item = entry.media;
3161
+ if (item.sourcePath !== entry.sourcePath || handles.has(item.mediaHandle))
3162
+ return false;
3163
+ handles.add(item.mediaHandle);
3164
+ }
3165
+ return expected.size === 0;
3166
+ };
3167
+ const preview = typeof property === "string" && property.startsWith("preview");
3168
+ const prepared = result;
3169
+ const verified = preview ? typeof prepared?.previewToken === "string" && prepared.previewToken.length > 0
3170
+ : contextMethods.has(property) ? prepared?.available === true
3171
+ : searchMethods.has(property) ? Array.isArray(result)
3172
+ : property === "locateOccurrence" || property === "locateOccurrenceForCanonicalTarget" ? ["none", "unique", "ambiguous"].includes(String(prepared?.status)) && Array.isArray(prepared?.occurrences)
3173
+ : property === "targetMedia" ? prepared?.status === "unique" && prepared.selected === true
3174
+ : property === "importMedia" ? media(result)
3175
+ : property === "executeImportMediaDirectory" ? verifiedDirectory()
3176
+ : reservationKind === "disposable"
3177
+ ? property === "undo"
3178
+ ? evidence?.undone === true && evidence.verification?.passed === true && restored
3179
+ : (evidence?.status === "VERIFIED" && evidence.verification?.passed === true)
3180
+ || (evidence?.status === "ROLLED_BACK" && restored)
3181
+ : evidence?.verification?.verified === true && (property !== "undo" || evidence.undone === true);
3182
+ if (!untrustedProvider && (verified || (!dispatched && contextMethods.has(property) && prepared?.available === false))) {
3183
+ await reservation.release();
3184
+ }
3185
+ return result;
3186
+ }
3187
+ catch (error) {
3188
+ if (!dispatched)
3189
+ await reservation.release();
3190
+ throw error;
3191
+ }
3192
+ }
3193
+ throw new Error("CAPABILITY_UNAVAILABLE: native operation is not available");
3194
+ };
3195
+ },
3196
+ });
3197
+ }
2613
3198
  function withBuildAlignmentGuard(provider, assertAlignment, synchronousMethods = []) {
2614
3199
  const synchronous = new Set(synchronousMethods);
2615
3200
  return new Proxy(provider, {