@morshoto/framekit 0.1.18 → 0.2.3

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 (192) hide show
  1. package/README.md +17 -12
  2. package/dist-package/adapters/final-cut/typescript/src/analyzers.d.ts +58 -0
  3. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +52 -13
  4. package/dist-package/adapters/final-cut/typescript/src/assets.d.ts +24 -0
  5. package/dist-package/adapters/final-cut/typescript/src/background-export.d.ts +98 -0
  6. package/dist-package/adapters/final-cut/typescript/src/background-materialization.d.ts +47 -0
  7. package/dist-package/adapters/final-cut/typescript/src/background-materialization.js +8 -2
  8. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.d.ts +32 -0
  9. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery-guard.js +275 -0
  10. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery.d.ts +22 -0
  11. package/dist-package/adapters/final-cut/typescript/src/canonical-verification.d.ts +11 -0
  12. package/dist-package/adapters/final-cut/typescript/src/canonical.d.ts +184 -0
  13. package/dist-package/adapters/final-cut/typescript/src/canonical.js +571 -78
  14. package/dist-package/adapters/final-cut/typescript/src/connection.d.ts +103 -0
  15. package/dist-package/adapters/final-cut/typescript/src/connection.js +6 -1
  16. package/dist-package/adapters/final-cut/typescript/src/disposable-native.d.ts +90 -0
  17. package/dist-package/adapters/final-cut/typescript/src/disposable-native.js +6 -0
  18. package/dist-package/adapters/final-cut/typescript/src/documents.d.ts +3 -0
  19. package/dist-package/adapters/final-cut/typescript/src/documents.js +3 -0
  20. package/dist-package/adapters/final-cut/typescript/src/experimental.d.ts +8 -0
  21. package/dist-package/adapters/final-cut/typescript/src/experimental.js +8 -0
  22. package/dist-package/adapters/final-cut/typescript/src/export.d.ts +125 -0
  23. package/dist-package/adapters/final-cut/typescript/src/fcpxml-console-experiment.d.ts +54 -0
  24. package/dist-package/adapters/final-cut/typescript/src/fcpxml.d.ts +75 -0
  25. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +28 -9
  26. package/dist-package/adapters/final-cut/typescript/src/index.d.ts +22 -0
  27. package/dist-package/adapters/final-cut/typescript/src/index.js +1 -7
  28. package/dist-package/adapters/final-cut/typescript/src/library-inspection.d.ts +101 -0
  29. package/dist-package/adapters/final-cut/typescript/src/live.d.ts +101 -0
  30. package/dist-package/adapters/final-cut/typescript/src/live.js +35 -2
  31. package/dist-package/adapters/final-cut/typescript/src/media.d.ts +12 -0
  32. package/dist-package/adapters/final-cut/typescript/src/native-operation.d.ts +6 -0
  33. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.d.ts +77 -0
  34. package/dist-package/adapters/final-cut/typescript/src/native-recovery-inspection.js +175 -0
  35. package/dist-package/adapters/final-cut/typescript/src/native-session.d.ts +130 -0
  36. package/dist-package/adapters/final-cut/typescript/src/native-session.js +11 -6
  37. package/dist-package/adapters/final-cut/typescript/src/native.d.ts +828 -0
  38. package/dist-package/adapters/final-cut/typescript/src/native.js +475 -189
  39. package/dist-package/adapters/final-cut/typescript/src/pasteboard-snapshot.d.ts +114 -0
  40. package/dist-package/adapters/final-cut/typescript/src/publish-readback.d.ts +26 -0
  41. package/dist-package/adapters/final-cut/typescript/src/publish-readback.js +19 -2
  42. package/dist-package/adapters/final-cut/typescript/src/publisher.d.ts +215 -0
  43. package/dist-package/adapters/final-cut/typescript/src/publisher.js +255 -14
  44. package/dist-package/adapters/final-cut/typescript/src/session.d.ts +43 -0
  45. package/dist-package/adapters/final-cut/typescript/src/session.js +43 -13
  46. package/dist-package/adapters/final-cut/typescript/src/shadow-mutation.d.ts +51 -0
  47. package/dist-package/adapters/final-cut/typescript/src/sqlite-experiment.d.ts +156 -0
  48. package/dist-package/adapters/final-cut/typescript/src/sqlite-inspection.d.ts +134 -0
  49. package/dist-package/adapters/final-cut/typescript/src/sqlite-materialization.d.ts +110 -0
  50. package/dist-package/adapters/final-cut/typescript/src/sqlite-wal-observation.d.ts +132 -0
  51. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.d.ts +61 -0
  52. package/dist-package/adapters/final-cut/typescript/src/timeline-ir-fcpxml.js +31 -5
  53. package/dist-package/adapters/final-cut/typescript/src/unattended-editing.d.ts +54 -0
  54. package/dist-package/adapters/headless/typescript/src/audio-output.d.ts +3 -0
  55. package/dist-package/adapters/headless/typescript/src/audio-output.js +3 -0
  56. package/dist-package/adapters/headless/typescript/src/ffmpeg-media-probe.d.ts +11 -0
  57. package/dist-package/adapters/headless/typescript/src/ffmpeg-media-probe.js +26 -2
  58. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.d.ts +25 -0
  59. package/dist-package/adapters/headless/typescript/src/ffmpeg-renderer.js +37 -14
  60. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.d.ts +15 -0
  61. package/dist-package/adapters/headless/typescript/src/ffmpeg-verifier.js +9 -4
  62. package/dist-package/adapters/headless/typescript/src/index.d.ts +3 -0
  63. package/dist-package/apps/cli/src/dev-doctor.d.ts +25 -0
  64. package/dist-package/apps/cli/src/dev-doctor.js +198 -0
  65. package/dist-package/apps/cli/src/headless-projects.d.ts +3 -0
  66. package/dist-package/apps/cli/src/headless-projects.js +5 -0
  67. package/dist-package/apps/cli/src/main.d.ts +10 -0
  68. package/dist-package/apps/cli/src/main.js +42 -0
  69. package/dist-package/apps/mcp-server/runtime/ffmpeg-audio-backend.py +129 -0
  70. package/dist-package/apps/mcp-server/runtime/speech-analyzer-wrapper.mjs +54 -0
  71. package/dist-package/apps/mcp-server/runtime/whisper-speech-backend.py +271 -0
  72. package/dist-package/apps/mcp-server/src/build-alignment.d.ts +10 -0
  73. package/dist-package/apps/mcp-server/src/build-identity.d.ts +7 -0
  74. package/dist-package/apps/mcp-server/src/build-identity.json +2 -2
  75. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.d.ts +8 -0
  76. package/dist-package/apps/mcp-server/src/canonical-native-snapshot.js +18 -0
  77. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.d.ts +5 -0
  78. package/dist-package/apps/mcp-server/src/final-cut-runtime-config.js +3 -0
  79. package/dist-package/apps/mcp-server/src/headless-project-snapshot.d.ts +3 -0
  80. package/dist-package/apps/mcp-server/src/headless-sessions.d.ts +89 -0
  81. package/dist-package/apps/mcp-server/src/main.d.ts +1 -0
  82. package/dist-package/apps/mcp-server/src/main.js +24 -19
  83. package/dist-package/apps/mcp-server/src/materialization-jobs.d.ts +204 -0
  84. package/dist-package/apps/mcp-server/src/materialization-jobs.js +143 -10
  85. package/dist-package/apps/mcp-server/src/readback-policy.d.ts +18 -0
  86. package/dist-package/apps/mcp-server/src/routing.d.ts +90 -0
  87. package/dist-package/apps/mcp-server/src/routing.js +2 -0
  88. package/dist-package/apps/mcp-server/src/server.d.ts +75 -0
  89. package/dist-package/apps/mcp-server/src/server.js +813 -158
  90. package/dist-package/apps/mcp-server/src/tools/skills/catalog.d.ts +19 -0
  91. package/dist-package/apps/mcp-server/src/tools/skills/catalog.js +142 -0
  92. package/dist-package/apps/mcp-server/src/tools/skills/metadata.d.ts +37 -0
  93. package/dist-package/apps/mcp-server/src/tools/skills/metadata.js +71 -0
  94. package/dist-package/apps/mcp-server/src/tools/skills/register.d.ts +11 -0
  95. package/dist-package/apps/mcp-server/src/tools/skills/register.js +101 -0
  96. package/dist-package/apps/mcp-server/src/version.d.ts +4 -0
  97. package/dist-package/packages/headless-application/src/external-edit.d.ts +30 -0
  98. package/dist-package/packages/headless-application/src/external-edit.js +72 -0
  99. package/dist-package/packages/headless-application/src/headless-projects.d.ts +233 -0
  100. package/dist-package/{apps/mcp-server → packages/headless-application}/src/headless-projects.js +392 -59
  101. package/dist-package/packages/headless-application/src/index.d.ts +2 -0
  102. package/dist-package/packages/headless-application/src/index.js +2 -0
  103. package/dist-package/packages/runtime/src/application/duration-policy-service.d.ts +4 -0
  104. package/dist-package/packages/runtime/src/application/local-media.d.ts +46 -0
  105. package/dist-package/packages/runtime/src/application/media-analysis-service.d.ts +40 -0
  106. package/dist-package/packages/runtime/src/application/media-analysis-service.js +105 -15
  107. package/dist-package/packages/runtime/src/application/project-service.d.ts +35 -0
  108. package/dist-package/packages/runtime/src/application/project-service.js +5 -1
  109. package/dist-package/packages/runtime/src/application/project-store.d.ts +56 -0
  110. package/dist-package/packages/runtime/src/application/project-store.js +13 -36
  111. package/dist-package/packages/runtime/src/application/project-transactions.d.ts +51 -0
  112. package/dist-package/packages/runtime/src/application/runtime-options.d.ts +15 -0
  113. package/dist-package/packages/runtime/src/application/semantic-media-index-store.d.ts +28 -0
  114. package/dist-package/packages/runtime/src/application/transaction-store.d.ts +10 -0
  115. package/dist-package/packages/runtime/src/application/transaction-store.js +1 -1
  116. package/dist-package/packages/runtime/src/audio/analysis.d.ts +3 -0
  117. package/dist-package/packages/runtime/src/audio/analysis.js +95 -0
  118. package/dist-package/packages/runtime/src/audio/dialogue-normalization.d.ts +47 -0
  119. package/dist-package/packages/runtime/src/audio/noise-reduction.d.ts +34 -0
  120. package/dist-package/packages/runtime/src/capabilities.d.ts +45 -0
  121. package/dist-package/packages/runtime/src/capabilities.js +1 -1
  122. package/dist-package/packages/runtime/src/color-correction.d.ts +33 -0
  123. package/dist-package/packages/runtime/src/context/context-engine.d.ts +28 -0
  124. package/dist-package/packages/runtime/src/context/context-engine.js +22 -16
  125. package/dist-package/packages/runtime/src/context/context-service.d.ts +20 -0
  126. package/dist-package/packages/runtime/src/context/context-service.js +2 -2
  127. package/dist-package/packages/runtime/src/context/project-catalog.d.ts +12 -0
  128. package/dist-package/packages/runtime/src/context/revision.d.ts +2 -0
  129. package/dist-package/packages/runtime/src/domain/capabilities.d.ts +170 -0
  130. package/dist-package/packages/runtime/src/domain/context.d.ts +179 -0
  131. package/dist-package/packages/runtime/src/domain/diff.d.ts +104 -0
  132. package/dist-package/packages/runtime/src/domain/duration.d.ts +63 -0
  133. package/dist-package/packages/runtime/src/domain/editing.d.ts +227 -0
  134. package/dist-package/packages/runtime/src/domain/incremental-sync.d.ts +67 -0
  135. package/dist-package/packages/runtime/src/domain/index.d.ts +14 -0
  136. package/dist-package/packages/runtime/src/domain/media.d.ts +406 -0
  137. package/dist-package/packages/runtime/src/domain/ports.d.ts +62 -0
  138. package/dist-package/packages/runtime/src/domain/primitives.d.ts +21 -0
  139. package/dist-package/packages/runtime/src/domain/project.d.ts +119 -0
  140. package/dist-package/packages/runtime/src/domain/rough-cut.d.ts +27 -0
  141. package/dist-package/packages/runtime/src/domain/skills.d.ts +145 -0
  142. package/dist-package/packages/runtime/src/domain/timeline-target.d.ts +57 -0
  143. package/dist-package/packages/runtime/src/domain/timeline-target.js +19 -1
  144. package/dist-package/packages/runtime/src/domain/types.d.ts +5 -0
  145. package/dist-package/packages/runtime/src/domain/verification.d.ts +92 -0
  146. package/dist-package/packages/runtime/src/editing/dialogue-normalization-service.d.ts +18 -0
  147. package/dist-package/packages/runtime/src/editing/duration-policy.d.ts +3 -0
  148. package/dist-package/packages/runtime/src/editing/edit-service.d.ts +44 -0
  149. package/dist-package/packages/runtime/src/editing/edit-service.js +76 -10
  150. package/dist-package/packages/runtime/src/editing/filler-removal-service.d.ts +23 -0
  151. package/dist-package/packages/runtime/src/editing/intent.d.ts +97 -0
  152. package/dist-package/packages/runtime/src/editing/music-service.d.ts +9 -0
  153. package/dist-package/packages/runtime/src/index.d.ts +32 -0
  154. package/dist-package/packages/runtime/src/index.js +2 -0
  155. package/dist-package/packages/runtime/src/planning/rough-cut.d.ts +3 -0
  156. package/dist-package/packages/runtime/src/render/render-and-verify.d.ts +71 -0
  157. package/dist-package/packages/runtime/src/render/render-contract.d.ts +96 -0
  158. package/dist-package/packages/runtime/src/runtime.d.ts +85 -0
  159. package/dist-package/packages/runtime/src/runtime.js +16 -7
  160. package/dist-package/packages/runtime/src/skills/builtin.d.ts +2 -0
  161. package/dist-package/packages/runtime/src/skills/index.d.ts +3 -0
  162. package/dist-package/packages/runtime/src/skills/registry.d.ts +10 -0
  163. package/dist-package/packages/runtime/src/skills/requirements.d.ts +38 -0
  164. package/dist-package/packages/runtime/src/skills/runtime.d.ts +38 -0
  165. package/dist-package/packages/runtime/src/speech/analysis.d.ts +18 -0
  166. package/dist-package/packages/runtime/src/speech/analysis.js +67 -0
  167. package/dist-package/packages/runtime/src/speech/filler-detector.d.ts +49 -0
  168. package/dist-package/packages/runtime/src/speech/filler-removal.d.ts +37 -0
  169. package/dist-package/packages/runtime/src/speech/mapping.d.ts +56 -0
  170. package/dist-package/packages/runtime/src/speech/mapping.js +27 -4
  171. package/dist-package/packages/runtime/src/speech/safe-cut-resolver.d.ts +52 -0
  172. package/dist-package/packages/runtime/src/timeline/drift-reconciliation.d.ts +42 -0
  173. package/dist-package/packages/runtime/src/timeline/editing-session.d.ts +271 -0
  174. package/dist-package/packages/runtime/src/timeline/editing-session.js +48 -2
  175. package/dist-package/packages/runtime/src/timeline/fast-observation.d.ts +77 -0
  176. package/dist-package/packages/runtime/src/timeline/rational-time.d.ts +11 -0
  177. package/dist-package/packages/runtime/src/timeline/reorder-preview.d.ts +32 -0
  178. package/dist-package/packages/runtime/src/timeline/reorder-preview.js +202 -0
  179. package/dist-package/packages/runtime/src/timeline/snapshot-diff.d.ts +3 -0
  180. package/dist-package/packages/runtime/src/timeline/snapshot-diff.js +1 -0
  181. package/dist-package/packages/runtime/src/timeline/snapshot-digest.d.ts +3 -0
  182. package/dist-package/packages/runtime/src/timeline/snapshot-digest.js +1 -1
  183. package/dist-package/packages/runtime/src/verification/verification.d.ts +6 -0
  184. package/dist-package/packages/testkit/src/fixture-analyzers.d.ts +37 -0
  185. package/dist-package/packages/testkit/src/in-memory-editor.d.ts +55 -0
  186. package/dist-package/packages/testkit/src/in-memory-editor.js +3 -3
  187. package/dist-package/packages/testkit/src/index.d.ts +4 -0
  188. package/dist-package/packages/testkit/src/index.js +1 -0
  189. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.d.ts +47 -0
  190. package/dist-package/packages/testkit/src/sender-lifecycle-fixture.js +192 -0
  191. package/dist-package/packages/testkit/src/skill-fixtures.d.ts +3 -0
  192. package/package.json +41 -14
@@ -1,16 +1,18 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { readdir, readFile, rename, writeFile, mkdir } from "node:fs/promises";
3
- import { dirname, join, resolve } from "node:path";
4
- import { FramekitProjectStore, LocalMediaRegistrar, ProjectTransactionService, createFramekitRenderRequest, renderAndVerifyFramekitProject, timelineIrDigest, } from "../../../packages/runtime/src/index.js";
5
- import { FcpxmlDocumentAdapter, compileTimelineIrToFcpxml, resolveMediaSource, } from "../../../adapters/final-cut/typescript/src/index.js";
2
+ import { readdir, readFile, rename, writeFile, mkdir, link, unlink, realpath, stat } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { FramekitProjectStore, LocalMediaRegistrar, ProjectTransactionService, createFramekitRenderRequest, renderAndVerifyFramekitProject, timelineIrDigest, } from "../../runtime/src/index.js";
5
+ import { FcpxmlDocumentAdapter, compileTimelineIrToFcpxml, resolveMediaSource, } from "../../../adapters/final-cut/typescript/src/documents.js";
6
6
  export class HeadlessProjectService {
7
7
  directory;
8
+ protectedStateDirectory;
8
9
  mediaProbe;
9
10
  renderer;
10
11
  verifier;
11
12
  clock;
12
13
  constructor(options) {
13
14
  this.directory = options.directory;
15
+ this.protectedStateDirectory = options.protectedStateDirectory ?? options.directory;
14
16
  this.mediaProbe = options.mediaProbe;
15
17
  this.renderer = options.renderer;
16
18
  this.verifier = options.verifier;
@@ -29,13 +31,42 @@ export class HeadlessProjectService {
29
31
  await mkdir(this.directory, { recursive: true });
30
32
  const entries = await readdir(this.directory, { withFileTypes: true });
31
33
  const summaries = [];
32
- for (const entry of entries.filter((candidate) => candidate.isFile() && candidate.name.endsWith(".json") && !candidate.name.startsWith("render-"))) {
34
+ for (const entry of entries.filter((candidate) => (candidate.isFile() || candidate.isSymbolicLink()) && candidate.name.endsWith(".json"))) {
33
35
  const projectId = entry.name.slice(0, -".json".length);
36
+ if (await this.isInternalRecord(entry.name))
37
+ continue;
34
38
  const project = await this.store(projectId).load();
39
+ if (project.timeline.project.id !== projectId) {
40
+ throw new Error("HEADLESS_PROJECT_IDENTITY_MISMATCH: stored project ID differs from its filename");
41
+ }
35
42
  summaries.push(toSummary(project, this.projectPath(projectId)));
36
43
  }
37
44
  return summaries.sort((left, right) => left.projectId.localeCompare(right.projectId));
38
45
  }
46
+ async isInternalRecord(name) {
47
+ let value;
48
+ try {
49
+ value = JSON.parse(await readFile(join(this.directory, name), "utf8"));
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ if (!value || typeof value !== "object" || Array.isArray(value))
55
+ return false;
56
+ const record = value;
57
+ // A document-shaped file remains a project even when its ID resembles an
58
+ // internal record. Unknown or corrupt files still fail through the store.
59
+ if ("timeline" in record || "metadata" in record)
60
+ return false;
61
+ const render = /^(render-[0-9a-f-]{36})\.json$/.exec(name);
62
+ if (render && record.renderId === render[1])
63
+ return true;
64
+ const execution = /^(rough-cut-[0-9a-f-]{36})\.json$/.exec(name);
65
+ if (execution && record.schemaVersion === 1 && record.executionId === execution[1])
66
+ return true;
67
+ const approval = /^([0-9a-f]{64})\.approval\.json$/.exec(name);
68
+ return Boolean(approval && record.schemaVersion === 1 && record.planDigest === approval[1]);
69
+ }
39
70
  async open(projectId) {
40
71
  const project = await this.store(projectId).load();
41
72
  const hasLocalMedia = project.timeline.resources.some((resource) => resource.sourceKind === "local-file");
@@ -43,7 +74,7 @@ export class HeadlessProjectService {
43
74
  throw new Error("HEADLESS_MEDIA_PROBE_UNAVAILABLE: local-file resources require a configured media probe");
44
75
  }
45
76
  if (this.mediaProbe)
46
- await new LocalMediaRegistrar(this.store(projectId), this.mediaProbe).reopen();
77
+ return new LocalMediaRegistrar(this.store(projectId), this.mediaProbe).reopen();
47
78
  return project;
48
79
  }
49
80
  async inspect(projectId) {
@@ -54,21 +85,99 @@ export class HeadlessProjectService {
54
85
  throw new Error("HEADLESS_MEDIA_PROBE_UNAVAILABLE: no local media metadata probe is configured");
55
86
  return new LocalMediaRegistrar(this.store(projectId), this.mediaProbe, { clock: this.clock }).register(sourcePath, expectedRevision);
56
87
  }
88
+ async searchMedia(projectId, query) {
89
+ const project = await this.open(projectId);
90
+ const needle = query.toLowerCase();
91
+ return {
92
+ revision: structuredClone(project.timeline.revision),
93
+ media: project.timeline.resources.filter((resource) => [resource.id, resource.name, resource.source].some((value) => value?.toLowerCase().includes(needle))).map((resource) => structuredClone(resource)),
94
+ };
95
+ }
57
96
  async previewEdit(projectId, command, sequenceId) {
58
- await this.open(projectId);
59
- const transaction = new ProjectTransactionService(this.store(projectId), { clock: this.clock });
97
+ const project = await this.open(projectId);
98
+ const transaction = new ProjectTransactionService(this.snapshotStore(projectId, project), { clock: this.clock });
60
99
  return transaction.preview({
61
100
  ...command,
62
101
  target: command.target ?? { projectId, sequenceId },
63
102
  });
64
103
  }
65
104
  async executeEdit(projectId, command, sequenceId) {
66
- await this.open(projectId);
67
- const transaction = new ProjectTransactionService(this.store(projectId), { clock: this.clock });
68
- return transaction.execute({
105
+ const project = await this.open(projectId);
106
+ const timestamp = this.clock();
107
+ const transaction = new ProjectTransactionService(this.snapshotStore(projectId, project), { clock: () => timestamp });
108
+ const editCommand = {
69
109
  ...command,
70
110
  target: command.target ?? { projectId, sequenceId },
71
- });
111
+ };
112
+ const preview = await transaction.preview(editCommand);
113
+ const recordId = `undo-${randomUUID()}`;
114
+ const afterDigest = timelineIrDigest(preview.after.timeline);
115
+ const record = {
116
+ version: 1, undoId: recordId, projectId, sequenceId,
117
+ before: preview.before,
118
+ beforeDigest: timelineIrDigest(preview.before.timeline),
119
+ afterDigest,
120
+ afterRevision: { id: `ir:${afterDigest}`, sequence: preview.before.timeline.revision.sequence + 1, timestamp },
121
+ };
122
+ const directory = join(this.directory, "undo");
123
+ await mkdir(directory, { recursive: true });
124
+ const serialized = JSON.stringify({ ...record, checksum: hash(stableJson(record)) });
125
+ // The client retains this commitment independently of the stored record.
126
+ const undoId = `${recordId}-${hash(serialized)}`;
127
+ await writeFile(join(directory, `${recordId}.json`), serialized, { encoding: "utf8", flag: "wx" });
128
+ const result = await transaction.execute(editCommand);
129
+ if (!sameRevision(result.after.timeline.revision, record.afterRevision) || timelineIrDigest(result.after.timeline) !== afterDigest) {
130
+ throw new Error("HEADLESS_EDIT_UNCERTAIN: committed edit differs from the recorded Undo state");
131
+ }
132
+ return { ...result, undoId };
133
+ }
134
+ async undoEdit(projectId, sequenceId, undoId, expectedRevision) {
135
+ const handle = /^(undo-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})-([0-9a-f]{64})$/.exec(undoId);
136
+ if (!handle) {
137
+ throw new Error("HEADLESS_UNDO_INVALID: invalid Undo identifier");
138
+ }
139
+ let record;
140
+ try {
141
+ const serialized = await readFile(join(this.directory, "undo", `${handle[1]}.json`), "utf8");
142
+ if (hash(serialized) !== handle[2])
143
+ throw new Error("record does not match client commitment");
144
+ record = JSON.parse(serialized);
145
+ const { checksum, ...content } = record;
146
+ if (record.version !== 1 || record.undoId !== handle[1] || checksum !== hash(stableJson(content))
147
+ || record.projectId !== projectId || record.sequenceId !== sequenceId
148
+ || record.before.timeline.project.id !== projectId || record.before.timeline.sequence.id !== sequenceId
149
+ || timelineIrDigest(record.before.timeline) !== record.beforeDigest)
150
+ throw new Error("invalid record");
151
+ }
152
+ catch {
153
+ throw new Error("HEADLESS_UNDO_INVALID: Undo record is missing or invalid");
154
+ }
155
+ const current = await this.open(projectId);
156
+ if (current.timeline.sequence.id !== sequenceId || !sameRevision(current.timeline.revision, expectedRevision)
157
+ || !sameRevision(current.timeline.revision, record.afterRevision) || timelineIrDigest(current.timeline) !== record.afterDigest) {
158
+ throw new Error("HEADLESS_UNDO_STALE: current target or revision differs from the recorded edit");
159
+ }
160
+ const restored = structuredClone(record.before);
161
+ const timestamp = this.clock();
162
+ restored.metadata.updatedAt = timestamp;
163
+ restored.timeline.revision = { id: `ir:${record.beforeDigest}`, sequence: current.timeline.revision.sequence + 1, timestamp };
164
+ await this.store(projectId).save(restored, current.timeline.revision);
165
+ const observed = await this.open(projectId);
166
+ const observedDigest = timelineIrDigest(observed.timeline);
167
+ if (!sameRevision(observed.timeline.revision, restored.timeline.revision) || observedDigest !== record.beforeDigest) {
168
+ throw new Error("HEADLESS_UNDO_UNVERIFIED: restored project could not be independently verified");
169
+ }
170
+ return { project: observed, verification: { verified: true, expectedDigest: record.beforeDigest, observedDigest } };
171
+ }
172
+ async exportFcpxml(projectId, sequenceId, expectedRevision, outputPath, target) {
173
+ const project = await this.open(projectId);
174
+ if (project.timeline.sequence.id !== sequenceId || !sameRevision(project.timeline.revision, expectedRevision)) {
175
+ throw new Error("HEADLESS_FCPXML_STALE: project target or revision does not match the requested export");
176
+ }
177
+ await this.assertOutputSeparation(project, [outputPath]);
178
+ const compiled = compileTimelineIrToFcpxml(project.timeline, { target });
179
+ const artifact = await writeVerifiedFcpxml(resolve(outputPath), compiled.xml, compiled.digest, false);
180
+ return { artifact, provenance: compiled.provenance, coverage: compiled.coverage };
72
181
  }
73
182
  async previewRoughCut(request) {
74
183
  const prepared = await this.prepareRoughCut(request);
@@ -120,7 +229,7 @@ export class HeadlessProjectService {
120
229
  || stableJson(approval.outputIntent) !== stableJson(prepared.outputIntent)) {
121
230
  throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: planDigest does not match the submitted rough-cut plan");
122
231
  }
123
- const transaction = new ProjectTransactionService(this.store(request.projectId), {
232
+ const transaction = new ProjectTransactionService(this.snapshotStore(request.projectId, prepared.project), {
124
233
  clock: () => approval.canonicalRevision.timestamp,
125
234
  });
126
235
  const { preview, fcpxml } = await this.previewPreparedRoughCut(request, prepared, approval.canonicalRevision.timestamp, transaction);
@@ -128,6 +237,7 @@ export class HeadlessProjectService {
128
237
  || fcpxml.digest !== approval.artifactDigest) {
129
238
  throw new Error("HEADLESS_ROUGH_CUT_PLAN_MISMATCH: replayed preview differs from the approved revision or FCPXML digest");
130
239
  }
240
+ await this.assertOutputSeparation(prepared.project, [request.render.outputPath, request.fcpxml.path]);
131
241
  const renderRequest = createFramekitRenderRequest({
132
242
  timeline: preview.after.timeline,
133
243
  target: { projectId: request.projectId, sequenceId: request.sequenceId },
@@ -152,29 +262,36 @@ export class HeadlessProjectService {
152
262
  if (outcome.status !== "passed") {
153
263
  throw new Error(`HEADLESS_ROUGH_CUT_RENDER_FAILED: render verification status was ${outcome.status}; inspect ${renderId}`);
154
264
  }
265
+ await this.assertOutputSeparation(prepared.project, [request.render.outputPath, request.fcpxml.path]);
155
266
  const fcpxmlArtifact = await writeVerifiedFcpxml(request.fcpxml.path, fcpxml.xml, fcpxml.digest, request.fcpxml.overwrite === true);
156
267
  const committed = await transaction.execute(prepared.command);
157
268
  const executionId = `rough-cut-${randomUUID()}`;
158
- await this.saveRoughCutExecution({
159
- schemaVersion: 1,
160
- executionId,
161
- approved: true,
162
- projectId: request.projectId,
163
- sequenceId: request.sequenceId,
164
- sourceRevision: structuredClone(request.plan.revision),
165
- canonicalRevision: structuredClone(committed.after.timeline.revision),
166
- plan: structuredClone(request.plan),
167
- operations: structuredClone(request.operations ?? []),
168
- outputIntent: structuredClone(prepared.outputIntent),
169
- planDigest: approval.planDigest,
170
- inputDigest: prepared.inputDigest,
171
- renderId,
172
- artifactPath: resolve(fcpxmlArtifact.path),
173
- artifactDigest: fcpxmlArtifact.digest,
174
- artifactBytes: fcpxmlArtifact.bytes,
175
- fcpxml: selectFcpxmlMetadata(fcpxml),
176
- provenance: structuredClone(prepared.provenance),
177
- });
269
+ try {
270
+ await this.saveRoughCutExecution({
271
+ schemaVersion: 1,
272
+ executionId,
273
+ approved: true,
274
+ projectId: request.projectId,
275
+ sequenceId: request.sequenceId,
276
+ sourceRevision: structuredClone(request.plan.revision),
277
+ canonicalRevision: structuredClone(committed.after.timeline.revision),
278
+ plan: structuredClone(request.plan),
279
+ operations: structuredClone(request.operations ?? []),
280
+ outputIntent: structuredClone(prepared.outputIntent),
281
+ planDigest: approval.planDigest,
282
+ inputDigest: prepared.inputDigest,
283
+ renderId,
284
+ artifactPath: resolve(fcpxmlArtifact.path),
285
+ artifactDigest: fcpxmlArtifact.digest,
286
+ artifactBytes: fcpxmlArtifact.bytes,
287
+ fcpxml: selectFcpxmlMetadata(fcpxml),
288
+ provenance: structuredClone(prepared.provenance),
289
+ });
290
+ }
291
+ catch (error) {
292
+ const details = { projectId: request.projectId, sequenceId: request.sequenceId, executionId, committedRevision: committed.after.timeline.revision };
293
+ throw new Error(`HEADLESS_ROUGH_CUT_HISTORY_UNCONFIRMED: project already committed; no execution or publish proof was returned; reinspect project before retry: ${JSON.stringify(details)}`, { cause: error });
294
+ }
178
295
  return {
179
296
  ...preview,
180
297
  after: committed.after,
@@ -307,6 +424,7 @@ export class HeadlessProjectService {
307
424
  if (!this.renderer || !this.verifier)
308
425
  throw new Error("HEADLESS_RENDER_UNAVAILABLE: renderer and verifier are not configured");
309
426
  const project = await this.open(projectId);
427
+ await this.assertOutputSeparation(project, [parameters.outputPath]);
310
428
  const request = createFramekitRenderRequest({
311
429
  timeline: project.timeline,
312
430
  target: { projectId, sequenceId },
@@ -338,9 +456,30 @@ export class HeadlessProjectService {
338
456
  throw error;
339
457
  }
340
458
  }
459
+ async assertOutputSeparation(project, paths) {
460
+ const summaries = await this.list();
461
+ const projects = await Promise.all(summaries.map((summary) => new FramekitProjectStore(summary.path).load()));
462
+ // Keep the already validated snapshot even if the project changed during enumeration.
463
+ await assertOutputSeparation([project, ...projects], this.protectedStateDirectory, paths);
464
+ }
341
465
  store(projectId) {
342
466
  return new FramekitProjectStore(this.projectPath(projectId));
343
467
  }
468
+ snapshotStore(projectId, project) {
469
+ const store = this.store(projectId);
470
+ return {
471
+ create: (value) => store.create(value),
472
+ load: async () => {
473
+ const current = await store.load();
474
+ if (!sameRevision(current.timeline.revision, project.timeline.revision)
475
+ || timelineIrDigest(current.timeline) !== timelineIrDigest(project.timeline)) {
476
+ throw new Error("HEADLESS_PROJECT_STALE: project changed after media validation");
477
+ }
478
+ return current;
479
+ },
480
+ save: (value, expectedRevision) => store.save(value, expectedRevision),
481
+ };
482
+ }
344
483
  projectPath(projectId) {
345
484
  validateProjectId(projectId);
346
485
  return join(this.directory, `${projectId}.json`);
@@ -356,25 +495,19 @@ export class HeadlessProjectService {
356
495
  async saveRender(record) {
357
496
  await mkdir(this.directory, { recursive: true });
358
497
  const path = join(this.directory, `${record.renderId}.json`);
359
- const temporary = `${path}.${randomUUID()}.tmp`;
360
- await writeFile(temporary, `${JSON.stringify(record)}\n`, { encoding: "utf8", flag: "wx" });
361
- await rename(temporary, path);
498
+ await publishHistory(path, `${JSON.stringify(record)}\n`);
362
499
  }
363
500
  async saveRoughCutExecution(record) {
364
501
  await mkdir(this.directory, { recursive: true });
365
502
  const execution = { ...record, evidenceDigest: hash(stableJson(record)) };
366
503
  const path = this.executionPath(record.executionId);
367
- const temporary = `${path}.${randomUUID()}.tmp`;
368
- await writeFile(temporary, `${JSON.stringify(execution)}\n`, { encoding: "utf8", flag: "wx" });
369
- await rename(temporary, path);
504
+ await publishHistory(path, `${JSON.stringify(execution)}\n`);
370
505
  }
371
506
  async saveRoughCutApproval(record) {
372
507
  await mkdir(this.directory, { recursive: true });
373
508
  const approval = { ...record, evidenceDigest: hash(stableJson(record)) };
374
509
  const path = this.approvalPath(record.planDigest);
375
- const temporary = `${path}.${randomUUID()}.tmp`;
376
- await writeFile(temporary, `${JSON.stringify(approval)}\n`, { encoding: "utf8", flag: "wx" });
377
- await rename(temporary, path);
510
+ await publishHistory(path, `${JSON.stringify(approval)}\n`, true);
378
511
  }
379
512
  async readRoughCutApproval(planDigest) {
380
513
  const approval = JSON.parse(await readFile(this.approvalPath(planDigest), "utf8"));
@@ -388,14 +521,14 @@ export class HeadlessProjectService {
388
521
  return approval;
389
522
  }
390
523
  async prepareRoughCut(request) {
391
- await this.open(request.projectId);
392
- const project = await this.store(request.projectId).load();
524
+ const project = await this.open(request.projectId);
393
525
  if (project.timeline.sequence.id !== request.sequenceId) {
394
526
  throw new Error("HEADLESS_ROUGH_CUT_TARGET_MISMATCH: sequenceId does not match the persisted project");
395
527
  }
396
528
  if (!sameRevision(project.timeline.revision, request.plan.revision)) {
397
529
  throw new Error("HEADLESS_ROUGH_CUT_STALE_REVISION: rough-cut plan revision does not match the persisted project");
398
530
  }
531
+ await this.assertOutputSeparation(project, [request.render.outputPath, request.fcpxml.path]);
399
532
  if (!request.plan.shots.length)
400
533
  throw new Error("HEADLESS_ROUGH_CUT_EMPTY_PLAN: rough-cut plan must contain at least one shot");
401
534
  const operations = structuredClone(request.operations ?? []);
@@ -427,9 +560,11 @@ export class HeadlessProjectService {
427
560
  if (!resource)
428
561
  throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_NOT_FOUND: ${shot.sourceIdentity.mediaId}`);
429
562
  assertSourceIdentity(resource, shot.sourceIdentity);
430
- const sourceStartTime = shot.range.startTime ?? secondsToRational(shot.range.start);
431
- const durationTime = shot.range.durationTime ?? secondsToRational(shot.range.end - shot.range.start);
432
- assertSourceRange(resource, shot.range, sourceStartTime, durationTime);
563
+ assertSourceRange(resource, shot.range);
564
+ const sourceRange = alignInferredRoughCutRange(resource, shot.range, project.timeline.sequence.frameDuration);
565
+ assertSourceRange(resource, sourceRange);
566
+ const sourceStartTime = sourceRange.startTime ?? secondsToRational(sourceRange.start);
567
+ const durationTime = sourceRange.durationTime ?? secondsToRational(sourceRange.end - sourceRange.start);
433
568
  const appendToPrimaryStoryline = hasPrimaryStoryContent || planOperations.length > 0;
434
569
  planOperations.push({
435
570
  type: "insert-occurrence",
@@ -451,7 +586,7 @@ export class HeadlessProjectService {
451
586
  occurrenceId,
452
587
  mediaId: resource.id,
453
588
  sourceIdentity: structuredClone(shot.sourceIdentity),
454
- sourceRange: structuredClone(shot.range),
589
+ sourceRange: structuredClone(sourceRange),
455
590
  confidence: shot.confidence,
456
591
  matchedProperties: [...shot.matchedProperties],
457
592
  rationale: shot.rationale,
@@ -465,9 +600,9 @@ export class HeadlessProjectService {
465
600
  expectedRevision: structuredClone(request.plan.revision),
466
601
  operations: editOperations,
467
602
  };
468
- return { command, inputDigest, provenance, outputIntent };
603
+ return { command, inputDigest, provenance, outputIntent, project };
469
604
  }
470
- async previewPreparedRoughCut(request, prepared, timestamp, transaction = new ProjectTransactionService(this.store(request.projectId), { clock: () => timestamp })) {
605
+ async previewPreparedRoughCut(request, prepared, timestamp, transaction = new ProjectTransactionService(this.snapshotStore(request.projectId, prepared.project), { clock: () => timestamp })) {
471
606
  const rawPreview = await transaction.preview(prepared.command);
472
607
  const canonicalRevision = {
473
608
  id: `ir:${timelineIrDigest(rawPreview.after.timeline)}`,
@@ -484,6 +619,32 @@ export class HeadlessProjectService {
484
619
  return { preview, fcpxml };
485
620
  }
486
621
  }
622
+ async function publishHistory(path, contents, allowIdentical = false) {
623
+ const temporary = `${path}.${randomUUID()}.tmp`;
624
+ try {
625
+ await writeFile(temporary, contents, { encoding: "utf8", flag: "wx" });
626
+ try {
627
+ // Linking a fully written file fails atomically if the destination exists.
628
+ await link(temporary, path);
629
+ }
630
+ catch (error) {
631
+ if (error.code !== "EEXIST")
632
+ throw error;
633
+ if (allowIdentical && await readFile(path, "utf8") === contents)
634
+ return;
635
+ throw new Error("HEADLESS_HISTORY_COLLISION: history destination already exists", { cause: error });
636
+ }
637
+ }
638
+ finally {
639
+ try {
640
+ await unlink(temporary);
641
+ }
642
+ catch (error) {
643
+ if (error.code !== "ENOENT")
644
+ throw error;
645
+ }
646
+ }
647
+ }
487
648
  function createRoughCutApproval(fields) {
488
649
  const digestFields = { schemaVersion: 1, ...fields };
489
650
  const planDigest = hash(stableJson(digestFields));
@@ -515,19 +676,105 @@ function assertSourceIdentity(resource, source) {
515
676
  throw new Error(`HEADLESS_ROUGH_CUT_SOURCE_MISMATCH: source duration differs for ${source.mediaId}`);
516
677
  }
517
678
  }
518
- function assertSourceRange(resource, range, sourceStartTime, durationTime) {
679
+ function assertSourceRange(resource, range) {
519
680
  if (!Number.isFinite(range.start) || !Number.isFinite(range.end) || range.start < 0 || range.end <= range.start) {
520
681
  throw new Error("HEADLESS_ROUGH_CUT_RANGE_INVALID: source range must be finite and non-empty");
521
682
  }
522
683
  if (resource.metadata?.durationTime !== undefined && range.end > rationalSeconds(resource.metadata.durationTime) + 0.001) {
523
684
  throw new Error(`HEADLESS_ROUGH_CUT_RANGE_INVALID: source range exceeds ${resource.id}`);
524
685
  }
686
+ const sourceStartTime = range.startTime ?? secondsToRational(range.start);
687
+ const durationTime = range.durationTime ?? secondsToRational(range.end - range.start);
525
688
  if (rationalSeconds(sourceStartTime) < 0 || rationalSeconds(durationTime) <= 0
526
689
  || Math.abs(rationalSeconds(sourceStartTime) - range.start) > 0.001
527
690
  || Math.abs(rationalSeconds(durationTime) - (range.end - range.start)) > 0.001) {
528
691
  throw new Error("HEADLESS_ROUGH_CUT_RANGE_INVALID: rational source range must be non-negative and non-empty");
529
692
  }
530
693
  }
694
+ function alignInferredRoughCutRange(resource, range, sequenceFrameDuration) {
695
+ if (range.startTime !== undefined || range.durationTime !== undefined
696
+ || !Number.isFinite(range.start) || !Number.isFinite(range.end) || range.end <= range.start) {
697
+ return structuredClone(range);
698
+ }
699
+ const frameRate = resource.metadata?.streams.find((stream) => stream.kind === "video" && stream.frameRate)?.frameRate;
700
+ if (!frameRate || BigInt(frameRate.value) <= 0n || BigInt(frameRate.timescale) <= 0n
701
+ || BigInt(sequenceFrameDuration.value) <= 0n || BigInt(sequenceFrameDuration.timescale) <= 0n) {
702
+ return structuredClone(range);
703
+ }
704
+ const sourceFrameDuration = { value: frameRate.timescale, timescale: frameRate.value };
705
+ const startTime = nearestFrameTime(secondsToRational(range.start), sourceFrameDuration);
706
+ const sourceEndTime = nearestFrameTime(secondsToRational(range.end), sourceFrameDuration);
707
+ let durationTime = nearestFrameTime(subtractRationalTimes(sourceEndTime, startTime), sequenceFrameDuration);
708
+ if (resource.metadata?.durationTime !== undefined) {
709
+ // The FCPXML compiler rounds source starts to the sequence grid. Bound
710
+ // both the canonical and exported ranges when that rounding moves later.
711
+ const exportedStartTime = nearestFrameTime(startTime, sequenceFrameDuration);
712
+ const latestStartTime = compareRationalTimes(startTime, exportedStartTime) >= 0 ? startTime : exportedStartTime;
713
+ const available = subtractRationalTimes(resource.metadata.durationTime, latestStartTime);
714
+ const maxDuration = floorFrameTime(available, sequenceFrameDuration);
715
+ if (compareRationalTimes(durationTime, maxDuration) > 0)
716
+ durationTime = maxDuration;
717
+ }
718
+ if (BigInt(durationTime.value) <= 0n) {
719
+ throw new Error("HEADLESS_ROUGH_CUT_RANGE_INVALID: frame alignment produced an empty source range");
720
+ }
721
+ const endTime = addRationalTimes(startTime, durationTime);
722
+ return {
723
+ ...structuredClone(range),
724
+ start: rationalSeconds(startTime),
725
+ end: rationalSeconds(endTime),
726
+ startTime,
727
+ durationTime,
728
+ };
729
+ }
730
+ function floorFrameTime(time, frameDuration) {
731
+ const numerator = BigInt(time.value) * BigInt(frameDuration.timescale);
732
+ const denominator = BigInt(time.timescale) * BigInt(frameDuration.value);
733
+ const frames = numerator > 0n ? numerator / denominator : 0n;
734
+ return normalizeRationalTime(frames * BigInt(frameDuration.value), BigInt(frameDuration.timescale));
735
+ }
736
+ function nearestFrameTime(time, frameDuration) {
737
+ const timeValue = BigInt(time.value);
738
+ const timeScale = BigInt(time.timescale);
739
+ const frameValue = BigInt(frameDuration.value);
740
+ const frameScale = BigInt(frameDuration.timescale);
741
+ const numerator = timeValue * frameScale;
742
+ const denominator = timeScale * frameValue;
743
+ const frameCount = (numerator * 2n + denominator) / (denominator * 2n);
744
+ return normalizeRationalTime(frameCount * frameValue, frameScale);
745
+ }
746
+ function compareRationalTimes(left, right) {
747
+ const difference = BigInt(left.value) * BigInt(right.timescale) - BigInt(right.value) * BigInt(left.timescale);
748
+ return difference < 0n ? -1 : difference > 0n ? 1 : 0;
749
+ }
750
+ function subtractRationalTimes(left, right) {
751
+ const leftValue = BigInt(left.value);
752
+ const leftScale = BigInt(left.timescale);
753
+ const rightValue = BigInt(right.value);
754
+ const rightScale = BigInt(right.timescale);
755
+ return normalizeRationalTime(leftValue * rightScale - rightValue * leftScale, leftScale * rightScale);
756
+ }
757
+ function addRationalTimes(left, right) {
758
+ const leftValue = BigInt(left.value);
759
+ const leftScale = BigInt(left.timescale);
760
+ const rightValue = BigInt(right.value);
761
+ const rightScale = BigInt(right.timescale);
762
+ return normalizeRationalTime(leftValue * rightScale + rightValue * leftScale, leftScale * rightScale);
763
+ }
764
+ function normalizeRationalTime(value, timescale) {
765
+ const divisor = greatestCommonDivisorBigInt(value < 0n ? -value : value, timescale);
766
+ return { value: String(value / divisor), timescale: String(timescale / divisor) };
767
+ }
768
+ function greatestCommonDivisorBigInt(left, right) {
769
+ let a = left;
770
+ let b = right;
771
+ while (b !== 0n) {
772
+ const remainder = a % b;
773
+ a = b;
774
+ b = remainder;
775
+ }
776
+ return a || 1n;
777
+ }
531
778
  function secondsToRational(seconds) {
532
779
  const timescale = 1_000_000;
533
780
  const value = Math.round(seconds * timescale);
@@ -557,21 +804,107 @@ function selectFcpxmlMetadata(result) {
557
804
  provenance: structuredClone(result.provenance),
558
805
  };
559
806
  }
560
- async function writeVerifiedFcpxml(path, xml, digest, overwrite) {
561
- await mkdir(dirname(path), { recursive: true });
562
- if (!overwrite) {
807
+ // Resolve symlinked ancestors even for a destination that does not exist yet.
808
+ async function canonicalOutputPath(path) {
809
+ const absolute = resolve(path);
810
+ try {
811
+ return await realpath(absolute);
812
+ }
813
+ catch (error) {
814
+ if (error.code !== "ENOENT")
815
+ throw error;
816
+ const parent = dirname(absolute);
817
+ if (parent === absolute)
818
+ throw error;
819
+ return join(await canonicalOutputPath(parent), basename(absolute));
820
+ }
821
+ }
822
+ async function sameExistingFile(left, right) {
823
+ try {
824
+ const [a, b] = await Promise.all([stat(left), stat(right)]);
825
+ return a.dev === b.dev && a.ino === b.ino;
826
+ }
827
+ catch (error) {
828
+ if (error.code === "ENOENT")
829
+ return false;
830
+ throw error;
831
+ }
832
+ }
833
+ async function stateTree(directory) {
834
+ const directories = [];
835
+ const files = [];
836
+ const visited = new Set();
837
+ async function visit(path, root = false) {
838
+ let canonical;
563
839
  try {
564
- await readFile(path);
565
- throw new Error(`HEADLESS_ROUGH_CUT_FCPXML_EXISTS: refusing to overwrite ${path}`);
840
+ canonical = await realpath(path);
566
841
  }
567
842
  catch (error) {
568
- if (error.code !== "ENOENT")
569
- throw error;
843
+ if (root && error.code === "ENOENT")
844
+ return;
845
+ throw error;
846
+ }
847
+ const info = await stat(canonical);
848
+ if (!info.isDirectory()) {
849
+ files.push(canonical);
850
+ return;
851
+ }
852
+ directories.push(canonical);
853
+ if (visited.has(canonical))
854
+ return;
855
+ visited.add(canonical);
856
+ for (const entry of await readdir(canonical, { withFileTypes: true })) {
857
+ await visit(join(canonical, entry.name));
858
+ }
859
+ }
860
+ await visit(directory, true);
861
+ return { directories, files };
862
+ }
863
+ function isInside(directory, path) {
864
+ const fromDirectory = relative(directory, path);
865
+ return !fromDirectory || (!isAbsolute(fromDirectory) && fromDirectory !== ".." && !fromDirectory.startsWith(`..${sep}`));
866
+ }
867
+ async function assertOutputSeparation(projects, stateDirectory, paths) {
868
+ const state = await canonicalOutputPath(stateDirectory);
869
+ const outputs = await Promise.all(paths.map(canonicalOutputPath));
870
+ const sources = await Promise.all(projects.flatMap((project) => project.timeline.resources)
871
+ .filter((resource) => resource.sourceKind === "local-file" && resource.source)
872
+ .map((resource) => canonicalOutputPath(resource.source)));
873
+ const protectedState = await stateTree(state);
874
+ const lexicalState = resolve(stateDirectory);
875
+ const collides = async (a, b) => a === b || await sameExistingFile(a, b);
876
+ for (let index = 0; index < outputs.length; index++) {
877
+ const output = outputs[index];
878
+ if (isInside(lexicalState, resolve(paths[index])) || isInside(state, output)
879
+ || protectedState.directories.some((directory) => isInside(directory, output))) {
880
+ throw new Error("HEADLESS_OUTPUT_COLLISION: output is inside Framekit state");
881
+ }
882
+ for (const protectedFile of [...sources, ...protectedState.files]) {
883
+ if (await collides(output, protectedFile))
884
+ throw new Error("HEADLESS_OUTPUT_COLLISION: output aliases protected state or registered media");
885
+ }
886
+ }
887
+ for (let i = 0; i < outputs.length; i++) {
888
+ for (let j = i + 1; j < outputs.length; j++) {
889
+ if (await collides(outputs[i], outputs[j]))
890
+ throw new Error("HEADLESS_OUTPUT_COLLISION: outputs alias each other");
570
891
  }
571
892
  }
893
+ }
894
+ async function writeVerifiedFcpxml(path, xml, digest, overwrite) {
895
+ await mkdir(dirname(path), { recursive: true });
572
896
  const temporary = `${path}.${randomUUID()}.tmp`;
573
897
  await writeFile(temporary, xml, { encoding: "utf8", flag: "wx" });
574
- await rename(temporary, path);
898
+ try {
899
+ if (overwrite)
900
+ await rename(temporary, path);
901
+ else
902
+ await link(temporary, path);
903
+ }
904
+ finally {
905
+ if (!overwrite)
906
+ await unlink(temporary).catch(() => { });
907
+ }
575
908
  const persisted = await readFile(path, "utf8");
576
909
  const persistedDigest = createHash("sha256").update(persisted).digest("hex");
577
910
  if (persistedDigest !== digest)
@@ -0,0 +1,2 @@
1
+ export * from "./headless-projects.js";
2
+ export * from "./external-edit.js";
@@ -0,0 +1,2 @@
1
+ export * from "./headless-projects.js";
2
+ export * from "./external-edit.js";
@@ -0,0 +1,4 @@
1
+ import type { DurationPolicyPlan, DurationPolicyRequest } from "../domain/duration.js";
2
+ export declare class DurationPolicyService {
3
+ plan(request: DurationPolicyRequest): DurationPolicyPlan;
4
+ }