@morshoto/framekit 0.1.11 → 0.1.13

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 (29) hide show
  1. package/README.md +1 -0
  2. package/dist-package/adapters/final-cut/typescript/src/analyzers.js +68 -5
  3. package/dist-package/adapters/final-cut/typescript/src/canonical-recovery.js +31 -0
  4. package/dist-package/adapters/final-cut/typescript/src/canonical-verification.js +16 -0
  5. package/dist-package/adapters/final-cut/typescript/src/canonical.js +978 -98
  6. package/dist-package/adapters/final-cut/typescript/src/fcpxml.js +26 -7
  7. package/dist-package/adapters/final-cut/typescript/src/index.js +3 -0
  8. package/dist-package/adapters/final-cut/typescript/src/library-inspection.js +2 -0
  9. package/dist-package/adapters/final-cut/typescript/src/native.js +321 -19
  10. package/dist-package/adapters/final-cut/typescript/src/shadow-mutation.js +71 -17
  11. package/dist-package/adapters/final-cut/typescript/src/sqlite-experiment.js +472 -0
  12. package/dist-package/adapters/final-cut/typescript/src/sqlite-materialization.js +230 -0
  13. package/dist-package/apps/mcp-server/src/headless-sessions.js +47 -4
  14. package/dist-package/apps/mcp-server/src/main.js +33 -1
  15. package/dist-package/apps/mcp-server/src/routing.js +17 -0
  16. package/dist-package/apps/mcp-server/src/server.js +87 -28
  17. package/dist-package/packages/runtime/src/application/media-analysis-service.js +52 -6
  18. package/dist-package/packages/runtime/src/context/context-engine.js +313 -8
  19. package/dist-package/packages/runtime/src/context/context-service.js +5 -2
  20. package/dist-package/packages/runtime/src/context/project-catalog.js +58 -2
  21. package/dist-package/packages/runtime/src/domain/incremental-sync.js +153 -0
  22. package/dist-package/packages/runtime/src/domain/index.js +1 -0
  23. package/dist-package/packages/runtime/src/editing/edit-service.js +8 -2
  24. package/dist-package/packages/runtime/src/runtime.js +5 -2
  25. package/dist-package/packages/runtime/src/skills/builtin.js +99 -8
  26. package/dist-package/packages/runtime/src/skills/runtime.js +1 -0
  27. package/dist-package/packages/runtime/src/timeline/editing-session.js +13 -0
  28. package/dist-package/packages/runtime/src/timeline/snapshot-diff.js +169 -10
  29. package/package.json +9 -5
@@ -1,6 +1,7 @@
1
1
  import { diffSnapshots } from "../timeline/snapshot-diff.js";
2
2
  import { sameMediaSourceIdentity } from "../domain/media.js";
3
3
  import { sameRevision } from "./revision.js";
4
+ import { withCanonicalTimelineMode, withCapabilityFamilies } from "../capabilities.js";
4
5
  export class ContextEngine {
5
6
  editor;
6
7
  snapshots = new Map();
@@ -29,38 +30,208 @@ export class ContextEngine {
29
30
  throw new Error(`REVISION_NOT_FOUND: ${revision.id}`);
30
31
  return diffSnapshots(before, await this.inspectProject());
31
32
  }
32
- async contextChangesSince(revision, waitMs = 0) {
33
+ async timelineChangesSince(request) {
34
+ const identity = await this.editor.getIdentity();
33
35
  const capabilities = await this.editor.getCapabilities();
36
+ const canonical = capabilities.editor.canonicalTimelineMode !== "metadata-only"
37
+ && (capabilities.editor.timelineSnapshotRead || capabilities.editor.incrementalChanges);
38
+ const source = {
39
+ source: identity.name,
40
+ backend: identity.backend,
41
+ guarantee: canonical ? "canonical-read" : "metadata-only",
42
+ };
43
+ if (!canonical) {
44
+ return {
45
+ status: "unavailable",
46
+ target: structuredClone(request.target),
47
+ source,
48
+ from: structuredClone(request.from),
49
+ changes: [],
50
+ reason: "canonical timeline changes are unavailable",
51
+ };
52
+ }
53
+ const resolvedTarget = await this.resolveTimelineChangesTarget(request.target, source);
54
+ if (resolvedTarget.status !== "ready") {
55
+ return {
56
+ ...resolvedTarget,
57
+ from: structuredClone(request.from),
58
+ changes: [],
59
+ };
60
+ }
61
+ const before = this.snapshots.get(request.from.id);
62
+ if (!before) {
63
+ return {
64
+ status: "stale",
65
+ target: resolvedTarget.target,
66
+ source,
67
+ from: structuredClone(request.from),
68
+ changes: [],
69
+ reason: `revision ${request.from.id} was not observed in the canonical context`,
70
+ };
71
+ }
72
+ if (!sameRevision(before.revision, request.from)) {
73
+ return {
74
+ status: "stale",
75
+ target: resolvedTarget.target,
76
+ source,
77
+ from: structuredClone(request.from),
78
+ changes: [],
79
+ reason: "requested revision does not match the observed canonical revision",
80
+ };
81
+ }
82
+ if (before.projectId !== resolvedTarget.target.projectId || before.timeline.id !== resolvedTarget.target.sequenceId) {
83
+ return {
84
+ status: "stale",
85
+ target: resolvedTarget.target,
86
+ source,
87
+ from: structuredClone(request.from),
88
+ changes: [],
89
+ reason: "requested target does not match the active target at the observed revision",
90
+ };
91
+ }
92
+ try {
93
+ const timeline = await this.changesSince(request.from);
94
+ const current = await this.inspectProject();
95
+ if (current.projectId !== resolvedTarget.target.projectId || current.timeline.id !== resolvedTarget.target.sequenceId) {
96
+ return {
97
+ status: "stale",
98
+ target: resolvedTarget.target,
99
+ source,
100
+ from: structuredClone(request.from),
101
+ changes: [],
102
+ reason: "active target changed while reading the canonical timeline",
103
+ };
104
+ }
105
+ return {
106
+ status: "ready",
107
+ target: resolvedTarget.target,
108
+ source,
109
+ from: structuredClone(request.from),
110
+ to: structuredClone(timeline.to),
111
+ changes: structuredClone(timeline.changes),
112
+ timeline,
113
+ };
114
+ }
115
+ catch (error) {
116
+ const reason = String(error);
117
+ if (reason.includes("REVISION_NOT_FOUND") || reason.includes("STALE_CONTEXT") || reason.includes("TARGET_MISMATCH")) {
118
+ return {
119
+ status: "stale",
120
+ target: resolvedTarget.target,
121
+ source,
122
+ from: structuredClone(request.from),
123
+ changes: [],
124
+ reason,
125
+ };
126
+ }
127
+ if (reason.includes("CAPABILITY_UNAVAILABLE")) {
128
+ return {
129
+ status: "unavailable",
130
+ target: resolvedTarget.target,
131
+ source,
132
+ from: structuredClone(request.from),
133
+ changes: [],
134
+ reason,
135
+ };
136
+ }
137
+ throw error;
138
+ }
139
+ }
140
+ async contextChangesSince(cursorOrRevision, waitMs = 0) {
141
+ const cursor = isContextCursor(cursorOrRevision) ? cursorOrRevision : undefined;
142
+ const revision = isContextCursor(cursorOrRevision) ? cursorOrRevision.revision : cursorOrRevision;
143
+ if (cursor?.target)
144
+ await this.validateCursorTarget(revision, cursor.target);
145
+ const identity = await this.editor.getIdentity();
146
+ const capabilities = withCanonicalTimelineMode(withCapabilityFamilies(await this.editor.getCapabilities(), {
147
+ backend: identity.backend,
148
+ }));
34
149
  const incremental = capabilities.editor.incrementalChanges
35
150
  ? await this.editor.readChanges?.(revision)
36
151
  : undefined;
37
- const timeline = incremental?.timeline ?? await this.optionalTimelineChanges(revision);
152
+ const timeline = canonicalTimelineAvailable(capabilities)
153
+ ? incremental?.timeline ?? await this.optionalTimelineChanges(revision)
154
+ : undefined;
38
155
  const stateChanges = [
39
156
  ...(incremental?.stateChanges ?? []),
40
157
  ...(await this.liveChangesSince(revision, waitMs)),
41
158
  ];
42
- const assetChanges = incremental?.assetChanges ?? [];
43
- const to = latestRevision(revision, timeline?.to, ...stateChanges.map((change) => change.revision), incremental?.to);
159
+ const assetChanges = canonicalTimelineAvailable(capabilities)
160
+ ? incremental?.assetChanges ?? []
161
+ : [];
162
+ // Canonical timeline revisions and live metadata revisions may come from
163
+ // independent sequence spaces. When timeline changes exist, keep their
164
+ // provider revision as the source-bound cursor instead of comparing the
165
+ // unrelated sequence numbers with live state revisions.
166
+ const to = timeline?.to
167
+ ?? latestRevision(revision, ...stateChanges.map((change) => change.revision), incremental?.to);
168
+ let target = contextTarget(this.snapshots.get(revision.id), stateChanges);
169
+ if (!target) {
170
+ const liveState = await this.optionalLiveState();
171
+ target = contextTarget(undefined, liveState ? [
172
+ { kind: "active-sequence-changed", revision: liveState.revision, state: liveState },
173
+ ] : []);
174
+ }
175
+ const provenance = contextProvenanceSet(identity.backend, capabilities, target, {
176
+ timeline,
177
+ stateChanges,
178
+ assetChanges,
179
+ });
44
180
  return {
45
181
  from: revision,
46
182
  to,
183
+ cursor: { revision: to, ...(target ? { target } : {}) },
184
+ provenance,
185
+ changedScopes: changedScopes(timeline, stateChanges, assetChanges),
47
186
  timeline,
48
187
  stateChanges: dedupeStateChanges(stateChanges),
49
188
  assetChanges,
50
189
  };
51
190
  }
191
+ async validateCursorTarget(revision, target) {
192
+ const revisionTarget = contextTarget(this.snapshots.get(revision.id), []);
193
+ if (revisionTarget) {
194
+ if (!sameContextTarget(revisionTarget, target)) {
195
+ throw new Error(`TARGET_MISMATCH: cursor target ${formatContextTarget(target)} does not match revision target ${formatContextTarget(revisionTarget)}`);
196
+ }
197
+ return;
198
+ }
199
+ const liveState = await this.optionalLiveState();
200
+ const activeTarget = contextTarget(undefined, liveState ? [
201
+ { kind: "active-sequence-changed", revision: liveState.revision, state: liveState },
202
+ ] : []);
203
+ if (!activeTarget || !sameContextTarget(activeTarget, target)) {
204
+ throw new Error(`TARGET_MISMATCH: cursor target ${formatContextTarget(target)} does not match the active target`);
205
+ }
206
+ }
52
207
  async inspectContext(capabilities) {
53
- const project = await this.inspectProject();
208
+ const identity = await this.editor.getIdentity();
209
+ const project = canonicalTimelineAvailable(capabilities)
210
+ ? await this.inspectProject()
211
+ : undefined;
54
212
  const editorState = await this.optionalLiveState();
55
- const revision = project.revision;
213
+ const revision = project?.revision ?? editorState?.revision;
214
+ if (!revision)
215
+ throw new Error("CAPABILITY_UNAVAILABLE: context revision");
216
+ const target = contextTarget(project, editorState ? [
217
+ { kind: "active-sequence-changed", revision: editorState.revision, state: editorState },
218
+ ] : []);
219
+ const provenance = primaryContextProvenance(identity.backend, capabilities, target);
220
+ const cursor = { revision, ...(target ? { target } : {}) };
56
221
  return {
57
222
  revision,
58
- project,
223
+ cursor,
224
+ provenance,
225
+ changedScopes: [],
226
+ ...(project ? { project } : {}),
59
227
  ...(editorState ? { editorState } : {}),
60
- media: project.media,
228
+ media: project?.media ?? [],
61
229
  recentChanges: {
62
230
  from: revision,
63
231
  to: revision,
232
+ cursor,
233
+ provenance: [provenance],
234
+ changedScopes: [],
64
235
  stateChanges: [],
65
236
  assetChanges: [],
66
237
  },
@@ -70,6 +241,46 @@ export class ContextEngine {
70
241
  attachMediaUnderstanding(understanding) {
71
242
  this.mediaUnderstanding.set(understanding.mediaId, structuredClone(understanding));
72
243
  }
244
+ async resolveTimelineChangesTarget(requested, source) {
245
+ if (requested.sequenceId) {
246
+ return {
247
+ status: "ready",
248
+ target: structuredClone({ projectId: requested.projectId, sequenceId: requested.sequenceId }),
249
+ source,
250
+ };
251
+ }
252
+ if (!this.editor.listProjects) {
253
+ return {
254
+ status: "unavailable",
255
+ target: structuredClone(requested),
256
+ source: { ...source, guarantee: "metadata-only" },
257
+ reason: "project sequence catalog is unavailable",
258
+ };
259
+ }
260
+ const catalog = await this.editor.listProjects();
261
+ const project = catalog.projects.find((candidate) => candidate.id === requested.projectId);
262
+ if (!project) {
263
+ return {
264
+ status: "stale",
265
+ target: structuredClone(requested),
266
+ source,
267
+ reason: `project ${requested.projectId} is not present in the canonical catalog`,
268
+ };
269
+ }
270
+ if (project.sequences.length !== 1 || !project.sequences[0]) {
271
+ return {
272
+ status: "ambiguous",
273
+ target: structuredClone(requested),
274
+ source,
275
+ reason: `project ${requested.projectId} has multiple sequences; sequenceId is required`,
276
+ };
277
+ }
278
+ return {
279
+ status: "ready",
280
+ target: { projectId: requested.projectId, sequenceId: project.sequences[0].id },
281
+ source,
282
+ };
283
+ }
73
284
  async listAssets(query) {
74
285
  if (!this.editor.listAssets)
75
286
  throw new Error("CAPABILITY_UNAVAILABLE: editor assets");
@@ -132,6 +343,100 @@ export class ContextEngine {
132
343
  return next;
133
344
  }
134
345
  }
346
+ function canonicalTimelineAvailable(capabilities) {
347
+ return Boolean(capabilities.editor.projectRead
348
+ && capabilities.editor.timelineSnapshotRead
349
+ && capabilities.editor.canonicalTimelineMode !== "metadata-only");
350
+ }
351
+ function primaryContextProvenance(provider, capabilities, target) {
352
+ const artifact = capabilities.editor.timelineArtifactWrite && !capabilities.editor.timelineWrite;
353
+ const canonical = capabilities.editor.canonicalTimelineMode === "canonical-read"
354
+ || capabilities.editor.canonicalTimelineMode === "canonical-write";
355
+ const headedNative = canonical && provider.includes("native");
356
+ const source = provider === "fixture"
357
+ ? "deterministic-fixture"
358
+ : artifact
359
+ ? "fcpxml-artifact"
360
+ : canonical
361
+ ? "canonical-timeline"
362
+ : "live-metadata";
363
+ const evidenceTier = source === "deterministic-fixture"
364
+ ? "deterministic"
365
+ : source === "fcpxml-artifact"
366
+ ? "fcpxml-artifact"
367
+ : headedNative
368
+ ? "headed-native"
369
+ : source === "canonical-timeline"
370
+ ? "canonical-live"
371
+ : "metadata-only";
372
+ return {
373
+ source,
374
+ provider,
375
+ evidenceTier,
376
+ ...(target ? { target } : {}),
377
+ };
378
+ }
379
+ function contextProvenanceSet(provider, capabilities, target, changes) {
380
+ const base = primaryContextProvenance(provider, capabilities, target);
381
+ const result = [];
382
+ if (changes.timeline || changes.assetChanges.length > 0)
383
+ result.push(base);
384
+ if (changes.stateChanges.length > 0) {
385
+ result.push({
386
+ source: "live-metadata",
387
+ provider,
388
+ evidenceTier: "metadata-only",
389
+ ...(target ? { target } : {}),
390
+ });
391
+ }
392
+ if (result.length === 0)
393
+ result.push(base);
394
+ return dedupeProvenance(result);
395
+ }
396
+ function contextTarget(project, stateChanges) {
397
+ if (project)
398
+ return { projectId: project.projectId, sequenceId: project.timeline.id };
399
+ const state = stateChanges.at(-1)?.state;
400
+ if (!state?.project?.id || !state.sequence?.id)
401
+ return undefined;
402
+ return { projectId: state.project.id, sequenceId: state.sequence.id };
403
+ }
404
+ function isContextCursor(value) {
405
+ return "revision" in value;
406
+ }
407
+ function sameContextTarget(left, right) {
408
+ return left.projectId === right.projectId && left.sequenceId === right.sequenceId;
409
+ }
410
+ function formatContextTarget(target) {
411
+ return `${target.projectId}/${target.sequenceId}`;
412
+ }
413
+ function changedScopes(timeline, stateChanges, assetChanges) {
414
+ const scopes = [];
415
+ if (timeline)
416
+ scopes.push("timeline");
417
+ if (timeline && timeline.mediaChanges.length > 0)
418
+ scopes.push("media");
419
+ if (assetChanges.length > 0)
420
+ scopes.push("assets");
421
+ for (const change of stateChanges) {
422
+ if (change.kind === "playhead-changed")
423
+ scopes.push("playhead");
424
+ if (change.kind === "active-sequence-changed" || change.kind === "sequence-time-range-changed") {
425
+ scopes.push("sequence");
426
+ }
427
+ }
428
+ return [...new Set(scopes)];
429
+ }
430
+ function dedupeProvenance(provenance) {
431
+ const seen = new Set();
432
+ return provenance.filter((entry) => {
433
+ const key = `${entry.source}:${entry.provider}:${entry.evidenceTier}:${entry.target?.projectId ?? ""}:${entry.target?.sequenceId ?? ""}`;
434
+ if (seen.has(key))
435
+ return false;
436
+ seen.add(key);
437
+ return true;
438
+ });
439
+ }
135
440
  function isCurrentUnderstanding(understanding, media, revision) {
136
441
  return sameMediaSourceIdentity(understanding.sourceIdentity, media)
137
442
  && sameRevision(understanding.analysisRevision, revision);
@@ -17,8 +17,11 @@ export class ContextService {
17
17
  async changesSince(revision) {
18
18
  return this.context.changesSince(revision);
19
19
  }
20
- async contextChangesSince(revision, waitMs = 0) {
21
- return this.context.contextChangesSince(revision, waitMs);
20
+ async timelineChangesSince(request) {
21
+ return this.context.timelineChangesSince(request);
22
+ }
23
+ async contextChangesSince(cursorOrRevision, waitMs = 0) {
24
+ return this.context.contextChangesSince(cursorOrRevision, waitMs);
22
25
  }
23
26
  liveAdapter() {
24
27
  const candidate = this.adapter;
@@ -17,11 +17,21 @@ export function reconcileProjectCatalog(catalog, options) {
17
17
  const sequence = state?.sequence && projectDescriptor
18
18
  ? matchIdentity(projectDescriptor.sequences, state.sequence.id, state.sequence.name, (candidate) => candidate.id, (candidate) => candidate.name)
19
19
  : unresolvedIdentity(state?.sequence?.id);
20
+ const diagnostics = [
21
+ identityDiagnostic("project", project, state?.project?.name),
22
+ ...(state?.sequence && projectDescriptor
23
+ ? [identityDiagnostic("sequence", sequence, state.sequence.name)]
24
+ : []),
25
+ ].filter((diagnostic) => diagnostic !== undefined);
20
26
  let status = project.method === "stable-id"
21
27
  && sequence.method === "stable-id"
22
28
  ? "matched"
23
29
  : "unresolved";
24
- let reason = status === "unresolved" ? "stable project and sequence IDs could not be reconciled" : undefined;
30
+ let reason = diagnostics.length > 0
31
+ ? diagnostics.map(formatDiagnostic).join("; ")
32
+ : status === "unresolved"
33
+ ? "stable project and sequence IDs could not be reconciled"
34
+ : undefined;
25
35
  if (status === "matched"
26
36
  && ((catalog.activeProjectId !== undefined && catalog.activeProjectId !== project.catalogId)
27
37
  || (catalog.activeSequenceId !== undefined && catalog.activeSequenceId !== sequence.catalogId))) {
@@ -42,6 +52,16 @@ export function reconcileProjectCatalog(catalog, options) {
42
52
  }
43
53
  }
44
54
  const result = structuredClone(catalog);
55
+ const blocker = status === "matched"
56
+ ? undefined
57
+ : {
58
+ code: "target-selection-required",
59
+ message: "target selection is required before canonical operations",
60
+ };
61
+ const selection = { ...options.provenance.selection };
62
+ if (blocker && !selection.available) {
63
+ selection.unavailableReason = `${blocker.message}: ${reason ?? "project and sequence identities did not reconcile"}`;
64
+ }
45
65
  if (status === "matched" && state?.project && state.sequence) {
46
66
  result.activeProjectId = project.catalogId;
47
67
  result.activeSequenceId = sequence.catalogId;
@@ -61,9 +81,11 @@ export function reconcileProjectCatalog(catalog, options) {
61
81
  sequence,
62
82
  ...(beforeRevision ? { beforeRevision: { ...beforeRevision } } : {}),
63
83
  ...(afterRevision ? { afterRevision: { ...afterRevision } } : {}),
84
+ ...(diagnostics.length > 0 ? { diagnostics } : {}),
85
+ ...(blocker ? { blocker } : {}),
64
86
  ...(reason ? { reason } : {}),
65
87
  },
66
- selection: { ...options.provenance.selection },
88
+ selection,
67
89
  };
68
90
  return result;
69
91
  }
@@ -74,6 +96,13 @@ function matchIdentity(values, liveId, liveName, id, name) {
74
96
  const named = values.filter((value) => name(value) === liveName);
75
97
  if (named.length === 1)
76
98
  return { method: "name-only", catalogId: id(named[0]), liveId };
99
+ if (named.length > 1) {
100
+ return {
101
+ method: "ambiguous-name",
102
+ liveId,
103
+ candidateCatalogIds: named.map((value) => id(value)),
104
+ };
105
+ }
77
106
  return unresolvedIdentity(liveId);
78
107
  }
79
108
  function unresolvedIdentity(liveId) {
@@ -86,6 +115,33 @@ function sameTarget(left, right) {
86
115
  function sameRevision(left, right) {
87
116
  return left.id === right.id && left.sequence === right.sequence;
88
117
  }
118
+ function identityDiagnostic(scope, match, liveName) {
119
+ if (match.method === "stable-id")
120
+ return undefined;
121
+ const diagnostic = {
122
+ scope,
123
+ code: match.method === "ambiguous-name"
124
+ ? "ambiguous-name"
125
+ : match.liveId
126
+ ? "stable-id-mismatch"
127
+ : "identity-unresolved",
128
+ ...(match.liveId ? { liveId: match.liveId } : {}),
129
+ ...(liveName ? { liveName } : {}),
130
+ ...(match.catalogId ? { catalogId: match.catalogId } : {}),
131
+ ...(match.candidateCatalogIds ? { candidateCatalogIds: [...match.candidateCatalogIds] } : {}),
132
+ };
133
+ return diagnostic;
134
+ }
135
+ function formatDiagnostic(diagnostic) {
136
+ const label = diagnostic.scope;
137
+ if (diagnostic.code === "ambiguous-name") {
138
+ return `${label} name is ambiguous across catalog IDs ${diagnostic.candidateCatalogIds?.join(", ") ?? "<none>"}`;
139
+ }
140
+ if (diagnostic.code === "stable-id-mismatch") {
141
+ return `${label} stable ID ${diagnostic.liveId ?? "<unavailable>"} did not match catalog ID ${diagnostic.catalogId ?? "<none>"}; name-only evidence is not canonical`;
142
+ }
143
+ return `${label} stable identity is unavailable for reconciliation`;
144
+ }
89
145
  export function validateProjectCatalog(catalog) {
90
146
  if (!Array.isArray(catalog.projects))
91
147
  throw new Error("PROJECT_CATALOG_INVALID: projects must be an array");
@@ -0,0 +1,153 @@
1
+ export const CANONICAL_INCREMENTAL_SYNC_CONTRACT_VERSION = 1;
2
+ /**
3
+ * Validates the structural guarantees shared by timeline.changes and
4
+ * context.changes. Provider-specific payload validation belongs at the edge.
5
+ */
6
+ export function assertCanonicalSyncResult(result) {
7
+ if (result.contractVersion !== CANONICAL_INCREMENTAL_SYNC_CONTRACT_VERSION) {
8
+ throw new Error("CANONICAL_SYNC_INVALID: unsupported contract version");
9
+ }
10
+ if (!result.ok) {
11
+ assertFailure(result);
12
+ return;
13
+ }
14
+ assertTarget(result.target);
15
+ assertCursor(result.from);
16
+ assertCursor(result.to);
17
+ if (!sameTarget(result.target, result.from.target) || !sameTarget(result.target, result.to.target)) {
18
+ throw new Error("CANONICAL_SYNC_INVALID: result cursors are not bound to the target");
19
+ }
20
+ if (result.to.revision.sequence < result.from.revision.sequence) {
21
+ throw new Error("CANONICAL_SYNC_INVALID: to revision precedes from revision");
22
+ }
23
+ assertProvenance(result.provenance);
24
+ if (result.provenance.source.evidenceTier === "metadata-only") {
25
+ throw new Error("CANONICAL_SYNC_INVALID: metadata-only evidence cannot return canonical changes");
26
+ }
27
+ assertChanges(result.changes, result.from.revision, result.to.revision);
28
+ }
29
+ function assertFailure(result) {
30
+ if (!result.failure.message.trim()) {
31
+ throw new Error("CANONICAL_SYNC_INVALID: failure message is required");
32
+ }
33
+ if (result.status === "unavailable"
34
+ && !["CAPABILITY_UNAVAILABLE", "METADATA_ONLY"].includes(result.failure.code)) {
35
+ throw new Error("CANONICAL_SYNC_INVALID: unavailable result has the wrong failure code");
36
+ }
37
+ if (result.status === "stale" && result.failure.code !== "STALE_CURSOR") {
38
+ throw new Error("CANONICAL_SYNC_INVALID: stale result has the wrong failure code");
39
+ }
40
+ if (result.status === "stale" && !result.cursor) {
41
+ throw new Error("CANONICAL_SYNC_INVALID: stale result requires a revision cursor");
42
+ }
43
+ if (result.status === "ambiguous" && result.failure.code !== "AMBIGUOUS_TARGET") {
44
+ throw new Error("CANONICAL_SYNC_INVALID: ambiguous result has the wrong failure code");
45
+ }
46
+ if (result.target)
47
+ assertTarget(result.target);
48
+ if (result.cursor)
49
+ assertCursor(result.cursor);
50
+ if (result.target && result.cursor && !sameTarget(result.target, result.cursor.target)) {
51
+ throw new Error("CANONICAL_SYNC_INVALID: failure target does not match its cursor");
52
+ }
53
+ if (result.provenance)
54
+ assertProvenance(result.provenance);
55
+ }
56
+ function assertCursor(cursor) {
57
+ assertTarget(cursor.target);
58
+ assertRevision(cursor.revision);
59
+ }
60
+ function assertTarget(target) {
61
+ if (!target.projectId.trim() || !target.sequenceId.trim()) {
62
+ throw new Error("CANONICAL_SYNC_INVALID: stable project and sequence identities are required");
63
+ }
64
+ }
65
+ function assertRevision(revision) {
66
+ if (!revision.id.trim() || !Number.isInteger(revision.sequence) || revision.sequence < 0) {
67
+ throw new Error("CANONICAL_SYNC_INVALID: valid revision identity is required");
68
+ }
69
+ if (!Number.isFinite(Date.parse(revision.timestamp))) {
70
+ throw new Error("CANONICAL_SYNC_INVALID: revision timestamp is invalid");
71
+ }
72
+ }
73
+ function assertProvenance(provenance) {
74
+ if (!provenance.source.provider.trim() || !provenance.source.backend.trim()) {
75
+ throw new Error("CANONICAL_SYNC_INVALID: provider and backend provenance are required");
76
+ }
77
+ if (!Number.isFinite(Date.parse(provenance.observedAt))) {
78
+ throw new Error("CANONICAL_SYNC_INVALID: observation timestamp is invalid");
79
+ }
80
+ const allowedTiers = SURFACE_EVIDENCE_TIERS[provenance.source.surface];
81
+ if (!allowedTiers.includes(provenance.source.evidenceTier)) {
82
+ throw new Error(`CANONICAL_SYNC_INVALID: evidence tier ${provenance.source.evidenceTier} is incompatible with surface ${provenance.source.surface}`);
83
+ }
84
+ }
85
+ const SURFACE_EVIDENCE_TIERS = {
86
+ live: ["metadata-only", "canonical-read", "canonical-live", "headed-native"],
87
+ artifact: ["artifact-only", "canonical-read"],
88
+ fixture: ["fixture"],
89
+ };
90
+ function assertChanges(changes, from, to) {
91
+ let previous;
92
+ changes.forEach((change, index) => {
93
+ if (change.order !== index) {
94
+ throw new Error("CANONICAL_SYNC_INVALID: change order must be contiguous");
95
+ }
96
+ assertRevision(change.revision);
97
+ if (change.revision.sequence < from.sequence || change.revision.sequence > to.sequence) {
98
+ throw new Error("CANONICAL_SYNC_INVALID: change revision is outside the result cursor");
99
+ }
100
+ if (!change.entityId.trim()) {
101
+ throw new Error("CANONICAL_SYNC_INVALID: change entity identity is required");
102
+ }
103
+ const hasBefore = Object.prototype.hasOwnProperty.call(change, "before");
104
+ const hasAfter = Object.prototype.hasOwnProperty.call(change, "after");
105
+ if (change.operation === "added" && (!hasAfter || hasBefore)) {
106
+ throw new Error("CANONICAL_SYNC_INVALID: added change must have after only");
107
+ }
108
+ if (change.operation === "removed" && (!hasBefore || hasAfter)) {
109
+ throw new Error("CANONICAL_SYNC_INVALID: removed change must have before only");
110
+ }
111
+ if (change.operation === "modified" && (!hasBefore || !hasAfter)) {
112
+ throw new Error("CANONICAL_SYNC_INVALID: modified change must have before and after");
113
+ }
114
+ if (previous && compareChanges(previous, change) > 0) {
115
+ throw new Error("CANONICAL_SYNC_INVALID: changes must be deterministically ordered");
116
+ }
117
+ previous = change;
118
+ });
119
+ }
120
+ const ENTITY_ORDER = {
121
+ clip: 0,
122
+ "connected-item": 1,
123
+ marker: 2,
124
+ caption: 3,
125
+ role: 4,
126
+ audio: 5,
127
+ playhead: 6,
128
+ };
129
+ const OPERATION_ORDER = {
130
+ added: 0,
131
+ modified: 1,
132
+ removed: 2,
133
+ };
134
+ function compareChanges(left, right) {
135
+ return left.revision.sequence - right.revision.sequence
136
+ || ENTITY_ORDER[left.entity] - ENTITY_ORDER[right.entity]
137
+ || compareCodePointStrings(left.entityId, right.entityId)
138
+ || OPERATION_ORDER[left.operation] - OPERATION_ORDER[right.operation];
139
+ }
140
+ function compareCodePointStrings(left, right) {
141
+ const leftCodePoints = Array.from(left, (character) => character.codePointAt(0));
142
+ const rightCodePoints = Array.from(right, (character) => character.codePointAt(0));
143
+ const length = Math.min(leftCodePoints.length, rightCodePoints.length);
144
+ for (let index = 0; index < length; index += 1) {
145
+ if (leftCodePoints[index] !== rightCodePoints[index]) {
146
+ return leftCodePoints[index] < rightCodePoints[index] ? -1 : 1;
147
+ }
148
+ }
149
+ return leftCodePoints.length - rightCodePoints.length;
150
+ }
151
+ function sameTarget(left, right) {
152
+ return left.projectId === right.projectId && left.sequenceId === right.sequenceId;
153
+ }
@@ -11,3 +11,4 @@ export * from "./timeline-target.js";
11
11
  export * from "./rough-cut.js";
12
12
  export * from "./duration.js";
13
13
  export * from "./skills.js";
14
+ export * from "./incremental-sync.js";
@@ -479,8 +479,14 @@ function postWriteAnalysisRequirements(policy) {
479
479
  }
480
480
  function sameDiffContent(left, right) {
481
481
  const comparable = (diff) => {
482
- const { from: _from, to: _to, ...content } = diff;
483
- return content;
482
+ const { from: _from, to: _to, provenance, ...content } = diff;
483
+ return {
484
+ target: provenance ? {
485
+ projectId: provenance.projectId,
486
+ sequenceId: provenance.sequenceId,
487
+ } : undefined,
488
+ ...content,
489
+ };
484
490
  };
485
491
  return JSON.stringify(comparable(left)) === JSON.stringify(comparable(right));
486
492
  }
@@ -144,8 +144,11 @@ export class AgentVideoRuntime {
144
144
  async changesSince(revision) {
145
145
  return this.contexts.changesSince(revision);
146
146
  }
147
- async contextChangesSince(revision, waitMs = 0) {
148
- return this.contexts.contextChangesSince(revision, waitMs);
147
+ async timelineChangesSince(request) {
148
+ return this.contexts.timelineChangesSince(request);
149
+ }
150
+ async contextChangesSince(cursorOrRevision, waitMs = 0) {
151
+ return this.contexts.contextChangesSince(cursorOrRevision, waitMs);
149
152
  }
150
153
  async analyzeSpeech(mediaId, range) {
151
154
  return this.media.analyzeSpeech(mediaId, range);