@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
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  <p align="center">
6
6
  <img src="https://img.shields.io/badge/Node.js-20%2B-339933?logo=node.js&logoColor=white" alt="Node.js 20 or newer" />
7
- <img src="https://img.shields.io/badge/pnpm-12.3.4-F69220?logo=pnpm&logoColor=white" alt="pnpm 12.3.4" />
7
+ <img src="https://img.shields.io/badge/pnpm-12.18.0-F69220?logo=pnpm&logoColor=white" alt="pnpm 12.18.0" />
8
8
  <img src="https://img.shields.io/badge/Final%20Cut%20Pro-macOS-000000?logo=apple&logoColor=white" alt="Final Cut Pro on macOS" />
9
9
  <a href="https://discord.gg/Dmp8FSF4vg"><img src="https://img.shields.io/badge/Discord-Join%20Chat-5865F2?logo=discord&logoColor=white" alt="Join the Framekit Discord" /></a>
10
10
  </p>
@@ -17,12 +17,16 @@ Agentic video editing runtime and MCP server for Final Cut Pro.
17
17
 
18
18
  For repository development, you need:
19
19
 
20
- - Node.js 20 or newer;
21
- - pnpm 12.3.4;
22
- - Xcode 16.4 and the macOS 15.5 SDK for native Final Cut work.
20
+ Contributor toolchain: Node.js 22.23.5 and pnpm 12.18.0.
21
+ Consumer runtime: Node.js >=20.
22
+ CI tests this contributor pair; the pre-commit hook accepts Node.js 22.23 or newer.
23
+ Install pnpm 12.18.0 using Corepack or your preferred package manager.
23
24
 
24
- The Xcode requirement is only needed for the native Workflow Extension. For the
25
- pinned Node and shell toolchain, enter the optional Nix shell first:
25
+ Xcode 16.4 and the macOS 15.5 SDK are required for native Final Cut work.
26
+
27
+ The Xcode requirement is only needed for the native Workflow Extension. The
28
+ optional Nix shell provides Node.js 22, pinned pnpm, FFmpeg/ffprobe, and SQLite
29
+ for fixture and headless work:
26
30
 
27
31
  ```sh
28
32
  nix develop ./nix
@@ -48,8 +52,8 @@ stdio. Start it from the repository root and connect it to an MCP client:
48
52
  pnpm run mcp
49
53
  ```
50
54
 
51
- See the [MCP tools](./docs/mcp/tools.md) and [MCP documentation](./docs/mcp/README.md)
52
- for the tool inventory and live-backend setup.
55
+ See [Getting started](./docs/getting-started.md) for local and live-backend
56
+ setup, and [Architecture](./docs/architecture.md) for capability boundaries.
53
57
 
54
58
  ## Connect Codex to Final Cut
55
59
 
@@ -66,10 +70,16 @@ Open `/plugins` in Codex, find **Framekit**, and select **Install**. Start a new
66
70
  Codex session to load the Framekit MCP tools. No repository checkout or manual
67
71
  `codex mcp add` is required.
68
72
 
69
- The plugin runs the published package in headless mode. It connects only to an
70
- existing Workflow Extension bridge and does not launch, activate, focus, or
71
- edit Final Cut through macOS UI automation. See the
72
- [first-run setup and capability boundaries](./docs/final-cut/installation.md).
73
+ The plugin runs the published package in headless mode. For live Final Cut
74
+ capabilities, it connects only to an existing Workflow Extension bridge and
75
+ does not launch, activate, focus, or edit Final Cut through macOS UI automation.
76
+ Framekit-owned video projects can register local media, analyze it, create an
77
+ approved rough-cut plan, and render a verified MP4 plus editable FCPXML without
78
+ a connected Final Cut session. Optional native publishing is experimental and
79
+ is not guaranteed in v0.1.18: a document-open dispatch does not prove that
80
+ Final Cut completed an import or created a native project. See the
81
+ [Codex video production runbook](./plugins/framekit/references/tests/codex-video-production-e2e.md)
82
+ and [first-run setup and capability boundaries](./docs/getting-started.md).
73
83
 
74
84
  For local native development, use the checkout's CLI wrapper from the repository
75
85
  root:
@@ -84,8 +94,9 @@ pnpm run framekit -- connect finalcut --development
84
94
 
85
95
  - [Documentation index](./docs/README.md)
86
96
  - [Getting started](./docs/getting-started.md)
87
- - [Architecture](./docs/ARCHITECTURE.md)
88
- - [Clean Codex and Claude Code MCP validation](./docs/tests/clean-mcp-clients.md)
97
+ - [Architecture](./docs/architecture.md)
98
+ - [Testing](./docs/testing.md)
99
+ - [Release](./docs/release.md)
89
100
 
90
101
  ## Development
91
102
 
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { spawn } from "node:child_process";
3
+ import { AsyncLocalStorage } from "node:async_hooks";
3
4
  import { readFile } from "node:fs/promises";
4
5
  import { timelineIrDigest, validateTimelineIr } from "../../../../packages/runtime/src/index.js";
5
6
  const DEFAULT_COMMAND_TIMEOUT_MS = 30_000;
@@ -10,6 +11,7 @@ const DEFAULT_COMMAND_TIMEOUT_MS = 30_000;
10
11
  */
11
12
  export class FinalCutBackgroundMaterializationPublisher {
12
13
  options;
14
+ dispatchContext = new AsyncLocalStorage();
13
15
  commandTimeoutMs;
14
16
  constructor(options = {}) {
15
17
  this.options = options;
@@ -21,8 +23,11 @@ export class FinalCutBackgroundMaterializationPublisher {
21
23
  isAvailable() {
22
24
  return this.options.executor !== undefined || Boolean(this.options.command?.trim());
23
25
  }
26
+ async trackNativeDispatch(operation, onDispatch) {
27
+ return this.dispatchContext.run(onDispatch, operation);
28
+ }
24
29
  async publish(request) {
25
- validateRequest(request);
30
+ validateFinalCutBackgroundMaterializationRequest(request);
26
31
  const executor = this.options.executor ?? (this.options.command?.trim()
27
32
  ? commandExecutor(this.options.command.trim(), this.commandTimeoutMs)
28
33
  : undefined);
@@ -41,11 +46,12 @@ export class FinalCutBackgroundMaterializationPublisher {
41
46
  if (timelineIrDigest(request.desired) !== request.desiredDigest) {
42
47
  throw new Error("MATERIALIZATION_DESIRED_SNAPSHOT_INVALID: the staged desired Timeline IR digest is invalid");
43
48
  }
49
+ this.dispatchContext.getStore()?.();
44
50
  const result = await executor({ ...request, desired: structuredClone(request.desired) });
45
51
  return validateResult(result);
46
52
  }
47
53
  }
48
- function validateRequest(request) {
54
+ export function validateFinalCutBackgroundMaterializationRequest(request) {
49
55
  if (!request.jobId.trim())
50
56
  throw new Error("MATERIALIZATION_REQUEST_INVALID: jobId is required");
51
57
  if (!request.artifactPath.trim() || !request.artifactDigest.trim()) {
@@ -0,0 +1,275 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { lstat, mkdir, open, readFile, unlink } from "node:fs/promises";
4
+ import { dirname } from "node:path";
5
+ import { inspectNativeRecoveryReadOnly, validRecoveryContext } from "./native-recovery-inspection.js";
6
+ /** A durable, exclusive checkpoint; unresolved checkpoints are never cleared automatically. */
7
+ export class FileCanonicalRecoveryGuard {
8
+ path;
9
+ owner;
10
+ constructor(path) {
11
+ this.path = path;
12
+ }
13
+ async assertClear() {
14
+ try {
15
+ await lstat(this.path);
16
+ }
17
+ catch (error) {
18
+ if (error.code === "ENOENT")
19
+ return;
20
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: cannot inspect recovery checkpoint", { cause: error });
21
+ }
22
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: unresolved canonical edit checkpoint exists");
23
+ }
24
+ /** Read native reservation and sender evidence without acquiring or modifying locks. */
25
+ async inspectNativeRecoveryEvidence() {
26
+ return inspectNativeRecoveryReadOnly(this.path);
27
+ }
28
+ /** Return evidence only; inspection never clears or claims recovery. */
29
+ async inspect() {
30
+ return (await this.inspectVersioned())?.checkpoint;
31
+ }
32
+ /** Inspect a direct native reservation without fabricating a canonical target. */
33
+ async inspectNativeReservation() {
34
+ let handle;
35
+ try {
36
+ handle = await open(this.path, constants.O_RDONLY | constants.O_NOFOLLOW);
37
+ const info = await handle.stat();
38
+ if (!info.isFile() || info.size > 16_384)
39
+ throw new Error("invalid reservation file");
40
+ const contents = await handle.readFile("utf8");
41
+ const record = JSON.parse(contents);
42
+ if ((record.version !== 2 && record.version !== 3) || record.kind !== "native-operation"
43
+ || typeof record.owner !== "string"
44
+ || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.owner)
45
+ || typeof record.operation !== "string" || !/^[a-z][a-z0-9.-]{0,127}$/.test(record.operation)
46
+ || (record.version === 3 && !validRecoveryContext(record.recoveryContext, record.operation))) {
47
+ throw new Error("invalid native reservation");
48
+ }
49
+ return { reservationId: createHash("sha256").update(contents).digest("hex"), operation: record.operation };
50
+ }
51
+ catch (error) {
52
+ if (error.code === "ENOENT")
53
+ return undefined;
54
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: cannot inspect native reservation", { cause: error });
55
+ }
56
+ finally {
57
+ await handle?.close();
58
+ }
59
+ }
60
+ /** Atomically reserve the same path used by canonical checkpoints. */
61
+ async beginNative(operation, context) {
62
+ if (!/^[a-z][a-z0-9.-]{0,127}$/.test(operation))
63
+ throw new Error("INVALID_OPERATION: invalid native reservation operation");
64
+ if (context && !validRecoveryContext(context, operation))
65
+ throw new Error("INVALID_OPERATION: invalid native recovery context");
66
+ await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
67
+ const owner = randomUUID();
68
+ let version = context ? 3 : 2;
69
+ let contents = JSON.stringify({ version, kind: "native-operation", owner, operation, ...(context ? { recoveryContext: context } : {}) }) + "\n";
70
+ let handle;
71
+ try {
72
+ handle = await open(this.path, "wx", 0o600);
73
+ await handle.writeFile(contents, "utf8");
74
+ await handle.sync();
75
+ await syncParentDirectory(this.path);
76
+ }
77
+ catch (error) {
78
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: cannot create exclusive native reservation", { cause: error });
79
+ }
80
+ finally {
81
+ await handle?.close();
82
+ }
83
+ let released = false;
84
+ let dispatchPossible = false;
85
+ let reservationId = createHash("sha256").update(contents).digest("hex");
86
+ let bindingStarted = false;
87
+ return { get reservationId() { return reservationId; }, markDispatchPossible: async () => {
88
+ if (released || dispatchPossible)
89
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: native dispatch boundary is unavailable");
90
+ // Mark first: even a failed or interrupted write must never authorize release.
91
+ dispatchPossible = true;
92
+ let marker;
93
+ try {
94
+ marker = await open(`${this.path}.dispatch-${reservationId}`, "wx", 0o600);
95
+ await marker.writeFile(JSON.stringify({ version: 1, reservationId, owner }) + "\n", "utf8");
96
+ await marker.sync();
97
+ await syncParentDirectory(this.path);
98
+ }
99
+ catch (error) {
100
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: cannot persist dispatch boundary", { cause: error });
101
+ }
102
+ finally {
103
+ await marker?.close();
104
+ }
105
+ }, bindRecoveryContext: async (newContext) => {
106
+ if (released || !dispatchPossible || version !== 2 || bindingStarted) {
107
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: native intent binding is unavailable");
108
+ }
109
+ // Binding is one-shot, including on error. Once provider code has run,
110
+ // no failure here may re-enable release or dispatch.
111
+ bindingStarted = true;
112
+ if (!validRecoveryContext(newContext, operation))
113
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: invalid native intent");
114
+ let recorded;
115
+ try {
116
+ recorded = structuredClone(newContext);
117
+ }
118
+ catch (error) {
119
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: cannot serialize native intent", { cause: error });
120
+ }
121
+ if (!validRecoveryContext(recorded, operation))
122
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: invalid serialized native intent");
123
+ const safeContext = recorded.kind === "publish"
124
+ ? { kind: recorded.kind, jobId: recorded.jobId, dispatchId: recorded.dispatchId,
125
+ requestedTarget: { libraryPath: recorded.requestedTarget.libraryPath }, artifactDigest: recorded.artifactDigest,
126
+ executorIdentity: null, nativeQuiescence: "unproven" }
127
+ : { kind: recorded.kind, jobId: recorded.jobId, dispatchId: recorded.dispatchId,
128
+ requestedTarget: { libraryUid: recorded.requestedTarget.libraryUid, eventUid: recorded.requestedTarget.eventUid,
129
+ projectUid: recorded.requestedTarget.projectUid, sequenceUid: recorded.requestedTarget.sequenceUid },
130
+ artifactDigest: recorded.artifactDigest, desiredDigest: recorded.desiredDigest,
131
+ ...(recorded.destination ? { destination: { mode: recorded.destination.mode, projectUid: recorded.destination.projectUid,
132
+ sequenceUid: recorded.destination.sequenceUid, projectName: recorded.destination.projectName,
133
+ sequenceName: recorded.destination.sequenceName } } : {}),
134
+ executorIdentity: null, nativeQuiescence: "unproven" };
135
+ const nextContents = JSON.stringify({ version: 3, kind: "native-operation", owner, operation, recoveryContext: safeContext }) + "\n";
136
+ if (Buffer.byteLength(nextContents) > 16_384)
137
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: native intent is too large");
138
+ const nextId = createHash("sha256").update(nextContents).digest("hex");
139
+ let marker;
140
+ let pending;
141
+ try {
142
+ // Persist the next identity's uncertainty marker before updating the
143
+ // reservation. A crash during the rewrite stays unknown and closed.
144
+ marker = await open(`${this.path}.dispatch-${nextId}`, "wx", 0o600);
145
+ await marker.writeFile(JSON.stringify({ version: 1, reservationId: nextId, owner }) + "\n", "utf8");
146
+ await marker.sync();
147
+ await syncParentDirectory(this.path);
148
+ pending = await open(this.path, constants.O_RDWR | constants.O_NOFOLLOW | constants.O_NONBLOCK);
149
+ const before = await pending.stat();
150
+ const current = await lstat(this.path);
151
+ if (!before.isFile() || !current.isFile() || before.dev !== current.dev || before.ino !== current.ino
152
+ || before.size > 16_384 || await pending.readFile("utf8") !== contents)
153
+ throw new Error("reservation ownership changed");
154
+ const data = Buffer.from(nextContents, "utf8");
155
+ let offset = 0;
156
+ while (offset < data.length) {
157
+ const { bytesWritten } = await pending.write(data, offset, data.length - offset, offset);
158
+ if (!bytesWritten)
159
+ throw new Error("short reservation write");
160
+ offset += bytesWritten;
161
+ }
162
+ await pending.truncate(data.length);
163
+ await pending.sync();
164
+ const after = await pending.stat();
165
+ const latest = await lstat(this.path);
166
+ if (!latest.isFile() || after.dev !== latest.dev || after.ino !== latest.ino)
167
+ throw new Error("reservation ownership changed");
168
+ contents = nextContents;
169
+ version = 3;
170
+ reservationId = nextId;
171
+ }
172
+ catch (error) {
173
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: cannot bind native intent", { cause: error });
174
+ }
175
+ finally {
176
+ await pending?.close();
177
+ await marker?.close();
178
+ }
179
+ }, release: async () => {
180
+ if (released)
181
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: native reservation was already released");
182
+ if (dispatchPossible)
183
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: native dispatch may have begun");
184
+ // Block dispatch immediately, including while the filesystem release is pending.
185
+ // A failed release remains closed instead of reopening the dispatch boundary.
186
+ released = true;
187
+ await this.completeOwned(owner, version);
188
+ } };
189
+ }
190
+ async inspectVersioned() {
191
+ let handle;
192
+ try {
193
+ handle = await open(this.path, constants.O_RDONLY | constants.O_NOFOLLOW);
194
+ const info = await handle.stat();
195
+ if (!info.isFile() || info.size > 16_384)
196
+ throw new Error("invalid checkpoint file");
197
+ const contents = await handle.readFile("utf8");
198
+ const record = JSON.parse(contents);
199
+ if (record.version !== 1 || typeof record.owner !== "string"
200
+ || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.owner)
201
+ || !record.checkpoint || typeof record.checkpoint !== "object" || Array.isArray(record.checkpoint)) {
202
+ throw new Error("invalid checkpoint record");
203
+ }
204
+ const checkpoint = record.checkpoint;
205
+ const { projectId, sequenceId, baseRevision, beforeDigest, operation, expectedRestoreDigest } = checkpoint;
206
+ if (typeof projectId !== "string" || !projectId.trim()
207
+ || typeof sequenceId !== "string" || !sequenceId.trim()
208
+ || typeof baseRevision !== "string" || !baseRevision.trim()
209
+ || typeof beforeDigest !== "string" || !/^[a-f0-9]{64}$/i.test(beforeDigest)
210
+ || typeof operation !== "string" || !["rename-clip", "trim-clip", "add-marker", "ripple-delete", "set-gain", "undo"].includes(operation)
211
+ || (expectedRestoreDigest !== undefined && (typeof expectedRestoreDigest !== "string" || !/^[a-f0-9]{64}$/i.test(expectedRestoreDigest)))) {
212
+ throw new Error("incomplete checkpoint evidence");
213
+ }
214
+ return {
215
+ checkpointId: createHash("sha256").update(contents).digest("hex"),
216
+ checkpoint: { projectId, sequenceId, baseRevision, beforeDigest, operation,
217
+ ...(typeof expectedRestoreDigest === "string" ? { expectedRestoreDigest } : {}) },
218
+ };
219
+ }
220
+ catch (error) {
221
+ if (error.code === "ENOENT")
222
+ return undefined;
223
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: cannot inspect recovery evidence", { cause: error });
224
+ }
225
+ finally {
226
+ await handle?.close();
227
+ }
228
+ }
229
+ async begin(checkpoint) {
230
+ await mkdir(dirname(this.path), { recursive: true, mode: 0o700 });
231
+ let handle;
232
+ try {
233
+ handle = await open(this.path, "wx", 0o600);
234
+ const owner = randomUUID();
235
+ await handle.writeFile(JSON.stringify({ version: 1, owner, checkpoint }) + "\n", "utf8");
236
+ await handle.sync();
237
+ this.owner = owner;
238
+ }
239
+ catch (error) {
240
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: cannot create exclusive recovery checkpoint", { cause: error });
241
+ }
242
+ finally {
243
+ await handle?.close();
244
+ }
245
+ }
246
+ async complete() {
247
+ if (!this.owner)
248
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: checkpoint ownership is unavailable");
249
+ await this.completeOwned(this.owner, 1);
250
+ this.owner = undefined;
251
+ }
252
+ async completeOwned(owner, version) {
253
+ try {
254
+ const info = await lstat(this.path);
255
+ if (!info.isFile() || info.isSymbolicLink())
256
+ throw new Error("invalid checkpoint");
257
+ const record = JSON.parse(await readFile(this.path, "utf8"));
258
+ if (record.version !== version || record.owner !== owner)
259
+ throw new Error("checkpoint ownership changed");
260
+ await unlink(this.path);
261
+ }
262
+ catch (error) {
263
+ throw new Error("FINAL_CUT_CANONICAL_RECOVERY_REQUIRED: cannot safely complete recovery checkpoint", { cause: error });
264
+ }
265
+ }
266
+ }
267
+ async function syncParentDirectory(path) {
268
+ const directory = await open(dirname(path), "r");
269
+ try {
270
+ await directory.sync();
271
+ }
272
+ finally {
273
+ await directory.close();
274
+ }
275
+ }