@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
@@ -21,6 +21,7 @@ const DEFAULT_EXTENSION_NAME = "FramekitFinalCutWorkflow.app";
21
21
  export class FinalCutConnectionManager {
22
22
  socketPath;
23
23
  headless;
24
+ existingSocketOnly;
24
25
  canonicalProviderRequired;
25
26
  extensionSourcePath;
26
27
  extensionInstallPath;
@@ -45,6 +46,7 @@ export class FinalCutConnectionManager {
45
46
  constructor(options = {}) {
46
47
  this.socketPath = options.socketPath ?? process.env.FRAMEKIT_FINAL_CUT_SOCKET ?? DEFAULT_FINAL_CUT_LIVE_SOCKET;
47
48
  this.headless = options.headless ?? process.env.FRAMEKIT_FINAL_CUT_HEADLESS === "1";
49
+ this.existingSocketOnly = options.existingSocketOnly ?? false;
48
50
  this.canonicalProviderRequired = options.canonicalProviderRequired
49
51
  ?? process.env.FRAMEKIT_FINAL_CUT_CANONICAL_REQUIRED === "1";
50
52
  this.extensionInstallPath = options.extensionInstallPath
@@ -107,8 +109,11 @@ export class FinalCutConnectionManager {
107
109
  this.update({ state: "detecting", lastError: undefined });
108
110
  const existing = await this.tryProbe();
109
111
  this.update({ extensionInstalled: await pathExists(this.extensionInstallPath) });
110
- if (existing.result && !this.installBeforeProbe)
112
+ if (existing.result && (this.existingSocketOnly || !this.installBeforeProbe))
111
113
  return this.ready(existing.result);
114
+ if (this.existingSocketOnly) {
115
+ return this.fail("FINAL_CUT_EXISTING_SOCKET_UNAVAILABLE", `No existing Workflow Extension responds at ${this.socketPath}; automatic setup is disabled`, "needs-user-action");
116
+ }
112
117
  if (this.canonicalProviderRequired && !existing.result) {
113
118
  return this.fail("FINAL_CUT_CANONICAL_PROVIDER_UNAVAILABLE", `Canonical live provider is unavailable at ${this.socketPath}; metadata-only fallback is disabled`, "needs-user-action");
114
119
  }
@@ -20,6 +20,12 @@ export class DisposableNativeEditWorkflow {
20
20
  throw new Error("INVALID_OPERATION: disposable native maxOperations must be a positive integer");
21
21
  }
22
22
  }
23
+ async trackNativeDispatch(operation, onDispatch) {
24
+ if (this.options.native.trackNativeDispatch)
25
+ return this.options.native.trackNativeDispatch(operation, onDispatch);
26
+ onDispatch();
27
+ return operation();
28
+ }
23
29
  async preview(request) {
24
30
  validateRequest(request);
25
31
  const before = await this.readCanonical("preview");
@@ -0,0 +1,8 @@
1
+ export * from "./sqlite-inspection.js";
2
+ export * from "./sqlite-wal-observation.js";
3
+ export * from "./sqlite-experiment.js";
4
+ export * from "./sqlite-materialization.js";
5
+ export * from "./shadow-mutation.js";
6
+ export * from "./fcpxml-console-experiment.js";
7
+ export * from "./unattended-editing.js";
8
+ export * from "./pasteboard-snapshot.js";
@@ -369,7 +369,9 @@ export class FcpxmlDocumentAdapter {
369
369
  case "ripple-delete":
370
370
  if (operation.timelineId !== timelineId)
371
371
  throw new Error(`TIMELINE_NOT_FOUND: ${operation.timelineId}`);
372
- this.applyRippleDelete(spine, operation.range.start, operation.range.end);
372
+ this.applyRippleDelete(spine, operation.range.start, operation.range.end, attribute(sequence, "duration") === undefined
373
+ ? rationalSeconds(timelineDuration(timelineEntries(spine)))
374
+ : rationalSeconds(parseRational(attribute(sequence, "duration"))));
373
375
  break;
374
376
  case "add-marker": {
375
377
  this.applyMarker(spine, timelineId, operation);
@@ -696,10 +698,13 @@ export class FcpxmlDocumentAdapter {
696
698
  throw new Error("INVALID_OPERATION: clip duration must fit the source");
697
699
  }
698
700
  }
699
- applyRippleDelete(spine, start, end) {
700
- if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || end <= start) {
701
+ applyRippleDelete(spine, start, end, sequenceDuration) {
702
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) {
701
703
  throw new Error("INVALID_OPERATION: ripple-delete range must be finite and increasing");
702
704
  }
705
+ if (start < 0 || end > sequenceDuration) {
706
+ throw new Error(`INVALID_OPERATION: ripple-delete range [${start}, ${end}) must fit timeline bounds [0, ${sequenceDuration})`);
707
+ }
703
708
  const direct = storyEntries(spine)
704
709
  .map(({ kind, node }) => timelineEntries(spine).find((entry) => entry.node === node && entry.kind === kind))
705
710
  .filter((entry) => entry !== undefined);
@@ -885,10 +890,13 @@ export class FcpxmlDocumentAdapter {
885
890
  const visual = pictureInPictureProperties(node);
886
891
  const fades = audioFadeProperties(node);
887
892
  const roleAttributeName = kind === "audio" ? "role" : kind === "asset-clip" ? "audioRole" : undefined;
888
- const roleAttribute = roleAttributeName === undefined ? undefined : attribute(node, roleAttributeName);
889
- const role = kind === "audio" || roleAttribute === "audio" || roleAttribute === "music"
893
+ const rawRoleAttribute = roleAttributeName === undefined ? undefined : attribute(node, roleAttributeName);
894
+ const roleAttribute = rawRoleAttribute === undefined ? undefined : String(rawRoleAttribute);
895
+ const audioRole = kind === "audio" || roleAttribute !== undefined
890
896
  ? audioRoleFromXml(node, roleAttributeName ?? "role")
891
897
  : undefined;
898
+ const isDialogue = roleAttribute === "dialogue" || roleAttribute?.startsWith("dialogue.");
899
+ const role = kind === "asset-clip" && isDialogue ? undefined : audioRole;
892
900
  const sourceStartValue = attribute(node, "start");
893
901
  const sourceStartTime = sourceStartValue === undefined ? undefined : parseRational(sourceStartValue);
894
902
  const sourceStart = sourceStartTime === undefined ? undefined : rationalSeconds(sourceStartTime);
@@ -903,6 +911,7 @@ export class FcpxmlDocumentAdapter {
903
911
  ...(sourceStart !== undefined ? { sourceStart, sourceStartTime } : {}),
904
912
  track: Number(attribute(node, "lane") ?? 0),
905
913
  ...(role !== undefined ? { role } : {}),
914
+ ...(isDialogue ? { nativeAudioRole: roleAttribute } : {}),
906
915
  ...(attribute(node, "framekit-attached-to") !== undefined ? { attachedTo: String(attribute(node, "framekit-attached-to")) } : {}),
907
916
  startTime,
908
917
  durationTime,
@@ -974,9 +983,11 @@ export class FcpxmlDocumentAdapter {
974
983
  const durationValue = attribute(node, "duration");
975
984
  const mediaKind = mediaKindFromResource(node);
976
985
  const originalMedia = storyEntries(node).find(({ kind, node: representation }) => kind === "media-rep" && attribute(representation, "kind") === "original-media")?.node;
986
+ const rawSource = attribute(node, "src") ?? (originalMedia && attribute(originalMedia, "src"));
987
+ const source = rawSource === undefined ? "" : String(rawSource);
977
988
  return {
978
989
  mediaId: String(attribute(node, "id") ?? ""),
979
- source: resolveMediaSource(String(attribute(node, "src") ?? (originalMedia && attribute(originalMedia, "src")) ?? attribute(node, "name") ?? attribute(node, "id") ?? ""), this.filePath),
990
+ source: source.trim() ? resolveMediaSource(source, this.filePath) : "",
980
991
  ...(mediaKind ? { mediaKind } : {}),
981
992
  ...(durationValue !== undefined ? { duration: parseSeconds(durationValue) } : {}),
982
993
  };
@@ -996,6 +1007,8 @@ export function resolveMediaSource(source, documentPath) {
996
1007
  return source;
997
1008
  }
998
1009
  }
1010
+ if (/^[a-z][a-z0-9+.-]*:/i.test(source))
1011
+ return source;
999
1012
  if (isAbsolute(source))
1000
1013
  return source;
1001
1014
  return resolve(dirname(documentPath), source);
@@ -1077,8 +1090,9 @@ function audioFadeProperties(node) {
1077
1090
  };
1078
1091
  }
1079
1092
  function audioRoleFromXml(node, attributeName = "role") {
1080
- const role = attribute(node, attributeName);
1081
- if (role === undefined || role === "audio")
1093
+ const value = attribute(node, attributeName);
1094
+ const role = value === undefined ? undefined : String(value);
1095
+ if (role === undefined || role === "audio" || /^dialogue(?:\.[^.]+)?$/.test(role))
1082
1096
  return "audio";
1083
1097
  if (role === "music")
1084
1098
  return "music";
@@ -16,13 +16,7 @@ export * from "./export.js";
16
16
  export * from "./background-export.js";
17
17
  export * from "./background-materialization.js";
18
18
  export * from "./library-inspection.js";
19
- export * from "./sqlite-inspection.js";
20
- export * from "./sqlite-wal-observation.js";
21
- export * from "./sqlite-experiment.js";
22
- export * from "./shadow-mutation.js";
23
19
  export * from "./native-operation.js";
24
20
  export * from "./native-session.js";
25
21
  export * from "./timeline-ir-fcpxml.js";
26
- export * from "./fcpxml-console-experiment.js";
27
- export * from "./unattended-editing.js";
28
- export * from "./pasteboard-snapshot.js";
22
+ export * from "./canonical-recovery-guard.js";
@@ -13,6 +13,8 @@ const READ_ONLY_LIVE_METHODS = new Set([
13
13
  "projects",
14
14
  "snapshot",
15
15
  ]);
16
+ // The extension waits up to five seconds for NSWorkspace's completion handler.
17
+ const DOCUMENT_DELIVERY_TIMEOUT_MS = 7_000;
16
18
  /** Newline-delimited JSON transport for the local Workflow Extension socket. */
17
19
  export class UnixSocketFinalCutLiveTransport {
18
20
  socketPath;
@@ -52,7 +54,7 @@ export class UnixSocketFinalCutLiveTransport {
52
54
  };
53
55
  const timer = setTimeout(() => {
54
56
  finish(() => reject(new Error(`FINAL_CUT_LIVE_TIMEOUT: ${this.socketPath}`)));
55
- }, this.timeoutMs);
57
+ }, request.method === "deliver-fcpxml" ? Math.max(this.timeoutMs, DOCUMENT_DELIVERY_TIMEOUT_MS) : this.timeoutMs);
56
58
  socket = createConnection(this.socketPath);
57
59
  socket.setEncoding("utf8");
58
60
  socket.on("connect", () => {
@@ -90,6 +92,7 @@ export class UnixSocketFinalCutLiveTransport {
90
92
  export class FinalCutLiveAdapter {
91
93
  transport;
92
94
  socketPath;
95
+ selectedTarget;
93
96
  constructor(transport, socketPath = "configured-socket") {
94
97
  this.transport = transport;
95
98
  this.socketPath = socketPath;
@@ -125,6 +128,11 @@ export class FinalCutLiveAdapter {
125
128
  throw new Error("FINAL_CUT_LIVE_PROTOCOL: snapshot response was empty");
126
129
  validateCanonicalSnapshot(response.snapshot);
127
130
  validateSnapshotTarget(response.snapshot, await this.listProjects());
131
+ if (this.selectedTarget
132
+ && (response.snapshot.projectId !== this.selectedTarget.projectId
133
+ || response.snapshot.timeline.id !== this.selectedTarget.sequenceId)) {
134
+ throw new Error("TARGET_MISMATCH: live canonical snapshot differs from the explicitly selected project and sequence");
135
+ }
128
136
  return response.snapshot;
129
137
  }
130
138
  async apply(operation, expectedRevision) {
@@ -133,6 +141,7 @@ export class FinalCutLiveAdapter {
133
141
  if (capabilities.editor.canonicalTimelineMode !== "canonical-write") {
134
142
  throw new Error("CAPABILITY_UNAVAILABLE: live Final Cut canonical mutation");
135
143
  }
144
+ await this.assertSelectedTargetActive();
136
145
  const response = await this.request({ method: "apply", operation, expectedRevision });
137
146
  if (!response.revision)
138
147
  throw new Error("FINAL_CUT_LIVE_PROTOCOL: apply response revision was empty");
@@ -148,6 +157,10 @@ export class FinalCutLiveAdapter {
148
157
  if (capabilities.editor.canonicalTimelineMode !== "canonical-write") {
149
158
  throw new Error("CAPABILITY_UNAVAILABLE: live Final Cut canonical rollback");
150
159
  }
160
+ await this.assertSelectedTargetActive();
161
+ if (this.selectedTarget && (snapshot.projectId !== this.selectedTarget.projectId || snapshot.timeline.id !== this.selectedTarget.sequenceId)) {
162
+ throw new Error("TARGET_MISMATCH: rollback snapshot differs from the explicitly selected project and sequence");
163
+ }
151
164
  await this.request({ method: "restore", snapshot, expectedRevision });
152
165
  }
153
166
  async readLiveState() {
@@ -204,7 +217,19 @@ export class FinalCutLiveAdapter {
204
217
  if (!response.revision)
205
218
  throw new Error("FINAL_CUT_LIVE_PROTOCOL: project selection response revision was empty");
206
219
  validateRevision(response.revision, "project selection response revision");
207
- return createProjectSelectionResult(response.catalog, selection, response.revision);
220
+ const result = createProjectSelectionResult(response.catalog, selection, response.revision);
221
+ this.selectedTarget = { ...result.observedActiveTarget };
222
+ return result;
223
+ }
224
+ async assertSelectedTargetActive() {
225
+ const selected = this.selectedTarget;
226
+ if (!selected)
227
+ return;
228
+ const catalog = await this.listProjects();
229
+ if (this.selectedTarget !== selected
230
+ || catalog.activeProjectId !== selected.projectId || catalog.activeSequenceId !== selected.sequenceId) {
231
+ throw new Error("TARGET_MISMATCH: active project and sequence differ from the explicitly selected target");
232
+ }
208
233
  }
209
234
  async request(input) {
210
235
  const response = await this.transport.request({
@@ -0,0 +1,175 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open } from "node:fs/promises";
4
+ import { isAbsolute, join } from "node:path";
5
+ function validPublishContext(value, operation) {
6
+ if (!value || typeof value !== "object" || Array.isArray(value))
7
+ return false;
8
+ const c = value;
9
+ const path = c.requestedTarget?.libraryPath;
10
+ return c.kind === "publish"
11
+ && typeof c.jobId === "string" && /^publish-job-[a-z0-9-]{1,80}$/.test(c.jobId)
12
+ && operation === `native.publish.${createHash("sha256").update(c.jobId).digest("hex")}`
13
+ && typeof c.dispatchId === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.dispatchId)
14
+ && typeof path === "string" && path.length <= 4096 && isAbsolute(path) && path.endsWith(".fcpbundle")
15
+ && typeof c.artifactDigest === "string" && /^[a-f0-9]{64}$/.test(c.artifactDigest)
16
+ && c.executorIdentity === null && c.nativeQuiescence === "unproven";
17
+ }
18
+ export function validRecoveryContext(value, operation) {
19
+ return validMaterializationContext(value, operation) || validPublishContext(value, operation);
20
+ }
21
+ function validRecoverableContext(value, operation) {
22
+ if (!value || typeof value !== "object" || Array.isArray(value))
23
+ return false;
24
+ const c = value;
25
+ if (typeof c.executorIdentity !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(c.executorIdentity)
26
+ || c.dispatchState !== "intent" || !/^[a-f0-9]{64}$/.test(c.expectedCanonicalDigest)
27
+ || (c.expectedRestoreDigest !== undefined && !/^[a-f0-9]{64}$/.test(c.expectedRestoreDigest))
28
+ || !validRecoveryContext({ ...c, executorIdentity: null }, operation))
29
+ return false;
30
+ const t = c.canonicalTarget;
31
+ if (!t || typeof t !== "object" || Array.isArray(t))
32
+ return false;
33
+ const keys = c.kind === "publish" ? ["libraryPath", "projectUid", "sequenceUid"] : ["libraryUid", "eventUid", "projectUid", "sequenceUid"];
34
+ if (Object.keys(t).length !== keys.length || !keys.every((key) => typeof t[key] === "string" && t[key].trim().length > 0 && t[key].length <= 1024))
35
+ return false;
36
+ if (c.kind === "publish")
37
+ return t.libraryPath === c.requestedTarget.libraryPath;
38
+ return keys.every((key) => t[key] === c.requestedTarget[key])
39
+ && c.expectedCanonicalDigest === c.desiredDigest;
40
+ }
41
+ function validMaterializationContext(value, operation) {
42
+ if (!value || typeof value !== "object" || Array.isArray(value))
43
+ return false;
44
+ const c = value;
45
+ const t = c.requestedTarget;
46
+ return c.kind === "materialization"
47
+ && typeof c.jobId === "string" && /^materialization-[a-z0-9-]{1,80}$/.test(c.jobId)
48
+ && operation === `native.materialize.${createHash("sha256").update(c.jobId).digest("hex")}`
49
+ && typeof c.dispatchId === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(c.dispatchId)
50
+ && Boolean(t && [t.libraryUid, t.eventUid, t.projectUid, t.sequenceUid].every((x) => typeof x === "string" && x.trim().length > 0 && x.length <= 1024))
51
+ && typeof c.artifactDigest === "string" && /^[a-f0-9]{64}$/.test(c.artifactDigest)
52
+ && typeof c.desiredDigest === "string" && /^[a-f0-9]{64}$/.test(c.desiredDigest)
53
+ && (c.destination === undefined || (c.destination.mode === "versioned" &&
54
+ [c.destination.projectUid, c.destination.sequenceUid, c.destination.projectName, c.destination.sequenceName]
55
+ .every((x) => typeof x === "string" && x.trim().length > 0 && x.length <= 1024)))
56
+ && c.executorIdentity === null && c.nativeQuiescence === "unproven";
57
+ }
58
+ const unknown = () => ({ status: "unknown", nativeQuiescence: "unproven", recoveryEligibility: "unavailable", sender: { status: "unknown" } });
59
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
60
+ /** Read a bounded regular file, refusing symlinks, replacement and in-place changes. */
61
+ async function readStable(path) {
62
+ let handle;
63
+ try {
64
+ handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
65
+ const before = await handle.stat();
66
+ if (!before.isFile() || before.size > 16_384)
67
+ throw new Error("invalid evidence file");
68
+ const data = await handle.readFile();
69
+ const after = await handle.stat();
70
+ const current = await lstat(path);
71
+ if (!current.isFile() || before.dev !== current.dev || before.ino !== current.ino || before.size !== after.size
72
+ || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || data.length !== after.size)
73
+ throw new Error("evidence changed");
74
+ return data.toString("utf8");
75
+ }
76
+ catch (error) {
77
+ if (error.code === "ENOENT")
78
+ return undefined;
79
+ throw error;
80
+ }
81
+ finally {
82
+ await handle?.close();
83
+ }
84
+ }
85
+ async function exists(path) {
86
+ try {
87
+ await lstat(path);
88
+ return true;
89
+ }
90
+ catch (error) {
91
+ if (error.code === "ENOENT")
92
+ return false;
93
+ throw error;
94
+ }
95
+ }
96
+ async function readSettlement(path, id) {
97
+ const directory = `${path}.sender-settled`;
98
+ try {
99
+ const info = await lstat(directory);
100
+ if (!info.isDirectory() || info.isSymbolicLink())
101
+ throw new Error("invalid sender directory");
102
+ return await readStable(join(directory, id));
103
+ }
104
+ catch (error) {
105
+ if (error.code === "ENOENT")
106
+ return undefined;
107
+ throw error;
108
+ }
109
+ }
110
+ function markerMatches(raw, reservationId) {
111
+ try {
112
+ const value = JSON.parse(raw);
113
+ return value !== null && value.reservationId === reservationId && typeof value.owner === "string" && uuid.test(value.owner);
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ }
119
+ /**
120
+ * Read-only, point-in-time observation; old writers do not share a lock, so even
121
+ * repeated reads cannot exclude concurrent changes or establish quiescence.
122
+ */
123
+ export async function inspectNativeRecoveryReadOnly(path) {
124
+ try {
125
+ if (await exists(`${path}.lock`))
126
+ return unknown();
127
+ const contents = await readStable(path);
128
+ const active = await readStable(`${path}.active`);
129
+ if (contents === undefined) {
130
+ if (active !== undefined || await exists(`${path}.lock`) || await readStable(path) !== undefined || await readStable(`${path}.active`) !== undefined)
131
+ return unknown();
132
+ return { status: "clear", nativeQuiescence: "unproven", recoveryEligibility: "unavailable", sender: { status: "unknown" } };
133
+ }
134
+ const record = JSON.parse(contents);
135
+ if (!record || typeof record !== "object" || Array.isArray(record) || ![2, 3, 4].includes(record.version)
136
+ || record.kind !== "native-operation" || typeof record.owner !== "string" || !uuid.test(record.owner)
137
+ || typeof record.operation !== "string" || !/^[a-z][a-z0-9.-]{0,127}$/.test(record.operation))
138
+ return unknown();
139
+ if (record.version === 3 && !validRecoveryContext(record.recoveryContext, record.operation))
140
+ return unknown();
141
+ if (record.version === 4 && !validRecoverableContext(record.recoveryContext, record.operation))
142
+ return unknown();
143
+ if (record.senderTracked !== undefined && typeof record.senderTracked !== "boolean")
144
+ return unknown();
145
+ const reservationId = createHash("sha256").update(contents).digest("hex");
146
+ const boundary = await readStable(`${path}.dispatch-${reservationId}`);
147
+ let boundaryEvidence = "unknown";
148
+ if (boundary !== undefined) {
149
+ try {
150
+ const marker = JSON.parse(boundary);
151
+ if (marker.version === 1 && marker.reservationId === reservationId && marker.owner === record.owner)
152
+ boundaryEvidence = "dispatch-possible-recorded";
153
+ }
154
+ catch { /* A damaged marker provides no proof. */ }
155
+ }
156
+ const settled = await readSettlement(path, reservationId);
157
+ const sender = record.senderTracked !== true ? (active !== undefined || settled !== undefined ? "unknown" : "untracked")
158
+ : active !== undefined ? (settled === undefined && markerMatches(active, reservationId) ? "active-or-interrupted" : "unknown")
159
+ : settled !== undefined && markerMatches(settled, reservationId) ? "sender-settled" : "unknown";
160
+ if (await exists(`${path}.lock`) || await readStable(path) !== contents || await readStable(`${path}.active`) !== active
161
+ || await readSettlement(path, reservationId) !== settled || await readStable(`${path}.dispatch-${reservationId}`) !== boundary)
162
+ return unknown();
163
+ const context = record.version === 3 || record.version === 4 ? record.recoveryContext : undefined;
164
+ return { status: "recovery-required", nativeQuiescence: "unproven", recoveryEligibility: "unavailable", sender: { status: sender },
165
+ dispatchState: "possibly-dispatched", boundaryEvidence, missingEvidence: ["receiver-terminal-quiescence", "independent-target-outcome", "legacy-writer-exclusion"],
166
+ safeNextActions: ["inspect", "retain-reservation"],
167
+ ...(context ? { intent: { requestedTarget: context.requestedTarget, artifactDigest: context.artifactDigest,
168
+ ...(context.kind === "materialization" ? { desiredDigest: context.desiredDigest, ...(context.destination ? { destination: context.destination } : {}) } : {}) } } : {}),
169
+ reservation: { version: record.version, reservationId, operation: record.operation,
170
+ ...(context ? { jobId: context.jobId, dispatchId: context.dispatchId, jobCorrelation: "unverified" } : {}) } };
171
+ }
172
+ catch {
173
+ return unknown();
174
+ }
175
+ }
@@ -281,14 +281,19 @@ export function createDisposableNativeOperationSession(options) {
281
281
  }
282
282
  },
283
283
  execute: async (request, context) => {
284
- const result = await options.workflow.execute(request.previewToken, {
284
+ const reservation = await options.recoveryGuard?.beginNative("native.job.disposable-rename");
285
+ // Trackers and workflows may defer work even after they return or fail.
286
+ // Persist uncertainty before invoking either and retain the reservation.
287
+ await reservation?.markDispatchPossible();
288
+ const invoke = () => options.workflow.execute(request.previewToken, {
285
289
  signal: context.signal,
286
- onMutationStart: context.markMutationStarted,
290
+ onMutationStart: () => { context.markMutationStarted(); },
287
291
  });
288
- return {
289
- outcome: result.status === "VERIFIED" ? "completed" : "rolled_back",
290
- evidence: disposableEvidence(result),
291
- };
292
+ const result = options.native.trackNativeDispatch
293
+ ? await options.native.trackNativeDispatch(invoke, () => { })
294
+ : await invoke();
295
+ const evidence = disposableEvidence(result);
296
+ return { outcome: result.status === "VERIFIED" ? "completed" : "rolled_back", evidence };
292
297
  },
293
298
  },
294
299
  });