diff --git a/src/workbench/extensions/agent/crdt/ecsFollowerAdapter.integration.test.ts b/src/workbench/extensions/agent/crdt/ecsFollowerAdapter.integration.test.ts index c2133ec0aae..599c5fc7788 100644 --- a/src/workbench/extensions/agent/crdt/ecsFollowerAdapter.integration.test.ts +++ b/src/workbench/extensions/agent/crdt/ecsFollowerAdapter.integration.test.ts @@ -1,4 +1,10 @@ -import { applyOps, mint, nodesMap } from '@comfyorg/comfy-multi-player' +import { + SCHEMA_VERSION, + applyOps, + linksMap, + mint, + nodesMap +} from '@comfyorg/comfy-multi-player' import type { WidgetCatalog } from '@comfyorg/comfy-multi-player' import { createTestingPinia } from '@pinia/testing' import { setActivePinia } from 'pinia' @@ -35,6 +41,53 @@ interface TestLayout { size: { width: number; height: number } } +function byId(entries: T[]): T[] { + return entries.sort((left, right) => Number(left.id) - Number(right.id)) +} + +function projectedNodeIds() { + return useNodeDataStore() + .getGraphNodesFor('root', 'root') + .map(({ id }) => Number(id)) + .sort((left, right) => left - right) +} + +function graphSnapshot() { + return { + nodes: byId( + useNodeDataStore() + .getGraphNodesFor('root', 'root') + .map((node) => ({ + id: node.id, + type: node.type, + title: node.title, + // Detached: updateNode splices these arrays in place, so holding the + // store's own arrays would compare a later snapshot to itself. + inputs: node.inputs.map((slot) => ({ ...slot })), + outputs: node.outputs.map((slot) => ({ ...slot })) + })) + ), + links: byId( + [...useLinkStore().graphTopologies(scope)].map((link) => ({ + id: link.id, + originNodeId: link.originNodeId, + originSlot: link.originSlot, + targetNodeId: link.targetNodeId, + targetSlot: link.targetSlot, + type: link.type + })) + ), + widgets: [toNodeId(1), toNodeId(2)].flatMap((nodeId) => + ['seed', 'stale'].flatMap((name) => { + const widget = useWidgetValueStore().getWidget( + widgetId('root', nodeId, name) + ) + return widget ? [{ nodeId, name, value: widget.value }] : [] + }) + ) + } +} + function op(id: string, baseVersion: number, payload: object) { return { op_id: id, @@ -421,6 +474,605 @@ describe('EcsFollowerAdapter integration', () => { host.destroy() }) + it('reprojects a saved follower snapshot after reload without byte drift', () => { + const host = mint( + { + nodes: [ + { + id: 1, + type: 'Source', + title: 'Saved source', + pos: [10, 20], + size: [180, 90], + inputs: [], + outputs: [{ name: 'out', type: 'IMAGE', links: [9] }], + widgets_values: { seed: 42 } + }, + { + id: 2, + type: 'Sink', + pos: [300, 20], + inputs: [{ name: 'in', type: 'IMAGE', link: 9 }], + outputs: [] + } + ], + links: [[9, 1, 0, 2, 0, 'IMAGE']] + }, + catalog + ) + const update = Y.encodeStateAsUpdate(host) + const follower = new FollowerDoc() + const adapter = new EcsFollowerAdapter( + createGraphMutations({ + getScope: () => scope, + layout: { createNode: vi.fn(), deleteNodes: vi.fn() } + }) + ) + adapter.bind('wf', follower) + follower.applyRemoteUpdate(update) + expect( + adapter.applyFrame({ + workflowId: 'wf', + seq: 1, + update, + actor: 'agent:test', + opIds: ['initial-save'] + }) + ).toBe(true) + + const projectedBeforeReload = graphSnapshot() + const savedSnapshot = Y.encodeStateAsUpdate(follower.doc) + const savedVector = Y.encodeStateVector(follower.doc) + adapter.destroy() + follower.destroy() + + setActivePinia(createTestingPinia({ stubActions: false })) + const reloadedFollower = new FollowerDoc() + reloadedFollower.applyRemoteUpdate(savedSnapshot) + expect(Y.encodeStateAsUpdate(reloadedFollower.doc)).toEqual(savedSnapshot) + expect(Y.encodeStateVector(reloadedFollower.doc)).toEqual(savedVector) + + const reloadedAdapter = new EcsFollowerAdapter( + createGraphMutations({ + getScope: () => scope, + layout: { createNode: vi.fn(), deleteNodes: vi.fn() } + }) + ) + reloadedAdapter.bind('wf', reloadedFollower) + expect(graphSnapshot()).toEqual({ nodes: [], links: [], widgets: [] }) + + expect( + reloadedAdapter.projectBaseline('wf', { + source: 'agent-remote', + actor: 'agent:replay', + opId: 'reload-replay' + }) + ).toBe(true) + expect(graphSnapshot()).toEqual(projectedBeforeReload) + + // A redelivered snapshot integrates no new struct: it must change nothing. + reloadedFollower.applyRemoteUpdate(savedSnapshot) + expect( + reloadedAdapter.applyFrame({ + workflowId: 'wf', + seq: 2, + update: savedSnapshot, + actor: 'agent:replay', + opIds: ['reload-replay'] + }) + ).toBe(true) + expect(graphSnapshot()).toEqual(projectedBeforeReload) + expect(Y.encodeStateAsUpdate(reloadedFollower.doc)).toEqual(savedSnapshot) + expect(Y.encodeStateVector(reloadedFollower.doc)).toEqual(savedVector) + + reloadedAdapter.destroy() + reloadedFollower.destroy() + host.destroy() + }) + + it('skips baseline links the graph would reject, keeping the rest', () => { + const host = mint( + { + nodes: [ + { + id: 1, + type: 'Source', + pos: [10, 20], + inputs: [], + outputs: [{ name: 'out', type: 'IMAGE', links: [9] }] + }, + { + id: 2, + type: 'Sink', + pos: [300, 20], + inputs: [{ name: 'in', type: 'IMAGE', link: 9 }], + outputs: [] + }, + { id: 3, type: 'Sink', pos: [500, 20] } + ], + links: [[9, 1, 0, 2, 0, 'IMAGE']] + }, + catalog + ) + const follower = new FollowerDoc() + follower.applyRemoteUpdate(Y.encodeStateAsUpdate(host)) + const links = linksMap(follower.doc) + links.set('10', [10, '404', 0, '2', 0, 'IMAGE']) + links.set('11', [11, '1', 7, '2', 0, 'IMAGE']) + links.set('12', [12, '1', 0, '2', 7, 'IMAGE']) + links.set('13', [13, '1', 0, '3', 0, 'IMAGE']) + links.set('14', [14, '1', -1, '2', 0, 'IMAGE']) + + const adapter = new EcsFollowerAdapter( + createGraphMutations({ + getScope: () => scope, + layout: { createNode: vi.fn(), deleteNodes: vi.fn() } + }) + ) + adapter.bind('wf', follower) + expect( + adapter.projectBaseline('wf', { + source: 'agent-remote', + actor: 'agent:replay', + opId: 'baseline' + }) + ).toBe(true) + + expect(projectedNodeIds()).toEqual([1, 2, 3]) + expect( + useLinkStore().getTopology(scope.rootGraphId, toLinkId(9)) + ).toBeDefined() + for (const rejected of [10, 11, 12, 13, 14]) { + expect( + useLinkStore().getTopology(scope.rootGraphId, toLinkId(rejected)) + ).toBeUndefined() + } + + adapter.destroy() + follower.destroy() + host.destroy() + }) + + it('does not replay the baseline again on the next frame', () => { + const host = mint( + { + nodes: [ + { + id: 1, + type: 'Source', + pos: [10, 20], + size: [180, 90], + inputs: [], + outputs: [{ name: 'out', type: 'IMAGE', links: [] }] + } + ], + links: [] + }, + catalog + ) + const createLayout = vi.fn() + const deleteLayouts = vi.fn() + const follower = new FollowerDoc() + const adapter = new EcsFollowerAdapter( + createGraphMutations({ + getScope: () => scope, + layout: { createNode: createLayout, deleteNodes: deleteLayouts } + }) + ) + + // Restoring after bind stages every node the snapshot carries. + adapter.bind('wf', follower) + follower.applyRemoteUpdate(Y.encodeStateAsUpdate(host)) + expect( + adapter.projectBaseline('wf', { + source: 'agent-remote', + actor: 'agent:replay', + opId: 'baseline' + }) + ).toBe(true) + const projected = graphSnapshot() + createLayout.mockClear() + deleteLayouts.mockClear() + + expect( + adapter.applyFrame({ + workflowId: 'wf', + seq: 1, + update: new Uint8Array(), + actor: 'agent:test', + opIds: ['unrelated'] + }) + ).toBe(true) + + expect(createLayout).not.toHaveBeenCalled() + expect(deleteLayouts).not.toHaveBeenCalled() + expect(graphSnapshot()).toEqual(projected) + + adapter.destroy() + follower.destroy() + host.destroy() + }) + + it('leaves entities the doc never mentions, and still drains a staged delete', () => { + const host = mint( + { + nodes: [ + { id: 1, type: 'Source', pos: [0, 0], inputs: [], outputs: [] }, + { id: 2, type: 'Sink', pos: [200, 0], inputs: [], outputs: [] } + ], + links: [] + }, + catalog + ) + const follower = new FollowerDoc() + follower.applyRemoteUpdate(Y.encodeStateAsUpdate(host)) + const deleteLayouts = vi.fn() + const adapter = new EcsFollowerAdapter( + createGraphMutations({ + getScope: () => scope, + layout: { createNode: vi.fn(), deleteNodes: deleteLayouts } + }) + ) + const context = { + source: 'agent-remote', + actor: 'agent:replay', + opId: 'baseline' + } as const + + adapter.bind('wf', follower) + expect(adapter.projectBaseline('wf', context)).toBe(true) + + // Node 2 leaves the doc after bind, so the observer stages its deletion. + nodesMap(follower.doc).delete('2') + expect(adapter.projectBaseline('wf', context)).toBe(true) + expect(projectedNodeIds()).toEqual([1, 2]) + + expect( + adapter.applyFrame({ + workflowId: 'wf', + seq: 1, + update: new Uint8Array(), + actor: 'agent:test', + opIds: ['later'] + }) + ).toBe(true) + expect(projectedNodeIds()).toEqual([1]) + expect(deleteLayouts).toHaveBeenCalledWith( + scope, + [toNodeId(2)], + expect.objectContaining({ opId: 'later' }) + ) + + adapter.destroy() + follower.destroy() + host.destroy() + }) + + it('does not let a skipped link poison the next frame', () => { + const host = mint( + { + nodes: [ + { + id: 1, + type: 'Source', + pos: [0, 0], + inputs: [], + outputs: [{ name: 'out', type: 'IMAGE', links: [] }] + } + ], + links: [] + }, + catalog + ) + const follower = new FollowerDoc() + const adapter = new EcsFollowerAdapter( + createGraphMutations({ + getScope: () => scope, + layout: { createNode: vi.fn(), deleteNodes: vi.fn() } + }) + ) + + adapter.bind('wf', follower) + follower.applyRemoteUpdate(Y.encodeStateAsUpdate(host)) + linksMap(follower.doc).set('99', [99, '1', 0, '404', 0, 'IMAGE']) + expect( + adapter.projectBaseline('wf', { + source: 'agent-remote', + actor: 'agent:replay', + opId: 'baseline' + }) + ).toBe(true) + + // The live path has no endpoint filter, so a skipped link left staged + // would fail this frame's whole batch and take the new node with it. + nodesMap(follower.doc).set('2', nodesMap(host).get('1')!.clone()) + expect( + adapter.applyFrame({ + workflowId: 'wf', + seq: 1, + update: new Uint8Array(), + actor: 'agent:test', + opIds: ['later'] + }) + ).toBe(true) + expect(projectedNodeIds()).toEqual([1, 2]) + + adapter.destroy() + follower.destroy() + host.destroy() + }) + + it('applies a remint wire delta after baseline projection', () => { + const host = mint( + { + nodes: [ + { + id: 1, + type: 'Source', + title: 'Saved', + pos: [0, 0], + inputs: [], + outputs: [{ name: 'out', type: 'IMAGE', links: [9] }] + }, + { + id: 2, + type: 'Sink', + pos: [200, 0], + inputs: [{ name: 'in', type: 'IMAGE', link: 9 }], + outputs: [] + } + ], + links: [[9, 1, 0, 2, 0, 'IMAGE']] + }, + catalog + ) + const reminted = mint( + { + nodes: [ + { + id: 1, + type: 'Source', + title: 'Reminted', + pos: [9, 9], + inputs: [], + outputs: [{ name: 'out', type: 'IMAGE', links: [9] }] + } + ], + links: [] + }, + catalog + ) + const follower = new FollowerDoc() + follower.applyRemoteUpdate(Y.encodeStateAsUpdate(host)) + const adapter = new EcsFollowerAdapter( + createGraphMutations({ + getScope: () => scope, + layout: { createNode: vi.fn(), deleteNodes: vi.fn() } + }) + ) + + adapter.bind('wf', follower) + expect( + adapter.projectBaseline('wf', { + source: 'agent-remote', + actor: 'agent:replay', + opId: 'baseline' + }) + ).toBe(true) + + const beforeRemint = follower.stateVector() + nodesMap(host).delete('1') + nodesMap(host).set('1', nodesMap(reminted).get('1')!.clone()) + const update = Y.encodeStateAsUpdate(host, beforeRemint) + follower.applyRemoteUpdate(update) + expect( + adapter.applyFrame({ + workflowId: 'wf', + seq: 1, + update, + actor: 'agent:test', + opIds: ['remint'] + }) + ).toBe(true) + + expect(projectedNodeIds()).toEqual([1, 2]) + expect( + useNodeDataStore() + .getGraphNodesFor('root', 'root') + .find(({ id }) => id === toNodeId(1))?.title + ).toBe('Reminted') + expect( + useLinkStore().getTopology(scope.rootGraphId, toLinkId(9)) + ).toMatchObject({ originNodeId: toNodeId(1), targetNodeId: toNodeId(2) }) + + adapter.destroy() + follower.destroy() + host.destroy() + reminted.destroy() + }) + + it('returns false when no session is bound to the target', () => { + const adapter = new EcsFollowerAdapter( + createGraphMutations({ + getScope: () => scope, + layout: { createNode: vi.fn(), deleteNodes: vi.fn() } + }) + ) + + expect( + adapter.projectBaseline('never-bound', { + source: 'agent-remote', + actor: 'agent:replay', + opId: 'baseline' + }) + ).toBe(false) + + adapter.destroy() + }) + + it('keeps the first frame armed after projecting an empty baseline', () => { + const host = mint({ nodes: [], links: [] }, catalog) + const follower = new FollowerDoc() + follower.applyRemoteUpdate(Y.encodeStateAsUpdate(host)) + const addNode = vi.fn() + const reconcileNode = vi.fn() + const adapter = new EcsFollowerAdapter(() => ({ + batch: (_context, define) => { + define({ + addNode, + reconcileNode, + setWidget: vi.fn(), + connect: vi.fn(), + removeMissing: vi.fn(), + removeLinks: vi.fn(), + deleteNode: vi.fn(), + clearSemanticGraph: vi.fn() + }) + return true + }, + addNode: () => true, + setWidget: () => true, + connect: () => true, + deleteNode: () => true, + clearSemanticGraph: () => true + })) + adapter.bind('wf', follower) + expect( + adapter.projectBaseline('wf', { + source: 'agent-remote', + actor: 'agent:replay', + opId: 'baseline' + }) + ).toBe(true) + + const stateVector = Y.encodeStateVector(host) + applyOps( + host, + [ + op('first-node', 1, { + op: 'add_node', + node_id: 1, + class_type: 'Source', + pos: [0, 0], + node: { id: 1, type: 'Source', pos: [0, 0] } + }) + ] as Parameters[1], + catalog + ) + const update = Y.encodeStateAsUpdate(host, stateVector) + follower.applyRemoteUpdate(update) + expect( + adapter.applyFrame({ + workflowId: 'wf', + seq: 1, + update, + actor: 'agent:test', + opIds: ['first-frame'] + }) + ).toBe(true) + expect(reconcileNode).toHaveBeenCalledOnce() + expect(addNode).not.toHaveBeenCalled() + + adapter.destroy() + follower.destroy() + host.destroy() + }) + + it('refuses to project a doc this build cannot read', () => { + const host = mint( + { nodes: [{ id: 1, type: 'Source', pos: [0, 0] }], links: [] }, + catalog + ) + const follower = new FollowerDoc() + follower.applyRemoteUpdate(Y.encodeStateAsUpdate(host)) + follower.doc.getMap('meta').set('schema_version', SCHEMA_VERSION + 1) + + const adapter = new EcsFollowerAdapter( + createGraphMutations({ + getScope: () => scope, + layout: { createNode: vi.fn(), deleteNodes: vi.fn() } + }) + ) + adapter.bind('wf', follower) + + expect( + adapter.projectBaseline('wf', { + source: 'agent-remote', + actor: 'agent:replay', + opId: 'baseline' + }) + ).toBe(false) + expect(useNodeDataStore().getGraphNodesFor('root', 'root')).toEqual([]) + + adapter.destroy() + follower.destroy() + host.destroy() + }) + + it('reconciles already-projected nodes without recreating their layout', () => { + const host = mint( + { + nodes: [ + { + id: 1, + type: 'Source', + pos: [10, 20], + size: [180, 90], + inputs: [], + outputs: [{ name: 'out', type: 'IMAGE', links: [] }] + } + ], + links: [] + }, + catalog + ) + const follower = new FollowerDoc() + follower.applyRemoteUpdate(Y.encodeStateAsUpdate(host)) + const createLayout = vi.fn() + const deleteLayouts = vi.fn() + const adapter = new EcsFollowerAdapter( + createGraphMutations({ + getScope: () => scope, + layout: { createNode: createLayout, deleteNodes: deleteLayouts } + }) + ) + const context = { + source: 'agent-remote', + actor: 'agent:replay', + opId: 'baseline' + } as const + + adapter.bind('wf', follower) + expect(adapter.projectBaseline('wf', context)).toBe(true) + const projected = graphSnapshot() + expect(deleteLayouts).not.toHaveBeenCalled() + createLayout.mockClear() + + adapter.unbind('wf') + adapter.bind('wf', follower) + expect( + adapter.applyFrame({ + workflowId: 'wf', + seq: 1, + update: new Uint8Array(), + actor: 'agent:test', + opIds: ['unrelated'] + }) + ).toBe(true) + expect(createLayout).not.toHaveBeenCalled() + expect(deleteLayouts).not.toHaveBeenCalled() + expect(graphSnapshot()).toEqual(projected) + + expect(adapter.projectBaseline('wf', context)).toBe(true) + expect(deleteLayouts).not.toHaveBeenCalled() + expect(createLayout).not.toHaveBeenCalled() + expect(graphSnapshot()).toEqual(projected) + + adapter.destroy() + follower.destroy() + host.destroy() + }) + it('applies an implicit disconnect when delete-wins installs no replacement', () => { const host = mint({ nodes: [], links: [] }, catalog) const follower = new FollowerDoc() @@ -703,6 +1355,90 @@ describe('EcsFollowerAdapter integration', () => { host.destroy() }) + it('never carries a reused doc into the next workflow bound to it', () => { + const host = mint( + { + nodes: [ + { + id: 1, + type: 'Source', + pos: [10, 20], + inputs: [], + outputs: [{ name: 'out', type: 'IMAGE', links: [9] }] + }, + { + id: 2, + type: 'Sink', + pos: [300, 20], + inputs: [{ name: 'in', type: 'IMAGE', link: 9 }], + outputs: [] + } + ], + links: [[9, 1, 0, 2, 0, 'IMAGE']] + }, + catalog + ) + const follower = new FollowerDoc() + follower.applyRemoteUpdate(Y.encodeStateAsUpdate(host)) + + const projectedNodes: string[] = [] + const projectedLinks: string[] = [] + const adapter = new EcsFollowerAdapter( + (workflowId): GraphMutations => ({ + batch: (_context, define) => { + define({ + addNode: ({ id }) => projectedNodes.push(`${workflowId}:${id}`), + reconcileNode: ({ id }) => + projectedNodes.push(`${workflowId}:${id}`), + setWidget: () => undefined, + connect: ({ id }) => projectedLinks.push(`${workflowId}:${id}`), + removeMissing: () => undefined, + removeLinks: () => undefined, + deleteNode: () => undefined, + clearSemanticGraph: () => undefined + }) + return true + }, + addNode: () => true, + setWidget: () => true, + connect: () => true, + deleteNode: () => true, + clearSemanticGraph: () => true + }) + ) + + // The bridge reuses one doc across a switch, so wf-b binds onto wf-a's. + adapter.bind('wf-a', follower) + expect( + adapter.projectBaseline('wf-a', { + source: 'agent-remote', + actor: 'agent:test', + opId: 'baseline-a' + }) + ).toBe(true) + expect(projectedNodes.sort()).toEqual(['wf-a:1', 'wf-a:2']) + expect(projectedLinks).toEqual(['wf-a:9']) + + adapter.unbind('wf-a') + adapter.bind('wf-b', follower) + expect( + adapter.applyFrame({ + workflowId: 'wf-b', + seq: 1, + update: new Uint8Array(), + actor: 'agent:test', + opIds: ['b'] + }) + ).toBe(true) + + expect(projectedNodes.sort()).toEqual(['wf-a:1', 'wf-a:2']) + expect(projectedLinks).toEqual(['wf-a:9']) + + adapter.destroy() + follower.destroy() + host.destroy() + }) + describe('remote widget map edits on an existing node', () => { function bindSeededHost() { const host = mint( diff --git a/src/workbench/extensions/agent/crdt/ecsFollowerAdapter.ts b/src/workbench/extensions/agent/crdt/ecsFollowerAdapter.ts index 6f72c7f37fe..067b6cd45c5 100644 --- a/src/workbench/extensions/agent/crdt/ecsFollowerAdapter.ts +++ b/src/workbench/extensions/agent/crdt/ecsFollowerAdapter.ts @@ -15,6 +15,7 @@ import { toNodeId } from '@/types/nodeId' import type { DocUpdate } from './docFrameClient' import type { FollowerDoc } from './followerDoc' +import { FollowerSchemaError, assertReadableSchema } from './schemaGuard' type NodeRootAction = 'add' | 'update' | 'delete' export type MutationsForTarget = @@ -93,6 +94,33 @@ function readNodeSlots( : 'originOutputs'] } +/** Slots `prepare` will keep: it drops every non-record entry before indexing. */ +function connectableSlots(slots: readonly unknown[] | undefined): number { + return (slots ?? []).filter( + (slot) => typeof slot === 'object' && slot !== null && !Array.isArray(slot) + ).length +} + +/** + * The `prepare` connect rejections observable from the doc alone, mirrored + * because it fails the whole batch on the first one. Graph ownership is not + * among them: only the link store knows an id already belongs elsewhere. + */ +function isConnectable( + link: SemanticLinkPayload, + projectedIds: ReadonlySet +): boolean { + return ( + link.id >= 0 && + link.originSlot >= 0 && + link.targetSlot >= 0 && + projectedIds.has(String(link.originNodeId)) && + projectedIds.has(String(link.targetNodeId)) && + link.originSlot < connectableSlots(link.originOutputs) && + link.targetSlot < connectableSlots(link.targetInputs) + ) +} + function frameContext(update: DocUpdate): RemoteMutationContext { const opIds = update.opIds?.filter((id) => id.length > 0) return { @@ -128,12 +156,18 @@ interface TargetSession { */ export class EcsFollowerAdapter { private readonly targets = new Map() + private readonly followerWorkflowIds = new WeakMap() constructor(private readonly mutations: MutationsForTarget) {} bind(workflowId: string, follower: FollowerDoc): void { this.unbind(workflowId) const session = this.createSession(workflowId, follower) + const previousWorkflowId = this.followerWorkflowIds.get(follower) + if (previousWorkflowId && previousWorkflowId !== workflowId) { + session.reconcileNextFrame = false + } + this.followerWorkflowIds.set(follower, workflowId) this.targets.set(workflowId, session) session.nodes.observeDeep(session.onNodesChanged) session.links.observe(session.onLinksChanged) @@ -169,6 +203,95 @@ export class EcsFollowerAdapter { return updateCommitted } + /** + * Commit the bound doc's current content under its own provenance, for a doc + * preloaded from a saved snapshot: Yjs observers only report what changes + * after `bind`, so that content would otherwise stay unprojected until an + * unrelated later delta arrived. + * + * Opt-in, never done by `bind`, because the bridge reuses one long-lived + * follower doc across workflow switches: seeding at bind would project the + * previous workflow's graph into this one, and re-reconcile every node on an + * ordinary unbind/rebind of an unchanged doc. + * + * An unprojectable link is skipped rather than batched, since `prepare` + * rejects a whole batch on its first invalid entry. A self-inconsistent doc + * can therefore land a node whose slot mirror still names a skipped link, + * leaving that slot pointing at a topology the link store does not hold. + * + * Additive for nodes: ECS nodes the doc does not mention are left alone, so + * this converges the graph on the doc rather than replacing it. A caller + * wanting a true replace must clear first, accepting two separate batches. + * + * Not additive for the slots of a node it reconciles: `reconcileNode` splices + * the doc's slot records over the store's, so a store link in a slot the doc + * omits is left registered with no slot referencing it. `applyQueuedFrame` + * has the same hole on its own reconcile path; both need `linkStore` access + * to close, so a caller must not restore onto a populated graph until it is. + * + * Returns false when nothing is bound, when the doc fails the KA-11 read gate + * with a {@link FollowerSchemaError}, or when the batch was rejected. + * Restores arrive out of band, so this is the only place that gate can run + * for them. + * + * No production caller yet: nothing persists or restores Yjs bytes today. + */ + projectBaseline(workflowId: string, context: RemoteMutationContext): boolean { + const session = this.targets.get(workflowId) + if (!session) return false + try { + assertReadableSchema(session.follower.doc) + } catch (error) { + if (!(error instanceof FollowerSchemaError)) throw error + return false + } + + const nodes = [...session.nodes.keys()].flatMap((id) => { + const payload = readSemanticNode(session.follower.doc, id) + return payload ? [payload] : [] + }) + const projectedIds = new Set(nodes.map(({ id }) => String(id))) + const links: SemanticLinkPayload[] = [] + const skippedLinks: string[] = [] + for (const id of session.links.keys()) { + const link = readSemanticLink(session.follower.doc, id) + if (link && isConnectable(link, projectedIds)) links.push(link) + else skippedLinks.push(id) + } + + const skippedNodes = [...session.nodes.keys()].filter( + (id) => !projectedIds.has(id) + ) + if (skippedNodes.length > 0 || skippedLinks.length > 0) { + console.warn( + `[agent-crdt] baseline for ${workflowId} skipped unprojectable nodes ` + + `[${skippedNodes.join(', ')}] and links [${skippedLinks.join(', ')}]` + ) + } + + const projected = session.mutations.batch(context, (batch) => { + for (const node of nodes) batch.reconcileNode(node) + for (const link of links) batch.connect(link) + }) + if (!projected) return false + + // Everything the doc holds, skipped included: a skipped entry left staged + // is retried next frame, whose whole batch `prepare` then rejects. A staged + // deletion is not in the doc, so it survives — nothing else can find it. + for (const id of session.nodes.keys()) { + session.nodeActions.delete(id) + session.changedWidgets.delete(id) + } + for (const id of session.links.keys()) session.changedLinks.delete(id) + + // This baseline performed the initial reconciliation. Later wire deltas + // must use the normal add/update paths so links are updated atomically. + if (nodes.length > 0 || links.length > 0) { + session.reconcileNextFrame = false + } + return true + } + /** Explicit lineage reset only; reconnect/gap recovery never calls it. */ clearForReset(workflowId: string, context: RemoteMutationContext): boolean { const session = this.targets.get(workflowId)