diff --git a/packages/core/src/agent-operations/author-scene.test.ts b/packages/core/src/agent-operations/author-scene.test.ts index da7f63707f..198f75521f 100644 --- a/packages/core/src/agent-operations/author-scene.test.ts +++ b/packages/core/src/agent-operations/author-scene.test.ts @@ -329,6 +329,48 @@ describe('author_scene', () => { ).toThrow() }) + test('a conversion is kept in pieces live collaboration takes: plain JSON, none past 64 KB', () => { + // Four storeys of the bedroom, every source id its own. + const storeys = structuredClone(bedroom) + storeys.levels = [0, 1, 2, 3].map((index) => { + const level = structuredClone(bedroom.levels[0]!) + level.name = `Storey ${index + 1}` + level.elevation = index * 3 + const suffix = (id: string) => `${id}-${index}` + for (const wall of level.walls ?? []) wall.id = suffix(wall.id) + for (const item of level.items ?? []) item.id = suffix(item.id) + return level + }) + const compiled = Object.fromEntries( + storeys.levels.flatMap((level) => (level.items ?? []).map((item) => [item.id, bed])), + ) + const outcome = authorScene(scaffold(), { payload: storeys, compiled }, { activeLevelId: null }) + const values = [ + ...(outcome.changes!.create ?? []).map((entry) => entry.node), + ...(outcome.changes!.update ?? []).map((entry) => entry.data), + ] + for (const value of values) { + expect(JSON.parse(JSON.stringify(value))).toEqual(value) + expect(JSON.stringify(value).length).toBeLessThan(62 * 1024) + } + const building = outcome.changes!.update!.find((entry) => entry.id === 'building_1')! + expect(building.data.metadata?.authorSceneState).toEqual({ + version: 2, + buildingId: 'building_1', + seed: outcome.candidate.seed, + }) + // Each storey lists what it holds, and each node carries the baseline it was written as. + const after = applySceneChanges(scaffold(), outcome.changes) + const levels = Object.values(after).filter((node) => node.type === 'level') + expect(levels).toHaveLength(4) + const listed = levels.flatMap( + (level) => + (level.metadata as { authorSceneWritten: { ids: string[] } }).authorSceneWritten.ids, + ) + expect(new Set(listed)).toEqual(new Set(Object.keys(outcome.candidate.nodes))) + for (const id of listed) expect(after[id]?.metadata?.authorSceneBase).toBeDefined() + }) + describe('a revision after Pascal rebuilt what it derives', () => { const floor = (script: string, artifact: string): CompiledGeometryScript => ({ ...bed, diff --git a/packages/core/src/agent-operations/author-scene.ts b/packages/core/src/agent-operations/author-scene.ts index 920f3daa92..718ed4a8b4 100644 --- a/packages/core/src/agent-operations/author-scene.ts +++ b/packages/core/src/agent-operations/author-scene.ts @@ -114,14 +114,65 @@ export type AuthorSceneInput = { prepareOnly?: boolean } -export type AuthorSceneState = { - version: 1 +/** + * What a conversion keeps between revisions, spread over the nodes it wrote so every save fits live + * collaboration (one shared change is at most 64 KB; a house's whole baseline is megabytes): + * - on its building, `authorSceneState`: the seed its identities come from; + * - on each level it wrote, `authorSceneWritten`: the nodes written under it and the source key of + * each keyed one, so a node the person deleted stays deleted; + * - on each node it wrote, `authorSceneBase`: the node as written, the baseline a revision merges + * the person's edits against. + */ +export type AuthorSceneState = { version: 2; buildingId: string; seed: string } +type AuthorSceneWritten = { ids: string[]; keys: Record } + +/** A conversion as computed, before it is spread over the scene (`finalizeAuthorScene`). */ +export type AuthorSceneCandidate = { buildingId: string seed: string ids: Record nodes: Record } +const BOOKKEEPING = ['authorSceneBase', 'authorSceneWritten'] as const + +/** A value as live collaboration and storage keep it: no undefined, no non-finite number. */ +const plain = (value: T): T => JSON.parse(JSON.stringify(value)) as T + +/** A node without the conversion's bookkeeping: what a person edits and a revision merges. */ +function withoutBookkeeping(node: AnyNode): AnyNode { + const metadata = node.metadata as Record | undefined + if (!(metadata && BOOKKEEPING.some((key) => key in metadata))) return node + const kept = { ...metadata } + for (const key of BOOKKEEPING) delete kept[key] + return { ...node, metadata: kept } as AnyNode +} + +/** A node the person deleted since the last conversion: present in the baseline, never read. */ +const DELETED = { type: 'deleted' } as unknown as AnyNode + +/** + * The last conversion of `building`, read back from its levels and nodes: its seed, its source-key + * identities, and the baseline of every node it wrote (a deleted one marked so). + */ +function authoredBaseline(scene: SceneNodes, building: AnyNode) { + const state = building.metadata?.authorSceneState as AuthorSceneState | undefined + if (!(state?.version === 2 && state.buildingId === building.id && typeof state.seed === 'string')) + return undefined + const ids: Record = {} + const nodes: Record = {} + for (const level of queryNodes(scene, { type: 'level', parentId: building.id })) { + const written = level.metadata?.authorSceneWritten as AuthorSceneWritten | undefined + if (!written) continue + Object.assign(ids, written.keys) + for (const id of written.ids) { + const node = scene[id as keyof typeof scene] as AnyNode | undefined + nodes[id] = (node?.metadata?.authorSceneBase as AnyNode | undefined) ?? DELETED + } + } + return { seed: state.seed, ids, nodes } +} + export type AuthorSceneDefect = { id: string; code: string; message: string } export type AuthorSceneReport = { @@ -655,7 +706,7 @@ export function authorScene( context: AgentContext, ): AgentOperationOutcome & { result: AuthorSceneReport - candidate: AuthorSceneState + candidate: AuthorSceneCandidate buildingId: string } { const { payload } = input @@ -703,15 +754,7 @@ export function authorScene( const existingLevels = Object.values(scene).filter( (n) => n.type === 'level' && n.parentId === building.id, ) - const saved = building.metadata?.authorSceneState as AuthorSceneState | undefined - const previous = - saved?.version === 1 && - saved.buildingId === building.id && - saved.nodes && - saved.ids && - typeof saved.seed === 'string' - ? saved - : undefined + const previous = authoredBaseline(scene, building) const converted = Boolean(previous) || existingLevels.some((l) => l.metadata?.authorScene) if (converted && !input.replace) refuse( @@ -2183,14 +2226,10 @@ export function authorScene( if (created) written[levelId] = { ...written[levelId], height: Math.max(rises, 0.2) } as AnyNode } - const nodes = Object.fromEntries(Object.entries(written).filter(([id]) => !scaffoldIds.has(id))) - const candidate: AuthorSceneState = { - version: 1, - buildingId: building.id, - seed, - ids: report.ids, - nodes, - } + const nodes = plain( + Object.fromEntries(Object.entries(written).filter(([id]) => !scaffoldIds.has(id))), + ) + const candidate: AuthorSceneCandidate = { buildingId: building.id, seed, ids: report.ids, nodes } const outcome = { result: report, candidate, @@ -2205,33 +2244,95 @@ export function finalizeAuthorScene( scene: SceneNodes, outcome: AgentOperationOutcome & { result: AuthorSceneReport - candidate: AuthorSceneState + candidate: AuthorSceneCandidate buildingId: string }, ) { const building = scene[outcome.buildingId] if (building?.type !== 'building') refuse('no_building', 'The target building no longer exists.') - const previous = building.metadata?.authorSceneState as AuthorSceneState | undefined + const { candidate } = outcome + const current = Object.fromEntries( + Object.entries(scene).map(([id, node]) => [id, withoutBookkeeping(node as AnyNode)]), + ) as SceneNodes const base = - previous?.nodes ?? + authoredBaseline(scene, building)?.nodes ?? Object.fromEntries( - Object.values(scene) - .filter((node) => node.type === 'level' && node.parentId === building.id) - .map((node) => [node.id, node]), + queryNodes(current, { type: 'level', parentId: building.id }).map((node) => [node.id, node]), ) - const changes = authoredSceneChanges(scene, base, outcome.candidate.nodes) + const changes = authoredSceneChanges(current, base, candidate.nodes) + + // Each written node keeps its own baseline, and each written level the list of what it holds. + const levelOf = (id: string): string | undefined => { + let node = candidate.nodes[id] + while (node && node.type !== 'level') + node = node.parentId ? candidate.nodes[node.parentId] : undefined + return node?.id + } + const keyOf = new Map(Object.entries(candidate.ids).map(([key, id]) => [id, key])) + const writtenOn = new Map() + for (const id of Object.keys(candidate.nodes)) { + const level = levelOf(id) + if (!level) continue + const written = writtenOn.get(level) ?? { ids: [], keys: {} } + written.ids.push(id) + const key = keyOf.get(id) + if (key) written.keys[key] = id + writtenOn.set(level, written) + } + const bookkeeping = (id: string): Record => ({ + authorSceneBase: withoutBookkeeping(candidate.nodes[id]!), + ...(writtenOn.has(id) ? { authorSceneWritten: writtenOn.get(id) } : {}), + }) + const create = (changes.create ?? []).map((entry) => + candidate.nodes[entry.node.id] + ? { + ...entry, + node: { + ...entry.node, + metadata: { ...entry.node.metadata, ...bookkeeping(entry.node.id) }, + } as AnyNode, + } + : entry, + ) + const created = new Set(create.map((entry) => entry.node.id)) + const removed = new Set(changes.delete ?? []) + const updated = new Map((changes.update ?? []).map((entry) => [entry.id, entry])) + for (const id of Object.keys(candidate.nodes)) { + const now = scene[id as keyof typeof scene] as AnyNode | undefined + if (created.has(id) || removed.has(id) || !now) continue + const kept = { ...bookkeeping(id) } + const stored = Object.fromEntries( + BOOKKEEPING.flatMap((key) => + now.metadata && key in now.metadata ? [[key, now.metadata[key]]] : [], + ), + ) + const entry = updated.get(id) + if (!entry && equalJson(stored, kept)) continue + const metadata = (entry?.data.metadata ?? + current[id as keyof typeof current]?.metadata ?? + {}) as Record + updated.set(id, { + id, + data: { ...entry?.data, metadata: { ...metadata, ...kept } } as Partial, + }) + } + const state: AuthorSceneState = { version: 2, buildingId: building.id, seed: candidate.seed } + updated.set(building.id, { + id: building.id, + data: { + ...updated.get(building.id)?.data, + metadata: { ...withoutBookkeeping(building).metadata, authorSceneState: state }, + } as Partial, + }) return { ...outcome, changes: { ...changes, + create, ...(outcome.changes?.materials ? { materials: outcome.changes.materials } : {}), - update: [ - ...(changes.update ?? []), - { - id: building.id, - data: { metadata: { ...building.metadata, authorSceneState: outcome.candidate } }, - }, - ], + update: [...updated.values()], }, } } + +const equalJson = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b) diff --git a/packages/core/src/contracts/reference-inventory.ts b/packages/core/src/contracts/reference-inventory.ts index 5232b9b14c..b9a2974f3d 100644 --- a/packages/core/src/contracts/reference-inventory.ts +++ b/packages/core/src/contracts/reference-inventory.ts @@ -831,13 +831,25 @@ export const METADATA_REFERENCES: readonly ExistingReference[] = [ ...policy('node', 'internal', 'drop', 'strip'), remaps: ['clone-scene-graph', 'clone-level-subtree'], dependents: ['metadata.authorSceneState'], - note: 'The building that owns this conversion baseline; a partial copy cannot overwrite its source building.', + note: 'The building that owns this conversion; a partial copy cannot overwrite its source building.', }), - meta('authorSceneState.ids.*', { + meta('authorSceneWritten.ids[]', { ...policy('node', 'internal', 'drop', 'strip'), remaps: ['clone-scene-graph', 'clone-level-subtree'], - dependents: ['metadata.authorSceneState.nodes'], - note: 'Stable source-to-node identities and the corresponding authored baseline snapshot; whole graph clones remap the snapshot recursively.', + dependents: ['metadata.authorSceneWritten'], + note: 'On an authored level: the nodes the last conversion wrote there, so the next revision can tell a node the person deleted from one it never made.', + }), + meta('authorSceneWritten.keys.*', { + ...policy('node', 'internal', 'drop', 'strip'), + remaps: ['clone-scene-graph', 'clone-level-subtree'], + dependents: ['metadata.authorSceneWritten'], + note: 'On an authored level: stable source-to-node identities, so a revision keeps the nodes the person already edited.', + }), + meta('authorSceneBase.id', { + ...policy('node', 'internal', 'drop', 'strip'), + remaps: ['clone-scene-graph', 'clone-level-subtree'], + dependents: ['metadata.authorSceneBase'], + note: "The node as the last conversion wrote it, the base of the next revision's three-way merge; whole graph clones remap the snapshot recursively.", }), meta('managedByLeanTo', { ...policy('node', 'internal', 'cascade', 'strip'), @@ -953,7 +965,7 @@ const described = (reason: string, paths: readonly string[]) => export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[] = [ { path: 'metadata.roomBoundary', reason: 'Boolean opt-out from room boundary detection.' }, ...described( - "author_scene's provenance: the payload's own ids on walls and openings, a room's seed, a level's elevation, a slab's finish, a wall's colour, and on the building the stored payload, the report, the payload items waiting for an add_object piece (by payload id and piece id) and when it was written; none of it names a node.", + "author_scene's provenance: the payload's own ids on walls and openings, a room's seed, a level's elevation, a slab's finish, a wall's colour, and on the building the stored payload's script hash, the payload items waiting for an add_object piece (by payload id and piece id) and when it was written; none of it names a node.", [ 'authorScene', 'authorScene.at', @@ -963,8 +975,6 @@ export const METADATA_NON_REFERENCES: readonly { path: string; reason: string }[ 'authorScene.id', 'authorScene.payload', 'authorScene.pending', - 'authorScene.report', - 'authorScene.report.defects', 'authorScene.seed', ], ), diff --git a/packages/mcp/src/tools/author-scene.test.ts b/packages/mcp/src/tools/author-scene.test.ts index 7f2ba39783..15c2a92e4c 100644 --- a/packages/mcp/src/tools/author-scene.test.ts +++ b/packages/mcp/src/tools/author-scene.test.ts @@ -313,10 +313,10 @@ describe('author_scene (MCP)', () => { expect(report.snapped).toEqual([{ id: 'w', end: 'end', movedM: 0.1 }]) expect(report.notes).toContain('The rug was left out.') // Two artifacts per module (GLB + code): three items, the round window and the ceiling point - // a room with no light would hang from (one, however many rooms), plus the design's module and - // the adapter. + // a room with no light would hang from (one, however many rooms), plus the design's module, the + // adapter and the payload they answered. expect(stored.filter((s) => s.startsWith('model/gltf-binary'))).toHaveLength(5) - expect(stored.filter((s) => s.startsWith('text/javascript'))).toHaveLength(7) + expect(stored.filter((s) => s.startsWith('text/javascript'))).toHaveLength(8) // The light rides on its fixture through the bridge, not only in the operation's draft. const lamp = await client.callTool({ name: 'find_by_type', arguments: { type: 'item' } }) expect(JSON.stringify(lamp.structuredContent ?? lamp.content)).toContain('Lamp') diff --git a/packages/mcp/src/tools/author-scene.ts b/packages/mcp/src/tools/author-scene.ts index dd352c185f..3887e8d466 100644 --- a/packages/mcp/src/tools/author-scene.ts +++ b/packages/mcp/src/tools/author-scene.ts @@ -38,14 +38,14 @@ type Input = { } /** - * What a conversion keeps on its building (`metadata.authorScene`): its module and adapter as - * stored scripts, the payload with every module as its stored script (`Script`) and every - * piece by id, the items still waiting for their piece, and the report. + * What a conversion keeps on its building (`metadata.authorScene`): its module, adapter and + * payload as stored scripts, and the items still waiting for their piece. The payload is a file of + * the scene, not metadata: a house's runs past what one live collaboration change carries. */ type StoredConversion = { module?: string adapter?: string - payload?: Record + payload?: string pending?: AuthorScenePending[] } @@ -169,19 +169,26 @@ export function registerAuthorScene( ...outcome.result, defects: [...pieces.defects, ...outcome.result.defects], } + const payloadText = storedPayloadText(await withScripts(source.payload)) + const payloadScript = await host.storeArtifact({ + sceneId: scene.id, + sha256: await sha256(payloadText), + bytes: new TextEncoder().encode(payloadText), + mimeType: GEOMETRY_SCRIPT_MIME_TYPES.three, + metadata: { kind: 'item' }, + }) const buildingUpdate = outcome.changes.update.find( (change) => change.id === outcome.buildingId, )! - buildingUpdate.data.metadata = { - ...buildingUpdate.data.metadata, - authorScene: { - ...provenance, - payload: await withScripts(source.payload), - pending: pieces.pending, - report, - at: new Date().toISOString(), - }, + const stored: StoredConversion & { at: string } = { + ...provenance, + payload: payloadScript, + pending: pieces.pending, + at: new Date().toISOString(), } + buildingUpdate.data.metadata = JSON.parse( + JSON.stringify({ ...buildingUpdate.data.metadata, authorScene: stored }), + ) // A revision's plates and ceilings follow its walls: what only the reconciler may change on // one that stays (its outline, its room) is left to the bridge's reconciliation after the // write, as in the editor; a new room's arrive with it. @@ -340,12 +347,15 @@ async function sourceOf( } return result(parsed.data, texts) } - if (!stored?.payload) + if (typeof stored?.payload !== 'string') refuse( 'nothing_to_write', 'Pass a payload, or a module and its adapter: this scene holds no stored conversion to write again.', ) - const rehydrated = (await withCode(stored.payload, readText)) as unknown + const rehydrated = (await withCode( + readStoredPayload(await readText(stored.payload)), + readText, + )) as unknown const parsed = authorScenePayload.safeParse(rehydrated) if (!parsed.success) refuse( @@ -414,6 +424,21 @@ async function withPieces( } } +const STORED_PAYLOAD_PREFIX = 'export default ' + +/** The payload as a module of the scene, the one script type its files take. */ +const storedPayloadText = (payload: unknown) => + `${STORED_PAYLOAD_PREFIX}${JSON.stringify(payload)}\n` + +function readStoredPayload(text: string): unknown { + if (!text.startsWith(STORED_PAYLOAD_PREFIX)) return undefined + try { + return JSON.parse(text.slice(STORED_PAYLOAD_PREFIX.length)) + } catch { + return undefined + } +} + /** The payload as kept with the scene: every module as its stored script's hash, pieces by id. */ async function withScripts(value: unknown): Promise { if (Array.isArray(value)) return Promise.all(value.map(withScripts))