@morshoto/framekit 0.1.17 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +25 -14
  2. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +8 -2
  3. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.js +275 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical.js +557 -84
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +10 -3
  6. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +6 -0
  7. package/dist-package/adapters/final-cut/typescript/src/experimental.js +8 -0
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +150 -37
  9. package/dist-package/adapters/final-cut/typescript/src/index.js +2 -7
  10. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +60 -1
  11. package/dist-package/adapters/final-cut/typescript/src/live.js +29 -4
  12. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.js +175 -0
  13. package/dist-package/adapters/final-cut/typescript/src/native-session.js +11 -6
  14. package/dist-package/adapters/final-cut/typescript/src/native.js +201 -82
  15. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +214 -0
  16. package/dist-package/adapters/final-cut/typescript/src/publisher.js +1008 -243
  17. package/dist-package/adapters/final-cut/typescript/src/session.js +49 -14
  18. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +203 -49
  19. package/dist-package/adapters/headless/typescript/src/audio-output.js +3 -0
  20. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +48 -20
  21. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +9 -4
  22. package/dist-package/apps/cli/src/dev-doctor.js +198 -0
  23. package/dist-package/apps/cli/src/headless-projects.js +5 -0
  24. package/dist-package/apps/cli/src/main.js +76 -19
  25. package/dist-package/apps/mcp-server/runtime/speech-analyzer-wrapper.mjs +54 -0
  26. package/dist-package/apps/mcp-server/runtime/whisper-speech-backend.py +181 -0
  27. package/dist-package/apps/mcp-server/src/build-alignment.js +59 -0
  28. package/dist-package/apps/mcp-server/src/build-identity.js +30 -0
  29. package/dist-package/apps/mcp-server/src/build-identity.json +5 -0
  30. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.js +18 -0
  31. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.js +3 -0
  32. package/dist-package/apps/mcp-server/src/headless-project-snapshot.js +101 -0
  33. package/dist-package/apps/mcp-server/src/main.js +50 -21
  34. package/dist-package/apps/mcp-server/src/materialization-jobs.js +143 -10
  35. package/dist-package/apps/mcp-server/src/routing.js +2 -0
  36. package/dist-package/apps/mcp-server/src/server.js +986 -180
  37. package/dist-package/apps/mcp-server/src/tools/skills/catalog.js +142 -0
  38. package/dist-package/apps/mcp-server/src/tools/skills/metadata.js +71 -0
  39. package/dist-package/apps/mcp-server/src/tools/skills/register.js +101 -0
  40. package/dist-package/apps/mcp-server/src/version.js +21 -2
  41. package/dist-package/packages/headless-application/src/headless-projects.js +942 -0
  42. package/dist-package/packages/headless-application/src/index.js +1 -0
  43. package/dist-package/packages/runtime/src/application/media-analysis-service.js +15 -5
  44. package/dist-package/packages/runtime/src/application/project-service.js +5 -1
  45. package/dist-package/packages/runtime/src/application/project-store.js +13 -36
  46. package/dist-package/packages/runtime/src/application/transaction-store.js +1 -1
  47. package/dist-package/packages/runtime/src/capabilities.js +1 -1
  48. package/dist-package/packages/runtime/src/context/context-engine.js +22 -16
  49. package/dist-package/packages/runtime/src/context/context-service.js +2 -2
  50. package/dist-package/packages/runtime/src/editing/edit-service.js +76 -10
  51. package/dist-package/packages/runtime/src/index.js +1 -0
  52. package/dist-package/packages/runtime/src/runtime.js +22 -7
  53. package/dist-package/packages/runtime/src/timeline/editing-session.js +23 -2
  54. package/dist-package/packages/testkit/src/in-memory-editor.js +3 -3
  55. package/dist-package/packages/testkit/src/index.js +1 -0
  56. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.js +192 -0
  57. package/package.json +36 -14
  58. package/dist-package/apps/mcp-server/src/headless-projects.js +0 -370
@@ -1,14 +1,29 @@
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";
4
- import { z } from "zod";
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";
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";
7
+ import { z } from "zod/v3";
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";
11
+ import { assessBuildAlignment } from "./build-alignment.js";
8
12
  import { FRAMEKIT_BUILD_FINGERPRINT, FRAMEKIT_VERSION, } from "./version.js";
9
13
  import { EditingSessionRepository } from "./headless-sessions.js";
10
14
  import { SessionMaterializationJobs, } from "./materialization-jobs.js";
15
+ import { projectSnapshotFromTimelineIr } from "./headless-project-snapshot.js";
11
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;
12
27
  const revisionValueSchema = z.object({
13
28
  id: z.string(),
14
29
  sequence: z.number().int().nonnegative(),
@@ -23,6 +38,8 @@ const timelineReadbackSchema = z.object({
23
38
  sessionId: z.string().min(1).optional(),
24
39
  requestedCanonical: z.boolean().optional().default(false),
25
40
  finalVerification: z.boolean().optional().default(false),
41
+ confirmHeadedRead: z.boolean().optional(),
42
+ expectedTarget: contextTargetSchema.optional(),
26
43
  }).strict();
27
44
  const contextCursorSchema = z.object({
28
45
  revision: revisionValueSchema,
@@ -53,9 +70,12 @@ const mediaIndexQuerySchema = z.object({
53
70
  const timelineSemanticContextQuerySchema = z.object({
54
71
  query: z.string().optional(),
55
72
  occurrenceIds: z.array(z.string().min(1)).optional(),
73
+ confirmHeadedRead: z.boolean().optional(),
74
+ expectedTarget: contextTargetSchema.optional(),
56
75
  }).strict();
57
76
  const roughCutPlanSchema = mediaIndexQuerySchema.extend({
58
77
  maxShots: z.number().int().positive().optional(),
78
+ projectId: z.string().min(1).optional(),
59
79
  });
60
80
  const durationRangeSchema = z.object({
61
81
  startSeconds: z.number().finite().nonnegative(),
@@ -146,7 +166,14 @@ const colorCorrectionSchema = z.object({
146
166
  }),
147
167
  baseRevision: revisionSchema,
148
168
  });
149
- 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
+ });
150
177
  const addMarkerSchema = z.object({ type: z.literal("add-marker"), timelineId: z.string().min(1), marker: markerSchema, baseRevision: revisionSchema });
151
178
  const roughCutImportSchema = z.object({
152
179
  type: z.literal("media.import"),
@@ -319,8 +346,10 @@ function installMcpSchemaCompatibility(server) {
319
346
  }
320
347
  const artifactPublishInputSchema = z.object({
321
348
  artifactPath: z.string().trim().min(1),
349
+ targetLibraryPath: z.string().trim().min(1),
322
350
  transactionId: z.string().min(1),
323
351
  confirm: z.boolean(),
352
+ confirmVerification: z.boolean().optional(),
324
353
  }).strict();
325
354
  const artifactTransactionInputSchema = z.object({
326
355
  artifactPath: z.string().trim().min(1),
@@ -756,32 +785,6 @@ function isDirectoryMediaImportError(error) {
756
785
  && typeof guidance.previewTool === "string"
757
786
  && typeof guidance.executeTool === "string";
758
787
  }
759
- function skillErrorResult(error) {
760
- const value = error && typeof error === "object" ? error : {};
761
- const message = error instanceof Error ? error.message : String(error);
762
- const code = error instanceof z.ZodError
763
- ? "SKILL_INPUT_INVALID"
764
- : typeof value.code === "string" ? value.code : message.split(":", 1)[0] || "SKILL_ERROR";
765
- return {
766
- isError: true,
767
- content: [{
768
- type: "text",
769
- text: JSON.stringify({
770
- code,
771
- message,
772
- ...(value.availability ? { availability: value.availability } : {}),
773
- }),
774
- }],
775
- };
776
- }
777
- function skillPreviewResult(preview) {
778
- const details = preview.plan.details ?? {};
779
- return jsonResult({
780
- ...preview,
781
- ...details,
782
- plan: { ...preview.plan, ...details },
783
- });
784
- }
785
788
  function normalizeConnectionStatus(value) {
786
789
  if (!value || typeof value !== "object")
787
790
  return value;
@@ -836,13 +839,74 @@ function frameResult(value) {
836
839
  }
837
840
  export function createMcpServer(runtime, options = {}) {
838
841
  runtime.registerBuiltinSkills();
842
+ if (options.requireBuildAlignment) {
843
+ const assertAlignment = () => assertRequiredBuildAlignment(runtime, options);
844
+ options = {
845
+ ...options,
846
+ ...(options.nativeEditor
847
+ ? { nativeEditor: withBuildAlignmentGuard(options.nativeEditor, assertAlignment, ["capabilities"]) }
848
+ : {}),
849
+ ...(options.disposableNative
850
+ ? { disposableNative: withBuildAlignmentGuard(options.disposableNative, assertAlignment) }
851
+ : {}),
852
+ ...(options.nativeOperationSession
853
+ ? { nativeOperationSession: withBuildAlignmentGuard(options.nativeOperationSession, assertAlignment) }
854
+ : {}),
855
+ ...(options.projectPublisher
856
+ ? {
857
+ projectPublisher: withBuildAlignmentGuard(options.projectPublisher, assertAlignment, ["isAvailable", "inspectReadiness", "executionMode", "getPublishJob", "loadPublishJob"]),
858
+ }
859
+ : {}),
860
+ ...(options.videoExporter
861
+ ? { videoExporter: withBuildAlignmentGuard(options.videoExporter, assertAlignment, ["isAvailable"]) }
862
+ : {}),
863
+ };
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
+ }
839
903
  const server = new McpServer({ name: "framekit", version: FRAMEKIT_VERSION }, { instructions: options.headlessProjects ? HEADLESS_FIRST_MCP_INSTRUCTIONS : EDITOR_FIRST_MCP_INSTRUCTIONS });
840
904
  const nativeTransitionAssets = new Map();
841
905
  const sessions = options.sessionDirectory
842
906
  ? new EditingSessionRepository(options.sessionDirectory, options.sessionChangeSource)
843
907
  : undefined;
844
908
  const materializations = sessions && options.materializationDirectory
845
- ? new SessionMaterializationJobs(options.materializationDirectory, sessions, options.sessionMaterializationPublisher)
909
+ ? new SessionMaterializationJobs(options.materializationDirectory, sessions, options.sessionMaterializationPublisher, options.canonicalRecovery)
846
910
  : undefined;
847
911
  const requireSessions = () => {
848
912
  if (!sessions)
@@ -955,7 +1019,11 @@ export function createMcpServer(runtime, options = {}) {
955
1019
  server.registerTool("session.materialize.execute", {
956
1020
  description: "Confirm, stage, checkpoint, and request publication of a versioned FCPXML project.",
957
1021
  inputSchema: { sessionId: z.string().min(1), target: sessionMaterializationTargetSchema, confirm: z.boolean() },
958
- }, 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
+ }));
959
1027
  server.registerTool("session.materialize.status", {
960
1028
  description: "Inspect a persisted materialization job after completion, blockage, or server restart.",
961
1029
  inputSchema: { jobId: z.string().min(1) },
@@ -963,7 +1031,11 @@ export function createMcpServer(runtime, options = {}) {
963
1031
  server.registerTool("session.materialize.retry", {
964
1032
  description: "Resume a retryable persisted materialization job with its verified immutable artifact.",
965
1033
  inputSchema: { jobId: z.string().min(1) },
966
- }, 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
+ }));
967
1039
  server.registerTool("session.materialize.resync", {
968
1040
  description: "Read the completed versioned handoff target and create a fresh editing-session baseline for continuation.",
969
1041
  inputSchema: { jobId: z.string().min(1), sessionId: z.string().min(1) },
@@ -972,71 +1044,111 @@ export function createMcpServer(runtime, options = {}) {
972
1044
  description: "Read Framekit's Final Cut connection state before editor-first capability discovery.",
973
1045
  inputSchema: {},
974
1046
  }, async () => jsonResult(await effectiveConnectionStatus(runtime, options)));
975
- server.registerTool("skill.list", {
976
- description: "List registered versioned Framekit Skills with current capability availability.",
1047
+ server.registerTool("editor.native.handoff.readiness", {
1048
+ description: "Read native Final Cut handoff readiness without launching, activating, importing, or mutating Final Cut.",
1049
+ inputSchema: { publishJobId: z.string().trim().min(1).optional() },
1050
+ }, async ({ publishJobId }) => jsonResult(await inspectNativeHandoffReadiness(runtime, options, publishJobId)));
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.",
977
1053
  inputSchema: {},
978
- }, async () => {
979
- try {
980
- return jsonResult((await runtime.listSkillAvailability()).map(({ manifest, availability }) => ({
981
- ...manifest,
982
- availability,
983
- })));
984
- }
985
- catch (error) {
986
- return skillErrorResult(error);
987
- }
988
- });
989
- server.registerTool("skill.inspect", {
990
- description: "Inspect one registered Framekit Skill version and its current capability availability.",
991
- inputSchema: { skill: z.string().min(1), version: z.string().min(1).optional() },
992
- }, 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;
993
1066
  try {
994
- const { manifest, availability } = await runtime.inspectSkillAvailability(skill, version);
995
- return jsonResult({ ...manifest, availability });
1067
+ evidence = await options.canonicalRecovery.inspectVersioned();
996
1068
  }
997
1069
  catch (error) {
998
- 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 };
999
1074
  }
1000
- });
1001
- server.registerTool("skill.preview", {
1002
- 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.",
1003
1081
  inputSchema: {
1004
- skill: z.string().min(1),
1005
- version: z.string().min(1).optional(),
1006
- arguments: z.record(z.unknown()),
1082
+ confirmHeadedRead: z.boolean().optional(),
1083
+ expectedTarget: contextTargetSchema.optional(),
1084
+ expectedCheckpointId: z.string().regex(/^[a-f0-9]{64}$/).optional(),
1007
1085
  },
1008
- }, 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;
1009
1094
  try {
1010
- const baseRevision = revisionValueSchema.parse(skillArguments.baseRevision);
1011
- const { baseRevision: _baseRevision, ...input } = skillArguments;
1012
- return skillPreviewResult(await runtime.previewSkill({
1013
- skillId: skill,
1014
- ...(version ? { version } : {}),
1015
- baseRevision,
1016
- input,
1017
- }));
1095
+ evidence = await options.canonicalRecovery.inspectVersioned();
1018
1096
  }
1019
1097
  catch (error) {
1020
- 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);
1021
1108
  }
1022
- });
1023
- server.registerTool("skill.execute", {
1024
- description: "Execute only a runtime-issued Skill preview token and return verification/rollback evidence.",
1025
- inputSchema: {
1026
- previewToken: z.string().min(1),
1027
- },
1028
- }, async ({ previewToken }) => {
1029
1109
  try {
1030
- 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);
1031
1133
  }
1032
1134
  catch (error) {
1033
- 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;
1034
1145
  }
1035
1146
  });
1147
+ registerSkillTools(server, runtime);
1036
1148
  server.registerTool("project.inspect", {
1037
1149
  description: "Read a bound session baseline or perform an explicit canonical project resync before editing.route selects a capability-checked path.",
1038
1150
  inputSchema: timelineReadbackSchema,
1039
- }, async ({ sessionId, requestedCanonical, finalVerification }) => {
1151
+ }, async ({ sessionId, requestedCanonical, finalVerification, confirmHeadedRead, expectedTarget }) => {
1040
1152
  if (sessionId) {
1041
1153
  const { stored, decision } = await prepareSessionReadback(sessionId, requestedCanonical, finalVerification);
1042
1154
  if (decision.route === "session" || decision.route === "fast-observation") {
@@ -1047,20 +1159,9 @@ export function createMcpServer(runtime, options = {}) {
1047
1159
  snapshot: stored.document.base,
1048
1160
  });
1049
1161
  }
1050
- const resynced = await canonicalResyncSession(sessionId, stored.document.provider?.id);
1051
- return jsonResult({ sessionId, readback: decision, ...resynced });
1052
- }
1053
- const inspected = await inspectMcpEditor(runtime, options);
1054
- const capability = inspected.capabilities.families.canonicalDocument.read;
1055
- if (!capability.available) {
1056
- return capabilityErrorResult("project.inspect", "canonicalDocument.read", capability);
1057
- }
1058
- try {
1059
- return jsonResult(await runtime.inspectProject());
1060
- }
1061
- catch (error) {
1062
- 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 }));
1063
1163
  }
1164
+ return inspectCanonicalReadForMcp(runtime, options, "project.inspect", confirmHeadedRead, expectedTarget, () => runtime.inspectProject(), (result) => ({ projectId: result.projectId, sequenceId: result.timeline.id }));
1064
1165
  });
1065
1166
  server.registerTool("artifact.inspect", {
1066
1167
  description: "Identify the managed FCPXML artifact used by the background artifact.edit and artifact.publish workflows.",
@@ -1122,6 +1223,10 @@ export function createMcpServer(runtime, options = {}) {
1122
1223
  expectedRevision: revisionValueSchema.optional(),
1123
1224
  },
1124
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)));
1125
1230
  server.registerTool("headless.edit.preview", {
1126
1231
  description: "Preview supported Framekit Timeline IR edits without persisting or mutating the project.",
1127
1232
  inputSchema: {
@@ -1148,6 +1253,10 @@ export function createMcpServer(runtime, options = {}) {
1148
1253
  expectedRevision,
1149
1254
  operations: operations,
1150
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)));
1151
1260
  const headlessRenderParametersSchema = z.object({
1152
1261
  outputPath: z.string().min(1),
1153
1262
  format: z.enum(["mp4", "mov"]),
@@ -1205,6 +1314,10 @@ export function createMcpServer(runtime, options = {}) {
1205
1314
  eventName: z.string().min(1).optional(),
1206
1315
  materialization: z.enum(["versioned", "reuse-existing"]).optional(),
1207
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)));
1208
1321
  const headlessRoughCutRequestSchema = z.object({
1209
1322
  projectId: z.string().min(1),
1210
1323
  sequenceId: z.string().min(1),
@@ -1287,7 +1400,11 @@ export function createMcpServer(runtime, options = {}) {
1287
1400
  editType: z.enum(EDITING_ROUTE_EDIT_TYPES).optional(),
1288
1401
  },
1289
1402
  }, async ({ operation, fallback, path, editType }) => {
1290
- const context = await editingRouteContext(runtime, options);
1403
+ const headlessOnly = fallback === "none"
1404
+ && (path === "headless" || (Boolean(options.headlessProjects) && operation === "timeline.edit" && path !== "headed"));
1405
+ const context = headlessOnly
1406
+ ? { connection: { state: "disconnected" }, ...headlessRoutingContext(options) }
1407
+ : await editingRouteContext(runtime, options);
1291
1408
  return jsonResult(resolveEditingRoute({
1292
1409
  operation,
1293
1410
  fallback,
@@ -1387,7 +1504,7 @@ export function createMcpServer(runtime, options = {}) {
1387
1504
  }, async ({ jobId }) => {
1388
1505
  if (!options.nativeOperationSession)
1389
1506
  throw new Error("CAPABILITY_UNAVAILABLE: native operation session is not configured");
1390
- return jsonResult(options.nativeOperationSession.status(jobId));
1507
+ return jsonResult(await options.nativeOperationSession.status(jobId));
1391
1508
  });
1392
1509
  server.registerTool("editor.native.operation.retry", {
1393
1510
  description: "Retry a waiting native Final Cut operation after the required headed session becomes ready.",
@@ -1500,11 +1617,18 @@ export function createMcpServer(runtime, options = {}) {
1500
1617
  return jsonResult(await options.nativeEditor.undo(operationId, { signal: extra.signal }));
1501
1618
  });
1502
1619
  server.registerTool("editor.native.media.search", {
1503
- 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.",
1504
1621
  inputSchema: { query: z.string().min(1) },
1505
1622
  }, async ({ query }, extra) => {
1506
1623
  if (!options.nativeEditor)
1507
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
+ }
1508
1632
  return jsonResult(await options.nativeEditor.searchMedia(query, { signal: extra.signal }));
1509
1633
  });
1510
1634
  server.registerTool("editor.native.media.select", {
@@ -1628,40 +1752,63 @@ export function createMcpServer(runtime, options = {}) {
1628
1752
  return nativeMutationResult(() => options.nativeEditor.executeTrimToDuration(previewToken, { signal: extra.signal }));
1629
1753
  });
1630
1754
  server.registerTool("artifact.publish.preview", {
1631
- description: "Prepare a verified FCPXML publish handoff without opening Final Cut; the configured native route may use non-activating document delivery or an explicit headed fallback.",
1755
+ description: "Prepare an experimental, opt-in native handoff from a verified artifact without opening Final Cut.",
1632
1756
  inputSchema: {
1633
1757
  artifactPath: z.string().trim().min(1),
1634
- transactionId: z.string().min(1),
1758
+ targetLibraryPath: z.string().trim().min(1),
1759
+ transactionId: z.string().min(1).optional(),
1760
+ headlessExecutionId: z.string().min(1).optional(),
1635
1761
  },
1636
- }, async ({ artifactPath, transactionId }) => {
1762
+ }, async ({ artifactPath, targetLibraryPath, transactionId, headlessExecutionId }) => {
1637
1763
  if (!options.projectPublisher)
1638
1764
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH and native writes");
1639
- const transaction = runtime.getTransaction(transactionId);
1640
- if (transaction.target?.kind !== "artifact" || transaction.target.artifactPath !== artifactPath) {
1641
- throw new Error(`PUBLISH_TARGET_MISMATCH: transaction ${transactionId} is not verified for artifact ${artifactPath}`);
1765
+ if (Boolean(transactionId) === Boolean(headlessExecutionId)) {
1766
+ throw new Error("PUBLISH_SOURCE_REQUIRED: provide exactly one of transactionId or headlessExecutionId");
1642
1767
  }
1643
- if (!transaction.artifactDigest) {
1644
- throw new Error(`PUBLISH_SOURCE_CHANGED: transaction ${transactionId} has no immutable artifact digest`);
1768
+ let sourceTransactionId;
1769
+ let artifactDigest;
1770
+ let sourceProof;
1771
+ if (headlessExecutionId) {
1772
+ sourceProof = await requireHeadlessProjects().verifyPublishableRoughCut(headlessExecutionId, artifactPath);
1773
+ sourceTransactionId = sourceProof.sourceTransactionId;
1774
+ artifactDigest = sourceProof.artifactDigest;
1645
1775
  }
1646
- const verification = await runtime.verifyTransaction(transactionId);
1647
- if (!verification.passed)
1648
- throw new Error(`FINAL_CUT_PUBLISH_VALIDATION_FAILED: source transaction ${transactionId} did not pass verification`);
1649
- return jsonResult(await options.projectPublisher.preparePublish({
1650
- sourceTransactionId: transactionId,
1776
+ else {
1777
+ const transaction = runtime.getTransaction(transactionId);
1778
+ if (transaction.target?.kind !== "artifact" || transaction.target.artifactPath !== artifactPath) {
1779
+ throw new Error(`PUBLISH_TARGET_MISMATCH: transaction ${transactionId} is not verified for artifact ${artifactPath}`);
1780
+ }
1781
+ if (!transaction.artifactDigest) {
1782
+ throw new Error(`PUBLISH_SOURCE_CHANGED: transaction ${transactionId} has no immutable artifact digest`);
1783
+ }
1784
+ const verification = await runtime.verifyTransaction(transactionId);
1785
+ if (!verification.passed)
1786
+ throw new Error(`FINAL_CUT_PUBLISH_VALIDATION_FAILED: source transaction ${transactionId} did not pass verification`);
1787
+ sourceTransactionId = transactionId;
1788
+ artifactDigest = transaction.artifactDigest;
1789
+ }
1790
+ const job = await options.projectPublisher.preparePublish({
1791
+ sourceTransactionId,
1651
1792
  artifactPath,
1652
- artifactDigest: transaction.artifactDigest,
1653
- }));
1793
+ artifactDigest,
1794
+ targetLibraryPath,
1795
+ });
1796
+ return jsonResult({ ...job, ...(sourceProof ? { sourceProof } : {}) });
1654
1797
  });
1655
1798
  server.registerTool("artifact.publish.execute", {
1656
- description: "Execute a prepared artifact publish job after explicit confirmation and return only a verified or resumable state.",
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.",
1657
1800
  inputSchema: {
1658
1801
  jobId: z.string().trim().min(1),
1659
1802
  confirm: z.literal(true),
1803
+ confirmVerification: z.boolean().optional(),
1660
1804
  },
1661
- }, async ({ jobId, confirm }) => {
1805
+ }, async ({ jobId, confirm, confirmVerification }) => {
1662
1806
  if (!options.projectPublisher)
1663
1807
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH and native writes");
1664
- return jsonResult(await options.projectPublisher.executePublishJob(jobId, confirm));
1808
+ if (!publishRouteIsGuarded && options.projectPublisher.isAvailable() && requiresHeadedPublishingRoute(options.projectPublisher)) {
1809
+ await requireEditingRoute(runtime, options, "timeline.publish.new-project");
1810
+ }
1811
+ return jsonResult(await options.projectPublisher.executePublishJob(jobId, confirm, confirmVerification));
1665
1812
  });
1666
1813
  server.registerTool("artifact.publish.status", {
1667
1814
  description: "Read the current state of a prepared artifact publish job without opening Final Cut or retrying it.",
@@ -1669,14 +1816,20 @@ export function createMcpServer(runtime, options = {}) {
1669
1816
  }, async ({ jobId }) => {
1670
1817
  if (!options.projectPublisher)
1671
1818
  throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH and native writes");
1672
- return jsonResult(options.projectPublisher.getPublishJob(jobId));
1819
+ return jsonResult(await options.projectPublisher.loadPublishJob(jobId));
1673
1820
  });
1674
1821
  server.registerTool("artifact.publish", {
1675
- description: "Import the validated FCPXML artifact as a new Final Cut project without replacing the active project; requires explicit confirmation.",
1822
+ description: "Experimental direct import; explicitly confirm both creation and headed readback for this artifact. Dispatch alone does not prove project creation.",
1676
1823
  inputSchema: artifactPublishInputSchema,
1677
- }, async ({ artifactPath, transactionId, confirm }) => {
1824
+ }, async ({ artifactPath, targetLibraryPath, transactionId, confirm, confirmVerification }) => {
1678
1825
  if (!options.projectPublisher)
1679
- throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH and native writes");
1826
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH, native writes, live project verification, and a target-binding provider");
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");
1832
+ }
1680
1833
  const transaction = runtime.getTransaction(transactionId);
1681
1834
  if (transaction.target?.kind !== "artifact" || transaction.target.artifactPath !== artifactPath) {
1682
1835
  throw new Error(`PUBLISH_TARGET_MISMATCH: transaction ${transactionId} is not verified for artifact ${artifactPath}`);
@@ -1691,15 +1844,28 @@ export function createMcpServer(runtime, options = {}) {
1691
1844
  sourceTransactionId: transactionId,
1692
1845
  artifactPath,
1693
1846
  artifactDigest: transaction.artifactDigest,
1847
+ targetLibraryPath,
1694
1848
  confirm,
1849
+ confirmVerification,
1695
1850
  }));
1696
1851
  });
1697
1852
  server.registerTool("timeline.publish.new-project", {
1698
- description: "Legacy alias for publishing a verified artifact transaction as a new Final Cut project.",
1699
- inputSchema: { transactionId: z.string().min(1) },
1700
- }, async ({ transactionId }) => {
1701
- if (!options.projectPublisher?.isAvailable())
1702
- throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH and native writes");
1853
+ description: "Experimental direct import of a verified artifact; explicitly confirm creation and headed readback before verified delivery.",
1854
+ inputSchema: {
1855
+ transactionId: z.string().min(1),
1856
+ targetLibraryPath: z.string().trim().min(1),
1857
+ confirm: z.literal(true),
1858
+ confirmVerification: z.boolean().optional(),
1859
+ },
1860
+ }, async ({ transactionId, targetLibraryPath, confirm, confirmVerification }) => {
1861
+ if (!options.projectPublisher)
1862
+ throw new Error("CAPABILITY_UNAVAILABLE: Final Cut project publishing requires FRAMEKIT_FCPXML_PATH, native writes, live project verification, and a target-binding provider");
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");
1868
+ }
1703
1869
  const transaction = runtime.getTransaction(transactionId);
1704
1870
  if (transaction.target?.kind !== "artifact") {
1705
1871
  throw new Error(`PUBLISH_TARGET_MISMATCH: transaction ${transactionId} is not verified for a managed artifact`);
@@ -1714,7 +1880,9 @@ export function createMcpServer(runtime, options = {}) {
1714
1880
  sourceTransactionId: transactionId,
1715
1881
  artifactPath: transaction.target.artifactPath,
1716
1882
  artifactDigest: transaction.artifactDigest,
1717
- confirm: true,
1883
+ targetLibraryPath,
1884
+ confirm,
1885
+ confirmVerification,
1718
1886
  }));
1719
1887
  });
1720
1888
  server.registerTool("timeline.export", {
@@ -1779,9 +1947,28 @@ export function createMcpServer(runtime, options = {}) {
1779
1947
  });
1780
1948
  });
1781
1949
  server.registerTool("context.inspect", {
1782
- description: "Read the queryable agent editing context and its current revision.",
1783
- inputSchema: {},
1784
- }, 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
+ }));
1785
1972
  server.registerTool("context.changes", {
1786
1973
  description: "Read incremental timeline, live-state, and native-asset changes after a context revision.",
1787
1974
  inputSchema: {
@@ -1830,7 +2017,7 @@ export function createMcpServer(runtime, options = {}) {
1830
2017
  server.registerTool("timeline.inspect", {
1831
2018
  description: "Read a bound session baseline or perform an explicit canonical timeline resync after canonical capability checks.",
1832
2019
  inputSchema: timelineReadbackSchema,
1833
- }, async ({ sessionId, requestedCanonical, finalVerification }) => {
2020
+ }, async ({ sessionId, requestedCanonical, finalVerification, confirmHeadedRead, expectedTarget }) => {
1834
2021
  if (sessionId) {
1835
2022
  const { stored, decision } = await prepareSessionReadback(sessionId, requestedCanonical, finalVerification);
1836
2023
  if (decision.route === "session" || decision.route === "fast-observation") {
@@ -1841,41 +2028,19 @@ export function createMcpServer(runtime, options = {}) {
1841
2028
  timeline: stored.document.base,
1842
2029
  });
1843
2030
  }
1844
- const resynced = await canonicalResyncSession(sessionId, stored.document.provider?.id);
1845
- return jsonResult({
1846
- sessionId,
1847
- readback: decision,
1848
- snapshot: resynced.snapshot.timeline,
1849
- session: resynced.session,
1850
- });
1851
- }
1852
- const inspected = await inspectMcpEditor(runtime, options);
1853
- const capability = inspected.capabilities.families.canonicalDocument.read;
1854
- if (!capability.available) {
1855
- return capabilityErrorResult("timeline.inspect", "canonicalDocument.read", capability);
1856
- }
1857
- try {
1858
- return jsonResult(await runtime.inspectTimeline());
1859
- }
1860
- catch (error) {
1861
- 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 }));
1862
2035
  }
2036
+ return inspectCanonicalReadForMcp(runtime, options, "timeline.inspect", confirmHeadedRead, expectedTarget, () => runtime.inspectTimeline(), (result) => ({ sequenceId: result.id }));
1863
2037
  });
1864
2038
  server.registerTool("timeline.semantic.inspect", {
1865
2039
  description: "Enrich timeline occurrences with source-range-bound semantic speech, visual, and metadata context without mutating the timeline.",
1866
2040
  inputSchema: timelineSemanticContextQuerySchema.shape,
1867
2041
  }, async (query) => {
1868
- const inspected = await inspectMcpEditor(runtime, options);
1869
- const capability = inspected.capabilities.families.canonicalDocument.read;
1870
- if (!capability.available) {
1871
- return capabilityErrorResult("timeline.semantic.inspect", "canonicalDocument.read", capability);
1872
- }
1873
- try {
1874
- return jsonResult(await runtime.inspectTimelineSemanticContext(query));
1875
- }
1876
- catch (error) {
1877
- return capabilityUnavailableErrorResult(error);
1878
- }
2042
+ const { confirmHeadedRead, expectedTarget, ...contextQuery } = query;
2043
+ return inspectCanonicalReadForMcp(runtime, options, "timeline.semantic.inspect", confirmHeadedRead, expectedTarget, () => runtime.inspectTimelineSemanticContext(contextQuery), (result) => ({ sequenceId: result.timelineId }));
1879
2044
  });
1880
2045
  server.registerTool("timeline.frame.capture", {
1881
2046
  description: "Capture an image at an exact timeline position with project, sequence, clip, and optional visual-analysis metadata.",
@@ -1916,13 +2081,28 @@ export function createMcpServer(runtime, options = {}) {
1916
2081
  },
1917
2082
  }, async ({ mediaId, range }) => jsonResult(await runtime.analyzeVisual(mediaId, range)));
1918
2083
  server.registerTool("media.understand", {
1919
- description: "Return combined speech, audio, and visual understanding for one media item.",
1920
- inputSchema: { mediaId: z.string().min(1) },
1921
- }, async ({ mediaId }) => jsonResult(await runtime.understandMedia(mediaId)));
2084
+ description: "Return combined speech, audio, and visual understanding for one media item in the selected editor project or a named headless project.",
2085
+ inputSchema: { mediaId: z.string().min(1), projectId: z.string().min(1).optional() },
2086
+ }, async ({ mediaId, projectId }) => {
2087
+ if (!projectId)
2088
+ return jsonResult(await runtime.understandMedia(mediaId));
2089
+ return sessionResult(async () => {
2090
+ const project = await requireHeadlessProjects().open(projectId);
2091
+ return runtime.understandMediaInProject(mediaId, projectSnapshotFromTimelineIr(project.timeline));
2092
+ });
2093
+ });
1922
2094
  server.registerTool("rough-cut.plan", {
1923
- description: "Create a deterministic, explainable, read-only shot plan from analyzed media; does not mutate the timeline.",
2095
+ description: "Create a deterministic, explainable, read-only shot plan from analyzed editor or named headless project media; does not mutate the timeline.",
1924
2096
  inputSchema: roughCutPlanSchema.shape,
1925
- }, async (request) => jsonResult(await runtime.planRoughCut(request)));
2097
+ }, async (request) => {
2098
+ const { projectId, ...planRequest } = request;
2099
+ if (!projectId)
2100
+ return jsonResult(await runtime.planRoughCut(planRequest));
2101
+ return sessionResult(async () => {
2102
+ const project = await requireHeadlessProjects().open(projectId);
2103
+ return runtime.planRoughCutInProject(planRequest, projectSnapshotFromTimelineIr(project.timeline));
2104
+ });
2105
+ });
1926
2106
  server.registerTool("editor.assets", {
1927
2107
  description: "Search installed transitions, effects, titles, generators, and templates; filesystem discovery is the default and native Browser discovery is explicit.",
1928
2108
  inputSchema: {
@@ -1942,6 +2122,18 @@ export function createMcpServer(runtime, options = {}) {
1942
2122
  sequence: z.number().int().nonnegative().optional(),
1943
2123
  },
1944
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
+ }
1945
2137
  const project = projectId && sequenceId && revision
1946
2138
  ? undefined
1947
2139
  : await runtime.inspectProject();
@@ -2309,7 +2501,7 @@ async function effectiveConnectionStatus(runtime, options) {
2309
2501
  ...status,
2310
2502
  state: "unavailable",
2311
2503
  lastError: {
2312
- code: "CAPABILITY_UNAVAILABLE",
2504
+ code: message.match(/\bFRAMEKIT_[A-Z_]+\b/)?.[0] ?? "CAPABILITY_UNAVAILABLE",
2313
2505
  message: `effective runtime capability inspection failed: ${message}`,
2314
2506
  },
2315
2507
  identity: undefined,
@@ -2318,15 +2510,68 @@ async function effectiveConnectionStatus(runtime, options) {
2318
2510
  });
2319
2511
  }
2320
2512
  }
2321
- async function inspectMcpEditor(runtime, options) {
2322
- 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 });
2559
+ const fingerprint = options.buildFingerprint ?? FRAMEKIT_BUILD_FINGERPRINT;
2560
+ const buildAlignment = assessBuildAlignment(fingerprint, inspected.identity.buildFingerprint, options.validationCommit);
2561
+ if (options.requireBuildAlignment && buildAlignment.status !== "matched") {
2562
+ throw new Error(`FRAMEKIT_BUILD_ALIGNMENT_MISMATCH: ${buildAlignment.message}`);
2563
+ }
2323
2564
  const native = options.nativeEditor?.capabilities();
2324
- const publishingAvailable = Boolean(options.projectPublisher && (typeof options.projectPublisher.isAvailable !== "function" || options.projectPublisher.isAvailable()));
2325
- const publishingMode = publishingAvailable
2565
+ const processMode = options.processMode ?? (native ? "headed" : "headless");
2566
+ const configuredPublisher = Boolean(options.projectPublisher && (typeof options.projectPublisher.isAvailable !== "function" || options.projectPublisher.isAvailable()));
2567
+ const publisherExecutionMode = configuredPublisher
2326
2568
  ? (typeof options.projectPublisher?.executionMode === "function"
2327
2569
  ? options.projectPublisher.executionMode()
2328
2570
  : "headed-only")
2329
2571
  : "unavailable";
2572
+ const publishingAvailable = configuredPublisher && (publisherExecutionMode === "background-capable"
2573
+ || processMode === "headed");
2574
+ const publishingMode = publishingAvailable ? publisherExecutionMode : "unavailable";
2330
2575
  const exportAvailable = Boolean(options.videoExporter?.isAvailable());
2331
2576
  const backgroundExportAvailable = Boolean(options.backgroundRenderer?.isAvailable());
2332
2577
  const capabilities = withCapabilityFamilies({
@@ -2335,6 +2580,7 @@ async function inspectMcpEditor(runtime, options) {
2335
2580
  ...inspected.capabilities.editor,
2336
2581
  artifactPublish: publishingAvailable,
2337
2582
  artifactPublishMode: publishingMode,
2583
+ ...(publishingAvailable ? { artifactPublishDispatchGuarantee: "requested-unverified" } : {}),
2338
2584
  ...(publishingAvailable ? {} : { timelinePublishNewProject: false }),
2339
2585
  videoExport: exportAvailable,
2340
2586
  backgroundRender: backgroundExportAvailable,
@@ -2369,6 +2615,7 @@ async function inspectMcpEditor(runtime, options) {
2369
2615
  },
2370
2616
  publishing: publishingAvailable,
2371
2617
  publishingBackend: publishingMode === "background-capable" ? "fcpxml-document-open" : "fcpxml-publisher",
2618
+ publishingGuarantee: "native-verified",
2372
2619
  export: exportAvailable,
2373
2620
  exportBackend: "final-cut-native-export",
2374
2621
  backgroundExport: {
@@ -2399,14 +2646,569 @@ async function inspectMcpEditor(runtime, options) {
2399
2646
  },
2400
2647
  preflight: {
2401
2648
  ...createCapabilityPreflight(inspected.identity, capabilities, {
2402
- processMode: options.processMode ?? (native ? "headed" : "headless"),
2649
+ processMode,
2403
2650
  nativeWrite: Boolean(native?.selectionEdit),
2404
2651
  }),
2405
- fingerprint: options.buildFingerprint ?? FRAMEKIT_BUILD_FINGERPRINT,
2652
+ fingerprint,
2653
+ buildAlignment,
2654
+ nativeHandoffReadiness: await createNativeHandoffReadiness(options.projectPublisher, buildAlignment),
2406
2655
  },
2407
2656
  ...(native ? { native } : {}),
2408
2657
  };
2409
2658
  }
2659
+ async function inspectNativeHandoffReadiness(runtime, options, publishJobId) {
2660
+ const fingerprint = options.buildFingerprint ?? FRAMEKIT_BUILD_FINGERPRINT;
2661
+ let extensionFingerprint;
2662
+ try {
2663
+ extensionFingerprint = (await runtime.inspectEditor({ probeCanonicalSnapshot: false })).identity.buildFingerprint;
2664
+ }
2665
+ catch {
2666
+ const status = await connectionStatus(options).catch(() => undefined);
2667
+ extensionFingerprint = status?.identity?.buildFingerprint;
2668
+ }
2669
+ const buildAlignment = assessBuildAlignment(fingerprint, extensionFingerprint, options.validationCommit);
2670
+ return createNativeHandoffReadiness(options.projectPublisher, buildAlignment, publishJobId);
2671
+ }
2672
+ async function createNativeHandoffReadiness(publisher, buildAlignment, publishJobId) {
2673
+ const publisherReadiness = inspectProjectPublisherReadiness(publisher);
2674
+ const reasons = [...publisherReadiness.reasons];
2675
+ if (buildAlignment.status !== "matched") {
2676
+ reasons.push({
2677
+ code: buildAlignment.status === "mismatched"
2678
+ ? "FRAMEKIT_BUILD_ALIGNMENT_MISMATCH"
2679
+ : "FRAMEKIT_BUILD_ALIGNMENT_MISSING",
2680
+ message: `Workflow Extension build alignment is ${buildAlignment.status}: ${buildAlignment.message}`,
2681
+ });
2682
+ }
2683
+ let publish;
2684
+ let verifiedTarget;
2685
+ if (publishJobId) {
2686
+ if (!publisher || typeof publisher.getPublishJob !== "function") {
2687
+ reasons.push({
2688
+ code: "FINAL_CUT_PUBLISH_JOB_UNAVAILABLE",
2689
+ message: `Publish job ${publishJobId} cannot be inspected because the publisher is unavailable`,
2690
+ });
2691
+ }
2692
+ else {
2693
+ try {
2694
+ const job = typeof publisher.loadPublishJob === "function"
2695
+ ? await publisher.loadPublishJob(publishJobId)
2696
+ : publisher.getPublishJob(publishJobId);
2697
+ publish = { jobId: job.jobId, state: job.state };
2698
+ const resultTarget = job.result?.createdTarget;
2699
+ const targetMatches = job.createdTarget
2700
+ && resultTarget
2701
+ && nativeTargetIdentityMatches(job.createdTarget, resultTarget);
2702
+ if (job.state === "verified" && job.result?.verified === true && targetMatches) {
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
+ }
2724
+ }
2725
+ else {
2726
+ reasons.push({
2727
+ code: "FINAL_CUT_PUBLISH_TARGET_UNVERIFIED",
2728
+ message: job.error?.message
2729
+ ? `Publish job ${job.jobId} is ${job.state}; native project and sequence IDs remain withheld: ${job.error.message}`
2730
+ : `Publish job ${job.jobId} is ${job.state}; native project and sequence IDs are reported only after native readback verifies them`,
2731
+ });
2732
+ }
2733
+ }
2734
+ catch (error) {
2735
+ const message = error instanceof Error ? error.message : String(error);
2736
+ reasons.push({
2737
+ code: "FINAL_CUT_PUBLISH_JOB_UNAVAILABLE",
2738
+ message: `Publish job ${publishJobId} could not be inspected: ${message}`,
2739
+ });
2740
+ }
2741
+ }
2742
+ }
2743
+ const ready = reasons.length === 0;
2744
+ return {
2745
+ status: ready ? (publishJobId ? "verified" : "ready") : "blocked",
2746
+ reasons,
2747
+ targetBinding: {
2748
+ available: publisherReadiness.targetBindingAvailable,
2749
+ guarantee: publisherReadiness.targetBindingAvailable ? "native-readback" : "none",
2750
+ },
2751
+ buildAlignment,
2752
+ ...(publish ? { publish } : {}),
2753
+ ...(ready && verifiedTarget ? { createdTarget: verifiedTarget } : {}),
2754
+ };
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
+ }
2763
+ function inspectProjectPublisherReadiness(publisher) {
2764
+ if (!publisher) {
2765
+ return {
2766
+ available: false,
2767
+ targetBindingAvailable: false,
2768
+ reasons: [{
2769
+ code: "FINAL_CUT_PUBLISH_PROVIDER_UNAVAILABLE",
2770
+ message: "No Final Cut project publisher is configured",
2771
+ }],
2772
+ };
2773
+ }
2774
+ if (typeof publisher.inspectReadiness === "function")
2775
+ return publisher.inspectReadiness();
2776
+ // Keep older injected publisher implementations fail-closed but inspectable.
2777
+ const available = typeof publisher.isAvailable === "function" && publisher.isAvailable();
2778
+ return {
2779
+ available,
2780
+ targetBindingAvailable: available,
2781
+ reasons: available ? [] : [{
2782
+ code: "FINAL_CUT_PUBLISH_TARGET_BINDING_UNAVAILABLE",
2783
+ message: "Native publisher readiness or target-binding provider is unavailable",
2784
+ }],
2785
+ };
2786
+ }
2787
+ async function assertRequiredBuildAlignment(runtime, options) {
2788
+ const inspected = await runtime.inspectEditor({ probeCanonicalSnapshot: false });
2789
+ const fingerprint = options.buildFingerprint ?? FRAMEKIT_BUILD_FINGERPRINT;
2790
+ const alignment = assessBuildAlignment(fingerprint, inspected.identity.buildFingerprint, options.validationCommit);
2791
+ if (alignment.status !== "matched") {
2792
+ throw new Error(`FRAMEKIT_BUILD_ALIGNMENT_MISMATCH: ${alignment.message}`);
2793
+ }
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
+ }
3198
+ function withBuildAlignmentGuard(provider, assertAlignment, synchronousMethods = []) {
3199
+ const synchronous = new Set(synchronousMethods);
3200
+ return new Proxy(provider, {
3201
+ get(target, property) {
3202
+ const value = Reflect.get(target, property, target);
3203
+ if (typeof value !== "function" || synchronous.has(property))
3204
+ return value;
3205
+ return async (...args) => {
3206
+ await assertAlignment();
3207
+ return Reflect.apply(value, target, args);
3208
+ };
3209
+ },
3210
+ });
3211
+ }
2410
3212
  function requireArtifactTransaction(runtime, transactionId, artifactPath) {
2411
3213
  const transaction = runtime.getTransaction(transactionId);
2412
3214
  const target = transaction.target;
@@ -2428,6 +3230,9 @@ async function requireEditingRoute(runtime, options, operation, path, editType)
2428
3230
  throw new Error(`${route.reason.code}: ${route.reason.message}`);
2429
3231
  }
2430
3232
  }
3233
+ function requiresHeadedPublishingRoute(publisher) {
3234
+ return publisher.executionMode() !== "background-capable";
3235
+ }
2431
3236
  async function editingRouteContext(runtime, options) {
2432
3237
  const connection = await effectiveConnectionStatus(runtime, options);
2433
3238
  let nativeReadiness;
@@ -2449,18 +3254,19 @@ async function editingRouteContext(runtime, options) {
2449
3254
  return {
2450
3255
  connection,
2451
3256
  ...(editor ? { editor } : {}),
2452
- ...(options.headlessProjects ? {
2453
- headless: {
2454
- available: true,
2455
- backend: "framekit-project-store",
2456
- guarantee: "canonical-write",
2457
- // Advertise only concrete Timeline IR edit capabilities. The legacy
2458
- // timeline.edit surface also accepts operations that the headless
2459
- // transaction layer does not implement.
2460
- supportedOperations: HEADLESS_TIMELINE_EDIT_TYPES.map((editType) => `timeline.edit:${editType}`),
2461
- },
2462
- } : {}),
3257
+ ...headlessRoutingContext(options),
2463
3258
  ...(options.nativeEditor ? { native: { ...options.nativeEditor.capabilities() } } : {}),
2464
3259
  ...(nativeReadiness ? { nativeReadiness } : {}),
2465
3260
  };
2466
3261
  }
3262
+ function headlessRoutingContext(options) {
3263
+ return options.headlessProjects ? {
3264
+ headless: {
3265
+ available: true,
3266
+ backend: "framekit-project-store",
3267
+ guarantee: "canonical-write",
3268
+ // The legacy timeline.edit surface also includes unsupported operations.
3269
+ supportedOperations: HEADLESS_TIMELINE_EDIT_TYPES.map((editType) => `timeline.edit:${editType}`),
3270
+ },
3271
+ } : {};
3272
+ }