@morshoto/framekit 0.1.12 → 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.
@@ -2,10 +2,20 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
2
  import { dirname, join, resolve } from "node:path";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { EditingSession, } from "../../../packages/runtime/src/index.js";
5
+ export function createCanonicalSessionChangeSource(readCurrent) {
6
+ return {
7
+ changesSince: async (revision) => ({
8
+ from: revision,
9
+ to: (await readCurrent()).revision,
10
+ }),
11
+ };
12
+ }
5
13
  export class EditingSessionRepository {
6
14
  directory;
7
- constructor(directory) {
15
+ changeSource;
16
+ constructor(directory, changeSource) {
8
17
  this.directory = directory;
18
+ this.changeSource = changeSource;
9
19
  }
10
20
  async create(input) {
11
21
  const sessionId = input.sessionId ?? `session-${randomUUID()}`;
@@ -19,15 +29,19 @@ export class EditingSessionRepository {
19
29
  }
20
30
  async preview(sessionId, operations, expectedRevision) {
21
31
  const session = await this.load(sessionId);
32
+ await this.refreshLoaded(sessionId, session);
22
33
  return session.preview(operations, expectedRevision);
23
34
  }
24
35
  async execute(sessionId, operations, expectedRevision) {
25
36
  const session = await this.load(sessionId);
37
+ await this.refreshLoaded(sessionId, session);
26
38
  session.apply(operations, expectedRevision);
27
39
  return this.save(sessionId, session);
28
40
  }
29
41
  async status(sessionId) {
30
- const { document } = await this.inspect(sessionId);
42
+ const session = await this.load(sessionId);
43
+ await this.refreshLoaded(sessionId, session);
44
+ const document = session.document();
31
45
  return {
32
46
  sessionId,
33
47
  state: document.state,
@@ -68,8 +82,22 @@ export class EditingSessionRepository {
68
82
  const stored = await this.save(sessionId, session);
69
83
  return { ...stored, observation, change };
70
84
  }
71
- loadForMaterialization(sessionId) {
72
- return this.load(sessionId);
85
+ async refresh(sessionId) {
86
+ const session = await this.load(sessionId);
87
+ if (!this.changeSource)
88
+ throw new Error("CAPABILITY_UNAVAILABLE: session provider change stream");
89
+ const change = await this.refreshLoaded(sessionId, session);
90
+ return {
91
+ sessionId,
92
+ document: session.document(),
93
+ providerRevision: change.to,
94
+ change: sameRevision(change.from, change.to) ? "unchanged" : "changed",
95
+ };
96
+ }
97
+ async loadForMaterialization(sessionId) {
98
+ const session = await this.load(sessionId);
99
+ await this.refreshLoaded(sessionId, session);
100
+ return session;
73
101
  }
74
102
  checkpoint(sessionId, session) {
75
103
  return this.save(sessionId, session);
@@ -85,6 +113,18 @@ export class EditingSessionRepository {
85
113
  throw error;
86
114
  }
87
115
  }
116
+ async refreshLoaded(sessionId, session) {
117
+ if (!this.changeSource)
118
+ return undefined;
119
+ const change = await this.changeSource.changesSince(session.base().revision);
120
+ if (!sameRevision(change.from, session.base().revision)) {
121
+ throw new Error("SESSION_CHANGE_STREAM_BASE_MISMATCH: provider change stream did not start at the session base");
122
+ }
123
+ const freshness = session.observeProviderRevision(change.to);
124
+ if (freshness === "changed")
125
+ await this.save(sessionId, session);
126
+ return change;
127
+ }
88
128
  async save(sessionId, session) {
89
129
  const path = this.path(sessionId);
90
130
  await mkdir(dirname(path), { recursive: true });
@@ -110,3 +150,6 @@ export class EditingSessionRepository {
110
150
  return join(this.directory, `${sessionId}.json`);
111
151
  }
112
152
  }
153
+ function sameRevision(left, right) {
154
+ return left.id === right.id && left.sequence === right.sequence;
155
+ }
@@ -6,6 +6,7 @@ import { createCommandAnalyzers, createFinalCutLiveAdapter, FcpxmlDocumentAdapte
6
6
  import { FixtureAudioAnalyzer, FixtureMetadataAnalyzer, FixtureSpeechAnalyzer, FixtureVisualAnalyzer } from "../../../packages/testkit/src/index.js";
7
7
  import { AgentVideoRuntime } from "../../../packages/runtime/src/index.js";
8
8
  import { createMcpServer } from "./server.js";
9
+ import { createCanonicalSessionChangeSource } from "./headless-sessions.js";
9
10
  const fixture = new InMemoryEditorAdapter({
10
11
  projectId: "project-1",
11
12
  projectName: "Phase 2 Fixture",
@@ -119,7 +120,17 @@ const canonicalNativeProvider = canonicalNativeProviderEnabled
119
120
  return { undone: result.undone, verification: result.verification };
120
121
  },
121
122
  },
122
- readSnapshot: () => new FinalCutCanonicalSnapshotSource().readSnapshot(),
123
+ readSnapshot: async () => {
124
+ const live = await liveAdapter.readLiveState();
125
+ const projectId = live.project?.id;
126
+ const sequenceId = live.sequence?.id;
127
+ if (!projectId || projectId.startsWith("final-cut:") || !sequenceId || sequenceId.startsWith("final-cut:")) {
128
+ throw new Error("TARGET_UNAVAILABLE: stable live project and sequence identities are required for canonical export");
129
+ }
130
+ return new FinalCutCanonicalSnapshotSource({
131
+ target: { projectId, projectUid: projectId, sequenceId },
132
+ }).readSnapshot();
133
+ },
123
134
  resolveTarget: createFinalCutNativeTargetResolver(nativeEditor),
124
135
  backgroundCatalog: backgroundLibraryProvider,
125
136
  })
@@ -211,6 +222,7 @@ const server = createMcpServer(runtime, {
211
222
  ...(sessionMaterializationPublisher?.isAvailable() ? { sessionMaterializationPublisher } : {}),
212
223
  videoExporter,
213
224
  sessionDirectory: join(framekitStateDirectory, "sessions"),
225
+ sessionChangeSource: createCanonicalSessionChangeSource(() => runtime.inspectProject()),
214
226
  materializationDirectory: join(framekitStateDirectory, "materializations"),
215
227
  sqliteObservationProvider,
216
228
  });
@@ -14,6 +14,14 @@ const revisionValueSchema = z.object({
14
14
  timestamp: z.string(),
15
15
  });
16
16
  const revisionSchema = revisionValueSchema.optional();
17
+ const contextTargetSchema = z.object({
18
+ projectId: z.string().min(1),
19
+ sequenceId: z.string().min(1),
20
+ }).strict();
21
+ const contextCursorSchema = z.object({
22
+ revision: revisionValueSchema,
23
+ target: contextTargetSchema.optional(),
24
+ }).strict();
17
25
  const rationalTimeSchema = z.object({
18
26
  value: z.string().regex(/^-?\d+$/),
19
27
  timescale: z.string().regex(/^\d+$/).refine((value) => Number(value) > 0),
@@ -818,7 +826,9 @@ export function createMcpServer(runtime, options = {}) {
818
826
  runtime.registerBuiltinSkills();
819
827
  const server = new McpServer({ name: "framekit", version: FRAMEKIT_VERSION }, { instructions: EDITOR_FIRST_MCP_INSTRUCTIONS });
820
828
  const nativeTransitionAssets = new Map();
821
- const sessions = options.sessionDirectory ? new EditingSessionRepository(options.sessionDirectory) : undefined;
829
+ const sessions = options.sessionDirectory
830
+ ? new EditingSessionRepository(options.sessionDirectory, options.sessionChangeSource)
831
+ : undefined;
822
832
  const materializations = sessions && options.materializationDirectory
823
833
  ? new SessionMaterializationJobs(options.materializationDirectory, sessions, options.sessionMaterializationPublisher)
824
834
  : undefined;
@@ -1562,14 +1572,21 @@ export function createMcpServer(runtime, options = {}) {
1562
1572
  server.registerTool("context.changes", {
1563
1573
  description: "Read incremental timeline, live-state, and native-asset changes after a context revision.",
1564
1574
  inputSchema: {
1565
- sequence: z.number().int().nonnegative(),
1575
+ cursor: contextCursorSchema.optional(),
1576
+ revision: revisionValueSchema.optional(),
1577
+ sequence: z.number().int().nonnegative().optional(),
1566
1578
  waitMs: z.number().int().min(0).max(30_000).optional(),
1567
1579
  },
1568
- }, async ({ sequence, waitMs }) => jsonResult(await runtime.contextChangesSince({
1569
- id: `rev-${sequence}`,
1570
- sequence,
1571
- timestamp: new Date(sequence).toISOString(),
1572
- }, waitMs ?? 0)));
1580
+ }, async ({ cursor, revision, sequence, waitMs }) => {
1581
+ const after = cursor ?? revision ?? (sequence === undefined ? undefined : {
1582
+ id: `rev-${sequence}`,
1583
+ sequence,
1584
+ timestamp: new Date(sequence).toISOString(),
1585
+ });
1586
+ if (!after)
1587
+ throw new Error("INVALID_CONTEXT_CURSOR: cursor, revision, or sequence is required");
1588
+ return jsonResult(await runtime.contextChangesSince(after, waitMs ?? 0));
1589
+ });
1573
1590
  server.registerTool("editor.live.inspect", {
1574
1591
  description: "Read observed live Final Cut state without requiring canonical timeline snapshot capability.",
1575
1592
  inputSchema: {},
@@ -1668,15 +1685,33 @@ export function createMcpServer(runtime, options = {}) {
1668
1685
  },
1669
1686
  }, async (query) => jsonResult(await runtime.listAssets(query)));
1670
1687
  server.registerTool("timeline.changes", {
1671
- description: "Return the canonical timeline diff since a previously observed revision.",
1672
- inputSchema: { sequence: z.number().int().nonnegative() },
1673
- }, async ({ sequence }) => {
1674
- const project = await runtime.inspectProject();
1675
- return jsonResult(await runtime.changesSince({
1676
- id: `rev-${sequence}`,
1677
- sequence,
1678
- timestamp: new Date(0 + sequence).toISOString(),
1679
- }));
1688
+ description: "Return ordered canonical timeline changes for one selected project and sequence.",
1689
+ inputSchema: {
1690
+ projectId: z.string().min(1).optional(),
1691
+ sequenceId: z.string().min(1).optional(),
1692
+ revision: revisionValueSchema.optional(),
1693
+ /** Legacy cursor retained for existing MCP clients. */
1694
+ sequence: z.number().int().nonnegative().optional(),
1695
+ },
1696
+ }, async ({ projectId, sequenceId, revision, sequence }) => {
1697
+ const project = projectId && sequenceId && revision
1698
+ ? undefined
1699
+ : await runtime.inspectProject();
1700
+ const from = revision ?? {
1701
+ id: `rev-${sequence ?? project.revision.sequence}`,
1702
+ sequence: sequence ?? project.revision.sequence,
1703
+ timestamp: new Date(sequence ?? project.revision.sequence).toISOString(),
1704
+ };
1705
+ const result = await runtime.timelineChangesSince({
1706
+ target: {
1707
+ projectId: projectId ?? project.projectId,
1708
+ sequenceId: sequenceId ?? project.timeline.id,
1709
+ },
1710
+ from,
1711
+ });
1712
+ return jsonResult(result.status === "ready" && result.timeline
1713
+ ? { ...result.timeline, ...result }
1714
+ : result);
1680
1715
  });
1681
1716
  server.registerTool("timeline.edit", {
1682
1717
  description: "Apply one supported edit after editing.route confirms the required capabilities; return read-after-write plus its diff.",
@@ -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;
@@ -52,6 +52,16 @@ export function reconcileProjectCatalog(catalog, options) {
52
52
  }
53
53
  }
54
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
+ }
55
65
  if (status === "matched" && state?.project && state.sequence) {
56
66
  result.activeProjectId = project.catalogId;
57
67
  result.activeSequenceId = sequence.catalogId;
@@ -72,9 +82,10 @@ export function reconcileProjectCatalog(catalog, options) {
72
82
  ...(beforeRevision ? { beforeRevision: { ...beforeRevision } } : {}),
73
83
  ...(afterRevision ? { afterRevision: { ...afterRevision } } : {}),
74
84
  ...(diagnostics.length > 0 ? { diagnostics } : {}),
85
+ ...(blocker ? { blocker } : {}),
75
86
  ...(reason ? { reason } : {}),
76
87
  },
77
- selection: { ...options.provenance.selection },
88
+ selection,
78
89
  };
79
90
  return result;
80
91
  }