Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions packages/core/src/agent-operations/author-scene.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
169 changes: 135 additions & 34 deletions packages/core/src/agent-operations/author-scene.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> }

/** A conversion as computed, before it is spread over the scene (`finalizeAuthorScene`). */
export type AuthorSceneCandidate = {
buildingId: string
seed: string
ids: Record<string, string>
nodes: Record<string, AnyNode>
}

const BOOKKEEPING = ['authorSceneBase', 'authorSceneWritten'] as const

/** A value as live collaboration and storage keep it: no undefined, no non-finite number. */
const plain = <T>(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<string, unknown> | 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

v1 conversions cannot be revised

High Severity

authoredBaseline accepts only v2 authorSceneState, so a v1 building blob yields no previous. Levels still carry authorScene, which makes converted true and the existing_design gate refuse every replace: true revision. The merge fallback is also only existing levels, not the current scene the PR describes as the v1 base, so seed, ids, and person edits from the v1 snapshot are discarded.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 80ee6d3. Configure here.

const ids: Record<string, string> = {}
const nodes: Record<string, AnyNode> = {}
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
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deleted levels lose conversion baseline

Medium Severity

The reconstructed baseline only walks levels that still exist and still have authorSceneWritten. Deleting a level cascade-removes that list and every child’s authorSceneBase. A later revision therefore has no record those nodes were authored and deleted, so the same seed remints the same ids and the merge recreates the storey.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 80ee6d3. Configure here.

return { seed: state.seed, ids, nodes }
}

export type AuthorSceneDefect = { id: string; code: string; message: string }

export type AuthorSceneReport = {
Expand Down Expand Up @@ -655,7 +706,7 @@ export function authorScene(
context: AgentContext,
): AgentOperationOutcome & {
result: AuthorSceneReport
candidate: AuthorSceneState
candidate: AuthorSceneCandidate
buildingId: string
} {
const { payload } = input
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand All @@ -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<string, AuthorSceneWritten>()
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<string, unknown> => ({
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<string>(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<string, unknown>
updated.set(id, {
id,
data: { ...entry?.data, metadata: { ...metadata, ...kept } } as Partial<AnyNode>,
})
}
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<AnyNode>,
})
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)
24 changes: 17 additions & 7 deletions packages/core/src/contracts/reference-inventory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand Down Expand Up @@ -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',
Expand All @@ -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',
],
),
Expand Down
6 changes: 3 additions & 3 deletions packages/mcp/src/tools/author-scene.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
Loading
Loading