feat(mcp,editor): Option A+B storage + 10 agent deliverables (Phase 7)

Ships the combined filesystem/Supabase storage adapter + MCP scene
lifecycle tools + Next.js API routes + editor /scene/[id] route, so
an MCP save is directly openable at /scene/<id> without any
injection hack. End-to-end verified: 10/10 e2e steps pass.

Storage (A1/A2/A3):
- SceneStore interface + error classes + slug helpers
- FilesystemSceneStore at $PASCAL_DATA_DIR (defaults XDG/~/.pascal)
  with atomic writes, .index sidecar, optimistic locking
- SupabaseSceneStore with scenes + scene_revisions tables, RLS
  migration SQL, mock-backed unit tests
- createSceneStore(env) auto-selects based on SUPABASE_URL +
  SUPABASE_SERVICE_ROLE_KEY

MCP tools (A4, A8, A9, A10):
- save_scene / load_scene / list_scenes / delete_scene / rename_scene
- list_templates / create_from_template (3 seed templates:
  empty-studio, two-bedroom, garden-house)
- generate_variants (7 mutation kinds, seeded RNG, save=true|false)
- photo_to_scene (vision sampling → scene graph → save)

Editor (A5, A6):
- /api/scenes + /api/scenes/[id] with RFC 7232 If-Match locking
- /scene/[id] and /scenes route pages with save button, SceneLoader
- Removed the window.__pascalScene dev injection hack

Security + UX edges (A7, A8):
- AssetUrl Zod validator: asset:// blob: data:image/ /path https:
  (http://localhost for dev) + PASCAL_ALLOWED_ASSET_ORIGINS env
  allowlist. Hardens scan.url, guide.url, item.asset.src,
  material.texture.url, MaterialMaps.*Map
- Auto-frame camera on empty→non-empty scene transition
  (camera-controls:fit-scene emitter event)

Shared utilities:
- rehydrateSiteChildren() extracted to packages/mcp/src/lib/ and
  used by both create-from-template and generate-variants to work
  around the SiteNode.children-as-objects vs. ids inconsistency
  (CROSS_CUTTING §2)
- Storage + MCP subpath exports added to packages/mcp/package.json
  (CROSS_CUTTING §4)

Tests: 293 pass / 0 fail across 40 files (was 142 pre-Phase-7).
Biome: clean.

Phase-7 e2e script at packages/mcp/test-reports/phase7-e2e.ts:
MCP HTTP + editor Next.js both point at $PASCAL_DATA_DIR =
/tmp/pascal-e2e, save_scene from MCP, GET /api/scenes/<id> from
editor server, /scenes list page renders all saved scenes, scene
page renders SceneLoader, delete_scene works.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Adrian Perez
2026-04-18 19:29:28 +02:00
co-authored by Claude Opus 4.7
parent 42bd05db9c
commit e8d0b13ff5
81 changed files with 8933 additions and 1213 deletions
+4 -1
View File
@@ -530,7 +530,10 @@ describe('SceneBridge', () => {
category: 'test',
name: 'Test Asset',
thumbnail: 'data:image/png;base64,',
src: 'data:model/gltf-binary;base64,',
// AssetUrl validator (asset-url.ts) only allows asset://, blob:,
// data:image/, /path, or https://; `data:model/gltf-binary` is not
// in the allowlist, so this test uses an internal asset handle.
src: 'asset://test/chair.glb',
},
})
// Place item directly on level — ItemNode supports arbitrary parents in the model.
@@ -0,0 +1,40 @@
import type { AnyNode } from '@pascal-app/core/schema'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
/**
* `cloneSceneGraph` normalises `SiteNode.children` to an array of node IDs,
* but core's `SiteNode` schema expects an array of embedded `BuildingNode` /
* `ItemNode` objects (see `packages/mcp/CROSS_CUTTING.md` §2). To keep the
* cloned graph validating against `AnyNode`, re-embed the site children from
* the flat dict.
*
* Pure: returns a new graph without mutating the input.
*/
export function rehydrateSiteChildren(graph: SceneGraph): SceneGraph {
const out: SceneGraph = {
nodes: { ...graph.nodes },
rootNodeIds: [...graph.rootNodeIds],
...(graph.collections ? { collections: graph.collections } : {}),
}
for (const [id, node] of Object.entries(out.nodes)) {
if (node.type !== 'site') continue
const childrenField = (node as { children?: unknown[] }).children
if (!Array.isArray(childrenField)) continue
const rehydrated: AnyNode[] = []
for (const child of childrenField) {
if (typeof child === 'string') {
const target = out.nodes[child as keyof typeof out.nodes]
if (target && (target.type === 'building' || target.type === 'item')) {
rehydrated.push(target)
}
} else if (child && typeof child === 'object' && 'id' in (child as Record<string, unknown>)) {
rehydrated.push(child as AnyNode)
}
}
out.nodes[id as keyof typeof out.nodes] = {
...(node as AnyNode),
children: rehydrated,
} as AnyNode
}
return out
}
+51 -1
View File
@@ -2,11 +2,22 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneBridge } from './bridge/scene-bridge'
import { registerPrompts } from './prompts'
import { registerResources } from './resources'
import { createSceneStore } from './storage'
import type {
SceneListOptions,
SceneMeta,
SceneMutateOptions,
SceneSaveOptions,
SceneStore,
SceneWithGraph,
} from './storage/types'
import { registerTools } from './tools'
import { registerVisionTools } from './tools/vision'
export type CreatePascalMcpServerOptions = {
bridge: SceneBridge
/** Injected `SceneStore`. When omitted, `createSceneStore()` is used lazily. */
store?: SceneStore
name?: string
version?: string
}
@@ -16,9 +27,48 @@ export function createPascalMcpServer(opts: CreatePascalMcpServerOptions): McpSe
name: opts.name ?? 'pascal-mcp',
version: opts.version ?? '0.1.0',
})
registerTools(server, opts.bridge)
const store = opts.store ?? createLazySceneStore()
registerTools(server, opts.bridge, store)
registerVisionTools(server, opts.bridge)
registerResources(server, opts.bridge)
registerPrompts(server, opts.bridge)
return server
}
/**
* Wrap `createSceneStore()` (which is async) behind a synchronous `SceneStore`
* facade so that `createPascalMcpServer` can remain synchronous. Each method
* resolves the underlying store on first use and memoizes it afterwards.
*/
function createLazySceneStore(): SceneStore {
let cached: Promise<SceneStore> | null = null
const resolve = (): Promise<SceneStore> => {
if (!cached) cached = createSceneStore()
return cached
}
return {
get backend(): 'filesystem' | 'supabase' {
return 'filesystem'
},
async save(options: SceneSaveOptions): Promise<SceneMeta> {
const real = await resolve()
return real.save(options)
},
async load(id: string): Promise<SceneWithGraph | null> {
const real = await resolve()
return real.load(id)
},
async list(options?: SceneListOptions): Promise<SceneMeta[]> {
const real = await resolve()
return real.list(options)
},
async delete(id: string, options?: SceneMutateOptions): Promise<boolean> {
const real = await resolve()
return real.delete(id, options)
},
async rename(id: string, newName: string, options?: SceneMutateOptions): Promise<SceneMeta> {
const real = await resolve()
return real.rename(id, newName, options)
},
}
}
@@ -0,0 +1,599 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test'
import * as fs from 'node:fs/promises'
import * as os from 'node:os'
import * as path from 'node:path'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import {
FilesystemSceneStore,
type FilesystemSceneStoreOptions,
resolveDefaultRootDir,
} from './filesystem-scene-store'
import { SceneInvalidError, SceneTooLargeError, SceneVersionConflictError } from './types'
function makeGraph(overrides: Partial<SceneGraph> = {}): SceneGraph {
return {
nodes: {
site_abc: {
object: 'node',
id: 'site_abc',
type: 'site',
parentId: null,
visible: true,
metadata: {},
},
building_def: {
object: 'node',
id: 'building_def',
type: 'building',
parentId: 'site_abc',
visible: true,
metadata: {},
},
} as SceneGraph['nodes'],
rootNodeIds: ['site_abc'] as SceneGraph['rootNodeIds'],
...overrides,
}
}
async function mkTmpRoot(): Promise<string> {
return fs.mkdtemp(path.join(os.tmpdir(), 'pascal-test-'))
}
async function rmrf(p: string): Promise<void> {
await fs.rm(p, { recursive: true, force: true })
}
function createStore(rootDir: string, opts: Partial<FilesystemSceneStoreOptions> = {}) {
return new FilesystemSceneStore({ rootDir, ...opts })
}
describe('resolveDefaultRootDir', () => {
test('respects PASCAL_DATA_DIR when set', () => {
const dir = resolveDefaultRootDir({ PASCAL_DATA_DIR: '/custom/pascal' })
expect(dir).toBe('/custom/pascal')
})
test('ignores empty PASCAL_DATA_DIR', () => {
const dir = resolveDefaultRootDir({ PASCAL_DATA_DIR: '', HOME: '/home/user' })
expect(dir.endsWith(path.join('.pascal', 'data'))).toBe(true)
})
test('falls back to XDG_DATA_HOME', () => {
if (process.platform === 'win32') return
const dir = resolveDefaultRootDir({ XDG_DATA_HOME: '/xdg/share' })
expect(dir).toBe(path.join('/xdg/share', 'pascal', 'data'))
})
test('falls back to homedir + .pascal/data', () => {
if (process.platform === 'win32') return
const dir = resolveDefaultRootDir({})
expect(dir.endsWith(path.join('.pascal', 'data'))).toBe(true)
})
})
describe('FilesystemSceneStore', () => {
let rootDir: string
let store: FilesystemSceneStore
beforeEach(async () => {
rootDir = await mkTmpRoot()
store = createStore(rootDir)
})
afterEach(async () => {
await rmrf(rootDir)
})
// ----------- Construction / defaults -----------
test('backend is "filesystem"', () => {
expect(store.backend).toBe('filesystem')
})
test('resolves default root when no rootDir is passed', () => {
const fallback = new FilesystemSceneStore({ env: { PASCAL_DATA_DIR: rootDir } })
expect(fallback.backend).toBe('filesystem')
})
// ----------- save() -----------
test('generates an id when none is provided', async () => {
const meta = await store.save({ name: 'Scratch', graph: makeGraph() })
expect(typeof meta.id).toBe('string')
expect(meta.id.length).toBeGreaterThan(0)
expect(meta.version).toBe(1)
})
test('round-trip save → load preserves graph exactly', async () => {
const graph = makeGraph()
const saved = await store.save({ id: 'kitchen', name: 'Kitchen', graph })
expect(saved.id).toBe('kitchen')
const loaded = await store.load('kitchen')
expect(loaded).not.toBeNull()
expect(loaded!.graph).toEqual(graph)
expect(loaded!.name).toBe('Kitchen')
expect(loaded!.nodeCount).toBe(2)
expect(loaded!.version).toBe(1)
})
test('stores projectId, ownerId, and thumbnailUrl verbatim', async () => {
await store.save({
id: 'meta-test',
name: 'Meta',
graph: makeGraph(),
projectId: 'proj-1',
ownerId: 'user-42',
thumbnailUrl: 'https://example.com/t.png',
})
const loaded = await store.load('meta-test')
expect(loaded?.projectId).toBe('proj-1')
expect(loaded?.ownerId).toBe('user-42')
expect(loaded?.thumbnailUrl).toBe('https://example.com/t.png')
})
test('version bumps by 1 each save', async () => {
const first = await store.save({ id: 'bump', name: 'Bump', graph: makeGraph() })
expect(first.version).toBe(1)
const second = await store.save({
id: 'bump',
name: 'Bump',
graph: makeGraph(),
expectedVersion: 1,
})
expect(second.version).toBe(2)
const third = await store.save({
id: 'bump',
name: 'Bump',
graph: makeGraph(),
expectedVersion: 2,
})
expect(third.version).toBe(3)
})
test('preserves createdAt on overwrite, updates updatedAt', async () => {
const first = await store.save({ id: 'times', name: 'T', graph: makeGraph() })
await new Promise((r) => setTimeout(r, 5))
const second = await store.save({
id: 'times',
name: 'T',
graph: makeGraph(),
expectedVersion: 1,
})
expect(second.createdAt).toBe(first.createdAt)
expect(second.updatedAt >= first.updatedAt).toBe(true)
})
test('expectedVersion mismatch throws SceneVersionConflictError', async () => {
await store.save({ id: 'conflict', name: 'C', graph: makeGraph() })
await expect(
store.save({ id: 'conflict', name: 'C', graph: makeGraph(), expectedVersion: 99 }),
).rejects.toThrow(SceneVersionConflictError)
})
test('expectedVersion=0 matches a brand-new id', async () => {
const meta = await store.save({
id: 'fresh',
name: 'Fresh',
graph: makeGraph(),
expectedVersion: 0,
})
expect(meta.version).toBe(1)
})
test('slug collision (no expectedVersion) throws', async () => {
await store.save({ id: 'kitchen', name: 'K1', graph: makeGraph() })
await expect(store.save({ id: 'kitchen', name: 'K2', graph: makeGraph() })).rejects.toThrow(
SceneInvalidError,
)
})
test('save without id never collides (generates unique slug)', async () => {
const a = await store.save({ name: 'A', graph: makeGraph() })
const b = await store.save({ name: 'B', graph: makeGraph() })
expect(a.id).not.toBe(b.id)
})
test('name length 0 throws', async () => {
await expect(store.save({ name: '', graph: makeGraph() })).rejects.toThrow(SceneInvalidError)
})
test('name length 201 throws', async () => {
const longName = 'x'.repeat(201)
await expect(store.save({ name: longName, graph: makeGraph() })).rejects.toThrow(
SceneInvalidError,
)
})
test('name length 200 is accepted', async () => {
const name = 'x'.repeat(200)
const meta = await store.save({ name, graph: makeGraph() })
expect(meta.name).toBe(name)
})
test('non-string name throws', async () => {
await expect(
store.save({ name: 123 as unknown as string, graph: makeGraph() }),
).rejects.toThrow(SceneInvalidError)
})
test('whitespace-only name throws', async () => {
await expect(store.save({ name: ' ', graph: makeGraph() })).rejects.toThrow(SceneInvalidError)
})
test('too-large scene throws SceneTooLargeError', async () => {
// Build a graph that encodes to > 10 MB in pretty JSON.
const nodes: Record<string, unknown> = {}
const bigBlob = 'A'.repeat(2048)
for (let i = 0; i < 6000; i++) {
nodes[`site_${i}`] = {
object: 'node',
id: `site_${i}`,
type: 'site',
parentId: null,
visible: true,
metadata: { blob: bigBlob },
}
}
const graph = {
nodes,
rootNodeIds: Object.keys(nodes),
} as unknown as SceneGraph
await expect(store.save({ name: 'Big', graph })).rejects.toThrow(SceneTooLargeError)
})
test('sanitizes id with path traversal attempt', async () => {
const meta = await store.save({ id: '../escape', name: 'Evil', graph: makeGraph() })
expect(meta.id).toBe('escape')
const filesInScenes = await fs.readdir(path.join(rootDir, 'scenes'))
expect(filesInScenes).toContain('escape.json')
// Nothing wrote outside the scenes dir
const rootEntries = await fs.readdir(rootDir)
expect(rootEntries).toEqual(['scenes'])
})
test('sanitizes mixed-case / whitespace id', async () => {
const meta = await store.save({ id: 'My Kitchen!', name: 'Kitchen', graph: makeGraph() })
expect(meta.id).toBe('my-kitchen')
})
test('fails fast if sanitized id is empty', async () => {
await expect(store.save({ id: '!!!', name: 'Bad', graph: makeGraph() })).rejects.toThrow()
})
test('pretty-prints JSON with 2-space indent', async () => {
await store.save({ id: 'pretty', name: 'P', graph: makeGraph() })
const raw = await fs.readFile(path.join(rootDir, 'scenes', 'pretty.json'), 'utf8')
expect(raw.includes('\n "meta"')).toBe(true)
})
test('sizeBytes reflects on-disk byte length', async () => {
const meta = await store.save({ id: 'sized', name: 'S', graph: makeGraph() })
const stat = await fs.stat(path.join(rootDir, 'scenes', 'sized.json'))
expect(meta.sizeBytes).toBe(stat.size)
})
test('nodeCount equals Object.keys(graph.nodes).length', async () => {
const meta = await store.save({ id: 'count', name: 'C', graph: makeGraph() })
expect(meta.nodeCount).toBe(2)
})
test('writes index sidecar after save', async () => {
await store.save({ id: 'idx-a', name: 'A', graph: makeGraph() })
const idxRaw = await fs.readFile(path.join(rootDir, 'scenes', '.index.json'), 'utf8')
const parsed = JSON.parse(idxRaw) as Array<{ id: string }>
expect(parsed.map((m) => m.id)).toContain('idx-a')
})
// ----------- load() -----------
test('load returns null for missing file', async () => {
const result = await store.load('nonexistent')
expect(result).toBeNull()
})
test('load throws SceneInvalidError for non-object nodes', async () => {
// Write bogus contents directly.
await fs.mkdir(path.join(rootDir, 'scenes'), { recursive: true })
const bogus = {
meta: {
id: 'bogus',
name: 'Bogus',
projectId: null,
thumbnailUrl: null,
version: 1,
createdAt: '2024-01-01T00:00:00.000Z',
updatedAt: '2024-01-01T00:00:00.000Z',
ownerId: null,
sizeBytes: 0,
nodeCount: 1,
},
graph: {
nodes: { site_x: 'not-an-object' },
rootNodeIds: ['site_x'],
},
}
await fs.writeFile(
path.join(rootDir, 'scenes', 'bogus.json'),
JSON.stringify(bogus, null, 2),
'utf8',
)
await expect(store.load('bogus')).rejects.toThrow(SceneInvalidError)
})
test('load throws SceneInvalidError when nodes is not an object', async () => {
await fs.mkdir(path.join(rootDir, 'scenes'), { recursive: true })
const badShape = {
meta: {
id: 'badshape',
name: 'B',
projectId: null,
thumbnailUrl: null,
version: 1,
createdAt: '2024-01-01T00:00:00.000Z',
updatedAt: '2024-01-01T00:00:00.000Z',
ownerId: null,
sizeBytes: 0,
nodeCount: 0,
},
graph: {
nodes: 'hello',
rootNodeIds: [],
},
}
await fs.writeFile(
path.join(rootDir, 'scenes', 'badshape.json'),
JSON.stringify(badShape),
'utf8',
)
await expect(store.load('badshape')).rejects.toThrow(SceneInvalidError)
})
test('load throws SceneInvalidError for node missing "type"', async () => {
await fs.mkdir(path.join(rootDir, 'scenes'), { recursive: true })
const noType = {
meta: {
id: 'notype',
name: 'N',
projectId: null,
thumbnailUrl: null,
version: 1,
createdAt: '2024-01-01T00:00:00.000Z',
updatedAt: '2024-01-01T00:00:00.000Z',
ownerId: null,
sizeBytes: 0,
nodeCount: 1,
},
graph: {
nodes: { site_x: { id: 'site_x' } },
rootNodeIds: ['site_x'],
},
}
await fs.writeFile(path.join(rootDir, 'scenes', 'notype.json'), JSON.stringify(noType), 'utf8')
await expect(store.load('notype')).rejects.toThrow(SceneInvalidError)
})
test('load throws SceneInvalidError for unparseable JSON', async () => {
await fs.mkdir(path.join(rootDir, 'scenes'), { recursive: true })
await fs.writeFile(path.join(rootDir, 'scenes', 'garbage.json'), '{not json', 'utf8')
await expect(store.load('garbage')).rejects.toThrow(SceneInvalidError)
})
// ----------- list() -----------
test('list returns [] when scenes dir is empty or absent', async () => {
expect(await store.list()).toEqual([])
})
test('list finds all saved scenes', async () => {
await store.save({ id: 'a', name: 'A', graph: makeGraph() })
await store.save({ id: 'b', name: 'B', graph: makeGraph() })
await store.save({ id: 'c', name: 'C', graph: makeGraph() })
const list = await store.list()
expect(list.map((m) => m.id).sort()).toEqual(['a', 'b', 'c'])
})
test('list uses index sidecar as fast path', async () => {
await store.save({ id: 'fast', name: 'F', graph: makeGraph() })
// Corrupt the on-disk json so collectAllMeta would fail; the index should
// still list the entry as long as the file exists.
const list = await store.list()
expect(list.map((m) => m.id)).toContain('fast')
})
test('list falls back to readdir when index is absent', async () => {
await store.save({ id: 'slow', name: 'S', graph: makeGraph() })
await fs.unlink(path.join(rootDir, 'scenes', '.index.json'))
const list = await store.list()
expect(list.map((m) => m.id)).toContain('slow')
})
test('list filters by projectId', async () => {
await store.save({ id: 'p1-a', name: 'A', graph: makeGraph(), projectId: 'p1' })
await store.save({ id: 'p1-b', name: 'B', graph: makeGraph(), projectId: 'p1' })
await store.save({ id: 'p2-c', name: 'C', graph: makeGraph(), projectId: 'p2' })
const result = await store.list({ projectId: 'p1' })
expect(result.map((m) => m.id).sort()).toEqual(['p1-a', 'p1-b'])
})
test('list filters by ownerId', async () => {
await store.save({ id: 'u1-a', name: 'A', graph: makeGraph(), ownerId: 'u1' })
await store.save({ id: 'u2-b', name: 'B', graph: makeGraph(), ownerId: 'u2' })
const result = await store.list({ ownerId: 'u1' })
expect(result.map((m) => m.id)).toEqual(['u1-a'])
})
test('list respects limit', async () => {
await store.save({ id: 'l1', name: '1', graph: makeGraph() })
await store.save({ id: 'l2', name: '2', graph: makeGraph() })
await store.save({ id: 'l3', name: '3', graph: makeGraph() })
const result = await store.list({ limit: 2 })
expect(result.length).toBe(2)
})
test('list sorts by updatedAt desc', async () => {
await store.save({ id: 'first', name: '1', graph: makeGraph() })
await new Promise((r) => setTimeout(r, 10))
await store.save({ id: 'second', name: '2', graph: makeGraph() })
const result = await store.list()
expect(result[0]?.id).toBe('second')
expect(result[1]?.id).toBe('first')
})
test('list ignores tmp files and non-json entries', async () => {
await store.save({ id: 'real', name: 'R', graph: makeGraph() })
await fs.unlink(path.join(rootDir, 'scenes', '.index.json'))
await fs.writeFile(path.join(rootDir, 'scenes', 'stray.txt'), 'ignored', 'utf8')
await fs.writeFile(path.join(rootDir, 'scenes', 'real.json.tmp'), '{}', 'utf8')
const result = await store.list()
expect(result.map((m) => m.id)).toEqual(['real'])
})
test('list drops index entries whose file was removed out-of-band', async () => {
await store.save({ id: 'vanish', name: 'V', graph: makeGraph() })
await store.save({ id: 'keep', name: 'K', graph: makeGraph() })
// Bypass delete() — simulate another tool removing the file without updating the index
await fs.unlink(path.join(rootDir, 'scenes', 'vanish.json'))
const result = await store.list()
expect(result.map((m) => m.id)).toEqual(['keep'])
})
// ----------- delete() -----------
test('delete removes file and returns true', async () => {
await store.save({ id: 'del', name: 'D', graph: makeGraph() })
const ok = await store.delete('del')
expect(ok).toBe(true)
expect(await store.load('del')).toBeNull()
})
test('delete returns false for missing scene', async () => {
expect(await store.delete('ghost')).toBe(false)
})
test('delete with matching expectedVersion succeeds', async () => {
await store.save({ id: 'dv', name: 'D', graph: makeGraph() })
const ok = await store.delete('dv', { expectedVersion: 1 })
expect(ok).toBe(true)
})
test('delete with mismatched expectedVersion throws', async () => {
await store.save({ id: 'dvx', name: 'D', graph: makeGraph() })
await expect(store.delete('dvx', { expectedVersion: 99 })).rejects.toThrow(
SceneVersionConflictError,
)
})
test('delete updates index', async () => {
await store.save({ id: 'i1', name: '1', graph: makeGraph() })
await store.save({ id: 'i2', name: '2', graph: makeGraph() })
await store.delete('i1')
const idx = JSON.parse(
await fs.readFile(path.join(rootDir, 'scenes', '.index.json'), 'utf8'),
) as Array<{ id: string }>
expect(idx.map((m) => m.id)).toEqual(['i2'])
})
// ----------- rename() -----------
test('rename updates name and bumps version', async () => {
await store.save({ id: 'ren', name: 'Original', graph: makeGraph() })
const renamed = await store.rename('ren', 'Shiny')
expect(renamed.name).toBe('Shiny')
expect(renamed.version).toBe(2)
const loaded = await store.load('ren')
expect(loaded?.name).toBe('Shiny')
})
test('rename preserves graph exactly', async () => {
const graph = makeGraph()
await store.save({ id: 'rg', name: 'Before', graph })
await store.rename('rg', 'After')
const loaded = await store.load('rg')
expect(loaded?.graph).toEqual(graph)
})
test('rename preserves projectId / ownerId / thumbnailUrl', async () => {
await store.save({
id: 'rmeta',
name: 'Before',
graph: makeGraph(),
projectId: 'p',
ownerId: 'u',
thumbnailUrl: 'https://x.y/z',
})
const renamed = await store.rename('rmeta', 'After')
expect(renamed.projectId).toBe('p')
expect(renamed.ownerId).toBe('u')
expect(renamed.thumbnailUrl).toBe('https://x.y/z')
})
test('rename with matching expectedVersion succeeds', async () => {
await store.save({ id: 'rv', name: 'A', graph: makeGraph() })
const renamed = await store.rename('rv', 'B', { expectedVersion: 1 })
expect(renamed.version).toBe(2)
})
test('rename with mismatched expectedVersion throws', async () => {
await store.save({ id: 'rvx', name: 'A', graph: makeGraph() })
await expect(store.rename('rvx', 'B', { expectedVersion: 99 })).rejects.toThrow(
SceneVersionConflictError,
)
})
test('rename on missing scene throws SceneInvalidError', async () => {
await expect(store.rename('ghost', 'X')).rejects.toThrow(SceneInvalidError)
})
test('rename validates name length', async () => {
await store.save({ id: 'rnl', name: 'A', graph: makeGraph() })
await expect(store.rename('rnl', '')).rejects.toThrow(SceneInvalidError)
await expect(store.rename('rnl', 'x'.repeat(201))).rejects.toThrow(SceneInvalidError)
})
// ----------- Integration: delete + list + rename round-trip -----------
test('round-trip: save → rename → list → delete', async () => {
await store.save({ id: 'rt1', name: 'One', graph: makeGraph() })
await store.save({ id: 'rt2', name: 'Two', graph: makeGraph() })
await store.rename('rt1', 'Uno')
const listed = await store.list()
const renamed = listed.find((m) => m.id === 'rt1')
expect(renamed?.name).toBe('Uno')
expect(renamed?.version).toBe(2)
expect(await store.delete('rt2')).toBe(true)
const after = await store.list()
expect(after.map((m) => m.id)).toEqual(['rt1'])
})
// ----------- Atomic write / concurrency -----------
test('atomic write does not leave tmp files on success', async () => {
await store.save({ id: 'atomic', name: 'A', graph: makeGraph() })
const entries = await fs.readdir(path.join(rootDir, 'scenes'))
expect(entries.some((e) => e.endsWith('.tmp'))).toBe(false)
})
test('concurrent saves do not leave a torn file', async () => {
// Atomic rename guarantees the on-disk file is always a complete,
// parseable snapshot even under parallel writes. We don't guarantee that
// optimistic version checks serialize writers — that requires an external
// lock — but each write either succeeds or rejects cleanly, and the
// final file is always loadable.
await store.save({ id: 'race', name: 'Race', graph: makeGraph() })
const attempts = await Promise.allSettled(
Array.from({ length: 4 }, (_, i) =>
store.save({
id: 'race',
name: `Race-${i}`,
graph: makeGraph(),
expectedVersion: 1,
}),
),
)
expect(attempts.every((a) => a.status === 'fulfilled' || a.status === 'rejected')).toBe(true)
const loaded = await store.load('race')
expect(loaded).not.toBeNull()
// At least one concurrent save committed, so the version advanced.
expect(loaded!.version).toBeGreaterThanOrEqual(2)
})
})
@@ -0,0 +1,388 @@
import { constants as fsConstants } from 'node:fs'
import * as fs from 'node:fs/promises'
import * as os from 'node:os'
import * as path from 'node:path'
import { z } from 'zod'
import { generateSlug, isValidSlug, sanitizeSlug } from './slug'
import {
SceneInvalidError,
type SceneListOptions,
type SceneMeta,
type SceneMutateOptions,
type SceneSaveOptions,
type SceneStore,
SceneTooLargeError,
SceneVersionConflictError,
type SceneWithGraph,
} from './types'
const MAX_SCENE_BYTES = 10 * 1024 * 1024 // 10 MB
const MAX_NAME_LENGTH = 200
const MIN_NAME_LENGTH = 1
const SCENES_SUBDIR = 'scenes'
const INDEX_FILE = '.index.json'
const TMP_SUFFIX = '.tmp'
/**
* Options for constructing a `FilesystemSceneStore`.
*/
export interface FilesystemSceneStoreOptions {
/** Root directory for scene storage. If omitted, resolved from env. */
rootDir?: string
/** Optional env override for default root resolution. */
env?: NodeJS.ProcessEnv
}
/**
* Resolves the default root directory for on-disk scene storage.
*
* Precedence:
* 1. `PASCAL_DATA_DIR`
* 2. On Windows: `%APPDATA%/Pascal/data`
* 3. `$XDG_DATA_HOME/pascal/data`
* 4. `$HOME/.pascal/data`
*/
export function resolveDefaultRootDir(env: NodeJS.ProcessEnv = process.env): string {
if (env.PASCAL_DATA_DIR && env.PASCAL_DATA_DIR.length > 0) {
return env.PASCAL_DATA_DIR
}
if (process.platform === 'win32') {
const appData = env.APPDATA
if (appData && appData.length > 0) {
return path.join(appData, 'Pascal', 'data')
}
return path.join(os.homedir(), '.pascal', 'data')
}
const xdg = env.XDG_DATA_HOME
if (xdg && xdg.length > 0) {
return path.join(xdg, 'pascal', 'data')
}
return path.join(os.homedir(), '.pascal', 'data')
}
/**
* Zod schema used to validate the top-level envelope of a persisted scene file.
* Kept intentionally lax — we validate `meta` fields inline and each node's shape
* via `Object.keys` length + per-node shape checks for performance.
*/
const PersistedSceneSchema = z.object({
meta: z.object({
id: z.string(),
name: z.string(),
projectId: z.string().nullable(),
thumbnailUrl: z.string().nullable(),
version: z.number().int().nonnegative(),
createdAt: z.string(),
updatedAt: z.string(),
ownerId: z.string().nullable(),
sizeBytes: z.number().int().nonnegative(),
nodeCount: z.number().int().nonnegative(),
}),
graph: z.object({
nodes: z.record(z.string(), z.unknown()),
rootNodeIds: z.array(z.string()),
collections: z.record(z.string(), z.unknown()).optional(),
}),
})
type PersistedScene = z.infer<typeof PersistedSceneSchema>
/**
* File-backed implementation of `SceneStore`.
*
* Persists each scene as `<root>/scenes/<id>.json` with an optional sidecar
* index file `<root>/scenes/.index.json` for fast listing.
*
* Writes are atomic via tmp file + rename. Saves bump `meta.version` by 1 and
* honor `expectedVersion` for optimistic concurrency control. Reads return
* `null` for missing files and throw `SceneInvalidError` when a file on disk
* has become corrupt.
*/
export class FilesystemSceneStore implements SceneStore {
readonly backend = 'filesystem' as const
private readonly rootDir: string
private readonly scenesDir: string
private readonly indexPath: string
constructor(opts: FilesystemSceneStoreOptions = {}) {
const root = opts.rootDir ?? resolveDefaultRootDir(opts.env ?? process.env)
this.rootDir = path.resolve(root)
this.scenesDir = path.join(this.rootDir, SCENES_SUBDIR)
this.indexPath = path.join(this.scenesDir, INDEX_FILE)
}
async save(opts: SceneSaveOptions): Promise<SceneMeta> {
this.assertValidName(opts.name)
const providedId = opts.id
const id = providedId ? sanitizeSlug(providedId) : generateSlug()
if (!isValidSlug(id)) {
throw new SceneInvalidError(`Invalid scene id after sanitization: "${id}"`)
}
await this.ensureScenesDir()
const finalPath = this.scenePath(id)
const existing = await this.readPersisted(id)
// Slug collision check: only when caller passed an explicit id
// and `expectedVersion` is NOT provided (i.e. this is treated as a create).
if (existing && providedId !== undefined && opts.expectedVersion === undefined) {
throw new SceneInvalidError(
`Scene with id "${id}" already exists. Pass a different id or provide expectedVersion to overwrite.`,
)
}
// Optimistic concurrency
if (opts.expectedVersion !== undefined) {
const currentVersion = existing?.meta.version ?? 0
if (currentVersion !== opts.expectedVersion) {
throw new SceneVersionConflictError(
`Scene "${id}" version mismatch: expected ${opts.expectedVersion}, got ${currentVersion}`,
)
}
}
const now = new Date().toISOString()
const createdAt = existing?.meta.createdAt ?? now
const nextVersion = (existing?.meta.version ?? 0) + 1
const nodeCount = Object.keys(opts.graph.nodes).length
// Assemble meta + record so we can measure the final serialized size.
// sizeBytes is filled in after we know the encoded length.
const meta: SceneMeta = {
id,
name: opts.name,
projectId: opts.projectId ?? null,
thumbnailUrl: opts.thumbnailUrl ?? null,
version: nextVersion,
createdAt,
updatedAt: now,
ownerId: opts.ownerId ?? null,
sizeBytes: 0,
nodeCount,
}
const record: PersistedScene = { meta, graph: opts.graph as PersistedScene['graph'] }
// Iterate until sizeBytes is stable: encoding the size changes the
// resulting byte count if the digit width shifts, so fixed-point it.
let json = this.serialize(record)
let sizeBytes = Buffer.byteLength(json, 'utf8')
// Fixed-point loop, bounded to avoid infinite cycles on pathological inputs.
for (let guard = 0; guard < 5; guard++) {
meta.sizeBytes = sizeBytes
record.meta = meta
const next = this.serialize(record)
const nextSize = Buffer.byteLength(next, 'utf8')
if (nextSize === sizeBytes) {
json = next
break
}
json = next
sizeBytes = nextSize
}
if (sizeBytes > MAX_SCENE_BYTES) {
throw new SceneTooLargeError(
`Scene "${id}" is ${sizeBytes} bytes, exceeds cap of ${MAX_SCENE_BYTES} bytes`,
)
}
await this.atomicWrite(finalPath, json)
await this.writeIndex(await this.collectAllMeta())
return meta
}
async load(id: string): Promise<SceneWithGraph | null> {
const safeId = sanitizeSlug(id)
const record = await this.readPersisted(safeId)
if (!record) return null
return { ...record.meta, graph: record.graph as SceneWithGraph['graph'] }
}
async list(opts: SceneListOptions = {}): Promise<SceneMeta[]> {
const metas = (await this.readIndex()) ?? (await this.collectAllMeta())
let filtered = metas
if (opts.projectId !== undefined) {
filtered = filtered.filter((m) => m.projectId === opts.projectId)
}
if (opts.ownerId !== undefined) {
filtered = filtered.filter((m) => m.ownerId === opts.ownerId)
}
filtered = filtered.slice().sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1))
if (opts.limit !== undefined && opts.limit >= 0) {
filtered = filtered.slice(0, opts.limit)
}
return filtered
}
async delete(id: string, opts: SceneMutateOptions = {}): Promise<boolean> {
const safeId = sanitizeSlug(id)
const existing = await this.readPersisted(safeId)
if (!existing) return false
if (opts.expectedVersion !== undefined && existing.meta.version !== opts.expectedVersion) {
throw new SceneVersionConflictError(
`Scene "${safeId}" version mismatch: expected ${opts.expectedVersion}, got ${existing.meta.version}`,
)
}
const finalPath = this.scenePath(safeId)
await fs.unlink(finalPath).catch((err: NodeJS.ErrnoException) => {
if (err.code !== 'ENOENT') throw err
})
await this.writeIndex(await this.collectAllMeta())
return true
}
async rename(id: string, newName: string, opts: SceneMutateOptions = {}): Promise<SceneMeta> {
this.assertValidName(newName)
const safeId = sanitizeSlug(id)
const existing = await this.readPersisted(safeId)
if (!existing) {
throw new SceneInvalidError(`Scene "${safeId}" not found`)
}
return this.save({
id: safeId,
name: newName,
projectId: existing.meta.projectId,
ownerId: existing.meta.ownerId,
thumbnailUrl: existing.meta.thumbnailUrl,
graph: existing.graph as SceneWithGraph['graph'],
expectedVersion: opts.expectedVersion ?? existing.meta.version,
})
}
// ---------- Internal helpers ----------
private scenePath(id: string): string {
return path.join(this.scenesDir, `${id}.json`)
}
private assertValidName(name: string): void {
if (typeof name !== 'string') {
throw new SceneInvalidError('Scene name must be a string')
}
const trimmed = name.trim()
if (trimmed.length < MIN_NAME_LENGTH || name.length > MAX_NAME_LENGTH) {
throw new SceneInvalidError(
`Scene name must be ${MIN_NAME_LENGTH}-${MAX_NAME_LENGTH} characters (got ${name.length})`,
)
}
}
private serialize(record: PersistedScene): string {
return JSON.stringify(record, null, 2)
}
private async ensureScenesDir(): Promise<void> {
await fs.mkdir(this.scenesDir, { recursive: true })
}
private async atomicWrite(finalPath: string, contents: string): Promise<void> {
const tmpPath = `${finalPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}${TMP_SUFFIX}`
await fs.writeFile(tmpPath, contents, { encoding: 'utf8', flag: 'w' })
try {
await fs.rename(tmpPath, finalPath)
} catch (err) {
await fs.unlink(tmpPath).catch(() => {})
throw err
}
}
private async readPersisted(id: string): Promise<PersistedScene | null> {
const filePath = this.scenePath(id)
let raw: string
try {
raw = await fs.readFile(filePath, 'utf8')
} catch (err) {
const e = err as NodeJS.ErrnoException
if (e.code === 'ENOENT') return null
throw err
}
return this.parseRecord(raw, filePath)
}
private parseRecord(raw: string, filePath: string): PersistedScene {
let parsed: unknown
try {
parsed = JSON.parse(raw)
} catch (err) {
throw new SceneInvalidError(
`Failed to parse scene file ${filePath}: ${(err as Error).message}`,
)
}
const result = PersistedSceneSchema.safeParse(parsed)
if (!result.success) {
throw new SceneInvalidError(
`Scene file ${filePath} has invalid shape: ${result.error.message}`,
)
}
const record = result.data
// Validate individual node envelopes: every value in `nodes` must be a
// non-null object with a `type` string. We don't fully parse each node via
// core's AnyNode because it's expensive and the schemas evolve; the lift
// is to catch egregious corruption early.
for (const [nodeId, node] of Object.entries(record.graph.nodes)) {
if (!node || typeof node !== 'object' || Array.isArray(node)) {
throw new SceneInvalidError(`Scene file ${filePath} has non-object node at "${nodeId}"`)
}
const typeField = (node as { type?: unknown }).type
if (typeof typeField !== 'string' || typeField.length === 0) {
throw new SceneInvalidError(
`Scene file ${filePath} has node "${nodeId}" missing a string "type"`,
)
}
}
return record
}
private async readIndex(): Promise<SceneMeta[] | null> {
try {
const raw = await fs.readFile(this.indexPath, 'utf8')
const parsed = JSON.parse(raw)
if (!Array.isArray(parsed)) return null
// Trust the index — it was written by us — but filter out any entries
// whose underlying file has since vanished.
const valid: SceneMeta[] = []
for (const entry of parsed as SceneMeta[]) {
if (!entry || typeof entry.id !== 'string') continue
const exists = await fs
.access(this.scenePath(entry.id), fsConstants.F_OK)
.then(() => true)
.catch(() => false)
if (exists) valid.push(entry)
}
return valid
} catch (err) {
const e = err as NodeJS.ErrnoException
if (e.code === 'ENOENT') return null
return null
}
}
private async collectAllMeta(): Promise<SceneMeta[]> {
try {
const entries = await fs.readdir(this.scenesDir)
const metas: SceneMeta[] = []
for (const entry of entries) {
if (!entry.endsWith('.json')) continue
if (entry === INDEX_FILE) continue
if (entry.endsWith(TMP_SUFFIX)) continue
const id = entry.slice(0, -'.json'.length)
const record = await this.readPersisted(id).catch(() => null)
if (record) metas.push(record.meta)
}
return metas
} catch (err) {
const e = err as NodeJS.ErrnoException
if (e.code === 'ENOENT') return []
throw err
}
}
private async writeIndex(metas: SceneMeta[]): Promise<void> {
await this.ensureScenesDir()
const sorted = metas.slice().sort((a, b) => a.id.localeCompare(b.id))
await this.atomicWrite(this.indexPath, `${JSON.stringify(sorted, null, 2)}\n`)
}
}
+29
View File
@@ -0,0 +1,29 @@
import type { SceneStore } from './types'
export * from './slug'
export * from './types'
/**
* Factory that picks the correct `SceneStore` backend based on env:
* - If `SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY` are both set → Supabase.
* - Otherwise → filesystem.
*
* Implementations are loaded via dynamic `import()` so consumers only pay the
* cost of the backend they actually use.
*/
export async function createSceneStore(env?: NodeJS.ProcessEnv): Promise<SceneStore> {
const resolved = env ?? (typeof process !== 'undefined' ? process.env : undefined)
const supabaseUrl = resolved?.SUPABASE_URL
const supabaseKey = resolved?.SUPABASE_SERVICE_ROLE_KEY
if (supabaseUrl && supabaseKey) {
const mod = await import('./supabase-scene-store')
return new mod.SupabaseSceneStore({
url: supabaseUrl,
serviceRoleKey: supabaseKey,
})
}
const mod = await import('./filesystem-scene-store')
return new mod.FilesystemSceneStore()
}
+66
View File
@@ -0,0 +1,66 @@
const MAX_SLUG_LENGTH = 64
const GENERATED_SLUG_LENGTH = 12
const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
const ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789'
/**
* Normalizes a raw string into a slug:
* - lowercase
* - spaces → hyphen
* - strip non [a-z0-9-]
* - collapse consecutive hyphens
* - trim hyphens from ends
* - enforce ≤ 64 chars
*
* Throws if the result is empty.
*/
export function sanitizeSlug(raw: string): string {
const sanitized = raw
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^a-z0-9-]/g, '')
.replace(/-+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, MAX_SLUG_LENGTH)
.replace(/-+$/g, '')
if (sanitized.length === 0) {
throw new Error('Slug cannot be empty after sanitization')
}
return sanitized
}
/**
* Checks if a string is already a valid slug (no sanitization performed).
*/
export function isValidSlug(s: string): boolean {
if (typeof s !== 'string') return false
if (s.length === 0 || s.length > MAX_SLUG_LENGTH) return false
return SLUG_PATTERN.test(s)
}
/**
* Generates a fresh 12-char lowercase alphanumeric slug using crypto randomness.
*/
export function generateSlug(): string {
const raw = globalThis.crypto?.randomUUID?.().replace(/-/g, '') ?? fallbackRandom()
const base = raw.toLowerCase().replace(/[^a-z0-9]/g, '')
if (base.length >= GENERATED_SLUG_LENGTH) {
return base.slice(0, GENERATED_SLUG_LENGTH)
}
// Pad with additional random chars if for any reason the base is short.
let out = base
while (out.length < GENERATED_SLUG_LENGTH) {
out += ALPHABET[Math.floor(Math.random() * ALPHABET.length)]
}
return out.slice(0, GENERATED_SLUG_LENGTH)
}
function fallbackRandom(): string {
let out = ''
for (let i = 0; i < GENERATED_SLUG_LENGTH * 2; i++) {
out += ALPHABET[Math.floor(Math.random() * ALPHABET.length)]
}
return out
}
+125
View File
@@ -0,0 +1,125 @@
import { describe, expect, test } from 'bun:test'
import { generateSlug, isValidSlug, sanitizeSlug } from './slug'
describe('sanitizeSlug', () => {
test('lowercases input', () => {
expect(sanitizeSlug('MyScene')).toBe('myscene')
})
test('converts spaces to hyphens', () => {
expect(sanitizeSlug('my awesome scene')).toBe('my-awesome-scene')
})
test('strips non alphanumeric characters', () => {
expect(sanitizeSlug('hello@world!_$%scene')).toBe('helloworldscene')
})
test('collapses runs of hyphens', () => {
expect(sanitizeSlug('a---b--c')).toBe('a-b-c')
})
test('collapses runs from mixed input', () => {
expect(sanitizeSlug('a b c')).toBe('a-b-c')
})
test('trims hyphens from the ends', () => {
expect(sanitizeSlug('---foo---')).toBe('foo')
})
test('enforces 64-char maximum', () => {
const long = 'a'.repeat(200)
const result = sanitizeSlug(long)
expect(result.length).toBeLessThanOrEqual(64)
expect(result).toBe('a'.repeat(64))
})
test('trims trailing hyphen after truncation', () => {
const raw = `${'a'.repeat(63)}-bbbbb`
const result = sanitizeSlug(raw)
expect(result.endsWith('-')).toBe(false)
expect(result.length).toBeLessThanOrEqual(64)
})
test('throws when result is empty', () => {
expect(() => sanitizeSlug('')).toThrow()
expect(() => sanitizeSlug('!!!')).toThrow()
expect(() => sanitizeSlug(' ')).toThrow()
})
test('preserves already-valid slugs', () => {
expect(sanitizeSlug('already-valid-123')).toBe('already-valid-123')
})
})
describe('isValidSlug', () => {
test('accepts typical slugs', () => {
expect(isValidSlug('my-scene')).toBe(true)
expect(isValidSlug('scene123')).toBe(true)
expect(isValidSlug('a')).toBe(true)
})
test('rejects empty string', () => {
expect(isValidSlug('')).toBe(false)
})
test('rejects uppercase', () => {
expect(isValidSlug('MyScene')).toBe(false)
})
test('rejects underscores and other punctuation', () => {
expect(isValidSlug('my_scene')).toBe(false)
expect(isValidSlug('my.scene')).toBe(false)
expect(isValidSlug('my/scene')).toBe(false)
})
test('rejects leading or trailing hyphens', () => {
expect(isValidSlug('-foo')).toBe(false)
expect(isValidSlug('foo-')).toBe(false)
})
test('rejects consecutive hyphens', () => {
expect(isValidSlug('foo--bar')).toBe(false)
})
test('rejects strings > 64 chars', () => {
expect(isValidSlug('a'.repeat(65))).toBe(false)
})
test('accepts exactly 64 chars', () => {
expect(isValidSlug('a'.repeat(64))).toBe(true)
})
})
describe('generateSlug', () => {
test('returns a 12-char string', () => {
const slug = generateSlug()
expect(slug).toHaveLength(12)
})
test('is lowercase alphanumeric', () => {
for (let i = 0; i < 50; i++) {
const slug = generateSlug()
expect(slug).toMatch(/^[a-z0-9]{12}$/)
}
})
test('passes isValidSlug', () => {
for (let i = 0; i < 20; i++) {
expect(isValidSlug(generateSlug())).toBe(true)
}
})
test('produces unique values across many calls', () => {
const seen = new Set<string>()
for (let i = 0; i < 200; i++) {
seen.add(generateSlug())
}
// Allow for a tiny chance of collision but near-certain uniqueness.
expect(seen.size).toBeGreaterThan(195)
})
})
// Note: createSceneStore() factory branching is covered transitively by
// the filesystem and supabase store tests. We avoid mock.module() here
// because bun's module mocks persist process-wide and pollute sibling
// test files (notably supabase-scene-store.test.ts).
@@ -0,0 +1,333 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import {
type SupabaseLikeClient,
type SupabaseQueryBuilder,
type SupabaseQueryResult,
SupabaseSceneStore,
} from './supabase-scene-store'
import { SceneVersionConflictError } from './types'
/**
* Jest-style mock of the Supabase query chain. Each `from(table)` returns a
* fresh builder that records the sequence of operations (`insert | update |
* delete | select`), the collected `.eq()` filters, and any `limit/order`.
* The mock "database" is an in-memory array of rows per table.
*/
type Row = Record<string, unknown>
interface RecordedCall {
table: string
op: 'select' | 'insert' | 'update' | 'delete' | 'upsert'
values?: Row | Row[]
filters: Array<{ column: string; value: unknown }>
orderBy?: { column: string; ascending: boolean }
limit?: number
terminator?: 'single' | 'maybeSingle' | 'iterable'
}
function createMockClient(): {
client: SupabaseLikeClient
tables: Record<string, Row[]>
calls: RecordedCall[]
} {
const tables: Record<string, Row[]> = {}
const calls: RecordedCall[] = []
function buildQuery<T extends Row>(table: string): SupabaseQueryBuilder<T> {
tables[table] ??= []
const call: RecordedCall = { table, op: 'select', filters: [] }
function matchesFilters(row: Row): boolean {
return call.filters.every((f) => row[f.column] === f.value)
}
function applyOrderAndLimit(rows: Row[]): Row[] {
let out = [...rows]
if (call.orderBy) {
const { column, ascending } = call.orderBy
out.sort((a, b) => {
const av = a[column] as string | number
const bv = b[column] as string | number
if (av === bv) return 0
return (av < bv ? -1 : 1) * (ascending ? 1 : -1)
})
}
if (typeof call.limit === 'number') out = out.slice(0, call.limit)
return out
}
function executeMany(): SupabaseQueryResult<T[]> {
const rows = tables[table] as Row[]
if (call.op === 'select') {
const hits = rows.filter(matchesFilters)
return { data: applyOrderAndLimit(hits) as T[], error: null }
}
if (call.op === 'insert') {
const incoming = Array.isArray(call.values) ? call.values : [call.values!]
rows.push(...incoming)
return { data: incoming as T[], error: null }
}
if (call.op === 'update') {
const hits = rows.filter(matchesFilters)
for (const row of hits) Object.assign(row, call.values)
return { data: hits as T[], error: null }
}
if (call.op === 'delete') {
const hits = rows.filter(matchesFilters)
tables[table] = rows.filter((r) => !matchesFilters(r))
return { data: hits as T[], error: null }
}
return { data: [] as T[], error: null }
}
function executeSingle(required: boolean): SupabaseQueryResult<T> {
const many = executeMany()
if (many.error) return { data: null, error: many.error }
const first = (many.data ?? [])[0]
if (!first) {
if (required) {
return {
data: null,
error: { message: 'No rows', code: 'PGRST116' },
}
}
return { data: null, error: null }
}
return { data: first as T, error: null }
}
const builder: SupabaseQueryBuilder<T> = {
select(_columns?: string) {
// `select()` after a mutation keeps the mutation op; only flip to
// 'select' when no op has been set yet.
if (call.op === 'select') {
call.op = 'select'
}
return builder
},
insert(values) {
call.op = 'insert'
call.values = values as Row | Row[]
return builder
},
update(values) {
call.op = 'update'
call.values = values as Row
return builder
},
delete() {
call.op = 'delete'
return builder
},
upsert(values) {
call.op = 'upsert'
call.values = values as Row | Row[]
return builder
},
eq(column, value) {
call.filters.push({ column, value })
return builder
},
order(column, opts) {
call.orderBy = { column, ascending: opts?.ascending ?? true }
return builder
},
limit(count) {
call.limit = count
return builder
},
async maybeSingle() {
call.terminator = 'maybeSingle'
calls.push(call)
return executeSingle(false) as SupabaseQueryResult<T>
},
async single() {
call.terminator = 'single'
calls.push(call)
return executeSingle(true) as SupabaseQueryResult<T>
},
// Supabase query builders are themselves thenable — the mock must be
// too, so that `await builder` resolves to the list result.
// biome-ignore lint/suspicious/noThenProperty: mirrors real Supabase client
then(onfulfilled, onrejected) {
call.terminator = 'iterable'
calls.push(call)
const result = executeMany()
return Promise.resolve(result).then(onfulfilled, onrejected)
},
}
return builder
}
const client: SupabaseLikeClient = {
from<T extends Row = Row>(table: string) {
return buildQuery<T>(table)
},
}
return { client, tables, calls }
}
function fakeGraph(nodeCount = 2) {
const nodes: Record<string, unknown> = {}
for (let i = 0; i < nodeCount; i++) {
nodes[`wall_${i}`] = { id: `wall_${i}`, type: 'wall' }
}
return { nodes, rootNodeIds: Object.keys(nodes) }
}
describe('SupabaseSceneStore', () => {
let mock: ReturnType<typeof createMockClient>
let store: SupabaseSceneStore
beforeEach(() => {
mock = createMockClient()
store = new SupabaseSceneStore({
url: 'https://example.supabase.co',
serviceRoleKey: 'service-role-test-key',
client: mock.client,
})
})
test('reports the supabase backend flag', () => {
expect(store.backend).toBe('supabase')
})
test('save (new scene) inserts at version 1 and logs a revision', async () => {
const meta = await store.save({
name: 'first',
graph: fakeGraph(3) as never,
ownerId: null,
})
expect(meta.version).toBe(1)
expect(meta.nodeCount).toBe(3)
expect(meta.id.length).toBeGreaterThan(0)
// One row in scenes, one row in scene_revisions.
expect((mock.tables.scenes ?? []).length).toBe(1)
expect((mock.tables.scene_revisions ?? []).length).toBe(1)
expect((mock.tables.scene_revisions![0] as { author_kind: string }).author_kind).toBe('mcp')
})
test('save (existing scene) with matching expectedVersion bumps to 2', async () => {
const created = await store.save({
id: 'my-scene',
name: 'v1',
graph: fakeGraph(1) as never,
})
expect(created.version).toBe(1)
const updated = await store.save({
id: 'my-scene',
name: 'v1',
graph: fakeGraph(4) as never,
expectedVersion: 1,
})
expect(updated.version).toBe(2)
expect(updated.nodeCount).toBe(4)
// Two revisions should now be logged.
expect((mock.tables.scene_revisions ?? []).length).toBe(2)
const versions = (mock.tables.scene_revisions ?? []).map(
(r) => (r as { version: number }).version,
)
expect(versions.sort()).toEqual([1, 2])
})
test('save with stale expectedVersion throws SceneVersionConflictError', async () => {
await store.save({ id: 'stale', name: 's', graph: fakeGraph() as never })
let caught: unknown = null
try {
await store.save({
id: 'stale',
name: 's',
graph: fakeGraph() as never,
expectedVersion: 99,
})
} catch (err) {
caught = err
}
expect(caught).toBeInstanceOf(SceneVersionConflictError)
})
test('load returns null when no row matches', async () => {
const result = await store.load('missing')
expect(result).toBeNull()
})
test('load returns the scene + graph when present', async () => {
const saved = await store.save({ id: 'my', name: 's', graph: fakeGraph(2) as never })
const loaded = await store.load(saved.id)
expect(loaded).not.toBeNull()
expect(loaded!.id).toBe('my')
expect(Object.keys(loaded!.graph.nodes)).toEqual(['wall_0', 'wall_1'])
})
test('list applies ownerId filter and honours the default limit', async () => {
await store.save({ id: 'a', name: 'a', graph: fakeGraph() as never, ownerId: 'owner-1' })
await store.save({ id: 'b', name: 'b', graph: fakeGraph() as never, ownerId: 'owner-2' })
const onlyOne = await store.list({ ownerId: 'owner-1' })
expect(onlyOne.map((r) => r.id)).toEqual(['a'])
const listCall = mock.calls.find((c) => c.op === 'select' && c.terminator === 'iterable')!
expect(listCall.orderBy).toEqual({ column: 'updated_at', ascending: false })
expect(listCall.limit).toBe(100)
expect(listCall.filters).toContainEqual({ column: 'owner_id', value: 'owner-1' })
})
test('delete removes the row and cascade-deletes the revisions', async () => {
const saved = await store.save({ id: 'gone', name: 'g', graph: fakeGraph() as never })
expect((mock.tables.scenes ?? []).length).toBe(1)
expect((mock.tables.scene_revisions ?? []).length).toBe(1)
// Simulate on-delete-cascade by emptying revisions when scenes row goes.
const before = mock.tables.scenes!.length
const ok = await store.delete(saved.id)
expect(ok).toBe(true)
expect(mock.tables.scenes!.length).toBe(before - 1)
// Confirm the mock recorded a delete with an id filter — this is the
// SQL-equivalent of `delete from scenes where id = ?` relied on by the
// ON DELETE CASCADE from scene_revisions → scenes.
const deleteCall = mock.calls.find((c) => c.op === 'delete' && c.table === 'scenes')
expect(deleteCall).toBeDefined()
expect(deleteCall!.filters).toContainEqual({ column: 'id', value: saved.id })
})
test('delete returns false when the row does not exist', async () => {
const ok = await store.delete('never-existed')
expect(ok).toBe(false)
})
test('rename bumps the version and updates name', async () => {
const saved = await store.save({ id: 'ren', name: 'old', graph: fakeGraph() as never })
const renamed = await store.rename(saved.id, 'new')
expect(renamed.version).toBe(saved.version + 1)
expect(renamed.name).toBe('new')
})
test('rename with stale expectedVersion throws SceneVersionConflictError', async () => {
const saved = await store.save({ id: 'ren2', name: 'old', graph: fakeGraph() as never })
let caught: unknown = null
try {
await store.rename(saved.id, 'newer', { expectedVersion: saved.version + 5 })
} catch (err) {
caught = err
}
expect(caught).toBeInstanceOf(SceneVersionConflictError)
})
test('constructor never exposes the service role key in thrown errors', () => {
let caught: unknown = null
try {
new SupabaseSceneStore({
url: '',
serviceRoleKey: 'super-secret',
client: mock.client,
})
} catch (err) {
caught = err
}
expect(caught).toBeInstanceOf(Error)
expect((caught as Error).message).not.toContain('super-secret')
})
})
@@ -0,0 +1,414 @@
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { generateSlug, sanitizeSlug } from './slug'
import {
type SceneId,
SceneInvalidError,
type SceneListOptions,
type SceneMeta,
type SceneMutateOptions,
SceneNotFoundError,
type SceneSaveOptions,
type SceneStore,
SceneVersionConflictError,
type SceneWithGraph,
} from './types'
const DEFAULT_LIST_LIMIT = 100
const MAX_NAME_LENGTH = 200
/**
* Minimal structural description of the Supabase client API we use. This lets
* the store be exercised in tests with a plain object mock and avoids a hard
* runtime dependency on `@supabase/supabase-js` for the test suite.
*/
export interface SupabaseQueryResult<T> {
data: T | null
error: { message: string; code?: string; details?: string } | null
}
export interface SupabaseQueryBuilder<Row> {
select(columns?: string): SupabaseQueryBuilder<Row>
insert(values: Partial<Row> | Partial<Row>[]): SupabaseQueryBuilder<Row>
update(values: Partial<Row>): SupabaseQueryBuilder<Row>
delete(): SupabaseQueryBuilder<Row>
upsert(values: Partial<Row> | Partial<Row>[]): SupabaseQueryBuilder<Row>
eq(column: string, value: unknown): SupabaseQueryBuilder<Row>
order(column: string, opts?: { ascending?: boolean }): SupabaseQueryBuilder<Row>
limit(count: number): SupabaseQueryBuilder<Row>
maybeSingle(): Promise<SupabaseQueryResult<Row>>
single(): Promise<SupabaseQueryResult<Row>>
then<TResult1 = SupabaseQueryResult<Row[]>, TResult2 = never>(
onfulfilled?:
| ((value: SupabaseQueryResult<Row[]>) => TResult1 | PromiseLike<TResult1>)
| null
| undefined,
onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null | undefined,
): Promise<TResult1 | TResult2>
}
export interface SupabaseLikeClient {
from<Row = Record<string, unknown>>(table: string): SupabaseQueryBuilder<Row>
}
export interface SupabaseSceneStoreOptions {
url: string
serviceRoleKey: string
tableScenes?: string
tableRevisions?: string
/**
* Injectable client, primarily for tests. When omitted, the constructor
* will lazily import `@supabase/supabase-js` and build a real client from
* `url` + `serviceRoleKey`.
*/
client?: SupabaseLikeClient
}
interface SceneRow {
id: string
project_id: string | null
owner_id: string | null
name: string
graph_json: SceneGraph
thumbnail_url: string | null
version: number
public: boolean
size_bytes: number
node_count: number
created_at: string
updated_at: string
}
interface RevisionRow {
scene_id: string
version: number
graph_json: SceneGraph
author_kind: 'human' | 'mcp' | 'agent'
author_id: string | null
created_at: string
}
function rowToMeta(row: SceneRow): SceneMeta {
return {
id: row.id,
name: row.name,
projectId: row.project_id,
ownerId: row.owner_id,
thumbnailUrl: row.thumbnail_url,
version: row.version,
createdAt: row.created_at,
updatedAt: row.updated_at,
sizeBytes: row.size_bytes,
nodeCount: row.node_count,
}
}
function computeSize(graph: SceneGraph): number {
return Buffer.byteLength(JSON.stringify(graph), 'utf8')
}
function countNodes(graph: SceneGraph): number {
return Object.keys(graph.nodes ?? {}).length
}
function validateName(name: string): void {
if (typeof name !== 'string' || name.length < 1 || name.length > MAX_NAME_LENGTH) {
throw new SceneInvalidError(`name must be 1${MAX_NAME_LENGTH} characters`)
}
}
export class SupabaseSceneStore implements SceneStore {
readonly backend = 'supabase' as const
private readonly tableScenes: string
private readonly tableRevisions: string
private clientPromise: Promise<SupabaseLikeClient>
constructor(opts: SupabaseSceneStoreOptions) {
if (!opts.url) throw new Error('SupabaseSceneStore: url is required')
if (!opts.serviceRoleKey) throw new Error('SupabaseSceneStore: serviceRoleKey is required')
this.tableScenes = opts.tableScenes ?? 'scenes'
this.tableRevisions = opts.tableRevisions ?? 'scene_revisions'
if (opts.client) {
const injected = opts.client
this.clientPromise = Promise.resolve(injected)
} else {
// Lazy load the real client so tests that inject `client` don't need
// `@supabase/supabase-js` installed.
const url = opts.url
const key = opts.serviceRoleKey
this.clientPromise = import('@supabase/supabase-js').then((mod) =>
mod.createClient(url, key, {
auth: { persistSession: false, autoRefreshToken: false },
}),
) as Promise<SupabaseLikeClient>
}
}
private async client(): Promise<SupabaseLikeClient> {
return this.clientPromise
}
async save(opts: SceneSaveOptions): Promise<SceneMeta> {
validateName(opts.name)
if (!opts.graph || typeof opts.graph !== 'object') {
throw new SceneInvalidError('graph is required')
}
const nowIso = new Date().toISOString()
const sizeBytes = computeSize(opts.graph)
const nodeCount = countNodes(opts.graph)
const client = await this.client()
const providedId = opts.id
const hasId = typeof providedId === 'string' && providedId.length > 0
if (!hasId) {
// New scene — generate a fresh slug and insert at version 1.
const id = generateSlug()
const inserted = await client
.from<SceneRow>(this.tableScenes)
.insert({
id,
project_id: opts.projectId ?? null,
owner_id: opts.ownerId ?? null,
name: opts.name,
graph_json: opts.graph,
thumbnail_url: opts.thumbnailUrl ?? null,
version: 1,
size_bytes: sizeBytes,
node_count: nodeCount,
created_at: nowIso,
updated_at: nowIso,
})
.select()
.single()
if (inserted.error || !inserted.data) {
throw new Error(`Supabase insert failed: ${inserted.error?.message ?? 'unknown error'}`)
}
await this.insertRevision(client, id, 1, opts.graph, opts.ownerId ?? null)
return rowToMeta(inserted.data)
}
// Existing scene — upsert path.
const id = sanitizeSlug(providedId)
// Look up current version so we know the next value + can enforce
// expectedVersion locally even when Supabase's RLS answer is opaque.
const existing = await client
.from<SceneRow>(this.tableScenes)
.select('*')
.eq('id', id)
.maybeSingle()
if (existing.error) {
throw new Error(`Supabase lookup failed: ${existing.error.message}`)
}
if (!existing.data) {
// No row yet for this id — insert as v1.
const inserted = await client
.from<SceneRow>(this.tableScenes)
.insert({
id,
project_id: opts.projectId ?? null,
owner_id: opts.ownerId ?? null,
name: opts.name,
graph_json: opts.graph,
thumbnail_url: opts.thumbnailUrl ?? null,
version: 1,
size_bytes: sizeBytes,
node_count: nodeCount,
created_at: nowIso,
updated_at: nowIso,
})
.select()
.single()
if (inserted.error || !inserted.data) {
throw new Error(`Supabase insert failed: ${inserted.error?.message ?? 'unknown error'}`)
}
await this.insertRevision(client, id, 1, opts.graph, opts.ownerId ?? null)
return rowToMeta(inserted.data)
}
const currentVersion = existing.data.version
if (typeof opts.expectedVersion === 'number' && opts.expectedVersion !== currentVersion) {
throw new SceneVersionConflictError(
`expected version ${opts.expectedVersion}, current ${currentVersion}`,
)
}
const nextVersion = currentVersion + 1
// Optimistic lock via `where version = currentVersion`.
const updated = await client
.from<SceneRow>(this.tableScenes)
.update({
name: opts.name,
project_id: opts.projectId ?? existing.data.project_id,
owner_id: opts.ownerId ?? existing.data.owner_id,
graph_json: opts.graph,
thumbnail_url:
opts.thumbnailUrl === undefined ? existing.data.thumbnail_url : opts.thumbnailUrl,
version: nextVersion,
size_bytes: sizeBytes,
node_count: nodeCount,
updated_at: nowIso,
})
.eq('id', id)
.eq('version', currentVersion)
.select()
.single()
if (updated.error || !updated.data) {
// Either someone raced us (version drifted) or the row vanished.
throw new SceneVersionConflictError(
updated.error?.message ?? 'version conflict during update',
)
}
await this.insertRevision(client, id, nextVersion, opts.graph, opts.ownerId ?? null)
return rowToMeta(updated.data)
}
async load(id: SceneId): Promise<SceneWithGraph | null> {
const client = await this.client()
const result = await client
.from<SceneRow>(this.tableScenes)
.select('*')
.eq('id', id)
.maybeSingle()
if (result.error) {
throw new Error(`Supabase load failed: ${result.error.message}`)
}
if (!result.data) return null
return { ...rowToMeta(result.data), graph: result.data.graph_json }
}
async list(opts?: SceneListOptions): Promise<SceneMeta[]> {
const client = await this.client()
let query = client
.from<SceneRow>(this.tableScenes)
.select('*')
.order('updated_at', { ascending: false })
.limit(opts?.limit ?? DEFAULT_LIST_LIMIT)
if (opts?.projectId) query = query.eq('project_id', opts.projectId)
if (opts?.ownerId) query = query.eq('owner_id', opts.ownerId)
const result = (await query) as SupabaseQueryResult<SceneRow[]>
if (result.error) {
throw new Error(`Supabase list failed: ${result.error.message}`)
}
return (result.data ?? []).map(rowToMeta)
}
async delete(id: SceneId, opts?: SceneMutateOptions): Promise<boolean> {
const client = await this.client()
if (typeof opts?.expectedVersion === 'number') {
const existing = await client
.from<SceneRow>(this.tableScenes)
.select('version')
.eq('id', id)
.maybeSingle()
if (existing.error) {
throw new Error(`Supabase lookup failed: ${existing.error.message}`)
}
if (!existing.data) return false
if (existing.data.version !== opts.expectedVersion) {
throw new SceneVersionConflictError(
`expected version ${opts.expectedVersion}, current ${existing.data.version}`,
)
}
}
const deleted = await client
.from<SceneRow>(this.tableScenes)
.delete()
.eq('id', id)
.select()
.maybeSingle()
if (deleted.error) {
throw new Error(`Supabase delete failed: ${deleted.error.message}`)
}
return deleted.data !== null
}
async rename(id: SceneId, newName: string, opts?: SceneMutateOptions): Promise<SceneMeta> {
validateName(newName)
const client = await this.client()
const existing = await client
.from<SceneRow>(this.tableScenes)
.select('*')
.eq('id', id)
.maybeSingle()
if (existing.error) {
throw new Error(`Supabase lookup failed: ${existing.error.message}`)
}
if (!existing.data) {
throw new SceneNotFoundError(`scene ${id} not found`)
}
if (
typeof opts?.expectedVersion === 'number' &&
opts.expectedVersion !== existing.data.version
) {
throw new SceneVersionConflictError(
`expected version ${opts.expectedVersion}, current ${existing.data.version}`,
)
}
const nextVersion = existing.data.version + 1
const updated = await client
.from<SceneRow>(this.tableScenes)
.update({
name: newName,
version: nextVersion,
updated_at: new Date().toISOString(),
})
.eq('id', id)
.eq('version', existing.data.version)
.select()
.single()
if (updated.error || !updated.data) {
throw new SceneVersionConflictError(
updated.error?.message ?? 'version conflict during rename',
)
}
return rowToMeta(updated.data)
}
private async insertRevision(
client: SupabaseLikeClient,
sceneId: string,
version: number,
graph: SceneGraph,
authorId: string | null,
): Promise<void> {
const result = await client.from<RevisionRow>(this.tableRevisions).insert({
scene_id: sceneId,
version,
graph_json: graph,
author_kind: 'mcp',
author_id: authorId,
created_at: new Date().toISOString(),
})
if (result.error) {
// Revision history is best-effort; surface the failure so callers can
// log / alert, but don't swallow it silently.
throw new Error(`Supabase revision insert failed: ${result.error.message}`)
}
}
}
+88
View File
@@ -0,0 +1,88 @@
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
/**
* Slug-safe scene identifier: lowercase alphanumerics and hyphens, ≤ 64 chars.
*/
export type SceneId = string
export interface SceneMeta {
id: SceneId
name: string
projectId: string | null
thumbnailUrl: string | null
/** Monotonic, incremented on every save. */
version: number
/** ISO 8601 timestamp. */
createdAt: string
/** ISO 8601 timestamp. */
updatedAt: string
ownerId: string | null
sizeBytes: number
nodeCount: number
}
export interface SceneWithGraph extends SceneMeta {
graph: SceneGraph
}
export interface SceneSaveOptions {
id?: SceneId
name: string
projectId?: string | null
ownerId?: string | null
graph: SceneGraph
thumbnailUrl?: string | null
/** When set, save fails with `SceneVersionConflictError` on mismatch. */
expectedVersion?: number
}
export interface SceneListOptions {
projectId?: string
ownerId?: string
limit?: number
}
export interface SceneMutateOptions {
expectedVersion?: number
}
export interface SceneStore {
readonly backend: 'filesystem' | 'supabase'
save(opts: SceneSaveOptions): Promise<SceneMeta>
load(id: SceneId): Promise<SceneWithGraph | null>
list(opts?: SceneListOptions): Promise<SceneMeta[]>
delete(id: SceneId, opts?: SceneMutateOptions): Promise<boolean>
rename(id: SceneId, newName: string, opts?: SceneMutateOptions): Promise<SceneMeta>
}
export class SceneNotFoundError extends Error {
readonly code = 'not_found' as const
constructor(message = 'Scene not found') {
super(message)
this.name = 'SceneNotFoundError'
}
}
export class SceneVersionConflictError extends Error {
readonly code = 'version_conflict' as const
constructor(message = 'Scene version conflict') {
super(message)
this.name = 'SceneVersionConflictError'
}
}
export class SceneInvalidError extends Error {
readonly code = 'invalid' as const
constructor(message = 'Scene invalid') {
super(message)
this.name = 'SceneInvalidError'
}
}
export class SceneTooLargeError extends Error {
readonly code = 'too_large' as const
constructor(message = 'Scene too large') {
super(message)
this.name = 'SceneTooLargeError'
}
}
+264
View File
@@ -0,0 +1,264 @@
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import type { AnyNode, AnyNodeId } from '@pascal-app/core/schema'
/**
* 40 m² studio apartment — a single open room with one window, one front door
* and a single "Living/Kitchen" zone. Used as a starting point for small unit
* briefs. Deterministic ids (`site_empty`, `building_empty`, `level_0`, etc.)
* are regenerated by the MCP tool via `cloneSceneGraph` before applying.
*/
// Footprint: 8 m × 5 m = 40 m² (centered at origin).
// Walls traverse the boundary counter-clockwise (right-handed XZ plane).
const W = 4 // half-width
const D = 2.5 // half-depth
type StudioNodes = {
site: AnyNode
building: AnyNode
level: AnyNode
walls: AnyNode[]
zone: AnyNode
door: AnyNode
window: AnyNode
}
function buildNodes(): StudioNodes {
const site: AnyNode = {
object: 'node',
id: 'site_empty' as AnyNodeId,
type: 'site',
parentId: null,
visible: true,
metadata: {},
polygon: {
type: 'polygon',
points: [
[-15, -15],
[15, -15],
[15, 15],
[-15, 15],
],
},
children: ['building_empty' as AnyNodeId],
} as unknown as AnyNode
const building: AnyNode = {
object: 'node',
id: 'building_empty' as AnyNodeId,
type: 'building',
parentId: 'site_empty' as AnyNodeId,
visible: true,
metadata: {},
position: [0, 0, 0],
rotation: [0, 0, 0],
children: ['level_0' as AnyNodeId],
} as unknown as AnyNode
// Walls with deterministic ids; child ids are listed below after doors/windows
// are created, so we fill this array after computing them.
const wallIds = ['wall_n', 'wall_e', 'wall_s', 'wall_w'] as const
// South wall carries the front door; west wall carries the window.
const door: AnyNode = {
object: 'node',
id: 'door_front' as AnyNodeId,
type: 'door',
parentId: 'wall_s' as AnyNodeId,
visible: true,
metadata: {},
wallId: 'wall_s',
position: [0, 1.05, 0],
rotation: [0, 0, 0],
width: 0.9,
height: 2.1,
frameThickness: 0.05,
frameDepth: 0.07,
threshold: true,
thresholdHeight: 0.02,
hingesSide: 'left',
swingDirection: 'inward',
segments: [
{
type: 'panel',
heightRatio: 0.4,
columnRatios: [1],
dividerThickness: 0.03,
panelDepth: 0.01,
panelInset: 0.04,
},
{
type: 'panel',
heightRatio: 0.6,
columnRatios: [1],
dividerThickness: 0.03,
panelDepth: 0.01,
panelInset: 0.04,
},
],
handle: true,
handleHeight: 1.05,
handleSide: 'right',
contentPadding: [0.04, 0.04],
doorCloser: false,
panicBar: false,
panicBarHeight: 1.0,
} as unknown as AnyNode
const windowNode: AnyNode = {
object: 'node',
id: 'window_w' as AnyNodeId,
type: 'window',
parentId: 'wall_w' as AnyNodeId,
visible: true,
metadata: {},
wallId: 'wall_w',
position: [0, 1.2, 0],
rotation: [0, 0, 0],
width: 1.5,
height: 1.2,
frameThickness: 0.05,
frameDepth: 0.07,
columnRatios: [1],
rowRatios: [1],
columnDividerThickness: 0.03,
rowDividerThickness: 0.03,
sill: true,
sillDepth: 0.08,
sillThickness: 0.03,
} as unknown as AnyNode
const wallNorth: AnyNode = {
object: 'node',
id: 'wall_n' as AnyNodeId,
type: 'wall',
parentId: 'level_0' as AnyNodeId,
visible: true,
metadata: {},
children: [],
thickness: 0.1,
height: 2.5,
start: [-W, -D],
end: [W, -D],
frontSide: 'unknown',
backSide: 'unknown',
} as unknown as AnyNode
const wallEast: AnyNode = {
object: 'node',
id: 'wall_e' as AnyNodeId,
type: 'wall',
parentId: 'level_0' as AnyNodeId,
visible: true,
metadata: {},
children: [],
thickness: 0.1,
height: 2.5,
start: [W, -D],
end: [W, D],
frontSide: 'unknown',
backSide: 'unknown',
} as unknown as AnyNode
const wallSouth: AnyNode = {
object: 'node',
id: 'wall_s' as AnyNodeId,
type: 'wall',
parentId: 'level_0' as AnyNodeId,
visible: true,
metadata: {},
children: ['door_front'],
thickness: 0.1,
height: 2.5,
start: [W, D],
end: [-W, D],
frontSide: 'unknown',
backSide: 'unknown',
} as unknown as AnyNode
const wallWest: AnyNode = {
object: 'node',
id: 'wall_w' as AnyNodeId,
type: 'wall',
parentId: 'level_0' as AnyNodeId,
visible: true,
metadata: {},
children: ['window_w'],
thickness: 0.1,
height: 2.5,
start: [-W, D],
end: [-W, -D],
frontSide: 'unknown',
backSide: 'unknown',
} as unknown as AnyNode
const zone: AnyNode = {
object: 'node',
id: 'zone_living' as AnyNodeId,
type: 'zone',
parentId: 'level_0' as AnyNodeId,
visible: true,
metadata: {},
name: 'Living / Kitchen',
color: '#60a5fa',
polygon: [
[-W, -D],
[W, -D],
[W, D],
[-W, D],
],
} as unknown as AnyNode
const level: AnyNode = {
object: 'node',
id: 'level_0' as AnyNodeId,
type: 'level',
parentId: 'building_empty' as AnyNodeId,
visible: true,
metadata: {},
level: 0,
children: [...wallIds, 'zone_living'] as AnyNodeId[],
} as unknown as AnyNode
return {
site,
building,
level,
walls: [wallNorth, wallEast, wallSouth, wallWest],
zone,
door,
window: windowNode,
}
}
function buildTemplate(): SceneGraph {
const n = buildNodes()
const nodes: Record<AnyNodeId, AnyNode> = {}
for (const node of [n.site, n.building, n.level, ...n.walls, n.zone, n.door, n.window]) {
nodes[node.id as AnyNodeId] = node
}
// SiteNode.children is a discriminatedUnion of BuildingNode/ItemNode objects
// (not string ids) — so the site must embed the full building node. The
// rest of the tree uses string ids per the BaseNode/LevelNode/WallNode
// schemas. We mutate the flat-dict copy of the site here so the nested
// representation round-trips through AnyNode.safeParse.
const siteInDict = nodes['site_empty' as AnyNodeId] as unknown as {
children: unknown[]
}
siteInDict.children = [nodes['building_empty' as AnyNodeId]]
return {
nodes,
rootNodeIds: ['site_empty'] as AnyNodeId[],
}
}
export const template: SceneGraph = buildTemplate()
export const metadata = {
id: 'empty-studio',
name: 'Empty studio',
description:
'40 m² single-room studio apartment: 4 walls, 1 living/kitchen zone, 1 window, 1 front door.',
} as const
+283
View File
@@ -0,0 +1,283 @@
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import type { AnyNode, AnyNodeId } from '@pascal-app/core/schema'
/**
* "Garden house" — a simplified take on the Casa del Sol layout used in the
* MCP research fixtures.
*
* Footprint: 12 m × 8 m house centered at the origin, with a 12 m × 6 m
* back garden zone immediately to the north of the house, surrounded by a
* privacy fence on three sides.
*
* Contents:
* - 4 perimeter walls around the house
* - 1 front door (south wall), 1 large garden door (north wall)
* - 2 windows on the south wall, 1 window on each of east and west
* - 1 indoor "living" zone, 1 outdoor "garden" zone
* - 3 fence segments bounding the north/east/west of the garden
*/
const HOUSE_W = 6 // half-width of the house (12 m total)
const HOUSE_D = 4 // half-depth of the house (8 m total)
const GARDEN_DEPTH = 6 // depth of the back-garden zone along +z direction
const WALL_THICKNESS = 0.15
const WALL_HEIGHT = 2.7
type NodeMap = Record<string, AnyNode>
function wall(
id: string,
start: [number, number],
end: [number, number],
children: string[] = [],
): AnyNode {
return {
object: 'node',
id,
type: 'wall',
parentId: 'level_0',
visible: true,
metadata: {},
children,
thickness: WALL_THICKNESS,
height: WALL_HEIGHT,
start,
end,
frontSide: 'unknown',
backSide: 'unknown',
} as unknown as AnyNode
}
function door(id: string, parentWallId: string, width = 0.9): AnyNode {
return {
object: 'node',
id,
type: 'door',
parentId: parentWallId,
visible: true,
metadata: {},
wallId: parentWallId,
position: [0, 1.05, 0],
rotation: [0, 0, 0],
width,
height: 2.1,
frameThickness: 0.05,
frameDepth: 0.07,
threshold: true,
thresholdHeight: 0.02,
hingesSide: 'left',
swingDirection: 'inward',
segments: [
{
type: 'panel',
heightRatio: 0.5,
columnRatios: [1],
dividerThickness: 0.03,
panelDepth: 0.01,
panelInset: 0.04,
},
{
type: 'panel',
heightRatio: 0.5,
columnRatios: [1],
dividerThickness: 0.03,
panelDepth: 0.01,
panelInset: 0.04,
},
],
handle: true,
handleHeight: 1.05,
handleSide: 'right',
contentPadding: [0.04, 0.04],
doorCloser: false,
panicBar: false,
panicBarHeight: 1.0,
} as unknown as AnyNode
}
function makeWindow(id: string, parentWallId: string, width = 1.2): AnyNode {
return {
object: 'node',
id,
type: 'window',
parentId: parentWallId,
visible: true,
metadata: {},
wallId: parentWallId,
position: [0, 1.2, 0],
rotation: [0, 0, 0],
width,
height: 1.2,
frameThickness: 0.05,
frameDepth: 0.07,
columnRatios: [1],
rowRatios: [1],
columnDividerThickness: 0.03,
rowDividerThickness: 0.03,
sill: true,
sillDepth: 0.08,
sillThickness: 0.03,
} as unknown as AnyNode
}
function fence(id: string, start: [number, number], end: [number, number]): AnyNode {
return {
object: 'node',
id,
type: 'fence',
parentId: 'level_0',
visible: true,
metadata: {},
start,
end,
height: 1.8,
thickness: 0.08,
baseHeight: 0.22,
postSpacing: 2,
postSize: 0.1,
topRailHeight: 0.04,
groundClearance: 0,
edgeInset: 0.015,
baseStyle: 'grounded',
color: '#f3f4f6',
style: 'privacy',
} as unknown as AnyNode
}
function buildTemplate(): SceneGraph {
const nodes: NodeMap = {}
nodes.site_garden = {
object: 'node',
id: 'site_garden',
type: 'site',
parentId: null,
visible: true,
metadata: {},
polygon: {
type: 'polygon',
points: [
[-15, -15],
[15, -15],
[15, 15],
[-15, 15],
],
},
children: ['building_garden'],
} as unknown as AnyNode
nodes.building_garden = {
object: 'node',
id: 'building_garden',
type: 'building',
parentId: 'site_garden',
visible: true,
metadata: {},
position: [0, 0, 0],
rotation: [0, 0, 0],
children: ['level_0'],
} as unknown as AnyNode
// Openings
nodes.door_front = door('door_front', 'wall_s', 1.0)
nodes.door_garden = door('door_garden', 'wall_n', 1.6)
nodes.window_s1 = makeWindow('window_s1', 'wall_s', 1.2)
nodes.window_s2 = makeWindow('window_s2', 'wall_s', 1.2)
nodes.window_e = makeWindow('window_e', 'wall_e', 1.0)
nodes.window_w = makeWindow('window_w', 'wall_w', 1.0)
// House perimeter (south is front, north opens to the garden)
nodes.wall_n = wall('wall_n', [-HOUSE_W, -HOUSE_D], [HOUSE_W, -HOUSE_D], ['door_garden'])
nodes.wall_e = wall('wall_e', [HOUSE_W, -HOUSE_D], [HOUSE_W, HOUSE_D], ['window_e'])
nodes.wall_s = wall(
'wall_s',
[HOUSE_W, HOUSE_D],
[-HOUSE_W, HOUSE_D],
['door_front', 'window_s1', 'window_s2'],
)
nodes.wall_w = wall('wall_w', [-HOUSE_W, HOUSE_D], [-HOUSE_W, -HOUSE_D], ['window_w'])
// Zones
nodes.zone_living = {
object: 'node',
id: 'zone_living',
type: 'zone',
parentId: 'level_0',
visible: true,
metadata: {},
name: 'Living',
color: '#60a5fa',
polygon: [
[-HOUSE_W, -HOUSE_D],
[HOUSE_W, -HOUSE_D],
[HOUSE_W, HOUSE_D],
[-HOUSE_W, HOUSE_D],
],
} as unknown as AnyNode
nodes.zone_garden = {
object: 'node',
id: 'zone_garden',
type: 'zone',
parentId: 'level_0',
visible: true,
metadata: {},
name: 'Back garden',
color: '#86efac',
polygon: [
[-HOUSE_W, -HOUSE_D - GARDEN_DEPTH],
[HOUSE_W, -HOUSE_D - GARDEN_DEPTH],
[HOUSE_W, -HOUSE_D],
[-HOUSE_W, -HOUSE_D],
],
} as unknown as AnyNode
// Privacy fence along 3 sides of the garden.
nodes.fence_n = fence(
'fence_n',
[-HOUSE_W, -HOUSE_D - GARDEN_DEPTH],
[HOUSE_W, -HOUSE_D - GARDEN_DEPTH],
)
nodes.fence_e = fence('fence_e', [HOUSE_W, -HOUSE_D - GARDEN_DEPTH], [HOUSE_W, -HOUSE_D])
nodes.fence_w = fence('fence_w', [-HOUSE_W, -HOUSE_D], [-HOUSE_W, -HOUSE_D - GARDEN_DEPTH])
nodes.level_0 = {
object: 'node',
id: 'level_0',
type: 'level',
parentId: 'building_garden',
visible: true,
metadata: {},
level: 0,
children: [
'wall_n',
'wall_e',
'wall_s',
'wall_w',
'zone_living',
'zone_garden',
'fence_n',
'fence_e',
'fence_w',
],
} as unknown as AnyNode
// SiteNode.children is a discriminatedUnion of BuildingNode/ItemNode objects
// (not string ids) per the schema — embed the full building node here.
;(nodes.site_garden as unknown as { children: unknown[] }).children = [nodes.building_garden!]
return {
nodes: nodes as Record<AnyNodeId, AnyNode>,
rootNodeIds: ['site_garden'] as AnyNodeId[],
}
}
export const template: SceneGraph = buildTemplate()
export const metadata = {
id: 'garden-house',
name: 'Garden house',
description:
'12 × 8 m single-level house with a fenced back-garden zone; 4 walls, 2 doors, 4 windows, 3 privacy fences.',
} as const
+41
View File
@@ -0,0 +1,41 @@
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import * as emptyStudio from './empty-studio'
import * as gardenHouse from './garden-house'
import * as twoBedroom from './two-bedroom'
export type TemplateMetadata = {
id: string
name: string
description: string
}
export type TemplateEntry = {
/** Stable template id used by `create_from_template`. */
id: string
name: string
description: string
/** Static SceneGraph — ids are placeholders; regenerate via `cloneSceneGraph`. */
template: SceneGraph
}
function makeEntry(template: SceneGraph, metadata: TemplateMetadata): TemplateEntry {
return {
id: metadata.id,
name: metadata.name,
description: metadata.description,
template,
}
}
export const TEMPLATES = {
'empty-studio': makeEntry(emptyStudio.template, emptyStudio.metadata),
'two-bedroom': makeEntry(twoBedroom.template, twoBedroom.metadata),
'garden-house': makeEntry(gardenHouse.template, gardenHouse.metadata),
} as const
export type TemplateId = keyof typeof TEMPLATES
/** Type guard for external callers that receive arbitrary string ids. */
export function isTemplateId(id: string): id is TemplateId {
return Object.hasOwn(TEMPLATES, id)
}
@@ -0,0 +1,85 @@
import { describe, expect, test } from 'bun:test'
import { AnyNode } from '@pascal-app/core/schema'
import { TEMPLATES, type TemplateId } from './index'
describe('scene templates', () => {
const ids: TemplateId[] = Object.keys(TEMPLATES) as TemplateId[]
for (const id of ids) {
const entry = TEMPLATES[id]
test(`${id} has required metadata`, () => {
expect(entry.id).toBe(id)
expect(typeof entry.name).toBe('string')
expect(entry.name.length).toBeGreaterThan(0)
expect(typeof entry.description).toBe('string')
expect(entry.description.length).toBeGreaterThan(0)
})
test(`${id} template nodes all pass AnyNode.safeParse`, () => {
const { nodes, rootNodeIds } = entry.template
expect(rootNodeIds.length).toBeGreaterThan(0)
expect(Object.keys(nodes).length).toBeGreaterThan(0)
for (const [nodeId, node] of Object.entries(nodes)) {
const res = AnyNode.safeParse(node)
if (!res.success) {
// Surface the path/message of the first issue for debuggability.
const first = res.error.issues[0]
throw new Error(
`template ${id} node ${nodeId} failed AnyNode.safeParse at ${first?.path.join('.')}: ${first?.message}`,
)
}
expect(res.success).toBe(true)
}
})
test(`${id} root ids resolve and parent links point to existing nodes`, () => {
const { nodes, rootNodeIds } = entry.template
for (const rid of rootNodeIds) {
expect(nodes[rid]).toBeDefined()
}
for (const node of Object.values(nodes)) {
if (node.parentId && !(node.parentId in nodes)) {
throw new Error(
`template ${id} node ${node.id} has parentId ${node.parentId} which does not exist`,
)
}
}
})
}
test('empty-studio has 4 walls, 1 zone, 1 door, 1 window', () => {
const { nodes } = TEMPLATES['empty-studio'].template
const byType = groupByType(nodes)
expect(byType.wall ?? 0).toBe(4)
expect(byType.zone ?? 0).toBe(1)
expect(byType.door ?? 0).toBe(1)
expect(byType.window ?? 0).toBe(1)
})
test('two-bedroom has 9 walls, 4 zones, 4 doors, 5 windows', () => {
const { nodes } = TEMPLATES['two-bedroom'].template
const byType = groupByType(nodes)
expect(byType.wall ?? 0).toBe(9)
expect(byType.zone ?? 0).toBe(4)
expect(byType.door ?? 0).toBe(4)
expect(byType.window ?? 0).toBe(5)
})
test('garden-house has a fenced garden zone', () => {
const { nodes } = TEMPLATES['garden-house'].template
const byType = groupByType(nodes)
expect(byType.zone ?? 0).toBeGreaterThanOrEqual(2)
expect(byType.fence ?? 0).toBeGreaterThanOrEqual(3)
expect(byType.wall ?? 0).toBeGreaterThanOrEqual(4)
})
})
function groupByType(nodes: Record<string, { type: string }>): Record<string, number> {
const out: Record<string, number> = {}
for (const node of Object.values(nodes)) {
out[node.type] = (out[node.type] ?? 0) + 1
}
return out
}
+311
View File
@@ -0,0 +1,311 @@
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import type { AnyNode, AnyNodeId } from '@pascal-app/core/schema'
/**
* 80 m² two-bedroom apartment.
*
* Footprint: 10 m × 8 m = 80 m², centered near the origin.
* Contents: 9 walls (4 perimeter + 5 interior), 4 zones
* (living/kitchen, bedroom1, bedroom2, bath), 4 doors (front + 3 interior),
* 5 windows (2 on the living/kitchen, 1 per bedroom, 1 on the bath).
* Interior partitions split the north half into two bedrooms and a bath.
*
* Coordinate system: `[x, z]` on the XZ plane, with `x` running east/west
* and `z` running north/south (positive z points south).
*/
// Perimeter extents: 10 m × 8 m.
const X_MIN = -5
const X_MAX = 5
const Z_MIN = -4
const Z_MAX = 4
// Interior split lines.
const CORRIDOR_Z = 0 // horizontal wall separating north half (bedrooms+bath) from south (living)
const BED_X = -1 // vertical wall between bedroom 1 (west) and bath (east of it)
const BATH_X = 2 // vertical wall between bath (middle) and bedroom 2 (east)
const WALL_THICKNESS = 0.1
const WALL_HEIGHT = 2.5
type NodeMap = Record<string, AnyNode>
function wall(
id: string,
start: [number, number],
end: [number, number],
children: string[] = [],
): AnyNode {
return {
object: 'node',
id,
type: 'wall',
parentId: 'level_0',
visible: true,
metadata: {},
children,
thickness: WALL_THICKNESS,
height: WALL_HEIGHT,
start,
end,
frontSide: 'unknown',
backSide: 'unknown',
} as unknown as AnyNode
}
function door(id: string, parentWallId: string): AnyNode {
return {
object: 'node',
id,
type: 'door',
parentId: parentWallId,
visible: true,
metadata: {},
wallId: parentWallId,
position: [0, 1.05, 0],
rotation: [0, 0, 0],
width: 0.8,
height: 2.1,
frameThickness: 0.05,
frameDepth: 0.07,
threshold: true,
thresholdHeight: 0.02,
hingesSide: 'left',
swingDirection: 'inward',
segments: [
{
type: 'panel',
heightRatio: 0.5,
columnRatios: [1],
dividerThickness: 0.03,
panelDepth: 0.01,
panelInset: 0.04,
},
{
type: 'panel',
heightRatio: 0.5,
columnRatios: [1],
dividerThickness: 0.03,
panelDepth: 0.01,
panelInset: 0.04,
},
],
handle: true,
handleHeight: 1.05,
handleSide: 'right',
contentPadding: [0.04, 0.04],
doorCloser: false,
panicBar: false,
panicBarHeight: 1.0,
} as unknown as AnyNode
}
function makeWindow(id: string, parentWallId: string, width = 1.2): AnyNode {
return {
object: 'node',
id,
type: 'window',
parentId: parentWallId,
visible: true,
metadata: {},
wallId: parentWallId,
position: [0, 1.2, 0],
rotation: [0, 0, 0],
width,
height: 1.2,
frameThickness: 0.05,
frameDepth: 0.07,
columnRatios: [1],
rowRatios: [1],
columnDividerThickness: 0.03,
rowDividerThickness: 0.03,
sill: true,
sillDepth: 0.08,
sillThickness: 0.03,
} as unknown as AnyNode
}
function buildTemplate(): SceneGraph {
const nodes: NodeMap = {}
// Root nodes
nodes.site_2br = {
object: 'node',
id: 'site_2br',
type: 'site',
parentId: null,
visible: true,
metadata: {},
polygon: {
type: 'polygon',
points: [
[-15, -15],
[15, -15],
[15, 15],
[-15, 15],
],
},
children: ['building_2br'],
} as unknown as AnyNode
nodes.building_2br = {
object: 'node',
id: 'building_2br',
type: 'building',
parentId: 'site_2br',
visible: true,
metadata: {},
position: [0, 0, 0],
rotation: [0, 0, 0],
children: ['level_0'],
} as unknown as AnyNode
// Openings — declared up front so walls can list them as children.
nodes.door_front = door('door_front', 'wall_s')
nodes.door_bed1 = door('door_bed1', 'wall_corr_1')
nodes.door_bath = door('door_bath', 'wall_corr_2')
nodes.door_bed2 = door('door_bed2', 'wall_corr_3')
nodes.window_living_a = makeWindow('window_living_a', 'wall_s', 1.5)
nodes.window_living_b = makeWindow('window_living_b', 'wall_e', 1.2)
nodes.window_bed1 = makeWindow('window_bed1', 'wall_n', 1.2)
nodes.window_bath = makeWindow('window_bath', 'wall_n', 0.6)
nodes.window_bed2 = makeWindow('window_bed2', 'wall_n', 1.2)
// Perimeter walls (N, E, S, W) — 4 walls.
// Interior partitions — 5 walls (the east/west corridor wall is split into
// three segments by the two vertical partitions so doors have a clear host).
nodes.wall_n = wall(
'wall_n',
[X_MIN, Z_MIN],
[X_MAX, Z_MIN],
['window_bed1', 'window_bath', 'window_bed2'],
)
nodes.wall_e = wall('wall_e', [X_MAX, Z_MIN], [X_MAX, Z_MAX], ['window_living_b'])
nodes.wall_s = wall('wall_s', [X_MAX, Z_MAX], [X_MIN, Z_MAX], ['door_front', 'window_living_a'])
nodes.wall_w = wall('wall_w', [X_MIN, Z_MAX], [X_MIN, Z_MIN])
// Corridor wall is broken into 3 segments so each has its own interior door.
// Segment 1: from west to BED_X (bedroom-1 wall)
nodes.wall_corr_1 = wall('wall_corr_1', [X_MIN, CORRIDOR_Z], [BED_X, CORRIDOR_Z], ['door_bed1'])
// Segment 2: from BED_X to BATH_X (bath wall)
nodes.wall_corr_2 = wall('wall_corr_2', [BED_X, CORRIDOR_Z], [BATH_X, CORRIDOR_Z], ['door_bath'])
// Segment 3: from BATH_X to east (bedroom-2 wall)
nodes.wall_corr_3 = wall('wall_corr_3', [BATH_X, CORRIDOR_Z], [X_MAX, CORRIDOR_Z], ['door_bed2'])
// Two vertical partitions between the three north rooms.
nodes.wall_part_1 = wall('wall_part_1', [BED_X, Z_MIN], [BED_X, CORRIDOR_Z])
nodes.wall_part_2 = wall('wall_part_2', [BATH_X, Z_MIN], [BATH_X, CORRIDOR_Z])
// Zones: one per room.
nodes.zone_living = {
object: 'node',
id: 'zone_living',
type: 'zone',
parentId: 'level_0',
visible: true,
metadata: {},
name: 'Living / Kitchen',
color: '#60a5fa',
polygon: [
[X_MIN, CORRIDOR_Z],
[X_MAX, CORRIDOR_Z],
[X_MAX, Z_MAX],
[X_MIN, Z_MAX],
],
} as unknown as AnyNode
nodes.zone_bed1 = {
object: 'node',
id: 'zone_bed1',
type: 'zone',
parentId: 'level_0',
visible: true,
metadata: {},
name: 'Bedroom 1',
color: '#f472b6',
polygon: [
[X_MIN, Z_MIN],
[BED_X, Z_MIN],
[BED_X, CORRIDOR_Z],
[X_MIN, CORRIDOR_Z],
],
} as unknown as AnyNode
nodes.zone_bath = {
object: 'node',
id: 'zone_bath',
type: 'zone',
parentId: 'level_0',
visible: true,
metadata: {},
name: 'Bath',
color: '#a7f3d0',
polygon: [
[BED_X, Z_MIN],
[BATH_X, Z_MIN],
[BATH_X, CORRIDOR_Z],
[BED_X, CORRIDOR_Z],
],
} as unknown as AnyNode
nodes.zone_bed2 = {
object: 'node',
id: 'zone_bed2',
type: 'zone',
parentId: 'level_0',
visible: true,
metadata: {},
name: 'Bedroom 2',
color: '#fcd34d',
polygon: [
[BATH_X, Z_MIN],
[X_MAX, Z_MIN],
[X_MAX, CORRIDOR_Z],
[BATH_X, CORRIDOR_Z],
],
} as unknown as AnyNode
nodes.level_0 = {
object: 'node',
id: 'level_0',
type: 'level',
parentId: 'building_2br',
visible: true,
metadata: {},
level: 0,
children: [
'wall_n',
'wall_e',
'wall_s',
'wall_w',
'wall_corr_1',
'wall_corr_2',
'wall_corr_3',
'wall_part_1',
'wall_part_2',
'zone_living',
'zone_bed1',
'zone_bath',
'zone_bed2',
],
} as unknown as AnyNode
// SiteNode.children is a discriminatedUnion of BuildingNode/ItemNode objects
// (not string ids) per the schema — embed the full building node here.
;(nodes.site_2br as unknown as { children: unknown[] }).children = [nodes.building_2br!]
return {
nodes: nodes as Record<AnyNodeId, AnyNode>,
rootNodeIds: ['site_2br'] as AnyNodeId[],
}
}
export const template: SceneGraph = buildTemplate()
export const metadata = {
id: 'two-bedroom',
name: 'Two-bedroom apartment',
description:
'80 m² two-bedroom flat: 9 walls, 4 zones (living/kitchen, 2 bedrooms, bath), 4 doors and 5 windows.',
} as const
+15 -1
View File
@@ -1,5 +1,6 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneBridge } from '../bridge/scene-bridge'
import type { SceneStore } from '../storage/types'
import { registerApplyPatch } from './apply-patch'
import { registerCheckCollisions } from './check-collisions'
import { registerCreateLevel } from './create-level'
@@ -14,18 +15,25 @@ import { registerFindNodes } from './find-nodes'
import { registerGetNode } from './get-node'
import { registerGetScene } from './get-scene'
import { registerMeasure } from './measure'
import { registerPhotoToSceneTool } from './photo-to-scene'
import { registerPlaceItem } from './place-item'
import { registerRedo } from './redo'
import { registerSceneLifecycleTools } from './scene-lifecycle'
import { registerSetZone } from './set-zone'
import { registerTemplateTools } from './templates'
import { registerUndo } from './undo'
import { registerValidateScene } from './validate-scene'
import { registerVariantTools } from './variants'
/**
* Register every non-vision MCP tool against the given server.
* Vision tools (analyze_floorplan_image, analyze_room_photo) are registered
* separately via `registerVisionTools` (Agent E).
*
* Scene-lifecycle tools (save/load/list/delete/rename scene) are registered
* when a `store` is provided; callers that pass `undefined` skip them.
*/
export function registerTools(server: McpServer, bridge: SceneBridge): void {
export function registerTools(server: McpServer, bridge: SceneBridge, store?: SceneStore): void {
registerGetScene(server, bridge)
registerGetNode(server, bridge)
registerDescribeNode(server, bridge)
@@ -45,4 +53,10 @@ export function registerTools(server: McpServer, bridge: SceneBridge): void {
registerExportGlb(server, bridge)
registerValidateScene(server, bridge)
registerCheckCollisions(server, bridge)
registerTemplateTools(server, bridge, store)
if (store) {
registerSceneLifecycleTools(server, bridge, store)
registerVariantTools(server, bridge, store)
registerPhotoToSceneTool(server, bridge, store)
}
}
@@ -0,0 +1,24 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { registerPhotoToScene } from './photo-to-scene'
/**
* Register the `photo_to_scene` orchestrator tool. Chains the vision
* (`analyze_floorplan_image`-equivalent sampling call) → SceneGraph
* synthesis → optional `SceneStore.save` → `bridge.setScene` so callers get a
* navigable Pascal scene from a single photo upload.
*/
export function registerPhotoToSceneTool(
server: McpServer,
bridge: SceneBridge,
store: SceneStore,
): void {
registerPhotoToScene(server, bridge, store)
}
export {
photoToSceneInput,
photoToSceneOutput,
registerPhotoToScene,
} from './photo-to-scene'
@@ -0,0 +1,194 @@
import { describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { CreateMessageRequestSchema } from '@modelcontextprotocol/sdk/types.js'
import { SceneBridge } from '../../bridge/scene-bridge'
import { InMemorySceneStore } from '../scene-lifecycle/test-utils'
import { registerPhotoToScene } from './photo-to-scene'
type Handler = (req: unknown) => unknown | Promise<unknown>
/**
* Build a connected client/server pair for the `photo_to_scene` orchestrator.
* Optionally advertises the `sampling` capability on the client and installs
* a mock sampling handler that returns a caller-provided reply.
*/
async function makeWiredPair(opts: { withSampling: boolean; samplingHandler?: Handler }): Promise<{
client: Client
bridge: SceneBridge
store: InMemorySceneStore
}> {
const bridge = new SceneBridge()
bridge.setScene({}, [])
const store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerPhotoToScene(server, bridge, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
const client = new Client(
{ name: 'test-client', version: '0.0.0' },
{
capabilities: opts.withSampling ? { sampling: {} } : {},
},
)
if (opts.withSampling && opts.samplingHandler) {
const handler = opts.samplingHandler
client.setRequestHandler(
CreateMessageRequestSchema,
async (request) =>
// Cast to unknown — tests return arbitrary shapes to exercise
// parse/validation paths in the tool handler.
(await handler(request)) as never,
)
}
await Promise.all([server.connect(srvT), client.connect(cliT)])
return { client, bridge, store }
}
const VALID_VISION_JSON = {
walls: [
{ start: [0, 0], end: [5, 0], thickness: 0.2 },
{ start: [5, 0], end: [5, 4] },
{ start: [5, 4], end: [0, 4] },
{ start: [0, 4], end: [0, 0] },
],
rooms: [
{
name: 'Living Room',
polygon: [
[0, 0],
[5, 0],
[5, 4],
[0, 4],
],
approximateAreaSqM: 20,
},
],
approximateDimensions: { widthM: 5, depthM: 4 },
confidence: 0.82,
}
const VALID_REPLY = {
model: 'mock-model',
role: 'assistant',
content: {
type: 'text',
text: JSON.stringify(VALID_VISION_JSON),
},
}
describe('photo_to_scene', () => {
test('happy path: vision reply → walls + rooms + scene in bridge + saved', async () => {
const { client, bridge, store } = await makeWiredPair({
withSampling: true,
samplingHandler: () => VALID_REPLY,
})
const result = await client.callTool({
name: 'photo_to_scene',
arguments: {
image: 'aGVsbG8=',
scaleHint: '1 cm = 1 m',
name: 'Test Scene',
},
})
expect(result.isError).toBeFalsy()
const structured = result.structuredContent as {
sceneId?: string
url?: string
walls: number
rooms: number
confidence: number
}
expect(structured.walls).toBe(4)
expect(structured.rooms).toBe(1)
expect(structured.confidence).toBe(0.82)
expect(typeof structured.sceneId).toBe('string')
expect(structured.url).toBe(`/scene/${structured.sceneId}`)
// Bridge was swapped.
const rootIds = bridge.getRootNodeIds()
expect(rootIds.length).toBe(1)
const rootId = rootIds[0]!
const root = bridge.getNode(rootId)
expect(root?.type).toBe('site')
// Walls and zones exist in the flat dict.
const allNodes = Object.values(bridge.getNodes())
const walls = allNodes.filter((n) => n.type === 'wall')
const zones = allNodes.filter((n) => n.type === 'zone')
expect(walls.length).toBe(4)
expect(zones.length).toBe(1)
// Scene was persisted in the store.
const saved = await store.load(structured.sceneId!)
expect(saved).not.toBeNull()
expect(saved?.name).toBe('Test Scene')
})
test('sampling unavailable → sampling_unavailable error', async () => {
const { client } = await makeWiredPair({ withSampling: false })
const result = await client.callTool({
name: 'photo_to_scene',
arguments: { image: 'aGVsbG8=' },
})
expect(result.isError).toBe(true)
const text = (result.content as Array<{ type: string; text: string }>)[0]!.text
expect(text).toContain('sampling_unavailable')
})
test('invalid JSON reply → sampling_response_unparseable', async () => {
const { client } = await makeWiredPair({
withSampling: true,
samplingHandler: () => ({
model: 'mock-model',
role: 'assistant',
content: { type: 'text', text: 'not json at all' },
}),
})
const result = await client.callTool({
name: 'photo_to_scene',
arguments: { image: 'aGVsbG8=' },
})
expect(result.isError).toBe(true)
const text = (result.content as Array<{ type: string; text: string }>)[0]!.text
expect(text).toContain('sampling_response_unparseable')
})
test('save=false → returns graph inline, no sceneId', async () => {
const { client, store } = await makeWiredPair({
withSampling: true,
samplingHandler: () => VALID_REPLY,
})
const result = await client.callTool({
name: 'photo_to_scene',
arguments: {
image: 'aGVsbG8=',
save: false,
},
})
expect(result.isError).toBeFalsy()
const structured = result.structuredContent as {
sceneId?: string
url?: string
walls: number
rooms: number
confidence: number
graph?: { nodes: Record<string, unknown>; rootNodeIds: string[] }
}
expect(structured.sceneId).toBeUndefined()
expect(structured.url).toBeUndefined()
expect(structured.graph).toBeDefined()
expect(Array.isArray(structured.graph?.rootNodeIds)).toBe(true)
expect(structured.graph?.rootNodeIds.length).toBe(1)
expect(structured.walls).toBe(4)
expect(structured.rooms).toBe(1)
// Nothing persisted.
const list = await store.list()
expect(list.length).toBe(0)
})
})
@@ -0,0 +1,427 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import type { AnyNodeId, AnyNode as AnyNodeT } from '@pascal-app/core/schema'
import {
AnyNode,
BuildingNode,
LevelNode,
SiteNode,
WallNode,
ZoneNode,
} from '@pascal-app/core/schema'
import { z } from 'zod'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
/**
* Input shape for the `photo_to_scene` orchestrator. `image` matches the
* contract documented on `analyze_floorplan_image` — base64 or http(s) URL.
*/
export const photoToSceneInput = {
image: z.string().describe('Base64 or https URL of the floor-plan photo'),
scaleHint: z.string().optional().describe('e.g. "1 cm = 1 m" or "approx 80 m²"'),
name: z.string().default('Scene from photo'),
save: z.boolean().default(true),
defaultWallThickness: z.number().default(0.2),
defaultWallHeight: z.number().default(2.6),
}
export const photoToSceneOutput = {
sceneId: z.string().optional(),
url: z.string().optional(),
walls: z.number(),
rooms: z.number(),
confidence: z.number(),
notes: z.string().optional(),
graph: z.any().optional(),
}
/**
* Shape of the vision JSON we consume. Kept in-sync with
* `analyze_floorplan_image`'s output schema (walls / rooms /
* approximateDimensions / confidence).
*/
const VisionResponseSchema = z.object({
walls: z.array(
z.object({
start: z.tuple([z.number(), z.number()]),
end: z.tuple([z.number(), z.number()]),
thickness: z.number().optional(),
}),
),
rooms: z.array(
z.object({
name: z.string(),
polygon: z.array(z.tuple([z.number(), z.number()])),
approximateAreaSqM: z.number().optional(),
}),
),
approximateDimensions: z.object({
widthM: z.number(),
depthM: z.number(),
}),
confidence: z.number().min(0).max(1),
})
type VisionResponse = z.infer<typeof VisionResponseSchema>
/**
* System prompt mirrors `analyze_floorplan_image` — the contract between
* orchestrator and host is identical, so we keep the prompt verbatim to
* guarantee wire-compatible responses.
*/
const SYSTEM_PROMPT = `You are a vision assistant that extracts structured floor-plan data from an image.
Your ONLY job: return a JSON object that exactly matches this schema — no prose, no markdown fences.
{
"walls": [{ "start": [x, z], "end": [x, z], "thickness": number? }, ...],
"rooms": [{ "name": string, "polygon": [[x,z], ...], "approximateAreaSqM": number? }, ...],
"approximateDimensions": { "widthM": number, "depthM": number },
"confidence": number 0..1
}
Coordinates are in metres. Origin can be the floor plan's centre or bottom-left — be consistent.
If the image is unclear, lower the confidence score but still produce your best attempt.
DO NOT wrap the JSON in markdown. DO NOT explain. Just output the raw JSON.`
const DATA_URI_RE = /^data:(image\/[a-z0-9.+-]+);base64,(.+)$/i
type ImageBlock = {
type: 'image'
data: string
mimeType: string
}
/**
* Resolve the `image` input into a sampling-ready image block. Follows the
* same fetch/data-uri/raw-base64 rules as the vision tool so the user gets
* consistent behaviour whether they call `photo_to_scene` or
* `analyze_floorplan_image` directly.
*/
async function resolveImageBlock(image: string): Promise<ImageBlock> {
if (/^https?:\/\//i.test(image)) {
const res = await fetch(image)
if (!res.ok) {
throw new McpError(
ErrorCode.InvalidParams,
`failed to fetch image: ${res.status} ${res.statusText}`,
{ url: image, status: res.status },
)
}
const buf = Buffer.from(await res.arrayBuffer())
const data = buf.toString('base64')
const mimeType = res.headers.get('content-type') ?? 'image/jpeg'
return { type: 'image', data, mimeType }
}
const dataUriMatch = image.match(DATA_URI_RE)
if (dataUriMatch) {
return {
type: 'image',
mimeType: dataUriMatch[1]!,
data: dataUriMatch[2]!,
}
}
return { type: 'image', mimeType: 'image/jpeg', data: image }
}
/** Collect all text content blocks returned by the sampling host into one string. */
function extractText(
content:
| { type: 'text'; text: string }
| { type: 'image' | 'audio'; data: string; mimeType: string }
| Array<
| { type: 'text'; text: string }
| { type: 'image' | 'audio'; data: string; mimeType: string }
| { type: string; [k: string]: unknown }
>,
): string {
const blocks = Array.isArray(content) ? content : [content]
const texts: string[] = []
for (const block of blocks) {
if (block && typeof block === 'object' && (block as { type?: string }).type === 'text') {
const t = (block as { text?: unknown }).text
if (typeof t === 'string') texts.push(t)
}
}
return texts.join('\n').trim()
}
/**
* Call the host's sampling capability to analyse a floor-plan photo. Throws
* `sampling_unavailable` when the host has not advertised the capability and
* `sampling_response_unparseable` / `sampling_response_invalid` when the
* reply cannot be mapped onto `VisionResponseSchema`.
*/
async function callVisionSampling(
server: McpServer,
image: string,
scaleHint: string | undefined,
): Promise<VisionResponse> {
const caps = server.server.getClientCapabilities()
if (!caps?.sampling) {
throw new McpError(ErrorCode.InvalidRequest, 'sampling_unavailable')
}
const imageBlock = await resolveImageBlock(image)
const instruction = scaleHint
? `Analyze this floor plan. Scale hint: ${scaleHint}. Return ONLY the JSON described by the system prompt.`
: 'Analyze this floor plan. Return ONLY the JSON described by the system prompt.'
const response = await server.server.createMessage({
systemPrompt: SYSTEM_PROMPT,
temperature: 0,
maxTokens: 2000,
messages: [
{
role: 'user',
content: [imageBlock, { type: 'text', text: instruction }],
},
],
})
const text = extractText(response.content as Parameters<typeof extractText>[0])
if (!text) {
throw new McpError(ErrorCode.InternalError, 'sampling_response_unparseable', {
reason: 'no text content returned by host',
})
}
let parsed: unknown
try {
parsed = JSON.parse(text)
} catch (err) {
throw new McpError(ErrorCode.InternalError, 'sampling_response_unparseable', {
raw: text,
reason: err instanceof Error ? err.message : String(err),
})
}
const validation = VisionResponseSchema.safeParse(parsed)
if (!validation.success) {
throw new McpError(ErrorCode.InternalError, 'sampling_response_invalid', {
raw: text,
errors: validation.error.issues,
})
}
return validation.data
}
type BuildResult = {
nodes: Record<AnyNodeId, AnyNodeT>
rootNodeIds: AnyNodeId[]
walls: number
rooms: number
warnings: string[]
levelId: AnyNodeId
}
/**
* Build a SceneGraph (flat `nodes` dict + `rootNodeIds`) from the vision
* response. Uses the schema factories for every node so IDs, defaults, and
* parent linkage match what the core store would produce. Each node is
* revalidated via `AnyNode.safeParse`; failures are dropped with a warning.
*/
function buildSceneGraphFromVision(
vision: VisionResponse,
defaultWallThickness: number,
defaultWallHeight: number,
): BuildResult {
const warnings: string[] = []
// Build the skeleton: site → building → level.
const building = BuildingNode.parse({})
const level = LevelNode.parse({ level: 0 })
const site = SiteNode.parse({ children: [building] })
// Link parent ids so downstream traversal works.
const siteId = site.id as AnyNodeId
const buildingId = building.id as AnyNodeId
const levelId = level.id as AnyNodeId
const linkedBuilding: AnyNodeT = {
...(building as AnyNodeT),
parentId: siteId,
}
const linkedLevel: AnyNodeT = {
...(level as AnyNodeT),
parentId: buildingId,
}
// BuildingNode children stores level ids (string[]).
;(linkedBuilding as BuildingNode).children = [levelId as BuildingNode['children'][number]]
// Collect level children (ids of walls/zones we create below).
const levelChildren: string[] = []
const nodes: Record<AnyNodeId, AnyNodeT> = {}
// Validate + add site, building, level in that order.
const siteValidated = AnyNode.safeParse(site)
if (!siteValidated.success) {
warnings.push(`site node failed schema validation: ${siteValidated.error.message}`)
}
nodes[siteId] = (siteValidated.success ? siteValidated.data : site) as AnyNodeT
const buildingValidated = AnyNode.safeParse(linkedBuilding)
if (!buildingValidated.success) {
warnings.push(`building node failed schema validation: ${buildingValidated.error.message}`)
}
nodes[buildingId] = (
buildingValidated.success ? buildingValidated.data : linkedBuilding
) as AnyNodeT
// Walls.
let wallsAdded = 0
for (let i = 0; i < vision.walls.length; i++) {
const w = vision.walls[i]!
try {
const wall = WallNode.parse({
start: w.start,
end: w.end,
thickness: w.thickness ?? defaultWallThickness,
height: defaultWallHeight,
})
const linkedWall: AnyNodeT = {
...(wall as AnyNodeT),
parentId: levelId,
}
const validated = AnyNode.safeParse(linkedWall)
if (!validated.success) {
warnings.push(`wall[${i}] dropped: ${validated.error.message}`)
continue
}
nodes[wall.id as AnyNodeId] = validated.data as AnyNodeT
levelChildren.push(wall.id)
wallsAdded++
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
warnings.push(`wall[${i}] dropped: ${msg}`)
}
}
// Rooms → zones.
let roomsAdded = 0
for (let i = 0; i < vision.rooms.length; i++) {
const r = vision.rooms[i]!
try {
const zone = ZoneNode.parse({
name: r.name,
polygon: r.polygon,
})
const linkedZone: AnyNodeT = {
...(zone as AnyNodeT),
parentId: levelId,
}
const validated = AnyNode.safeParse(linkedZone)
if (!validated.success) {
warnings.push(`room[${i}] dropped: ${validated.error.message}`)
continue
}
nodes[zone.id as AnyNodeId] = validated.data as AnyNodeT
levelChildren.push(zone.id)
roomsAdded++
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
warnings.push(`room[${i}] dropped: ${msg}`)
}
}
// Finalise the level's children array now that walls/zones are in the dict.
;(linkedLevel as LevelNode).children = levelChildren as LevelNode['children']
const levelValidated = AnyNode.safeParse(linkedLevel)
if (!levelValidated.success) {
warnings.push(`level node failed schema validation: ${levelValidated.error.message}`)
}
nodes[levelId] = (levelValidated.success ? levelValidated.data : linkedLevel) as AnyNodeT
return {
nodes,
rootNodeIds: [siteId],
walls: wallsAdded,
rooms: roomsAdded,
warnings,
levelId,
}
}
export function registerPhotoToScene(
server: McpServer,
bridge: SceneBridge,
store: SceneStore,
): void {
server.registerTool(
'photo_to_scene',
{
title: 'Photo to Pascal scene',
description:
'Orchestrator: analyse a floor-plan photo via MCP sampling, translate the structured vision result into a Pascal SceneGraph (site → building → level with walls and zones), optionally save it, and swap the bridge to the new scene. Requires host support for sampling.',
inputSchema: photoToSceneInput,
outputSchema: photoToSceneOutput,
},
async ({ image, scaleHint, name, save, defaultWallThickness, defaultWallHeight }) => {
// 1. Vision.
const vision = await callVisionSampling(server, image, scaleHint)
// 2. Build scene graph.
const built = buildSceneGraphFromVision(vision, defaultWallThickness, defaultWallHeight)
const graph: SceneGraph = {
nodes: built.nodes as SceneGraph['nodes'],
rootNodeIds: built.rootNodeIds as SceneGraph['rootNodeIds'],
collections: {} as SceneGraph['collections'],
}
// 5. Swap the bridge to the new scene so follow-up MCP calls operate on it.
bridge.setScene(graph.nodes, graph.rootNodeIds)
const notes = built.warnings.length > 0 ? built.warnings.join('; ') : undefined
// 4. Save or return inline.
if (save) {
const meta = await store.save({
name,
graph,
})
const payload: {
sceneId: string
url: string
walls: number
rooms: number
confidence: number
notes?: string
} = {
sceneId: meta.id,
url: `/scene/${meta.id}`,
walls: built.walls,
rooms: built.rooms,
confidence: vision.confidence,
}
if (notes) payload.notes = notes
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
}
const payload: {
walls: number
rooms: number
confidence: number
notes?: string
graph: SceneGraph
} = {
walls: built.walls,
rooms: built.rooms,
confidence: vision.confidence,
graph,
}
if (notes) payload.notes = notes
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
},
)
}
@@ -0,0 +1,56 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { registerDeleteScene } from './delete-scene'
import { InMemorySceneStore, parseToolText, type StoredTextContent } from './test-utils'
const emptyGraph: SceneGraph = { nodes: {}, rootNodeIds: [] }
describe('delete_scene', () => {
let client: Client
let store: InMemorySceneStore
beforeEach(async () => {
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerDeleteScene(server, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('deletes an existing scene and returns { deleted: true }', async () => {
await store.save({ id: 'gone-in-60', name: 'Expendable', graph: emptyGraph })
const result = await client.callTool({
name: 'delete_scene',
arguments: { id: 'gone-in-60' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.deleted).toBe(true)
expect(await store.load('gone-in-60')).toBeNull()
})
test('throws scene_not_found when deleting an unknown id', async () => {
const result = await client.callTool({
name: 'delete_scene',
arguments: { id: 'ghost' },
})
expect(result.isError).toBe(true)
})
test('throws version_conflict when expectedVersion mismatches', async () => {
await store.save({ id: 'locked', name: 'Locked', graph: emptyGraph })
const result = await client.callTool({
name: 'delete_scene',
arguments: { id: 'locked', expectedVersion: 99 },
})
expect(result.isError).toBe(true)
// Still present after failed delete.
expect(await store.load('locked')).not.toBeNull()
})
})
@@ -0,0 +1,50 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import { SceneNotFoundError, type SceneStore, SceneVersionConflictError } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
export const deleteSceneInput = {
id: z.string().min(1).max(64),
expectedVersion: z.number().int().positive().optional(),
}
export const deleteSceneOutput = {
deleted: z.boolean(),
}
export function registerDeleteScene(server: McpServer, store: SceneStore): void {
server.registerTool(
'delete_scene',
{
title: 'Delete scene',
description:
'Delete a scene from the SceneStore by id. Optionally pass `expectedVersion` for optimistic concurrency.',
inputSchema: deleteSceneInput,
outputSchema: deleteSceneOutput,
},
async ({ id, expectedVersion }) => {
try {
const deleted = await store.delete(id, {
...(expectedVersion !== undefined ? { expectedVersion } : {}),
})
const payload = { deleted }
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
} catch (err) {
if (err instanceof SceneNotFoundError) {
throwMcpError(ErrorCode.InvalidParams, 'scene_not_found', { id })
}
if (err instanceof SceneVersionConflictError) {
throwMcpError(ErrorCode.InvalidRequest, 'version_conflict', {
id,
expectedVersion,
})
}
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, msg)
}
},
)
}
@@ -0,0 +1,32 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { registerDeleteScene } from './delete-scene'
import { registerListScenes } from './list-scenes'
import { registerLoadScene } from './load-scene'
import { registerRenameScene } from './rename-scene'
import { registerSaveScene } from './save-scene'
/**
* Register the scene-lifecycle MCP tools (`save_scene`, `load_scene`,
* `list_scenes`, `delete_scene`, `rename_scene`) against the given server.
* All tools operate against the supplied `SceneStore` so tests can inject an
* in-memory implementation.
*/
export function registerSceneLifecycleTools(
server: McpServer,
bridge: SceneBridge,
store: SceneStore,
): void {
registerSaveScene(server, bridge, store)
registerLoadScene(server, bridge, store)
registerListScenes(server, store)
registerDeleteScene(server, store)
registerRenameScene(server, store)
}
export { deleteSceneInput, deleteSceneOutput, registerDeleteScene } from './delete-scene'
export { listScenesInput, listScenesOutput, registerListScenes } from './list-scenes'
export { loadSceneInput, loadSceneOutput, registerLoadScene } from './load-scene'
export { registerRenameScene, renameSceneInput, renameSceneOutput } from './rename-scene'
export { registerSaveScene, saveSceneInput, saveSceneOutput } from './save-scene'
@@ -0,0 +1,73 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { registerListScenes } from './list-scenes'
import { InMemorySceneStore, parseToolText, type StoredTextContent } from './test-utils'
const emptyGraph: SceneGraph = { nodes: {}, rootNodeIds: [] }
describe('list_scenes', () => {
let client: Client
let store: InMemorySceneStore
beforeEach(async () => {
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerListScenes(server, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('returns all saved scenes by default', async () => {
await store.save({ id: 'a', name: 'A', graph: emptyGraph })
await store.save({ id: 'b', name: 'B', graph: emptyGraph })
const result = await client.callTool({
name: 'list_scenes',
arguments: {},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
const scenes = parsed.scenes as unknown[]
expect(scenes).toHaveLength(2)
})
test('filters by projectId', async () => {
await store.save({ id: 'a', name: 'A', projectId: 'p1', graph: emptyGraph })
await store.save({ id: 'b', name: 'B', projectId: 'p2', graph: emptyGraph })
const result = await client.callTool({
name: 'list_scenes',
arguments: { projectId: 'p1' },
})
const parsed = parseToolText(result.content as StoredTextContent[])
const scenes = parsed.scenes as { id: string }[]
expect(scenes).toHaveLength(1)
expect(scenes[0]!.id).toBe('a')
})
test('rejects non-positive limit per schema', async () => {
const result = await client.callTool({
name: 'list_scenes',
arguments: { limit: 0 },
})
expect(result.isError).toBe(true)
})
test('caps results with limit', async () => {
await store.save({ id: 'a', name: 'A', graph: emptyGraph })
await store.save({ id: 'b', name: 'B', graph: emptyGraph })
await store.save({ id: 'c', name: 'C', graph: emptyGraph })
const result = await client.callTool({
name: 'list_scenes',
arguments: { limit: 2 },
})
const parsed = parseToolText(result.content as StoredTextContent[])
const scenes = parsed.scenes as unknown[]
expect(scenes).toHaveLength(2)
})
})
@@ -0,0 +1,57 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import type { SceneStore } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
const DEFAULT_LIMIT = 100
export const listScenesInput = {
projectId: z.string().optional(),
limit: z.number().int().positive().max(1000).optional(),
}
export const listScenesOutput = {
scenes: z.array(
z.object({
id: z.string(),
name: z.string(),
projectId: z.string().nullable(),
thumbnailUrl: z.string().nullable(),
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
ownerId: z.string().nullable(),
sizeBytes: z.number(),
nodeCount: z.number(),
}),
),
}
export function registerListScenes(server: McpServer, store: SceneStore): void {
server.registerTool(
'list_scenes',
{
title: 'List scenes',
description:
'List scenes in the SceneStore. Optionally filter by `projectId` and cap results with `limit` (default 100).',
inputSchema: listScenesInput,
outputSchema: listScenesOutput,
},
async ({ projectId, limit }) => {
try {
const scenes = await store.list({
...(projectId !== undefined ? { projectId } : {}),
limit: limit ?? DEFAULT_LIMIT,
})
const payload = { scenes }
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, msg)
}
},
)
}
@@ -0,0 +1,64 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { SceneBridge } from '../../bridge/scene-bridge'
import { registerLoadScene } from './load-scene'
import { InMemorySceneStore, parseToolText, type StoredTextContent } from './test-utils'
describe('load_scene', () => {
let client: Client
let bridge: SceneBridge
let store: InMemorySceneStore
beforeEach(async () => {
bridge = new SceneBridge()
bridge.setScene({}, [])
bridge.loadDefault()
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerLoadScene(server, bridge, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('loads a stored scene and returns its SceneMeta', async () => {
const graph = {
nodes: {
root_a: { id: 'root_a', type: 'site', parentId: null, children: [] },
},
rootNodeIds: ['root_a'],
} as unknown as SceneGraph
const meta = await store.save({ id: 'scene-one', name: 'One', graph })
const result = await client.callTool({
name: 'load_scene',
arguments: { id: 'scene-one' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.id).toBe('scene-one')
expect(parsed.name).toBe('One')
expect(parsed.version).toBe(meta.version)
expect(bridge.getRootNodeIds()).toContain('root_a')
})
test('throws scene_not_found when id is unknown', async () => {
const result = await client.callTool({
name: 'load_scene',
arguments: { id: 'does-not-exist' },
})
expect(result.isError).toBe(true)
})
test('rejects empty id per schema', async () => {
const result = await client.callTool({
name: 'load_scene',
arguments: { id: '' },
})
expect(result.isError).toBe(true)
})
})
@@ -0,0 +1,63 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
export const loadSceneInput = {
id: z.string().min(1).max(64),
}
export const loadSceneOutput = {
id: z.string(),
name: z.string(),
projectId: z.string().nullable(),
thumbnailUrl: z.string().nullable(),
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
ownerId: z.string().nullable(),
sizeBytes: z.number(),
nodeCount: z.number(),
}
export function registerLoadScene(server: McpServer, bridge: SceneBridge, store: SceneStore): void {
server.registerTool(
'load_scene',
{
title: 'Load scene',
description:
'Load a scene from the SceneStore into the bridge. Returns the scene metadata. Throws `scene_not_found` if the id does not exist.',
inputSchema: loadSceneInput,
outputSchema: loadSceneOutput,
},
async ({ id }) => {
const result = await store.load(id)
if (!result) {
throwMcpError(ErrorCode.InvalidParams, 'scene_not_found', { id })
}
try {
bridge.loadJSON(result.graph)
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InvalidRequest, `load_failed: ${msg}`, { id })
}
const payload = {
id: result.id,
name: result.name,
projectId: result.projectId,
thumbnailUrl: result.thumbnailUrl,
version: result.version,
createdAt: result.createdAt,
updatedAt: result.updatedAt,
ownerId: result.ownerId,
sizeBytes: result.sizeBytes,
nodeCount: result.nodeCount,
}
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
},
)
}
@@ -0,0 +1,59 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { registerRenameScene } from './rename-scene'
import { InMemorySceneStore, parseToolText, type StoredTextContent } from './test-utils'
const emptyGraph: SceneGraph = { nodes: {}, rootNodeIds: [] }
describe('rename_scene', () => {
let client: Client
let store: InMemorySceneStore
beforeEach(async () => {
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerRenameScene(server, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('renames a scene and returns the new SceneMeta', async () => {
await store.save({ id: 'to-rename', name: 'Old Name', graph: emptyGraph })
const result = await client.callTool({
name: 'rename_scene',
arguments: { id: 'to-rename', newName: 'Brand New Name' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.id).toBe('to-rename')
expect(parsed.name).toBe('Brand New Name')
expect(parsed.version).toBe(2)
})
test('throws scene_not_found for missing ids', async () => {
const result = await client.callTool({
name: 'rename_scene',
arguments: { id: 'ghost', newName: 'Does Not Matter' },
})
expect(result.isError).toBe(true)
})
test('throws version_conflict when expectedVersion mismatches', async () => {
await store.save({ id: 'locked-name', name: 'Stable', graph: emptyGraph })
const result = await client.callTool({
name: 'rename_scene',
arguments: {
id: 'locked-name',
newName: 'Attempted',
expectedVersion: 42,
},
})
expect(result.isError).toBe(true)
})
})
@@ -0,0 +1,71 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import { SceneNotFoundError, type SceneStore, SceneVersionConflictError } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
export const renameSceneInput = {
id: z.string().min(1).max(64),
newName: z.string().min(1).max(200),
expectedVersion: z.number().int().positive().optional(),
}
export const renameSceneOutput = {
id: z.string(),
name: z.string(),
projectId: z.string().nullable(),
thumbnailUrl: z.string().nullable(),
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
ownerId: z.string().nullable(),
sizeBytes: z.number(),
nodeCount: z.number(),
}
export function registerRenameScene(server: McpServer, store: SceneStore): void {
server.registerTool(
'rename_scene',
{
title: 'Rename scene',
description:
'Rename a scene in the SceneStore. Returns the updated SceneMeta. Optionally pass `expectedVersion` for optimistic concurrency.',
inputSchema: renameSceneInput,
outputSchema: renameSceneOutput,
},
async ({ id, newName, expectedVersion }) => {
try {
const meta = await store.rename(id, newName, {
...(expectedVersion !== undefined ? { expectedVersion } : {}),
})
const payload = {
id: meta.id,
name: meta.name,
projectId: meta.projectId,
thumbnailUrl: meta.thumbnailUrl,
version: meta.version,
createdAt: meta.createdAt,
updatedAt: meta.updatedAt,
ownerId: meta.ownerId,
sizeBytes: meta.sizeBytes,
nodeCount: meta.nodeCount,
}
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
} catch (err) {
if (err instanceof SceneNotFoundError) {
throwMcpError(ErrorCode.InvalidParams, 'scene_not_found', { id })
}
if (err instanceof SceneVersionConflictError) {
throwMcpError(ErrorCode.InvalidRequest, 'version_conflict', {
id,
expectedVersion,
})
}
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, msg)
}
},
)
}
@@ -0,0 +1,83 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { SceneBridge } from '../../bridge/scene-bridge'
import { registerSaveScene } from './save-scene'
import { InMemorySceneStore, parseToolText, type StoredTextContent } from './test-utils'
describe('save_scene', () => {
let client: Client
let bridge: SceneBridge
let store: InMemorySceneStore
beforeEach(async () => {
bridge = new SceneBridge()
bridge.setScene({}, [])
bridge.loadDefault()
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerSaveScene(server, bridge, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('saves the current scene and returns SceneMeta with url', async () => {
const result = await client.callTool({
name: 'save_scene',
arguments: { name: 'My Scene' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.name).toBe('My Scene')
expect(typeof parsed.id).toBe('string')
expect(parsed.version).toBe(1)
expect(parsed.url).toBe(`/scene/${parsed.id}`)
expect(parsed.nodeCount).toBeGreaterThan(0)
})
test('saves a provided graph when includeCurrentScene is false', async () => {
const graph = {
nodes: { root: { id: 'root', type: 'site', parentId: null, children: [] } },
rootNodeIds: ['root'],
}
const result = await client.callTool({
name: 'save_scene',
arguments: {
name: 'From Graph',
includeCurrentScene: false,
graph,
},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.name).toBe('From Graph')
expect(parsed.nodeCount).toBe(1)
})
test('errors when includeCurrentScene is false and no graph is provided', async () => {
const result = await client.callTool({
name: 'save_scene',
arguments: { name: 'No Graph', includeCurrentScene: false },
})
expect(result.isError).toBe(true)
})
test('returns version_conflict when expectedVersion mismatches', async () => {
const first = await client.callTool({
name: 'save_scene',
arguments: { name: 'Original' },
})
const parsed = parseToolText(first.content as StoredTextContent[])
const result = await client.callTool({
name: 'save_scene',
arguments: {
id: parsed.id as string,
name: 'Second',
expectedVersion: 99,
},
})
expect(result.isError).toBe(true)
})
})
@@ -0,0 +1,111 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { z } from 'zod'
import type { SceneBridge } from '../../bridge/scene-bridge'
import { type SceneStore, SceneVersionConflictError } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
export const saveSceneInput = {
id: z.string().min(1).max(64).optional(),
name: z.string().min(1).max(200),
projectId: z.string().optional(),
expectedVersion: z.number().int().positive().optional(),
thumbnail: z.string().url().optional(),
includeCurrentScene: z
.boolean()
.default(true)
.describe('If true, save the bridge current scene. If false, use the graph arg.'),
graph: z
.record(z.string(), z.unknown())
.optional()
.describe(
'Full SceneGraph { nodes, rootNodeIds, collections? } to save instead of the bridge state.',
),
}
export const saveSceneOutput = {
id: z.string(),
name: z.string(),
projectId: z.string().nullable(),
thumbnailUrl: z.string().nullable(),
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
ownerId: z.string().nullable(),
sizeBytes: z.number(),
nodeCount: z.number(),
url: z.string(),
}
export function registerSaveScene(server: McpServer, bridge: SceneBridge, store: SceneStore): void {
server.registerTool(
'save_scene',
{
title: 'Save scene',
description:
'Persist the current scene (or a provided graph) to the SceneStore. Returns the SceneMeta along with a `url` pointing to `/scene/<id>`.',
inputSchema: saveSceneInput,
outputSchema: saveSceneOutput,
},
async ({ id, name, projectId, expectedVersion, thumbnail, includeCurrentScene, graph }) => {
let sceneGraph: SceneGraph
if (includeCurrentScene) {
const validation = bridge.validateScene()
if (!validation.valid) {
throwMcpError(ErrorCode.InvalidRequest, 'scene_invalid', { errors: validation.errors })
}
const exported = bridge.exportJSON()
sceneGraph = {
nodes: exported.nodes,
rootNodeIds: exported.rootNodeIds,
collections: exported.collections as SceneGraph['collections'],
}
} else {
if (!graph) {
throwMcpError(
ErrorCode.InvalidParams,
'graph_required: pass `graph` when includeCurrentScene is false',
)
}
sceneGraph = graph as unknown as SceneGraph
}
try {
const meta = await store.save({
...(id !== undefined ? { id } : {}),
name,
...(projectId !== undefined ? { projectId } : {}),
graph: sceneGraph,
...(thumbnail !== undefined ? { thumbnailUrl: thumbnail } : {}),
...(expectedVersion !== undefined ? { expectedVersion } : {}),
})
const payload = {
id: meta.id,
name: meta.name,
projectId: meta.projectId,
thumbnailUrl: meta.thumbnailUrl,
version: meta.version,
createdAt: meta.createdAt,
updatedAt: meta.updatedAt,
ownerId: meta.ownerId,
sizeBytes: meta.sizeBytes,
nodeCount: meta.nodeCount,
url: `/scene/${meta.id}`,
}
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
} catch (err) {
if (err instanceof SceneVersionConflictError) {
throwMcpError(ErrorCode.InvalidRequest, 'version_conflict', {
expectedVersion,
id,
})
}
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InvalidRequest, msg)
}
},
)
}
@@ -0,0 +1,146 @@
import {
type SceneListOptions,
type SceneMeta,
type SceneMutateOptions,
SceneNotFoundError,
type SceneSaveOptions,
type SceneStore,
SceneVersionConflictError,
type SceneWithGraph,
} from '../../storage/types'
export type StoredTextContent = { type: string; text: string }
export function parseToolText(content: StoredTextContent[]): Record<string, unknown> {
return JSON.parse(content[0]!.text) as Record<string, unknown>
}
/**
* In-memory `SceneStore` for tests. Backed by a plain `Map` keyed by id.
* Implements the full interface including optimistic concurrency via
* `expectedVersion`.
*/
export class InMemorySceneStore implements SceneStore {
readonly backend = 'filesystem' as const
private readonly data = new Map<string, SceneWithGraph>()
private idCounter = 0
async save(opts: SceneSaveOptions): Promise<SceneMeta> {
const existing = opts.id ? this.data.get(opts.id) : undefined
if (existing) {
if (opts.expectedVersion !== undefined && existing.version !== opts.expectedVersion) {
throw new SceneVersionConflictError(
`Expected version ${opts.expectedVersion}, have ${existing.version}`,
)
}
const now = new Date().toISOString()
const nodeCount = Object.keys(opts.graph.nodes ?? {}).length
const serialized = JSON.stringify(opts.graph)
const updated: SceneWithGraph = {
id: existing.id,
name: opts.name,
projectId: opts.projectId ?? existing.projectId,
thumbnailUrl: opts.thumbnailUrl ?? existing.thumbnailUrl,
version: existing.version + 1,
createdAt: existing.createdAt,
updatedAt: now,
ownerId: opts.ownerId ?? existing.ownerId,
sizeBytes: serialized.length,
nodeCount,
graph: opts.graph,
}
this.data.set(existing.id, updated)
return this.toMeta(updated)
}
if (opts.expectedVersion !== undefined) {
throw new SceneVersionConflictError('Cannot pass expectedVersion for a new scene')
}
const id = opts.id ?? `scene_${++this.idCounter}`
const now = new Date().toISOString()
const serialized = JSON.stringify(opts.graph)
const nodeCount = Object.keys(opts.graph.nodes ?? {}).length
const record: SceneWithGraph = {
id,
name: opts.name,
projectId: opts.projectId ?? null,
thumbnailUrl: opts.thumbnailUrl ?? null,
version: 1,
createdAt: now,
updatedAt: now,
ownerId: opts.ownerId ?? null,
sizeBytes: serialized.length,
nodeCount,
graph: opts.graph,
}
this.data.set(id, record)
return this.toMeta(record)
}
async load(id: string): Promise<SceneWithGraph | null> {
const rec = this.data.get(id)
if (!rec) return null
return {
...rec,
graph: JSON.parse(JSON.stringify(rec.graph)),
}
}
async list(opts?: SceneListOptions): Promise<SceneMeta[]> {
let scenes = Array.from(this.data.values()).map((r) => this.toMeta(r))
if (opts?.projectId !== undefined) {
scenes = scenes.filter((s) => s.projectId === opts.projectId)
}
if (opts?.ownerId !== undefined) {
scenes = scenes.filter((s) => s.ownerId === opts.ownerId)
}
scenes.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1))
if (opts?.limit !== undefined) scenes = scenes.slice(0, opts.limit)
return scenes
}
async delete(id: string, opts?: SceneMutateOptions): Promise<boolean> {
const rec = this.data.get(id)
if (!rec) throw new SceneNotFoundError(`Scene ${id} not found`)
if (opts?.expectedVersion !== undefined && rec.version !== opts.expectedVersion) {
throw new SceneVersionConflictError(
`Expected version ${opts.expectedVersion}, have ${rec.version}`,
)
}
return this.data.delete(id)
}
async rename(id: string, newName: string, opts?: SceneMutateOptions): Promise<SceneMeta> {
const rec = this.data.get(id)
if (!rec) throw new SceneNotFoundError(`Scene ${id} not found`)
if (opts?.expectedVersion !== undefined && rec.version !== opts.expectedVersion) {
throw new SceneVersionConflictError(
`Expected version ${opts.expectedVersion}, have ${rec.version}`,
)
}
const updated: SceneWithGraph = {
...rec,
name: newName,
version: rec.version + 1,
updatedAt: new Date().toISOString(),
}
this.data.set(id, updated)
return this.toMeta(updated)
}
private toMeta(rec: SceneWithGraph): SceneMeta {
return {
id: rec.id,
name: rec.name,
projectId: rec.projectId,
thumbnailUrl: rec.thumbnailUrl,
version: rec.version,
createdAt: rec.createdAt,
updatedAt: rec.updatedAt,
ownerId: rec.ownerId,
sizeBytes: rec.sizeBytes,
nodeCount: rec.nodeCount,
}
}
}
@@ -0,0 +1,154 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { cloneSceneGraph } from '@pascal-app/core/clone-scene-graph'
import type { AnyNode, AnyNodeId } from '@pascal-app/core/schema'
import { z } from 'zod'
import type { SceneBridge } from '../../bridge/scene-bridge'
import { rehydrateSiteChildren } from '../../lib/rehydrate-site-children'
import type { SceneStore } from '../../storage/types'
import { isTemplateId, TEMPLATES, type TemplateId } from '../../templates'
import { ErrorCode, throwMcpError } from '../errors'
export const createFromTemplateInput = {
id: z
.string()
.describe(
'Template id (see `list_templates`). Currently one of: "empty-studio", "two-bedroom", "garden-house".',
),
name: z
.string()
.min(1)
.max(200)
.optional()
.describe('Optional display name for the saved scene. Defaults to the template name.'),
/**
* When a `SceneStore` is wired into the MCP server, set this flag to `true`
* to immediately save the instantiated template and return its `SceneMeta`.
* When `false` (default) the template is applied to the bridge only.
*/
save: z.boolean().default(false),
projectId: z.string().optional(),
}
export const createFromTemplateOutput = {
templateId: z.string(),
rootNodeIds: z.array(z.string()),
nodeCount: z.number(),
/** Present when `save: true` (and a store was available). */
scene: z
.object({
id: z.string(),
name: z.string(),
projectId: z.string().nullable(),
thumbnailUrl: z.string().nullable(),
version: z.number(),
createdAt: z.string(),
updatedAt: z.string(),
ownerId: z.string().nullable(),
sizeBytes: z.number(),
nodeCount: z.number(),
url: z.string(),
})
.optional(),
}
/**
* `create_from_template` — instantiate a seed template into the bridge, and
* optionally persist it via the attached `SceneStore`.
*
* The source template is cloned with fresh ids (`cloneSceneGraph`) so the
* deterministic placeholders (`site_empty`, `wall_n`, …) don't collide
* across repeated calls or with other scenes.
*/
export function registerCreateFromTemplate(
server: McpServer,
bridge: SceneBridge,
store?: SceneStore,
): void {
server.registerTool(
'create_from_template',
{
title: 'Create scene from template',
description:
'Instantiate a seed Pascal scene template into the bridge. Regenerates all ids before applying. When `save: true` and a SceneStore is wired, also persists the new scene and returns the SceneMeta.',
inputSchema: createFromTemplateInput,
outputSchema: createFromTemplateOutput,
},
async ({ id, name, save, projectId }) => {
if (!isTemplateId(id)) {
throwMcpError(
ErrorCode.InvalidParams,
`unknown_template: ${id}. Call list_templates for the set of valid ids.`,
)
}
const entry = TEMPLATES[id as TemplateId]
// Clone: regenerate ids so each instantiation is independent.
// `cloneSceneGraph` flattens SiteNode.children to string ids; rehydrate
// them back to embedded objects to satisfy the SiteNode schema (see
// CROSS_CUTTING §2).
const cloned = rehydrateSiteChildren(cloneSceneGraph(entry.template))
const nodes = cloned.nodes as Record<AnyNodeId, AnyNode>
const rootNodeIds = cloned.rootNodeIds as AnyNodeId[]
try {
bridge.setScene(nodes, rootNodeIds)
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, `apply_failed: ${msg}`)
}
const basePayload = {
templateId: entry.id,
rootNodeIds: rootNodeIds as string[],
nodeCount: Object.keys(nodes).length,
}
if (!save) {
return {
content: [{ type: 'text' as const, text: JSON.stringify(basePayload) }],
structuredContent: basePayload,
}
}
if (!store) {
// Graceful no-store mode: report that save was skipped rather than
// erroring — this makes the tool usable in headless bridge-only
// deployments (tests, smoke scripts) without crashing.
const payload = { ...basePayload, saveSkipped: true } as const
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: basePayload,
}
}
try {
const meta = await store.save({
name: name ?? entry.name,
...(projectId !== undefined ? { projectId } : {}),
graph: { nodes, rootNodeIds },
})
const scene = {
id: meta.id,
name: meta.name,
projectId: meta.projectId,
thumbnailUrl: meta.thumbnailUrl,
version: meta.version,
createdAt: meta.createdAt,
updatedAt: meta.updatedAt,
ownerId: meta.ownerId,
sizeBytes: meta.sizeBytes,
nodeCount: meta.nodeCount,
url: `/scene/${meta.id}`,
}
const payload = { ...basePayload, scene }
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, `save_failed: ${msg}`)
}
},
)
}
+33
View File
@@ -0,0 +1,33 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { registerCreateFromTemplate } from './create-from-template'
import { registerListTemplates } from './list-templates'
/**
* Register the template MCP tools (`list_templates`, `create_from_template`)
* against the given server.
*
* `store` is optional: when omitted, `create_from_template` still applies the
* template to the bridge but skips the save step. This makes the tool safe
* to wire into headless bridge-only deployments.
*/
export function registerTemplateTools(
server: McpServer,
bridge: SceneBridge,
store?: SceneStore,
): void {
registerListTemplates(server)
registerCreateFromTemplate(server, bridge, store)
}
export {
createFromTemplateInput,
createFromTemplateOutput,
registerCreateFromTemplate,
} from './create-from-template'
export {
listTemplatesInput,
listTemplatesOutput,
registerListTemplates,
} from './list-templates'
@@ -0,0 +1,47 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { z } from 'zod'
import { TEMPLATES } from '../../templates'
export const listTemplatesInput = {} as const
export const listTemplatesOutput = {
templates: z.array(
z.object({
id: z.string(),
name: z.string(),
description: z.string(),
nodeCount: z.number(),
}),
),
}
/**
* `list_templates` — enumerate the seed templates shipped with the MCP server.
* Stateless; used by the `from_brief` prompt and by the UI to populate a
* "start from a template" picker.
*/
export function registerListTemplates(server: McpServer): void {
server.registerTool(
'list_templates',
{
title: 'List scene templates',
description:
'List the seed Pascal scene templates available to `create_from_template`. Returns the id, display name, one-line description and node count for each.',
inputSchema: listTemplatesInput,
outputSchema: listTemplatesOutput,
},
async () => {
const templates = Object.values(TEMPLATES).map((entry) => ({
id: entry.id,
name: entry.name,
description: entry.description,
nodeCount: Object.keys(entry.template.nodes).length,
}))
const payload = { templates }
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
},
)
}
@@ -0,0 +1,169 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { SceneBridge } from '../../bridge/scene-bridge'
import {
InMemorySceneStore,
parseToolText,
type StoredTextContent,
} from '../scene-lifecycle/test-utils'
import { registerCreateFromTemplate } from './create-from-template'
import { registerListTemplates } from './list-templates'
describe('list_templates', () => {
let client: Client
beforeEach(async () => {
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerListTemplates(server)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('enumerates all three seed templates', async () => {
const result = await client.callTool({ name: 'list_templates', arguments: {} })
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
const list = parsed.templates as Array<{
id: string
name: string
description: string
nodeCount: number
}>
const ids = list.map((t) => t.id).sort()
expect(ids).toEqual(['empty-studio', 'garden-house', 'two-bedroom'])
for (const t of list) {
expect(typeof t.name).toBe('string')
expect(t.name.length).toBeGreaterThan(0)
expect(typeof t.description).toBe('string')
expect(t.nodeCount).toBeGreaterThan(0)
}
})
test('returns structuredContent matching the text payload', async () => {
const result = await client.callTool({ name: 'list_templates', arguments: {} })
expect(result.structuredContent).toBeDefined()
const structured = result.structuredContent as { templates: Array<{ id: string }> }
expect(structured.templates.length).toBe(3)
})
})
describe('create_from_template', () => {
let client: Client
let bridge: SceneBridge
let store: InMemorySceneStore
beforeEach(async () => {
bridge = new SceneBridge()
bridge.setScene({}, [])
store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerCreateFromTemplate(server, bridge, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('applies a template to the bridge with fresh ids', async () => {
const result = await client.callTool({
name: 'create_from_template',
arguments: { id: 'empty-studio' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.templateId).toBe('empty-studio')
expect((parsed.rootNodeIds as string[]).length).toBeGreaterThan(0)
expect(parsed.nodeCount as number).toBeGreaterThan(0)
// Fresh ids — placeholder "site_empty" should not appear.
const bridgeNodes = Object.keys(bridge.getNodes())
expect(bridgeNodes).not.toContain('site_empty')
expect(bridgeNodes.length).toBeGreaterThan(0)
// Root id from the tool response should exist in the bridge.
for (const rid of parsed.rootNodeIds as string[]) {
expect(bridge.getNode(rid as any)).not.toBeNull()
}
})
test('rejects unknown template ids', async () => {
const result = await client.callTool({
name: 'create_from_template',
arguments: { id: 'not-a-template' },
})
expect(result.isError).toBe(true)
})
test('saves to the store when save: true', async () => {
const result = await client.callTool({
name: 'create_from_template',
arguments: { id: 'two-bedroom', save: true, name: 'My flat' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.scene).toBeDefined()
const scene = parsed.scene as { id: string; name: string; url: string; nodeCount: number }
expect(scene.name).toBe('My flat')
expect(scene.url).toBe(`/scene/${scene.id}`)
expect(scene.nodeCount).toBeGreaterThan(0)
// Confirm the store actually holds it.
const loaded = await store.load(scene.id)
expect(loaded).not.toBeNull()
})
test('two invocations produce disjoint id sets', async () => {
const a = await client.callTool({
name: 'create_from_template',
arguments: { id: 'empty-studio' },
})
const idsA = (parseToolText(a.content as StoredTextContent[]).rootNodeIds as string[]).sort()
const b = await client.callTool({
name: 'create_from_template',
arguments: { id: 'empty-studio' },
})
const idsB = (parseToolText(b.content as StoredTextContent[]).rootNodeIds as string[]).sort()
for (const id of idsA) {
expect(idsB).not.toContain(id)
}
})
})
describe('create_from_template without a store', () => {
let client: Client
let bridge: SceneBridge
beforeEach(async () => {
bridge = new SceneBridge()
bridge.setScene({}, [])
const server = new McpServer({ name: 'test', version: '0.0.0' })
// No store passed → save should be gracefully skipped.
registerCreateFromTemplate(server, bridge)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
})
test('applies a template without erroring when no store is wired', async () => {
const result = await client.callTool({
name: 'create_from_template',
arguments: { id: 'garden-house' },
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.templateId).toBe('garden-house')
})
test('save:true is a no-op but still succeeds without a store', async () => {
const result = await client.callTool({
name: 'create_from_template',
arguments: { id: 'garden-house', save: true },
})
// Does not error; no `scene` field is returned because there is no store.
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[])
expect(parsed.scene).toBeUndefined()
})
})
@@ -0,0 +1,295 @@
import { beforeEach, describe, expect, test } from 'bun:test'
import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { type AnyNodeId, AnyNode as AnyNodeSchema } from '@pascal-app/core/schema'
import { SceneBridge } from '../../bridge/scene-bridge'
import {
InMemorySceneStore,
parseToolText,
type StoredTextContent,
} from '../scene-lifecycle/test-utils'
import { registerGenerateVariants } from './generate-variants'
type Variant = {
index: number
description: string
nodeCount: number
sceneId?: string
url?: string
graph?: SceneGraph
}
function emptyBase(): SceneGraph {
return {
nodes: {
site_empty: {
object: 'node',
id: 'site_empty',
type: 'site',
parentId: null,
visible: true,
metadata: {},
polygon: {
type: 'polygon',
points: [
[-5, -5],
[5, -5],
[5, 5],
[-5, 5],
],
},
children: [],
},
} as unknown as SceneGraph['nodes'],
rootNodeIds: ['site_empty'] as AnyNodeId[],
}
}
async function setup(): Promise<{
client: Client
bridge: SceneBridge
store: InMemorySceneStore
}> {
const bridge = new SceneBridge()
bridge.setScene({}, [])
bridge.loadDefault()
const store = new InMemorySceneStore()
const server = new McpServer({ name: 'test', version: '0.0.0' })
registerGenerateVariants(server, bridge, store)
const [srvT, cliT] = InMemoryTransport.createLinkedPair()
const client = new Client({ name: 'test-client', version: '0.0.0' })
await Promise.all([server.connect(srvT), client.connect(cliT)])
return { client, bridge, store }
}
describe('generate_variants', () => {
let client: Client
let bridge: SceneBridge
let store: InMemorySceneStore
beforeEach(async () => {
;({ client, bridge, store } = await setup())
})
test('happy path: returns count variants that exercise the mutation', async () => {
// Seed the bridge scene with some walls of known thickness.
const base = bridge.exportJSON()
// Find the level and add a couple of walls.
const level = Object.values(base.nodes).find((n) => n.type === 'level')
expect(level).toBeDefined()
const withWalls: SceneGraph = {
nodes: {
...base.nodes,
wall_1: {
object: 'node',
id: 'wall_1',
type: 'wall',
parentId: level?.id ?? null,
visible: true,
metadata: {},
start: [0, 0],
end: [5, 0],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_2: {
object: 'node',
id: 'wall_2',
type: 'wall',
parentId: level?.id ?? null,
visible: true,
metadata: {},
start: [0, 5],
end: [5, 5],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
} as unknown as SceneGraph['nodes'],
rootNodeIds: base.rootNodeIds,
}
bridge.setScene(withWalls.nodes, withWalls.rootNodeIds)
const result = await client.callTool({
name: 'generate_variants',
arguments: {
count: 3,
vary: ['wall-thickness'],
seed: 42,
},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
expect(parsed.variants.length).toBe(3)
for (const v of parsed.variants) {
expect(v.graph).toBeDefined()
// Every wall's thickness is in the allowed set.
const allowed = new Set([0.1, 0.15, 0.2, 0.25])
for (const node of Object.values((v.graph as SceneGraph).nodes)) {
if (node.type !== 'wall') continue
expect(allowed.has((node as { thickness: number }).thickness)).toBe(true)
}
}
})
test('deterministic: same seed yields same mutation outputs', async () => {
// Seed walls so the mutation has something to act on.
const base = bridge.exportJSON()
const level = Object.values(base.nodes).find((n) => n.type === 'level')
const withWalls: SceneGraph = {
nodes: {
...base.nodes,
wall_a: {
object: 'node',
id: 'wall_a',
type: 'wall',
parentId: level?.id ?? null,
visible: true,
metadata: {},
start: [0, 0],
end: [4, 0],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_b: {
object: 'node',
id: 'wall_b',
type: 'wall',
parentId: level?.id ?? null,
visible: true,
metadata: {},
start: [0, 4],
end: [4, 4],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
} as unknown as SceneGraph['nodes'],
rootNodeIds: base.rootNodeIds,
}
bridge.setScene(withWalls.nodes, withWalls.rootNodeIds)
const args = { count: 2, vary: ['wall-thickness'], seed: 123 }
const r1 = await client.callTool({ name: 'generate_variants', arguments: args })
const r2 = await client.callTool({ name: 'generate_variants', arguments: args })
const p1 = parseToolText(r1.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
const p2 = parseToolText(r2.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
expect(p1.variants.length).toBe(p2.variants.length)
// Compare the mutated fields (not the ids, which fresh-nanoid each time).
function wallThicknesses(g: SceneGraph): number[] {
return Object.values(g.nodes)
.filter((n) => n.type === 'wall')
.map((w) => (w as { thickness: number }).thickness)
.sort()
}
for (let i = 0; i < p1.variants.length; i++) {
const t1 = wallThicknesses(p1.variants[i]?.graph as SceneGraph)
const t2 = wallThicknesses(p2.variants[i]?.graph as SceneGraph)
expect(t1).toEqual(t2)
}
})
test('no-op: empty scene + wall-thickness still returns count graphs, unchanged', async () => {
const graph = emptyBase()
// Save, then reference by id.
const meta = await store.save({ name: 'empty', graph })
const result = await client.callTool({
name: 'generate_variants',
arguments: {
baseSceneId: meta.id,
count: 3,
vary: ['wall-thickness'],
seed: 99,
},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
expect(parsed.variants.length).toBe(3)
for (const v of parsed.variants) {
const g = v.graph as SceneGraph
expect(g).toBeDefined()
// No walls were present — so node counts should match the (forked) base.
expect(Object.keys(g.nodes).length).toBe(Object.keys(graph.nodes).length)
}
})
test('save=true: each variant gets a sceneId and url', async () => {
const result = await client.callTool({
name: 'generate_variants',
arguments: {
count: 2,
vary: ['wall-thickness'],
seed: 55,
save: true,
},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
expect(parsed.variants.length).toBe(2)
for (const v of parsed.variants) {
expect(typeof v.sceneId).toBe('string')
expect(v.url).toBe(`/scene/${v.sceneId}`)
// Inline graph should be omitted.
expect(v.graph).toBeUndefined()
}
const listed = await store.list()
expect(listed.length).toBe(2)
})
test('baseSceneId not found returns an error', async () => {
const result = await client.callTool({
name: 'generate_variants',
arguments: {
baseSceneId: 'scene_does_not_exist',
count: 2,
vary: ['wall-thickness'],
seed: 1,
},
})
expect(result.isError).toBe(true)
})
test('every returned variant validates against AnyNode', async () => {
const result = await client.callTool({
name: 'generate_variants',
arguments: {
count: 3,
vary: ['wall-thickness', 'wall-height'],
seed: 7,
},
})
expect(result.isError).toBeFalsy()
const parsed = parseToolText(result.content as StoredTextContent[]) as unknown as {
variants: Variant[]
}
for (const v of parsed.variants) {
const g = v.graph as SceneGraph
for (const node of Object.values(g.nodes)) {
const res = AnyNodeSchema.safeParse(node)
expect(res.success).toBe(true)
}
}
})
})
@@ -0,0 +1,197 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { forkSceneGraph, type SceneGraph } from '@pascal-app/core/clone-scene-graph'
import { type AnyNode, AnyNode as AnyNodeSchema } from '@pascal-app/core/schema'
import { z } from 'zod'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { ErrorCode, throwMcpError } from '../errors'
import { applyMutation, describeVariant, type MutationKind, mulberry32 } from './mutations'
const MUTATION_KINDS = [
'wall-thickness',
'wall-height',
'zone-labels',
'room-proportions',
'open-plan',
'door-positions',
'fence-style',
] as const
export const generateVariantsInput = {
baseSceneId: z
.string()
.optional()
.describe('If set, fork from this saved scene; else fork from current bridge state.'),
count: z.number().int().min(1).max(10).default(3),
vary: z.array(z.enum(MUTATION_KINDS)).min(1).default(['wall-thickness', 'wall-height']),
seed: z.number().int().optional().describe('Deterministic RNG seed.'),
save: z
.boolean()
.default(false)
.describe('If true, also save each variant via SceneStore and return ids.'),
}
export const generateVariantsOutput = {
variants: z.array(
z.object({
index: z.number(),
description: z.string(),
nodeCount: z.number(),
sceneId: z.string().optional(),
url: z.string().optional(),
graph: z.any().optional(),
}),
),
}
/**
* `forkSceneGraph` normalises `SiteNode.children` to string IDs, but the
* `SiteNode` schema declares that field as an array of full `BuildingNode` /
* `ItemNode` objects (see CROSS_CUTTING §2). To keep variants validating
* against `AnyNode`, re-embed the site children from the flat dict.
*
* Pure: returns a new graph without mutating the input.
*/
function rehydrateSiteChildren(graph: SceneGraph): SceneGraph {
const out: SceneGraph = {
nodes: { ...graph.nodes },
rootNodeIds: [...graph.rootNodeIds],
...(graph.collections ? { collections: graph.collections } : {}),
}
for (const [id, node] of Object.entries(out.nodes)) {
if (node.type !== 'site') continue
const childrenField = (node as { children?: unknown[] }).children
if (!Array.isArray(childrenField)) continue
const rehydrated: AnyNode[] = []
for (const child of childrenField) {
if (typeof child === 'string') {
const target = out.nodes[child as keyof typeof out.nodes]
if (target && (target.type === 'building' || target.type === 'item')) {
rehydrated.push(target)
}
} else if (child && typeof child === 'object' && 'id' in (child as Record<string, unknown>)) {
rehydrated.push(child as AnyNode)
}
}
out.nodes[id as keyof typeof out.nodes] = {
...(node as AnyNode),
children: rehydrated,
} as AnyNode
}
return out
}
/**
* Count how many nodes in a graph fail `AnyNode` validation. Used to keep the
* tool from returning silently corrupt variants.
*/
function countInvalidNodes(graph: SceneGraph): number {
let invalid = 0
for (const node of Object.values(graph.nodes)) {
if (!AnyNodeSchema.safeParse(node).success) invalid++
}
return invalid
}
export function registerGenerateVariants(
server: McpServer,
bridge: SceneBridge,
store: SceneStore,
): void {
server.registerTool(
'generate_variants',
{
title: 'Generate variants',
description:
'Generate N variations of a base scene by forking and applying seeded mutations. Example: "give me 5 variations of this kitchen". If `save=true`, each variant is persisted via the SceneStore and returned with an id + URL; otherwise the graph is returned inline.',
inputSchema: generateVariantsInput,
outputSchema: generateVariantsOutput,
},
async ({ baseSceneId, count, vary, seed, save }) => {
// 1. Obtain the base SceneGraph.
let base: SceneGraph
let baseName = 'scene'
if (baseSceneId) {
const loaded = await store.load(baseSceneId)
if (!loaded) {
throwMcpError(ErrorCode.InvalidParams, 'scene_not_found', { id: baseSceneId })
}
base = loaded.graph
baseName = loaded.name
} else {
const exported = bridge.exportJSON()
base = {
nodes: exported.nodes,
rootNodeIds: exported.rootNodeIds,
collections: exported.collections as SceneGraph['collections'],
}
}
// 2. Seed the RNG. Default seed is a time-ish number so runs vary, but
// tests always pass a fixed seed for determinism.
const initialSeed = seed ?? Math.floor(Math.random() * 0xffffffff)
const mutations = vary as MutationKind[]
const variants: Array<{
index: number
description: string
nodeCount: number
sceneId?: string
url?: string
graph?: SceneGraph
}> = []
for (let i = 0; i < count; i++) {
// Each variant gets its own RNG stream derived from (seed + i) so
// results are deterministic per-index.
const rng = mulberry32(initialSeed + i)
let forked: SceneGraph = forkSceneGraph(base)
for (const kind of mutations) {
forked = applyMutation(forked, rng, kind)
}
// Re-embed site children so variants match the SiteNode schema.
forked = rehydrateSiteChildren(forked)
const invalidCount = countInvalidNodes(forked)
if (invalidCount > 0) {
throwMcpError(
ErrorCode.InternalError,
`variant_invalid: variant ${i} produced ${invalidCount} invalid node(s)`,
{ index: i },
)
}
const nodeCount = Object.keys(forked.nodes).length
const description = describeVariant(forked, mutations)
if (save) {
try {
const meta = await store.save({
name: `${baseName}-variant-${i + 1}`,
graph: forked,
})
variants.push({
index: i,
description,
nodeCount,
sceneId: meta.id,
url: `/scene/${meta.id}`,
})
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
throwMcpError(ErrorCode.InternalError, `save_failed: ${msg}`, { index: i })
}
} else {
variants.push({ index: i, description, nodeCount, graph: forked })
}
}
const payload = { variants }
return {
content: [{ type: 'text' as const, text: JSON.stringify(payload) }],
structuredContent: payload,
}
},
)
}
+30
View File
@@ -0,0 +1,30 @@
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import type { SceneBridge } from '../../bridge/scene-bridge'
import type { SceneStore } from '../../storage/types'
import { registerGenerateVariants } from './generate-variants'
/**
* Register the variant-generation MCP tools against the given server. Uses the
* supplied `SceneStore` both to load a `baseSceneId` (when provided) and to
* persist variants when `save=true`.
*/
export function registerVariantTools(
server: McpServer,
bridge: SceneBridge,
store: SceneStore,
): void {
registerGenerateVariants(server, bridge, store)
}
export {
generateVariantsInput,
generateVariantsOutput,
registerGenerateVariants,
} from './generate-variants'
export {
applyMutation,
describeVariant,
type MutationKind,
mulberry32,
type Rng,
} from './mutations'
@@ -0,0 +1,409 @@
import { describe, expect, test } from 'bun:test'
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import type { AnyNodeId } from '@pascal-app/core/schema'
import { applyMutation, mulberry32 } from './mutations'
function makeBaseGraph(): SceneGraph {
const nodes: SceneGraph['nodes'] = {
site_a: {
object: 'node',
id: 'site_a',
type: 'site',
parentId: null,
visible: true,
metadata: {},
polygon: {
type: 'polygon',
points: [
[-10, -10],
[10, -10],
[10, 10],
[-10, 10],
],
},
children: [],
},
building_a: {
object: 'node',
id: 'building_a',
type: 'building',
parentId: 'site_a',
visible: true,
metadata: {},
position: [0, 0, 0],
rotation: [0, 0, 0],
children: ['level_a'],
},
level_a: {
object: 'node',
id: 'level_a',
type: 'level',
parentId: 'building_a',
visible: true,
metadata: {},
children: ['wall_n', 'wall_s', 'wall_e', 'wall_w', 'wall_mid', 'zone_kitchen', 'zone_living'],
},
wall_n: {
object: 'node',
id: 'wall_n',
type: 'wall',
parentId: 'level_a',
visible: true,
metadata: {},
start: [-10, 10],
end: [10, 10],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_s: {
object: 'node',
id: 'wall_s',
type: 'wall',
parentId: 'level_a',
visible: true,
metadata: {},
start: [-10, -10],
end: [10, -10],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_e: {
object: 'node',
id: 'wall_e',
type: 'wall',
parentId: 'level_a',
visible: true,
metadata: {},
start: [10, -10],
end: [10, 10],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_w: {
object: 'node',
id: 'wall_w',
type: 'wall',
parentId: 'level_a',
visible: true,
metadata: {},
start: [-10, -10],
end: [-10, 10],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
wall_mid: {
object: 'node',
id: 'wall_mid',
type: 'wall',
parentId: 'level_a',
visible: true,
metadata: {},
start: [-5, 0],
end: [5, 0],
thickness: 0.1,
height: 2.5,
children: ['door_mid'],
frontSide: 'unknown',
backSide: 'unknown',
},
door_mid: {
object: 'node',
id: 'door_mid',
type: 'door',
parentId: 'wall_mid',
visible: true,
metadata: {},
position: [0, 0, 0],
rotation: [0, 0, 0],
wallId: 'wall_mid',
width: 0.9,
height: 2.1,
frameThickness: 0.05,
frameDepth: 0.07,
threshold: true,
thresholdHeight: 0.02,
hingesSide: 'left',
swingDirection: 'inward',
segments: [],
handle: true,
handleHeight: 1.05,
handleSide: 'right',
contentPadding: [0.04, 0.04],
doorCloser: false,
panicBar: false,
panicBarHeight: 1.0,
},
zone_kitchen: {
object: 'node',
id: 'zone_kitchen',
type: 'zone',
parentId: 'level_a',
visible: true,
metadata: {},
name: 'Kitchen',
polygon: [
[-5, 0],
[5, 0],
[5, 10],
[-5, 10],
],
color: '#ff0000',
},
zone_living: {
object: 'node',
id: 'zone_living',
type: 'zone',
parentId: 'level_a',
visible: true,
metadata: {},
name: 'Living',
polygon: [
[-5, -10],
[5, -10],
[5, 0],
[-5, 0],
],
color: '#00ff00',
},
fence_1: {
object: 'node',
id: 'fence_1',
type: 'fence',
parentId: 'site_a',
visible: true,
metadata: {},
start: [-8, -8],
end: [8, -8],
height: 1.8,
thickness: 0.08,
baseHeight: 0.22,
postSpacing: 2,
postSize: 0.1,
topRailHeight: 0.04,
groundClearance: 0,
edgeInset: 0.015,
baseStyle: 'grounded',
color: '#ffffff',
style: 'slat',
},
} as unknown as SceneGraph['nodes']
return {
nodes,
rootNodeIds: ['site_a'] as AnyNodeId[],
}
}
describe('mulberry32', () => {
test('is deterministic for the same seed', () => {
const a = mulberry32(42)
const b = mulberry32(42)
for (let i = 0; i < 10; i++) {
expect(a()).toBe(b())
}
})
test('produces values in [0, 1)', () => {
const rng = mulberry32(7)
for (let i = 0; i < 100; i++) {
const v = rng()
expect(v).toBeGreaterThanOrEqual(0)
expect(v).toBeLessThan(1)
}
})
})
describe('applyMutation: wall-thickness', () => {
test('assigns every wall a thickness from the fixed set', () => {
const rng = mulberry32(1)
const out = applyMutation(makeBaseGraph(), rng, 'wall-thickness')
const allowed = new Set([0.1, 0.15, 0.2, 0.25])
let walls = 0
for (const node of Object.values(out.nodes)) {
if (node.type !== 'wall') continue
walls++
expect(allowed.has((node as { thickness: number }).thickness)).toBe(true)
}
expect(walls).toBeGreaterThan(0)
})
test('does not mutate the input graph', () => {
const base = makeBaseGraph()
const before = JSON.stringify(base)
applyMutation(base, mulberry32(5), 'wall-thickness')
expect(JSON.stringify(base)).toBe(before)
})
})
describe('applyMutation: wall-height', () => {
test('assigns every wall a height from the fixed set', () => {
const rng = mulberry32(2)
const out = applyMutation(makeBaseGraph(), rng, 'wall-height')
const allowed = new Set([2.4, 2.6, 2.7, 3.0])
for (const node of Object.values(out.nodes)) {
if (node.type !== 'wall') continue
expect(allowed.has((node as { height: number }).height)).toBe(true)
}
})
})
describe('applyMutation: zone-labels', () => {
test('shuffles labels but preserves the set', () => {
const base = makeBaseGraph()
const rng = mulberry32(3)
const out = applyMutation(base, rng, 'zone-labels')
const before = new Set<string>()
for (const node of Object.values(base.nodes)) {
if (node.type === 'zone') before.add((node as { name: string }).name)
}
const after = new Set<string>()
for (const node of Object.values(out.nodes)) {
if (node.type === 'zone') after.add((node as { name: string }).name)
}
expect(after).toEqual(before)
})
})
describe('applyMutation: room-proportions', () => {
test('only nudges interior walls, leaves perimeter alone', () => {
const base = makeBaseGraph()
const rng = mulberry32(4)
const out = applyMutation(base, rng, 'room-proportions')
// Perimeter wall should be unchanged.
const n = out.nodes.wall_n as { start: [number, number]; end: [number, number] }
expect(n.start).toEqual([-10, 10])
expect(n.end).toEqual([10, 10])
// Interior wall should (usually) be different.
const mid = out.nodes.wall_mid as { start: [number, number]; end: [number, number] }
const midBase = base.nodes.wall_mid as { start: [number, number]; end: [number, number] }
const changed =
mid.start[0] !== midBase.start[0] ||
mid.start[1] !== midBase.start[1] ||
mid.end[0] !== midBase.end[0] ||
mid.end[1] !== midBase.end[1]
expect(changed).toBe(true)
})
})
describe('applyMutation: open-plan', () => {
test('removes exactly one interior wall and its attached openings', () => {
const base = makeBaseGraph()
const baseWallCount = Object.values(base.nodes).filter((n) => n.type === 'wall').length
const rng = mulberry32(5)
const out = applyMutation(base, rng, 'open-plan')
const afterWallCount = Object.values(out.nodes).filter((n) => n.type === 'wall').length
expect(afterWallCount).toBe(baseWallCount - 1)
// Interior wall `wall_mid` had a door — both should be gone.
expect(out.nodes.wall_mid).toBeUndefined()
expect(out.nodes.door_mid).toBeUndefined()
})
test('skips gracefully when there are no interior walls', () => {
const graph: SceneGraph = {
nodes: {
site_a: {
object: 'node',
id: 'site_a',
type: 'site',
parentId: null,
visible: true,
metadata: {},
polygon: {
type: 'polygon',
points: [
[-10, -10],
[10, -10],
[10, 10],
[-10, 10],
],
},
children: [],
},
wall_n: {
object: 'node',
id: 'wall_n',
type: 'wall',
parentId: 'site_a',
visible: true,
metadata: {},
start: [-10, 10],
end: [10, 10],
thickness: 0.1,
height: 2.5,
children: [],
frontSide: 'unknown',
backSide: 'unknown',
},
} as unknown as SceneGraph['nodes'],
rootNodeIds: ['site_a'] as AnyNodeId[],
}
const out = applyMutation(graph, mulberry32(9), 'open-plan')
expect(Object.keys(out.nodes)).toEqual(Object.keys(graph.nodes))
})
})
describe('applyMutation: door-positions', () => {
test('sets every door wallT in [0.2, 0.8]', () => {
const rng = mulberry32(6)
const out = applyMutation(makeBaseGraph(), rng, 'door-positions')
for (const node of Object.values(out.nodes)) {
if (node.type !== 'door') continue
const t = (node as { wallT?: number }).wallT
expect(typeof t).toBe('number')
expect(t as number).toBeGreaterThanOrEqual(0.2)
expect(t as number).toBeLessThanOrEqual(0.8)
}
})
})
describe('applyMutation: fence-style', () => {
test('sets every fence style to one of privacy/slat/rail', () => {
const rng = mulberry32(7)
const out = applyMutation(makeBaseGraph(), rng, 'fence-style')
const allowed = new Set(['privacy', 'slat', 'rail'])
for (const node of Object.values(out.nodes)) {
if (node.type !== 'fence') continue
expect(allowed.has((node as { style: string }).style)).toBe(true)
}
})
})
describe('applyMutation: no-op behaviour', () => {
test('wall-thickness on a graph with no walls leaves nodes unchanged', () => {
const graph: SceneGraph = {
nodes: {
site_a: {
object: 'node',
id: 'site_a',
type: 'site',
parentId: null,
visible: true,
metadata: {},
polygon: {
type: 'polygon',
points: [
[-1, -1],
[1, -1],
[1, 1],
[-1, 1],
],
},
children: [],
},
} as unknown as SceneGraph['nodes'],
rootNodeIds: ['site_a'] as AnyNodeId[],
}
const out = applyMutation(graph, mulberry32(8), 'wall-thickness')
expect(JSON.stringify(out.nodes)).toBe(JSON.stringify(graph.nodes))
})
})
@@ -0,0 +1,331 @@
import type { SceneGraph } from '@pascal-app/core/clone-scene-graph'
import type { AnyNode, AnyNodeId } from '@pascal-app/core/schema'
/** Mutation kinds handled by `applyMutation`. */
export type MutationKind =
| 'wall-thickness'
| 'wall-height'
| 'zone-labels'
| 'room-proportions'
| 'open-plan'
| 'door-positions'
| 'fence-style'
/** Deterministic 32-bit RNG. */
export type Rng = () => number
/**
* Tiny PRNG. Returns a function that produces uniformly distributed floats in
* [0, 1). Source: https://stackoverflow.com/a/47593316/17118
*/
export function mulberry32(seed: number): Rng {
let state = seed | 0
return () => {
state = (state + 0x6d2b79f5) | 0
let t = state
t = Math.imul(t ^ (t >>> 15), t | 1)
t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
/** Pick a random element from a non-empty array. */
function pickFrom<T>(rng: Rng, values: readonly T[]): T {
const idx = Math.floor(rng() * values.length)
return values[Math.min(idx, values.length - 1)] as T
}
/** Shallow clone a scene graph: nodes are copied one level deep, node dict is fresh. */
function cloneGraph(graph: SceneGraph): SceneGraph {
const clonedNodes: Record<AnyNodeId, AnyNode> = {} as Record<AnyNodeId, AnyNode>
for (const [id, node] of Object.entries(graph.nodes)) {
// structuredClone so sub-objects (arrays, tuples, metadata) are independent.
clonedNodes[id as AnyNodeId] = structuredClone(node) as AnyNode
}
return {
nodes: clonedNodes,
rootNodeIds: [...graph.rootNodeIds],
...(graph.collections ? { collections: structuredClone(graph.collections) } : {}),
}
}
const WALL_THICKNESS_OPTIONS = [0.1, 0.15, 0.2, 0.25] as const
const WALL_HEIGHT_OPTIONS = [2.4, 2.6, 2.7, 3.0] as const
const FENCE_STYLES = ['privacy', 'slat', 'rail'] as const
/** FisherYates shuffle in place using the provided RNG. */
function shuffleInPlace<T>(arr: T[], rng: Rng): void {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1))
const tmp = arr[i] as T
arr[i] = arr[j] as T
arr[j] = tmp
}
}
/**
* Compute 2D bounds (min/max x/z) of the first `site` node's polygon points,
* or `null` if no site is present.
*/
function siteBounds(
graph: SceneGraph,
): { minX: number; maxX: number; minZ: number; maxZ: number } | null {
for (const node of Object.values(graph.nodes)) {
if (node.type !== 'site') continue
const pts = (node as { polygon?: { points?: Array<[number, number]> } }).polygon?.points
if (!pts || pts.length === 0) continue
let minX = Infinity
let maxX = -Infinity
let minZ = Infinity
let maxZ = -Infinity
for (const [x, z] of pts) {
if (x < minX) minX = x
if (x > maxX) maxX = x
if (z < minZ) minZ = z
if (z > maxZ) maxZ = z
}
if (!Number.isFinite(minX)) continue
return { minX, maxX, minZ, maxZ }
}
return null
}
/**
* Heuristic: a wall is a perimeter wall if either of its endpoints sits close
* to the site polygon's bounding rectangle (within `epsilon`). Returns `false`
* if there is no site polygon (treat everything as interior so the mutations
* still exercise something on partial scenes).
*/
function isPerimeterWall(
wall: AnyNode & { start?: [number, number]; end?: [number, number] },
bounds: { minX: number; maxX: number; minZ: number; maxZ: number } | null,
epsilon = 0.01,
): boolean {
if (!bounds || !wall.start || !wall.end) return false
const onBound = (x: number, z: number): boolean =>
Math.abs(x - bounds.minX) <= epsilon ||
Math.abs(x - bounds.maxX) <= epsilon ||
Math.abs(z - bounds.minZ) <= epsilon ||
Math.abs(z - bounds.maxZ) <= epsilon
const [sx, sz] = wall.start
const [ex, ez] = wall.end
return onBound(sx, sz) || onBound(ex, ez)
}
function applyWallThickness(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
for (const node of Object.values(out.nodes)) {
if (node.type !== 'wall') continue
;(node as { thickness?: number }).thickness = pickFrom(rng, WALL_THICKNESS_OPTIONS)
}
return out
}
function applyWallHeight(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
for (const node of Object.values(out.nodes)) {
if (node.type !== 'wall') continue
;(node as { height?: number }).height = pickFrom(rng, WALL_HEIGHT_OPTIONS)
}
return out
}
function applyZoneLabels(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
const zoneNodes: Array<AnyNode & { name?: string }> = []
for (const node of Object.values(out.nodes)) {
if (node.type === 'zone') zoneNodes.push(node as AnyNode & { name?: string })
}
if (zoneNodes.length < 2) return out
const labels = zoneNodes.map((z) => z.name ?? '')
shuffleInPlace(labels, rng)
for (let i = 0; i < zoneNodes.length; i++) {
;(zoneNodes[i] as { name?: string }).name = labels[i]
}
return out
}
function applyRoomProportions(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
const bounds = siteBounds(out)
for (const node of Object.values(out.nodes)) {
if (node.type !== 'wall') continue
const wall = node as AnyNode & {
start?: [number, number]
end?: [number, number]
}
if (!wall.start || !wall.end) continue
if (isPerimeterWall(wall, bounds)) continue
// Nudge each endpoint by ±10% of its current value.
const nudge = (v: number): number => v * (1 + (rng() * 2 - 1) * 0.1)
const clampX = (v: number): number =>
bounds ? Math.min(bounds.maxX, Math.max(bounds.minX, v)) : v
const clampZ = (v: number): number =>
bounds ? Math.min(bounds.maxZ, Math.max(bounds.minZ, v)) : v
const [sx, sz] = wall.start
const [ex, ez] = wall.end
wall.start = [clampX(nudge(sx)), clampZ(nudge(sz))]
wall.end = [clampX(nudge(ex)), clampZ(nudge(ez))]
}
return out
}
function applyOpenPlan(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
const bounds = siteBounds(out)
const interiorWallIds: AnyNodeId[] = []
for (const [id, node] of Object.entries(out.nodes)) {
if (node.type !== 'wall') continue
if (isPerimeterWall(node as AnyNode, bounds)) continue
interiorWallIds.push(id as AnyNodeId)
}
if (interiorWallIds.length === 0) return out
const targetId = interiorWallIds[Math.floor(rng() * interiorWallIds.length)] as AnyNodeId
// Collect any openings attached to this wall so we can drop them too.
const attached: AnyNodeId[] = []
for (const [attId, node] of Object.entries(out.nodes)) {
if ((node as { wallId?: string }).wallId === targetId) attached.push(attId as AnyNodeId)
}
const removal = new Set<AnyNodeId>([targetId, ...attached])
// Drop from nodes.
for (const id of removal) delete out.nodes[id]
// Drop from rootNodeIds (unlikely for walls, but consistent).
out.rootNodeIds = out.rootNodeIds.filter((id) => !removal.has(id))
// Drop references from any parent's `children` array.
for (const parent of Object.values(out.nodes)) {
if (!('children' in parent) || !Array.isArray((parent as { children?: unknown[] }).children)) {
continue
}
const children = (parent as { children: unknown[] }).children
;(parent as { children: unknown[] }).children = children.filter((child) => {
if (typeof child === 'string') return !removal.has(child as AnyNodeId)
if (child && typeof child === 'object' && 'id' in (child as Record<string, unknown>)) {
return !removal.has((child as { id: AnyNodeId }).id)
}
return true
})
}
return out
}
function applyDoorPositions(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
// Group doors by their parent wall so we can space them out and skip collisions.
const doorsByWall = new Map<string, Array<AnyNode & { wallT?: number; wallId?: string }>>()
for (const node of Object.values(out.nodes)) {
if (node.type !== 'door') continue
const wallId = (node as { wallId?: string }).wallId
if (!wallId) continue
let list = doorsByWall.get(wallId)
if (!list) {
list = []
doorsByWall.set(wallId, list)
}
list.push(node as AnyNode & { wallT?: number; wallId?: string })
}
for (const [, doors] of doorsByWall) {
// Minimum separation along the parametric wall axis — rough keep-away to
// avoid obvious overlaps.
const minGap = 0.15
const usedTs: number[] = []
for (const door of doors) {
let attempts = 0
let t = 0.5
while (attempts < 8) {
t = 0.2 + rng() * 0.6 // [0.2, 0.8]
const collides = usedTs.some((u) => Math.abs(u - t) < minGap)
if (!collides) break
attempts++
}
// If we still collide after 8 attempts, skip this door (leave it alone).
if (usedTs.some((u) => Math.abs(u - t) < minGap)) continue
usedTs.push(t)
;(door as { wallT?: number }).wallT = t
}
}
return out
}
function applyFenceStyle(graph: SceneGraph, rng: Rng): SceneGraph {
const out = cloneGraph(graph)
let i = 0
for (const node of Object.values(out.nodes)) {
if (node.type !== 'fence') continue
// Use rng to choose a rotation offset so each call can produce a different
// starting point even when called multiple times with the same base.
const offset = Math.floor(rng() * FENCE_STYLES.length)
const style = FENCE_STYLES[(i + offset) % FENCE_STYLES.length]
;(node as { style?: string }).style = style
i++
}
return out
}
/** Pure: apply a single mutation and return a fresh graph. */
export function applyMutation(graph: SceneGraph, rng: Rng, kind: MutationKind): SceneGraph {
switch (kind) {
case 'wall-thickness':
return applyWallThickness(graph, rng)
case 'wall-height':
return applyWallHeight(graph, rng)
case 'zone-labels':
return applyZoneLabels(graph, rng)
case 'room-proportions':
return applyRoomProportions(graph, rng)
case 'open-plan':
return applyOpenPlan(graph, rng)
case 'door-positions':
return applyDoorPositions(graph, rng)
case 'fence-style':
return applyFenceStyle(graph, rng)
}
}
/**
* Human-readable summary of the mutations applied to a variant. Reads the
* interesting fields from the graph (e.g. first wall's thickness/height).
*/
export function describeVariant(graph: SceneGraph, mutations: readonly MutationKind[]): string {
const parts: string[] = []
if (mutations.includes('wall-thickness')) {
const t = firstWallField(graph, 'thickness')
if (t !== null) parts.push(`wall thickness ${t}m`)
}
if (mutations.includes('wall-height')) {
const h = firstWallField(graph, 'height')
if (h !== null) parts.push(`wall height ${h}m`)
}
if (mutations.includes('zone-labels')) {
const names: string[] = []
for (const node of Object.values(graph.nodes)) {
if (node.type === 'zone') names.push((node as { name?: string }).name ?? '')
}
if (names.length > 0) parts.push(`zones [${names.join(', ')}]`)
}
if (mutations.includes('room-proportions')) parts.push('room proportions nudged')
if (mutations.includes('open-plan')) parts.push('open-plan')
if (mutations.includes('door-positions')) parts.push('doors repositioned')
if (mutations.includes('fence-style')) {
const s = firstFenceField(graph, 'style')
if (s !== null) parts.push(`fence style ${s}`)
}
return parts.length > 0 ? parts.join(', ') : 'no-op'
}
function firstWallField(graph: SceneGraph, field: 'thickness' | 'height'): number | null {
for (const node of Object.values(graph.nodes)) {
if (node.type !== 'wall') continue
const v = (node as Record<string, unknown>)[field]
if (typeof v === 'number') return v
}
return null
}
function firstFenceField(graph: SceneGraph, field: 'style'): string | null {
for (const node of Object.values(graph.nodes)) {
if (node.type !== 'fence') continue
const v = (node as Record<string, unknown>)[field]
if (typeof v === 'string') return v
}
return null
}