@morshoto/framekit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +67 -0
  2. package/bin/framekit.mjs +26 -0
  3. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +116 -0
  4. package/dist-package/adapters/final-cut/typescript/src/assets.js +112 -0
  5. package/dist-package/adapters/final-cut/typescript/src/connection.js +379 -0
  6. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +282 -0
  7. package/dist-package/adapters/final-cut/typescript/src/export.js +382 -0
  8. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +503 -0
  9. package/dist-package/adapters/final-cut/typescript/src/index.js +11 -0
  10. package/dist-package/adapters/final-cut/typescript/src/live.js +415 -0
  11. package/dist-package/adapters/final-cut/typescript/src/native-operation.js +18 -0
  12. package/dist-package/adapters/final-cut/typescript/src/native.js +3134 -0
  13. package/dist-package/adapters/final-cut/typescript/src/publisher.js +102 -0
  14. package/dist-package/adapters/final-cut/typescript/src/session.js +171 -0
  15. package/dist-package/apps/cli/src/main.js +130 -0
  16. package/dist-package/apps/mcp-server/src/main.js +146 -0
  17. package/dist-package/apps/mcp-server/src/server.js +617 -0
  18. package/dist-package/packages/runtime/src/capabilities.js +24 -0
  19. package/dist-package/packages/runtime/src/context/context-engine.js +142 -0
  20. package/dist-package/packages/runtime/src/diff/diff.js +145 -0
  21. package/dist-package/packages/runtime/src/domain/types.js +1 -0
  22. package/dist-package/packages/runtime/src/editing/intent.js +83 -0
  23. package/dist-package/packages/runtime/src/index.js +8 -0
  24. package/dist-package/packages/runtime/src/runtime.js +890 -0
  25. package/dist-package/packages/runtime/src/snapshot-digest.js +24 -0
  26. package/dist-package/packages/runtime/src/speech/filler-removal.js +87 -0
  27. package/dist-package/packages/runtime/src/verification/verification.js +113 -0
  28. package/dist-package/packages/testkit/src/fixture-analyzers.js +39 -0
  29. package/dist-package/packages/testkit/src/in-memory-editor.js +520 -0
  30. package/dist-package/packages/testkit/src/index.js +2 -0
  31. package/package.json +64 -0
@@ -0,0 +1,379 @@
1
+ import { execFile as execFileCallback } from "node:child_process";
2
+ import { access, cp, mkdir, rename, rm } from "node:fs/promises";
3
+ import { existsSync } from "node:fs";
4
+ import { promisify } from "node:util";
5
+ import { homedir } from "node:os";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import { createFinalCutLiveAdapter, DEFAULT_FINAL_CUT_LIVE_SOCKET } from "./live.js";
8
+ const execFile = promisify(execFileCallback);
9
+ const DEFAULT_EXTENSION_NAME = "FramekitFinalCutWorkflow.app";
10
+ /**
11
+ * Owns the user-facing lifecycle around the native Workflow Extension.
12
+ * The live adapter remains the source of truth for Final Cut state; this class
13
+ * only installs, activates, probes, and reconnects the bridge.
14
+ */
15
+ export class FinalCutConnectionManager {
16
+ socketPath;
17
+ headless;
18
+ extensionSourcePath;
19
+ extensionInstallPath;
20
+ finalCutApp;
21
+ pollIntervalMs;
22
+ startupTimeoutMs;
23
+ activationRetryIntervalMs;
24
+ detectFinalCut;
25
+ launchFinalCut;
26
+ installExtensionAction;
27
+ launchExtension;
28
+ registerExtension;
29
+ activateExtension;
30
+ restartFinalCut;
31
+ restartAfterInstall;
32
+ probe;
33
+ sleep;
34
+ status;
35
+ attempt;
36
+ interval;
37
+ constructor(options = {}) {
38
+ this.socketPath = options.socketPath ?? process.env.FRAMEKIT_FINAL_CUT_SOCKET ?? DEFAULT_FINAL_CUT_LIVE_SOCKET;
39
+ this.headless = options.headless ?? process.env.FRAMEKIT_FINAL_CUT_HEADLESS === "1";
40
+ this.extensionInstallPath = options.extensionInstallPath
41
+ ?? process.env.FRAMEKIT_EXTENSION_INSTALL_PATH
42
+ ?? join(homedir(), "Applications", DEFAULT_EXTENSION_NAME);
43
+ this.extensionSourcePath = options.extensionSourcePath
44
+ ?? process.env.FRAMEKIT_EXTENSION_APP_PATH
45
+ ?? (existsSync(this.extensionInstallPath) ? undefined : defaultExtensionSourcePath());
46
+ this.finalCutApp = options.finalCutApp ?? "/Applications/Final Cut Pro.app";
47
+ this.pollIntervalMs = options.pollIntervalMs ?? 5_000;
48
+ this.startupTimeoutMs = options.startupTimeoutMs ?? 20_000;
49
+ this.activationRetryIntervalMs = 2_000;
50
+ this.detectFinalCut = options.detectFinalCut ?? (() => defaultDetectFinalCut(this.finalCutApp));
51
+ this.launchFinalCut = options.launchFinalCut ?? (() => defaultLaunchFinalCut(this.finalCutApp));
52
+ this.installExtensionAction = options.installExtension ?? (() => this.installExtensionIfAvailable());
53
+ // Final Cut must host the Workflow Extension. Opening the container app
54
+ // directly can create an unhosted extension process that never publishes
55
+ // the bridge socket, so the default launch action is intentionally a no-op.
56
+ this.launchExtension = options.launchExtension ?? (async () => { });
57
+ this.registerExtension = options.registerExtension ?? (() => defaultRegisterExtension(this.extensionInstallPath));
58
+ this.activateExtension = options.activateExtension ?? ((activationOptions) => defaultActivateFinalCut(activationOptions));
59
+ this.restartAfterInstall = options.restartAfterInstall ?? false;
60
+ this.restartFinalCut = options.restartFinalCut ?? (() => defaultRestartFinalCut(this.detectFinalCut, this.launchFinalCut, this.sleep));
61
+ this.probe = options.probe ?? defaultProbe(this.socketPath);
62
+ this.sleep = options.sleep ?? ((milliseconds) => new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds)));
63
+ this.status = {
64
+ state: "disconnected",
65
+ editorDetected: false,
66
+ extensionInstalled: false,
67
+ extensionPath: this.extensionInstallPath,
68
+ socketPath: this.socketPath,
69
+ updatedAt: new Date().toISOString(),
70
+ };
71
+ }
72
+ getStatus() {
73
+ return structuredClone(this.status);
74
+ }
75
+ startAutoConnect() {
76
+ if (this.interval)
77
+ return;
78
+ void this.ensureConnected();
79
+ this.interval = setInterval(() => void this.ensureConnected(), this.pollIntervalMs);
80
+ }
81
+ stopAutoConnect() {
82
+ if (this.interval)
83
+ clearInterval(this.interval);
84
+ this.interval = undefined;
85
+ }
86
+ async ensureConnected() {
87
+ if (this.attempt)
88
+ return this.attempt;
89
+ this.attempt = this.connect().finally(() => {
90
+ this.attempt = undefined;
91
+ });
92
+ return this.attempt;
93
+ }
94
+ async connect() {
95
+ try {
96
+ this.update({ state: "detecting", lastError: undefined });
97
+ const existing = await this.tryProbe();
98
+ if (existing)
99
+ return this.ready(existing);
100
+ if (this.headless) {
101
+ return this.fail("FINAL_CUT_HEADLESS_SOCKET_UNAVAILABLE", `Headless mode only probes the existing Workflow Extension socket at ${this.socketPath}; it does not launch or activate Final Cut Pro`, "unavailable");
102
+ }
103
+ const editorDetected = await this.detectFinalCut();
104
+ this.update({ editorDetected });
105
+ if (!editorDetected) {
106
+ this.update({ state: "launching" });
107
+ await this.launchFinalCut();
108
+ const deadline = Date.now() + Math.min(5_000, this.startupTimeoutMs);
109
+ while (Date.now() < deadline && !(await this.detectFinalCut())) {
110
+ await this.sleep(250);
111
+ }
112
+ const detectedAfterLaunch = await this.detectFinalCut();
113
+ this.update({ editorDetected: detectedAfterLaunch });
114
+ if (!detectedAfterLaunch) {
115
+ return this.fail("FINAL_CUT_NOT_RUNNING", "Final Cut Pro could not be launched", "unavailable");
116
+ }
117
+ }
118
+ const installed = await pathExists(this.extensionInstallPath);
119
+ this.update({ extensionInstalled: installed });
120
+ const shouldInstall = !installed
121
+ || (this.extensionSourcePath && resolve(this.extensionSourcePath) !== resolve(this.extensionInstallPath));
122
+ const extensionChanged = Boolean(shouldInstall);
123
+ if (shouldInstall) {
124
+ this.update({ state: "installing" });
125
+ await this.installExtensionAction();
126
+ }
127
+ const installedAfterSetup = await pathExists(this.extensionInstallPath);
128
+ this.update({ extensionInstalled: installedAfterSetup });
129
+ if (!installedAfterSetup) {
130
+ return this.fail("EXTENSION_NOT_INSTALLED", "Framekit's Final Cut Workflow Extension is not installed and no installable artifact was found", "needs-user-action");
131
+ }
132
+ if (extensionChanged)
133
+ await this.registerExtension();
134
+ if (this.restartAfterInstall && extensionChanged && editorDetected) {
135
+ this.update({ state: "restarting" });
136
+ await this.restartFinalCut();
137
+ this.update({ editorDetected: true });
138
+ }
139
+ this.update({ state: "launching" });
140
+ await this.launchExtension();
141
+ this.update({ state: "activating" });
142
+ const deadline = Date.now() + this.startupTimeoutMs;
143
+ await this.activateUntil(deadline);
144
+ this.update({ state: "waiting-for-socket" });
145
+ let nextActivationAt = Date.now() + this.activationRetryIntervalMs;
146
+ while (Date.now() < deadline) {
147
+ const result = await this.tryProbe();
148
+ if (result)
149
+ return this.ready(result);
150
+ if (Date.now() >= nextActivationAt) {
151
+ try {
152
+ await this.activateWithDeadline(deadline);
153
+ }
154
+ catch (error) {
155
+ if (isPermissionError(error))
156
+ throw error;
157
+ }
158
+ nextActivationAt = Date.now() + this.activationRetryIntervalMs;
159
+ }
160
+ await this.sleep(Math.min(250, Math.max(25, deadline - Date.now())));
161
+ }
162
+ return this.fail("FINAL_CUT_LIVE_TIMEOUT", `The Workflow Extension did not publish ${this.socketPath} within ${this.startupTimeoutMs}ms; Final Cut Pro may need to be reopened after installing the extension`, "unavailable");
163
+ }
164
+ catch (error) {
165
+ const message = String(error);
166
+ const code = isPermissionError(error)
167
+ ? "MACOS_PERMISSION_REQUIRED"
168
+ : message.match(/\bFINAL_CUT_[A-Z_]+\b/)?.[0] ?? "FINAL_CUT_CONNECTION_FAILED";
169
+ const state = code === "MACOS_PERMISSION_REQUIRED" || code === "FINAL_CUT_RESTART_TIMEOUT"
170
+ ? "needs-user-action"
171
+ : "unavailable";
172
+ return this.fail(code, message, state);
173
+ }
174
+ }
175
+ async tryProbe() {
176
+ try {
177
+ return await this.probe();
178
+ }
179
+ catch {
180
+ return undefined;
181
+ }
182
+ }
183
+ ready(result) {
184
+ this.update({
185
+ state: "ready",
186
+ editorDetected: true,
187
+ extensionInstalled: true,
188
+ identity: result.identity,
189
+ capabilities: result.capabilities,
190
+ lastError: undefined,
191
+ });
192
+ return this.getStatus();
193
+ }
194
+ fail(code, message, state) {
195
+ this.update({ state, lastError: { code, message } });
196
+ return this.getStatus();
197
+ }
198
+ update(patch) {
199
+ this.status = {
200
+ ...this.status,
201
+ ...patch,
202
+ updatedAt: new Date().toISOString(),
203
+ };
204
+ }
205
+ async activateUntil(deadline) {
206
+ let lastError;
207
+ while (Date.now() < deadline) {
208
+ try {
209
+ await this.activateWithDeadline(deadline);
210
+ return;
211
+ }
212
+ catch (error) {
213
+ if (isPermissionError(error))
214
+ throw error;
215
+ lastError = error;
216
+ await this.sleep(Math.min(250, Math.max(25, deadline - Date.now())));
217
+ }
218
+ }
219
+ const detail = lastError ? ` (${String(lastError)})` : "";
220
+ throw new Error(`FINAL_CUT_ACTIVATION_TIMEOUT: Framekit extension menu was not available before the connection deadline${detail}`);
221
+ }
222
+ async activateWithDeadline(deadline) {
223
+ const remainingMs = deadline - Date.now();
224
+ if (remainingMs <= 0)
225
+ throw new Error("FINAL_CUT_ACTIVATION_TIMEOUT: Framekit extension activation deadline expired");
226
+ const controller = new AbortController();
227
+ let timer;
228
+ let timedOut = false;
229
+ const activation = Promise.resolve().then(() => this.activateExtension({ signal: controller.signal, timeoutMs: remainingMs }));
230
+ const timeout = new Promise((_, reject) => {
231
+ timer = setTimeout(() => {
232
+ timedOut = true;
233
+ controller.abort();
234
+ reject(new Error("FINAL_CUT_ACTIVATION_TIMEOUT: Framekit extension activation exceeded the connection deadline"));
235
+ }, remainingMs);
236
+ });
237
+ try {
238
+ await Promise.race([activation, timeout]);
239
+ }
240
+ catch (error) {
241
+ if (timedOut || isActivationTimeout(error)) {
242
+ throw new Error(`FINAL_CUT_ACTIVATION_TIMEOUT: Framekit extension activation did not complete (${String(error)})`);
243
+ }
244
+ throw error;
245
+ }
246
+ finally {
247
+ if (timer !== undefined)
248
+ clearTimeout(timer);
249
+ if (!timedOut)
250
+ controller.abort();
251
+ void activation.catch(() => { });
252
+ }
253
+ }
254
+ async installExtensionIfAvailable() {
255
+ if (!this.extensionSourcePath)
256
+ return;
257
+ const source = resolve(this.extensionSourcePath);
258
+ const destination = resolve(this.extensionInstallPath);
259
+ if (source === destination)
260
+ return;
261
+ if (!(await pathExists(source)))
262
+ return;
263
+ const staging = `${destination}.staging-${process.pid}`;
264
+ await rm(staging, { recursive: true, force: true });
265
+ await mkdir(dirname(destination), { recursive: true });
266
+ await cp(source, staging, { recursive: true, force: true });
267
+ const backup = `${destination}.previous-${Date.now()}`;
268
+ let backedUp = false;
269
+ try {
270
+ if (await pathExists(destination)) {
271
+ await rename(destination, backup);
272
+ backedUp = true;
273
+ }
274
+ await rename(staging, destination);
275
+ if (backedUp)
276
+ await rm(backup, { recursive: true, force: true });
277
+ }
278
+ catch (error) {
279
+ await rm(staging, { recursive: true, force: true });
280
+ if (backedUp && !(await pathExists(destination)))
281
+ await rename(backup, destination);
282
+ throw error;
283
+ }
284
+ }
285
+ }
286
+ function defaultProbe(socketPath) {
287
+ const adapter = createFinalCutLiveAdapter(socketPath);
288
+ return async () => ({
289
+ identity: await adapter.getIdentity(),
290
+ capabilities: await adapter.getCapabilities(),
291
+ });
292
+ }
293
+ async function defaultDetectFinalCut(appPath) {
294
+ try {
295
+ await access(appPath);
296
+ const result = await execFile("pgrep", ["-f", `${appPath}/Contents/MacOS/Final Cut Pro`]);
297
+ return result.stdout.trim().length > 0;
298
+ }
299
+ catch {
300
+ return false;
301
+ }
302
+ }
303
+ async function defaultLaunchFinalCut(appPath) {
304
+ if (appPath === "/Applications/Final Cut Pro.app") {
305
+ await execFile("open", ["-a", "Final Cut Pro"]);
306
+ return;
307
+ }
308
+ await execFile("open", [appPath]);
309
+ }
310
+ async function defaultRegisterExtension(extensionPath) {
311
+ const lsregister = "/System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/LaunchServices.framework/Versions/Current/Support/lsregister";
312
+ await execFile(lsregister, ["-f", "-R", "-trusted", extensionPath]);
313
+ }
314
+ async function defaultRestartFinalCut(detectFinalCut, launchFinalCut, sleep) {
315
+ await execFile("osascript", ["-e", 'quit app "Final Cut Pro"']);
316
+ const quitDeadline = Date.now() + 15_000;
317
+ while (await detectFinalCut()) {
318
+ if (Date.now() >= quitDeadline) {
319
+ throw new Error("FINAL_CUT_RESTART_TIMEOUT: Final Cut Pro did not quit; close it and retry");
320
+ }
321
+ await sleep(250);
322
+ }
323
+ // Reuse the configured launcher so tests and nonstandard app paths remain
324
+ // injectable; the default launcher opens the Final Cut Pro application.
325
+ const launchDeadline = Date.now() + 15_000;
326
+ let lastLaunchError;
327
+ while (Date.now() < launchDeadline) {
328
+ try {
329
+ await launchFinalCut();
330
+ lastLaunchError = undefined;
331
+ }
332
+ catch (error) {
333
+ lastLaunchError = error;
334
+ }
335
+ if (await detectFinalCut())
336
+ return;
337
+ await sleep(500);
338
+ }
339
+ const detail = lastLaunchError ? ` (${String(lastLaunchError)})` : "";
340
+ throw new Error(`FINAL_CUT_RESTART_TIMEOUT: Final Cut Pro did not reopen; open it and retry${detail}`);
341
+ }
342
+ async function defaultActivateFinalCut(options = {}) {
343
+ const script = [
344
+ 'tell application "System Events"',
345
+ 'tell process "Final Cut Pro"',
346
+ 'set frontmost to true',
347
+ 'click menu item "Framekit" of menu 1 of menu item "Extensions" of menu 1 of menu bar item "Window" of menu bar 1',
348
+ "end tell",
349
+ "end tell",
350
+ ].join("\n");
351
+ await execFile("osascript", ["-e", script], {
352
+ ...(options.signal ? { signal: options.signal } : {}),
353
+ ...(options.timeoutMs ? { timeout: options.timeoutMs } : {}),
354
+ });
355
+ }
356
+ async function pathExists(path) {
357
+ try {
358
+ await access(path);
359
+ return true;
360
+ }
361
+ catch {
362
+ return false;
363
+ }
364
+ }
365
+ function defaultExtensionSourcePath() {
366
+ const candidates = [
367
+ join("/Applications", DEFAULT_EXTENSION_NAME),
368
+ join(process.cwd(), "resources", DEFAULT_EXTENSION_NAME),
369
+ ];
370
+ return candidates.find((candidate) => existsSync(candidate));
371
+ }
372
+ function isPermissionError(error) {
373
+ const message = String(error);
374
+ return message.includes("not authorized") || message.includes("Automation");
375
+ }
376
+ function isActivationTimeout(error) {
377
+ const message = String(error);
378
+ return message.includes("-1712") || message.includes("ETIMEDOUT") || message.includes("timed out");
379
+ }
@@ -0,0 +1,282 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { canonicalSnapshotDigest, diffSnapshots, } from "../../../../packages/runtime/src/index.js";
3
+ /**
4
+ * Composes one guarded native UI edit with a canonical snapshot provider.
5
+ * Native UI is the mutation surface; canonical snapshots are the proof surface.
6
+ */
7
+ export class DisposableNativeEditWorkflow {
8
+ options;
9
+ previews = new Map();
10
+ operations = new Map();
11
+ now;
12
+ previewTtlMs;
13
+ maxOperations;
14
+ constructor(options) {
15
+ this.options = options;
16
+ this.now = options.now ?? Date.now;
17
+ this.previewTtlMs = options.previewTtlMs ?? 30_000;
18
+ this.maxOperations = options.maxOperations ?? 100;
19
+ if (!Number.isInteger(this.maxOperations) || this.maxOperations < 1) {
20
+ throw new Error("INVALID_OPERATION: disposable native maxOperations must be a positive integer");
21
+ }
22
+ }
23
+ async preview(request) {
24
+ validateRequest(request);
25
+ const before = await this.readCanonical("preview");
26
+ if (request.baseRevision && !sameRevision(request.baseRevision, before.revision)) {
27
+ throw new Error("STALE_CONTEXT: disposable native preview base revision does not match current canonical state");
28
+ }
29
+ const target = before.timeline.clips.find((clip) => clip.id === request.clipId);
30
+ if (!target)
31
+ throw new Error(`TARGET_MISMATCH: canonical target occurrence was not found: ${request.clipId}`);
32
+ if (target.name === request.name) {
33
+ throw new Error("INVALID_OPERATION: disposable native rename must change the target name");
34
+ }
35
+ const nativeTarget = await this.assertNativeTarget(before, target.name);
36
+ const previewToken = `disposable-native-preview-${randomToken()}`;
37
+ const expiresAt = this.now() + this.previewTtlMs;
38
+ this.prunePreviews();
39
+ this.previews.set(previewToken, { request: structuredClone(request), before, nativeTarget, expiresAt });
40
+ return {
41
+ previewToken,
42
+ operation: { type: "rename-selected-clip", name: request.name },
43
+ target: { clipId: target.id, name: target.name },
44
+ baseRevision: structuredClone(before.revision),
45
+ expiresAt: new Date(expiresAt).toISOString(),
46
+ };
47
+ }
48
+ async execute(previewToken) {
49
+ const preview = this.previews.get(previewToken);
50
+ if (!preview)
51
+ throw new Error(`PREVIEW_TOKEN_INVALID: unknown or already used preview ${previewToken}`);
52
+ this.previews.delete(previewToken);
53
+ if (this.now() > preview.expiresAt)
54
+ throw new Error("PREVIEW_TOKEN_EXPIRED: disposable native preview has expired");
55
+ const current = await this.readCanonical("execute");
56
+ if (!sameRevision(preview.before.revision, current.revision)) {
57
+ throw new Error("STALE_CONTEXT: disposable native preview base revision does not match current canonical state");
58
+ }
59
+ const currentTarget = current.timeline.clips.find((clip) => clip.id === preview.request.clipId);
60
+ if (!currentTarget || currentTarget.name !== preview.before.timeline.clips.find((clip) => clip.id === preview.request.clipId)?.name) {
61
+ throw new Error("TARGET_MISMATCH: canonical target changed after disposable native preview");
62
+ }
63
+ await this.assertNativeTarget(current, currentTarget.name, preview.nativeTarget);
64
+ const native = await this.options.native.edit({ type: "rename-selected-clip", name: preview.request.name });
65
+ let after;
66
+ try {
67
+ after = await this.readCanonical("read-after-write");
68
+ }
69
+ catch (error) {
70
+ await this.compensate(native.operationId, preview.before, preview.request.clipId, error, "READ_AFTER_WRITE_FAILED");
71
+ throw new Error(`READ_AFTER_WRITE_FAILED: canonical state was restored (${String(error)})`);
72
+ }
73
+ const diff = diffSnapshots(preview.before, after);
74
+ const beforeDigest = canonicalSnapshotDigest(preview.before);
75
+ const afterDigest = canonicalSnapshotDigest(after);
76
+ const verification = verifyDisposableRename(preview.before, after, diff, preview.request);
77
+ if (!verification.passed) {
78
+ const restored = await this.compensate(native.operationId, preview.before, preview.request.clipId, verification, "VERIFICATION_FAILED");
79
+ return {
80
+ operationId: native.operationId,
81
+ previewToken,
82
+ operation: structuredClone(preview.request),
83
+ native,
84
+ before: preview.before,
85
+ after,
86
+ diff,
87
+ beforeDigest,
88
+ afterDigest,
89
+ verification,
90
+ status: "ROLLED_BACK",
91
+ undoAvailable: false,
92
+ restored,
93
+ restoredDigest: canonicalSnapshotDigest(restored),
94
+ };
95
+ }
96
+ this.pruneOperations();
97
+ this.operations.set(native.operationId, {
98
+ request: structuredClone(preview.request),
99
+ before: preview.before,
100
+ after,
101
+ beforeDigest,
102
+ operationId: native.operationId,
103
+ });
104
+ return {
105
+ operationId: native.operationId,
106
+ previewToken,
107
+ operation: structuredClone(preview.request),
108
+ native,
109
+ before: preview.before,
110
+ after,
111
+ diff,
112
+ beforeDigest,
113
+ afterDigest,
114
+ verification,
115
+ status: "VERIFIED",
116
+ undoAvailable: native.undoAvailable,
117
+ };
118
+ }
119
+ async undo(operationId) {
120
+ const operation = this.operations.get(operationId);
121
+ if (!operation)
122
+ throw new Error(`NATIVE_DISPOSABLE_UNDO_UNAVAILABLE: unknown operation ${operationId}`);
123
+ const current = await this.readCanonical("undo");
124
+ if (!sameRevision(current.revision, operation.after.revision)) {
125
+ throw new Error("STALE_CONTEXT: disposable native operation changed after execute");
126
+ }
127
+ if (current.projectId !== operation.before.projectId || current.timeline.id !== operation.before.timeline.id) {
128
+ throw new Error("TARGET_MISMATCH: disposable native operation target changed before undo");
129
+ }
130
+ const native = await this.options.native.undo(operationId);
131
+ if (!native.undone)
132
+ throw new Error("ROLLBACK_FAILED: native Undo did not report restoration");
133
+ let restored;
134
+ try {
135
+ restored = await this.readCanonical("undo read-after-write");
136
+ }
137
+ catch (error) {
138
+ throw new Error(`READ_AFTER_UNDO_FAILED: native Undo completed but canonical restoration could not be observed (${String(error)})`);
139
+ }
140
+ const restoredDigest = canonicalSnapshotDigest(restored);
141
+ const verification = verifyRestoration(operation.before, restored, operation.beforeDigest, operation.request.clipId);
142
+ if (!verification.passed) {
143
+ throw new Error(`ROLLBACK_FAILED: ${verification.checks.find((check) => !check.passed)?.detail ?? "canonical digest mismatch"}`);
144
+ }
145
+ this.operations.delete(operationId);
146
+ return {
147
+ operationId,
148
+ undone: true,
149
+ native,
150
+ restored,
151
+ beforeDigest: operation.beforeDigest,
152
+ restoredDigest,
153
+ verification,
154
+ };
155
+ }
156
+ async readCanonical(stage) {
157
+ const capabilities = await this.options.readCanonicalCapabilities().catch((error) => {
158
+ throw new Error(`CAPABILITY_UNAVAILABLE: disposable native canonical snapshot (${String(error)})`);
159
+ });
160
+ const editor = capabilities.editor;
161
+ if (editor.canonicalTimelineMode === "metadata-only"
162
+ || !editor.projectRead
163
+ || !editor.timelineSnapshotRead
164
+ || !editor.projectCatalogRead
165
+ || !editor.projectSelection) {
166
+ throw new Error(`CAPABILITY_UNAVAILABLE: disposable native canonical snapshot is unavailable during ${stage}`);
167
+ }
168
+ try {
169
+ return await this.options.readCanonicalSnapshot();
170
+ }
171
+ catch (error) {
172
+ throw new Error(`CAPABILITY_UNAVAILABLE: disposable native canonical snapshot (${String(error)})`);
173
+ }
174
+ }
175
+ async assertNativeTarget(snapshot, expectedName, previousTarget) {
176
+ const capabilities = this.options.native.capabilities();
177
+ assertNativeCapabilities(capabilities);
178
+ const context = await this.options.native.inspect();
179
+ if (!context.available || !context.frontmost || !context.timelineWindowAvailable || !context.timelineFocused) {
180
+ throw new Error("CAPABILITY_UNAVAILABLE: disposable native timeline preflight");
181
+ }
182
+ if (context.project && context.project !== snapshot.projectName) {
183
+ throw new Error("TARGET_MISMATCH: native project does not match canonical project");
184
+ }
185
+ if (context.sequence && context.sequence !== snapshot.timeline.name) {
186
+ throw new Error("TARGET_MISMATCH: native sequence does not match canonical timeline");
187
+ }
188
+ if (context.target.kind !== "selected-clip" || context.target.name !== expectedName) {
189
+ throw new Error("TARGET_MISMATCH: native selected clip does not match the canonical target");
190
+ }
191
+ if (previousTarget?.identity && context.target.identity && previousTarget.identity !== context.target.identity) {
192
+ throw new Error("TARGET_MISMATCH: native selected clip identity changed after disposable preview");
193
+ }
194
+ return context.target;
195
+ }
196
+ async compensate(operationId, before, clipId, cause, code) {
197
+ try {
198
+ const native = await this.options.native.undo(operationId);
199
+ if (!native.undone)
200
+ throw new Error("native Undo did not report restoration");
201
+ const restored = await this.readCanonical("compensating undo");
202
+ const verification = verifyRestoration(before, restored, canonicalSnapshotDigest(before), clipId);
203
+ if (!verification.passed)
204
+ throw new Error(verification.checks.find((check) => !check.passed)?.detail ?? "canonical digest mismatch");
205
+ return restored;
206
+ }
207
+ catch (rollbackError) {
208
+ throw new Error(`${code}: compensating native Undo failed (${String(cause)}; ${String(rollbackError)})`);
209
+ }
210
+ }
211
+ prunePreviews() {
212
+ const now = this.now();
213
+ for (const [token, preview] of this.previews) {
214
+ if (now > preview.expiresAt)
215
+ this.previews.delete(token);
216
+ }
217
+ }
218
+ pruneOperations() {
219
+ while (this.operations.size >= this.maxOperations) {
220
+ const oldestOperationId = this.operations.keys().next().value;
221
+ if (!oldestOperationId)
222
+ return;
223
+ this.operations.delete(oldestOperationId);
224
+ }
225
+ }
226
+ }
227
+ function validateRequest(request) {
228
+ if (!request.clipId.trim())
229
+ throw new Error("INVALID_OPERATION: disposable native clipId is required");
230
+ if (!request.name.trim())
231
+ throw new Error("INVALID_OPERATION: disposable native name is required");
232
+ }
233
+ function assertNativeCapabilities(capabilities) {
234
+ if (!capabilities.selectionEdit || !capabilities.undo) {
235
+ throw new Error("CAPABILITY_UNAVAILABLE: disposable native edit requires selection edit and Undo");
236
+ }
237
+ }
238
+ function verifyDisposableRename(before, after, diff, request) {
239
+ const beforeTarget = before.timeline.clips.find((clip) => clip.id === request.clipId);
240
+ const afterTarget = after.timeline.clips.find((clip) => clip.id === request.clipId);
241
+ const modifiedIds = diff.modified.map((change) => change.itemId);
242
+ const checks = [
243
+ {
244
+ name: "canonical-revision-advanced",
245
+ passed: after.revision.sequence > before.revision.sequence,
246
+ detail: `canonical revision ${before.revision.sequence} -> ${after.revision.sequence}`,
247
+ },
248
+ {
249
+ name: "target-renamed",
250
+ passed: Boolean(beforeTarget && afterTarget && beforeTarget.name !== afterTarget.name && afterTarget.name === request.name),
251
+ detail: afterTarget ? `observed target name ${afterTarget.name}` : "target occurrence is missing after native edit",
252
+ },
253
+ {
254
+ name: "deterministic-target-diff",
255
+ passed: diff.added.length === 0 && diff.removed.length === 0 && modifiedIds.length === 1 && modifiedIds[0] === request.clipId,
256
+ detail: `diff added=${diff.added.length}, removed=${diff.removed.length}, modified=${modifiedIds.join(",") || "none"}`,
257
+ },
258
+ ];
259
+ return { passed: checks.every((check) => check.passed), checks };
260
+ }
261
+ function verifyRestoration(before, restored, beforeDigest, clipId) {
262
+ const restoredDigest = canonicalSnapshotDigest(restored);
263
+ const checks = [
264
+ {
265
+ name: "canonical-digest-restored",
266
+ passed: restoredDigest === beforeDigest,
267
+ detail: `expected digest ${beforeDigest}, observed ${restoredDigest}`,
268
+ },
269
+ {
270
+ name: "canonical-target-restored",
271
+ passed: restored.timeline.clips.some((clip) => clip.id === clipId),
272
+ detail: `canonical target occurrence ${clipId} is present after native Undo`,
273
+ },
274
+ ];
275
+ return { passed: checks.every((check) => check.passed), checks };
276
+ }
277
+ function sameRevision(left, right) {
278
+ return left.id === right.id && left.sequence === right.sequence;
279
+ }
280
+ function randomToken() {
281
+ return randomUUID();
282
+ }