@morshoto/framekit 0.1.0 → 0.1.4

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 (62) hide show
  1. package/README.md +42 -17
  2. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +57 -0
  3. package/dist-package/adapters/final-cut/typescript/src/connection.js +5 -1
  4. package/dist-package/adapters/final-cut/typescript/src/export.js +231 -8
  5. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +55 -5
  6. package/dist-package/adapters/final-cut/typescript/src/live.js +2 -2
  7. package/dist-package/adapters/final-cut/typescript/src/native.js +1000 -100
  8. package/dist-package/adapters/final-cut/typescript/src/publisher.js +40 -5
  9. package/dist-package/adapters/final-cut/typescript/src/session.js +21 -5
  10. package/dist-package/apps/mcp-server/src/main.js +9 -1
  11. package/dist-package/apps/mcp-server/src/routing.js +172 -0
  12. package/dist-package/apps/mcp-server/src/server.js +780 -33
  13. package/dist-package/packages/runtime/src/application/duration-policy-service.js +6 -0
  14. package/dist-package/packages/runtime/src/application/media-analysis-service.js +370 -0
  15. package/dist-package/packages/runtime/src/application/project-service.js +127 -0
  16. package/dist-package/packages/runtime/src/application/runtime-options.js +1 -0
  17. package/dist-package/packages/runtime/src/application/transaction-store.js +12 -0
  18. package/dist-package/packages/runtime/src/audio/dialogue-normalization.js +64 -0
  19. package/dist-package/packages/runtime/src/audio/noise-reduction.js +46 -0
  20. package/dist-package/packages/runtime/src/capabilities.js +112 -1
  21. package/dist-package/packages/runtime/src/color-correction.js +48 -0
  22. package/dist-package/packages/runtime/src/context/context-engine.js +11 -6
  23. package/dist-package/packages/runtime/src/context/context-service.js +30 -0
  24. package/dist-package/packages/runtime/src/context/revision.js +3 -0
  25. package/dist-package/packages/runtime/src/domain/capabilities.js +1 -0
  26. package/dist-package/packages/runtime/src/domain/context.js +1 -0
  27. package/dist-package/packages/runtime/src/domain/diff.js +1 -0
  28. package/dist-package/packages/runtime/src/domain/duration.js +1 -0
  29. package/dist-package/packages/runtime/src/domain/editing.js +1 -0
  30. package/dist-package/packages/runtime/src/domain/index.js +12 -0
  31. package/dist-package/packages/runtime/src/domain/media.js +7 -0
  32. package/dist-package/packages/runtime/src/domain/ports.js +1 -0
  33. package/dist-package/packages/runtime/src/domain/primitives.js +1 -0
  34. package/dist-package/packages/runtime/src/domain/project.js +1 -0
  35. package/dist-package/packages/runtime/src/domain/rough-cut.js +69 -0
  36. package/dist-package/packages/runtime/src/domain/skills.js +33 -0
  37. package/dist-package/packages/runtime/src/domain/types.js +5 -1
  38. package/dist-package/packages/runtime/src/domain/verification.js +1 -0
  39. package/dist-package/packages/runtime/src/editing/dialogue-normalization-service.js +141 -0
  40. package/dist-package/packages/runtime/src/editing/duration-policy.js +187 -0
  41. package/dist-package/packages/runtime/src/editing/edit-service.js +413 -0
  42. package/dist-package/packages/runtime/src/editing/filler-removal-service.js +337 -0
  43. package/dist-package/packages/runtime/src/editing/music-service.js +85 -0
  44. package/dist-package/packages/runtime/src/index.js +12 -3
  45. package/dist-package/packages/runtime/src/planning/rough-cut.js +65 -0
  46. package/dist-package/packages/runtime/src/runtime.js +130 -825
  47. package/dist-package/packages/runtime/src/skills/builtin.js +339 -0
  48. package/dist-package/packages/runtime/src/skills/index.js +3 -0
  49. package/dist-package/packages/runtime/src/skills/registry.js +74 -0
  50. package/dist-package/packages/runtime/src/skills/requirements.js +170 -0
  51. package/dist-package/packages/runtime/src/skills/runtime.js +239 -0
  52. package/dist-package/packages/runtime/src/speech/filler-detector.js +132 -0
  53. package/dist-package/packages/runtime/src/speech/safe-cut-resolver.js +314 -0
  54. package/dist-package/packages/runtime/src/timeline/rational-time.js +58 -0
  55. package/dist-package/packages/runtime/src/verification/verification.js +712 -1
  56. package/dist-package/packages/testkit/src/fixture-analyzers.js +27 -0
  57. package/dist-package/packages/testkit/src/in-memory-editor.js +286 -3
  58. package/dist-package/packages/testkit/src/index.js +1 -0
  59. package/dist-package/packages/testkit/src/skill-fixtures.js +64 -0
  60. package/package.json +15 -7
  61. /package/dist-package/packages/runtime/src/{diff/diff.js → timeline/snapshot-diff.js} +0 -0
  62. /package/dist-package/packages/runtime/src/{snapshot-digest.js → timeline/snapshot-digest.js} +0 -0
@@ -1,3 +1,4 @@
1
+ import { CAPABILITY_SCHEMA_VERSION } from "./domain/capabilities.js";
1
2
  export function canonicalTimelineMode(capabilities) {
2
3
  const editor = capabilities.editor;
3
4
  const hasExplicitTargeting = Boolean(editor.projectCatalogRead && editor.projectSelection);
@@ -14,11 +15,121 @@ export function canonicalTimelineMode(capabilities) {
14
15
  return "metadata-only";
15
16
  }
16
17
  export function withCanonicalTimelineMode(capabilities) {
17
- return {
18
+ const normalized = {
18
19
  ...capabilities,
19
20
  editor: {
20
21
  ...capabilities.editor,
21
22
  canonicalTimelineMode: canonicalTimelineMode(capabilities),
22
23
  },
23
24
  };
25
+ const previous = capabilities.families;
26
+ if (!previous)
27
+ return normalized;
28
+ return withCapabilityFamilies(normalized, {
29
+ backend: previous.connection.status.backend,
30
+ nativeBackend: previous.native.selectionWrite.backend,
31
+ publishingBackend: previous.publishing.projectCreation.backend,
32
+ exportBackend: previous.export.timeline.backend,
33
+ analyzerBackend: previous.analyzers.speechTranscribe.backend,
34
+ connection: previous.connection.status,
35
+ native: nativeAvailability(previous.native),
36
+ publishing: previous.publishing.projectCreation,
37
+ export: previous.export.timeline,
38
+ });
39
+ }
40
+ /**
41
+ * Adds the versioned operation-level contract while retaining the legacy
42
+ * boolean fields used by existing runtime consumers.
43
+ */
44
+ export function withCapabilityFamilies(capabilities, options = {}) {
45
+ const previous = capabilities.families;
46
+ const backend = options.backend ?? previous?.connection.status.backend ?? "unknown";
47
+ const normalized = {
48
+ ...capabilities,
49
+ schemaVersion: CAPABILITY_SCHEMA_VERSION,
50
+ editor: {
51
+ ...capabilities.editor,
52
+ canonicalTimelineMode: canonicalTimelineMode(capabilities),
53
+ },
54
+ };
55
+ const editor = normalized.editor;
56
+ const native = {
57
+ ...nativeAvailability(previous?.native),
58
+ ...options.native,
59
+ };
60
+ const families = {
61
+ connection: {
62
+ status: descriptorFrom(options.connection ?? previous?.connection.status ?? true, options.connectionBackend ?? backend, "observed", "editor connection is unavailable"),
63
+ },
64
+ observation: {
65
+ timeline: descriptorFrom(editor.timelineSnapshotRead || editor.liveStateRead, backend, editor.timelineSnapshotRead ? "canonical-read" : "observed", "timeline observation is unavailable"),
66
+ media: descriptorFrom(editor.timelineSnapshotRead && editor.projectRead, backend, "canonical-read", "media observation is unavailable"),
67
+ },
68
+ canonicalDocument: {
69
+ read: descriptorFrom(editor.canonicalTimelineMode === "canonical-read"
70
+ || editor.canonicalTimelineMode === "canonical-write", backend, "canonical-read", "canonical timeline reads are unavailable"),
71
+ write: descriptorFrom(editor.canonicalTimelineMode === "canonical-write", backend, "canonical-write", "canonical timeline writes are unavailable"),
72
+ artifactWrite: descriptorFrom(editor.timelineArtifactWrite, backend, "artifact-write", "canonical artifact writes are unavailable"),
73
+ },
74
+ native: nativeFamily(native, options.nativeBackend ?? previous?.native.selectionWrite.backend ?? backend),
75
+ publishing: {
76
+ projectCreation: descriptorFrom(options.publishing ?? previous?.publishing.projectCreation ?? false, options.publishingBackend ?? backend, "verified", "new project publishing is unavailable"),
77
+ },
78
+ export: {
79
+ timeline: descriptorFrom(options.export ?? previous?.export.timeline ?? false, options.exportBackend ?? backend, "verified", "timeline export is unavailable"),
80
+ },
81
+ analyzers: {
82
+ speechTranscribe: analyzerDescriptor(capabilities.analyzers.speechTranscribe, options.analyzerBackend ?? backend, "speech transcription"),
83
+ speechVad: analyzerDescriptor(capabilities.analyzers.speechVad, options.analyzerBackend ?? backend, "speech VAD"),
84
+ audioLoudness: analyzerDescriptor(capabilities.analyzers.audioLoudness, options.analyzerBackend ?? backend, "audio loudness analysis"),
85
+ audioNoise: analyzerDescriptor(Boolean(capabilities.analyzers.audioNoise), options.analyzerBackend ?? backend, "audio noise analysis"),
86
+ visualTrack: analyzerDescriptor(capabilities.analyzers.visualTrack, options.analyzerBackend ?? backend, "visual analysis"),
87
+ },
88
+ };
89
+ return { ...normalized, families };
90
+ }
91
+ function descriptorFrom(value, backend, guarantee, unavailableReason) {
92
+ if (typeof value !== "boolean")
93
+ return value;
94
+ return value
95
+ ? { available: true, backend, guarantee }
96
+ : { available: false, backend, guarantee: "none", unavailableReason };
97
+ }
98
+ function analyzerDescriptor(available, backend, operation) {
99
+ return descriptorFrom(available, backend, "verified", `${operation} is unavailable`);
100
+ }
101
+ function nativeFamily(native, backend) {
102
+ const nativeOperations = [
103
+ "selectionWrite",
104
+ "undo",
105
+ "mediaLibrarySearch",
106
+ "mediaImport",
107
+ "mediaSelection",
108
+ "mediaAppendSelected",
109
+ "timelineOccurrenceLocate",
110
+ "bladeAtPlayhead",
111
+ "deleteRange",
112
+ "trimToDuration",
113
+ "mediaAppend",
114
+ "mediaInsert",
115
+ "titlePlacement",
116
+ "timelineFocus",
117
+ "projectCreation",
118
+ "clipInsertion",
119
+ "clipMovement",
120
+ "transitionDiscovery",
121
+ "transitionPlacement",
122
+ ];
123
+ return Object.fromEntries(nativeOperations.map((operation) => [
124
+ operation,
125
+ descriptorFrom(Boolean(native[operation]), backend, "native-verified", `native ${nativeOperationLabel(operation)} is unavailable`),
126
+ ]));
127
+ }
128
+ function nativeOperationLabel(operation) {
129
+ return operation.replace(/[A-Z]/g, (character) => ` ${character.toLowerCase()}`);
130
+ }
131
+ function nativeAvailability(native) {
132
+ if (!native)
133
+ return {};
134
+ return Object.fromEntries(Object.entries(native).map(([operation, capability]) => [operation, capability.available]));
24
135
  }
@@ -0,0 +1,48 @@
1
+ export const COLOR_CORRECTION_PRESETS = {
2
+ neutral: { exposure: 0, contrast: 0, saturation: 0, temperature: 0, tint: 0, preset: "neutral" },
3
+ warm: { exposure: 0.1, contrast: 0, saturation: 0.1, temperature: 15, tint: 0, preset: "warm" },
4
+ cool: { exposure: 0.1, contrast: 0, saturation: 0, temperature: -15, tint: 0, preset: "cool" },
5
+ "high-contrast": { exposure: 0, contrast: 0.25, saturation: 0.05, temperature: 0, tint: 0, preset: "high-contrast" },
6
+ };
7
+ export function planColorCorrection(clip, request) {
8
+ const before = normalizeCorrection(clip.colorCorrection);
9
+ const preset = request.preset ? COLOR_CORRECTION_PRESETS[request.preset] : before;
10
+ const after = {
11
+ exposure: request.exposure ?? preset.exposure,
12
+ contrast: request.contrast ?? preset.contrast,
13
+ saturation: request.saturation ?? preset.saturation,
14
+ temperature: request.temperature ?? preset.temperature,
15
+ tint: request.tint ?? preset.tint,
16
+ ...(request.preset ? { preset: request.preset } : clip.colorCorrection?.preset ? { preset: clip.colorCorrection.preset } : {}),
17
+ };
18
+ validateCorrection(after);
19
+ const changedFields = Object.keys(after)
20
+ .filter((field) => after[field] !== before[field]);
21
+ return {
22
+ decision: changedFields.length > 0 ? "APPLY" : "NO_OP",
23
+ clipId: clip.id,
24
+ before,
25
+ after,
26
+ changedFields,
27
+ reasonCodes: changedFields.length > 0 ? ["APPLY_COLOR_CORRECTION"] : ["ALREADY_MATCHES"],
28
+ };
29
+ }
30
+ export function normalizeCorrection(correction) {
31
+ return {
32
+ exposure: correction?.exposure ?? 0,
33
+ contrast: correction?.contrast ?? 0,
34
+ saturation: correction?.saturation ?? 0,
35
+ temperature: correction?.temperature ?? 0,
36
+ tint: correction?.tint ?? 0,
37
+ ...(correction?.preset ? { preset: correction.preset } : {}),
38
+ };
39
+ }
40
+ function validateCorrection(correction) {
41
+ if (!Number.isFinite(correction.exposure) || correction.exposure < -4 || correction.exposure > 4
42
+ || !Number.isFinite(correction.contrast) || correction.contrast < -1 || correction.contrast > 1
43
+ || !Number.isFinite(correction.saturation) || correction.saturation < -1 || correction.saturation > 1
44
+ || !Number.isFinite(correction.temperature) || correction.temperature < -100 || correction.temperature > 100
45
+ || !Number.isFinite(correction.tint) || correction.tint < -100 || correction.tint > 100) {
46
+ throw new Error("INVALID_OPERATION: color correction values are outside the supported basic range");
47
+ }
48
+ }
@@ -1,4 +1,5 @@
1
- import { diffSnapshots } from "../diff/diff.js";
1
+ import { diffSnapshots } from "../timeline/snapshot-diff.js";
2
+ import { sameMediaSourceIdentity } from "../domain/media.js";
2
3
  export class ContextEngine {
3
4
  editor;
4
5
  snapshots = new Map();
@@ -109,14 +110,18 @@ export class ContextEngine {
109
110
  const next = structuredClone(snapshot);
110
111
  next.media = next.media.map((media) => {
111
112
  const understanding = this.mediaUnderstanding.get(media.mediaId);
112
- if (!understanding || understanding.source !== media.source)
113
+ if (!understanding || !sameMediaSourceIdentity(understanding.sourceIdentity, media))
113
114
  return media;
115
+ const attached = structuredClone(understanding);
114
116
  return {
115
117
  ...media,
116
- speech: understanding.speech,
117
- audio: understanding.audio,
118
- visual: understanding.visual,
119
- analysisRevision: understanding.analysisRevision.id,
118
+ metadata: attached.metadata,
119
+ speech: attached.speech,
120
+ audio: attached.audio,
121
+ visual: attached.visual,
122
+ semantic: attached.semantic,
123
+ analysis: attached.analysis,
124
+ analysisRevision: attached.analysisRevision.id,
120
125
  };
121
126
  });
122
127
  return next;
@@ -0,0 +1,30 @@
1
+ export class ContextService {
2
+ adapter;
3
+ context;
4
+ constructor(adapter, context) {
5
+ this.adapter = adapter;
6
+ this.context = context;
7
+ }
8
+ async inspectContext(capabilities) {
9
+ return this.context.inspectContext(capabilities);
10
+ }
11
+ async inspectLiveEditor() {
12
+ return this.liveAdapter().readLiveState();
13
+ }
14
+ async liveChangesSince(revision, waitMs = 0) {
15
+ return this.liveAdapter().liveChangesSince(revision, waitMs);
16
+ }
17
+ async changesSince(revision) {
18
+ return this.context.changesSince(revision);
19
+ }
20
+ async contextChangesSince(revision, waitMs = 0) {
21
+ return this.context.contextChangesSince(revision, waitMs);
22
+ }
23
+ liveAdapter() {
24
+ const candidate = this.adapter;
25
+ if (typeof candidate.readLiveState !== "function" || typeof candidate.liveChangesSince !== "function") {
26
+ throw new Error("CAPABILITY_UNAVAILABLE: live Framekit editor state");
27
+ }
28
+ return candidate;
29
+ }
30
+ }
@@ -0,0 +1,3 @@
1
+ export function sameRevision(left, right) {
2
+ return left.id === right.id && left.sequence === right.sequence;
3
+ }
@@ -0,0 +1 @@
1
+ export const CAPABILITY_SCHEMA_VERSION = 1;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ export * from "./primitives.js";
2
+ export * from "./project.js";
3
+ export * from "./context.js";
4
+ export * from "./media.js";
5
+ export * from "./editing.js";
6
+ export * from "./diff.js";
7
+ export * from "./capabilities.js";
8
+ export * from "./ports.js";
9
+ export * from "./verification.js";
10
+ export * from "./rough-cut.js";
11
+ export * from "./duration.js";
12
+ export * from "./skills.js";
@@ -0,0 +1,7 @@
1
+ export function sameMediaSourceIdentity(left, right) {
2
+ return left.mediaId === right.mediaId
3
+ && left.source === right.source
4
+ && left.sourceDigest === right.sourceDigest
5
+ && left.mediaKind === right.mediaKind
6
+ && left.duration === right.duration;
7
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,69 @@
1
+ /** Build a deterministic primary-storyline workflow without mutating a project. */
2
+ export function planRoughCutConstruction(snapshot, request) {
3
+ assertRevision(snapshot.revision, request.baseRevision);
4
+ if (request.shots.length === 0)
5
+ throw new Error("INVALID_ROUGH_CUT: at least one shot is required");
6
+ const imports = request.imports ?? [];
7
+ const knownMedia = new Map(snapshot.media.map((media) => [media.mediaId, media]));
8
+ const importedIds = new Set();
9
+ for (const media of imports) {
10
+ if (importedIds.has(media.mediaId) || knownMedia.has(media.mediaId)) {
11
+ throw new Error(`MEDIA_ALREADY_EXISTS: ${media.mediaId}`);
12
+ }
13
+ if (!media.mediaId.trim() || !media.source.trim() || !media.sourceDigest.trim()
14
+ || !Number.isFinite(media.duration) || media.duration <= 0) {
15
+ throw new Error("INVALID_OPERATION: imported media requires mediaId, source, duration, and digest");
16
+ }
17
+ if (media.mediaKind !== "video") {
18
+ throw new Error(`ROUGH_CUT_VIDEO_REQUIRED: ${media.mediaId}`);
19
+ }
20
+ importedIds.add(media.mediaId);
21
+ knownMedia.set(media.mediaId, media);
22
+ }
23
+ const occurrenceIds = new Set(snapshot.timeline.clips.map((clip) => clip.id));
24
+ const operations = imports.map((media) => ({ ...media }));
25
+ let start = snapshot.timeline.duration;
26
+ for (const shot of request.shots) {
27
+ if (!shot.occurrenceId.trim() || !shot.mediaId.trim()) {
28
+ throw new Error("INVALID_ROUGH_CUT: shot occurrenceId and mediaId are required");
29
+ }
30
+ if (occurrenceIds.has(shot.occurrenceId)) {
31
+ throw new Error(`OCCURRENCE_ALREADY_EXISTS: ${shot.occurrenceId}`);
32
+ }
33
+ occurrenceIds.add(shot.occurrenceId);
34
+ const media = knownMedia.get(shot.mediaId);
35
+ if (!media)
36
+ throw new Error(`MEDIA_NOT_FOUND: ${shot.mediaId}`);
37
+ if (media.mediaKind !== "video")
38
+ throw new Error(`ROUGH_CUT_VIDEO_REQUIRED: ${shot.mediaId}`);
39
+ const duration = shot.duration ?? media.duration;
40
+ if (duration === undefined || !Number.isFinite(duration) || duration <= 0) {
41
+ throw new Error(`ROUGH_CUT_DURATION_REQUIRED: ${shot.mediaId}`);
42
+ }
43
+ if (media.duration !== undefined && duration > media.duration) {
44
+ throw new Error(`ROUGH_CUT_DURATION_EXCEEDS_SOURCE: ${shot.mediaId}`);
45
+ }
46
+ operations.push({
47
+ type: "timeline.media.add",
48
+ occurrenceId: shot.occurrenceId,
49
+ mediaId: shot.mediaId,
50
+ role: "video",
51
+ start,
52
+ duration,
53
+ targetLane: "primary",
54
+ });
55
+ start += duration;
56
+ }
57
+ return {
58
+ projectId: snapshot.projectId,
59
+ timelineId: snapshot.timeline.id,
60
+ baseRevision: structuredClone(request.baseRevision),
61
+ operations,
62
+ duration: start,
63
+ };
64
+ }
65
+ function assertRevision(actual, expected) {
66
+ if (actual.id !== expected.id || actual.sequence !== expected.sequence) {
67
+ throw new Error("STALE_CONTEXT: rough-cut plan base revision does not match current project");
68
+ }
69
+ }
@@ -0,0 +1,33 @@
1
+ /** Version of the editor-independent Skill contract. */
2
+ export const SKILL_CONTRACT_VERSION = 1;
3
+ /** The ordered phases shared by every Skill implementation. */
4
+ export const SKILL_LIFECYCLE = [
5
+ "discover",
6
+ "resolve",
7
+ "plan",
8
+ "preview",
9
+ "execute",
10
+ "verify",
11
+ "accept",
12
+ "rollback",
13
+ ];
14
+ /** Semantic operation names are deliberately independent of editor commands. */
15
+ export const SKILL_OPERATIONS = [
16
+ "rename-clip",
17
+ "trim-clip",
18
+ "set-gain",
19
+ "reduce-noise",
20
+ "set-color-correction",
21
+ "ripple-delete",
22
+ "add-marker",
23
+ "media.import",
24
+ "timeline.media.add",
25
+ "timeline.audio.fades",
26
+ "timeline.title.add",
27
+ "timeline.media.move",
28
+ "timeline.media.replace",
29
+ "timeline.media.remove",
30
+ "timeline.transition.add",
31
+ "timeline.audio.attach",
32
+ "timeline.audio.mix",
33
+ ];
@@ -1 +1,5 @@
1
- export {};
1
+ /**
2
+ * Backwards-compatible type barrel. New code should import from the focused
3
+ * domain modules when it needs a narrower dependency surface.
4
+ */
5
+ export * from "./index.js";
@@ -0,0 +1,141 @@
1
+ import { planDialogueGain } from "../audio/dialogue-normalization.js";
2
+ import { sameRevision } from "../context/revision.js";
3
+ export class DialogueNormalizationService {
4
+ adapter;
5
+ project;
6
+ analysis;
7
+ edits;
8
+ previews = new Map();
9
+ constructor(adapter, project, analysis, edits) {
10
+ this.adapter = adapter;
11
+ this.project = project;
12
+ this.analysis = analysis;
13
+ this.edits = edits;
14
+ }
15
+ async preview(request) {
16
+ const before = await this.project.inspectProject();
17
+ if (!sameRevision(request.baseRevision, before.revision)) {
18
+ throw new Error("STALE_CONTEXT: dialogue normalization base revision does not match current editor state");
19
+ }
20
+ await this.assertCapabilities();
21
+ const measurement = await this.analysis.measureAudio(request.mediaId, request.occurrenceId);
22
+ const plan = planDialogueGain(measurement, request);
23
+ const result = {
24
+ measurement,
25
+ plan,
26
+ operations: [],
27
+ warnings: plan.decision === "SKIP" ? [...plan.reasonCodes] : [],
28
+ };
29
+ if (plan.decision !== "APPLY")
30
+ return result;
31
+ const operation = {
32
+ type: "set-gain",
33
+ clipId: request.occurrenceId,
34
+ gainDb: plan.clampedGainDb,
35
+ baseRevision: request.baseRevision,
36
+ };
37
+ const editPreview = await this.edits.previewEdit({
38
+ baseRevision: request.baseRevision,
39
+ operations: [operation],
40
+ });
41
+ this.previews.set(editPreview.previewToken, { request: structuredClone(request), measurement });
42
+ return {
43
+ ...result,
44
+ operations: [operation],
45
+ expectedDiff: editPreview.expectedDiff,
46
+ previewToken: editPreview.previewToken,
47
+ warnings: editPreview.warnings,
48
+ expiresAt: editPreview.expiresAt,
49
+ };
50
+ }
51
+ async execute(previewToken) {
52
+ const stored = this.previews.get(previewToken);
53
+ if (!stored)
54
+ throw new Error(`PREVIEW_TOKEN_INVALID: unknown dialogue normalization preview ${previewToken}`);
55
+ this.previews.delete(previewToken);
56
+ const transaction = await this.edits.executeEdit(previewToken);
57
+ if (transaction.status !== "VERIFIED")
58
+ return transaction;
59
+ let afterMeasurement;
60
+ try {
61
+ afterMeasurement = await this.analysis.measureAudio(stored.request.mediaId, stored.request.occurrenceId);
62
+ }
63
+ catch (error) {
64
+ return this.rollbackAfterMeasurementFailure(transaction, error);
65
+ }
66
+ const checks = [
67
+ measurementCheck(afterMeasurement),
68
+ loudnessCheck(afterMeasurement, stored.request),
69
+ peakCheck(afterMeasurement, stored.request),
70
+ ];
71
+ const verification = transaction.verification ?? { passed: true, checks: [] };
72
+ transaction.verification = {
73
+ ...verification,
74
+ checks: [...verification.checks, ...checks],
75
+ passed: verification.passed && checks.every((check) => check.passed),
76
+ };
77
+ if (transaction.verification.passed)
78
+ return transaction;
79
+ const restored = await this.edits.undo(transaction.id);
80
+ transaction.after = restored;
81
+ transaction.status = "ROLLED_BACK";
82
+ return transaction;
83
+ }
84
+ async assertCapabilities() {
85
+ const capabilities = (await this.adapter.getCapabilities()).editor;
86
+ if (!capabilities.timelineSnapshotRead || !capabilities.timelineWrite
87
+ || !capabilities.readAfterWrite || !capabilities.rollback || !capabilities.compositeTransactions) {
88
+ throw new Error("CAPABILITY_UNAVAILABLE: dialogue normalization requires canonical timeline write, read-after-write, and rollback");
89
+ }
90
+ }
91
+ async rollbackAfterMeasurementFailure(transaction, error) {
92
+ const restored = await this.edits.undo(transaction.id);
93
+ transaction.after = restored;
94
+ transaction.status = "ROLLED_BACK";
95
+ const check = {
96
+ name: "dialogue-measurement",
97
+ passed: false,
98
+ status: "failed",
99
+ reason: "POST_WRITE_MEASUREMENT_FAILED",
100
+ detail: String(error),
101
+ };
102
+ transaction.verification = {
103
+ ...(transaction.verification ?? { passed: true, checks: [] }),
104
+ passed: false,
105
+ checks: [...(transaction.verification?.checks ?? []), check],
106
+ };
107
+ return transaction;
108
+ }
109
+ }
110
+ function measurementCheck(measurement) {
111
+ return {
112
+ name: "dialogue-measurement",
113
+ passed: measurement.valid,
114
+ status: measurement.valid ? "passed" : "failed",
115
+ observed: measurement,
116
+ reason: measurement.valid ? undefined : "MEASUREMENT_INVALID",
117
+ detail: measurement.valid ? "post-write dialogue measurement is valid" : "post-write dialogue measurement is invalid",
118
+ };
119
+ }
120
+ function loudnessCheck(measurement, request) {
121
+ const passed = measurement.valid && Math.abs(measurement.integratedLufs - request.targetLufs) <= request.toleranceDb;
122
+ return {
123
+ name: "dialogue-loudness",
124
+ passed,
125
+ status: passed ? "passed" : "failed",
126
+ expected: { targetLufs: request.targetLufs, toleranceDb: request.toleranceDb },
127
+ observed: { integratedLufs: measurement.integratedLufs },
128
+ detail: passed ? "post-write loudness is inside the configured tolerance" : "post-write loudness is outside the configured tolerance",
129
+ };
130
+ }
131
+ function peakCheck(measurement, request) {
132
+ const passed = measurement.valid && measurement.truePeakDb <= request.maxTruePeakDb;
133
+ return {
134
+ name: "dialogue-true-peak",
135
+ passed,
136
+ status: passed ? "passed" : "failed",
137
+ expected: { maxTruePeakDb: request.maxTruePeakDb },
138
+ observed: { truePeakDb: measurement.truePeakDb },
139
+ detail: passed ? "post-write true peak is within the configured limit" : "post-write true peak exceeds the configured limit",
140
+ };
141
+ }