Adrian Perez e8d0b13ff5 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>
2026-04-18 19:29:28 +02:00

192 lines
5.8 KiB
TypeScript

import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSceneStore } from '@/lib/scene-store-server'
export const dynamic = 'force-dynamic'
type RouteParams = { params: Promise<{ id: string }> }
const graphSchema = z.unknown().refine((v: unknown) => v !== null && typeof v === 'object', {
message: 'graph must be an object',
})
const putSceneSchema = z.object({
name: z.string().min(1).max(200).optional(),
graph: graphSchema,
thumbnailUrl: z.string().url().nullable().optional(),
expectedVersion: z.number().int().nonnegative().optional(),
})
const patchSceneSchema = z.object({
name: z.string().min(1).max(200),
expectedVersion: z.number().int().nonnegative().optional(),
})
export async function GET(_request: NextRequest, { params }: RouteParams) {
const { id } = await params
const store = await getSceneStore()
try {
const scene = await store.load(id)
if (!scene) {
return NextResponse.json({ error: 'not_found' }, { status: 404 })
}
return NextResponse.json(scene, {
headers: { ETag: `"${scene.version}"` },
})
} catch (error) {
return handleStoreError(error)
}
}
export async function PUT(request: NextRequest, { params }: RouteParams) {
const { id } = await params
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json(
{ error: 'invalid_request', details: 'body must be valid JSON' },
{ status: 400 },
)
}
const parsed = putSceneSchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json(
{ error: 'invalid_request', details: parsed.error.issues },
{ status: 400 },
)
}
const ifMatch = parseIfMatch(request.headers.get('If-Match'))
const expectedVersion = ifMatch ?? parsed.data.expectedVersion
const store = await getSceneStore()
try {
const existing = await store.load(id)
if (!existing) {
return NextResponse.json({ error: 'not_found' }, { status: 404 })
}
const meta = await store.save({
id,
name: parsed.data.name ?? existing.name,
projectId: existing.projectId,
ownerId: existing.ownerId,
graph: parsed.data.graph as never,
thumbnailUrl:
parsed.data.thumbnailUrl === undefined ? existing.thumbnailUrl : parsed.data.thumbnailUrl,
expectedVersion,
})
return NextResponse.json(meta, {
headers: { ETag: `"${meta.version}"` },
})
} catch (error) {
return handleStoreError(error, { includeCurrentVersionFor: id })
}
}
export async function DELETE(request: NextRequest, { params }: RouteParams) {
const { id } = await params
const ifMatch = parseIfMatch(request.headers.get('If-Match'))
const store = await getSceneStore()
try {
const removed = await store.delete(id, { expectedVersion: ifMatch })
if (!removed) {
return NextResponse.json({ error: 'not_found' }, { status: 404 })
}
return new NextResponse(null, { status: 204 })
} catch (error) {
return handleStoreError(error, { includeCurrentVersionFor: id })
}
}
export async function PATCH(request: NextRequest, { params }: RouteParams) {
const { id } = await params
let body: unknown
try {
body = await request.json()
} catch {
return NextResponse.json(
{ error: 'invalid_request', details: 'body must be valid JSON' },
{ status: 400 },
)
}
const parsed = patchSceneSchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json(
{ error: 'invalid_request', details: parsed.error.issues },
{ status: 400 },
)
}
const ifMatch = parseIfMatch(request.headers.get('If-Match'))
const expectedVersion = ifMatch ?? parsed.data.expectedVersion
const store = await getSceneStore()
try {
const meta = await store.rename(id, parsed.data.name, { expectedVersion })
return NextResponse.json(meta, {
headers: { ETag: `"${meta.version}"` },
})
} catch (error) {
return handleStoreError(error, { includeCurrentVersionFor: id })
}
}
/**
* Parses an `If-Match` header value per RFC 7232. Accepts `"<version>"` or
* weak `W/"<version>"` forms. Returns `undefined` when the header is absent,
* the wildcard `*`, or unparseable as a non-negative integer.
*/
function parseIfMatch(raw: string | null): number | undefined {
if (!raw) return undefined
const trimmed = raw.trim()
if (trimmed === '*') return undefined
const match = trimmed.match(/^(?:W\/)?"([^"]+)"$/)
const inner = match ? match[1] : trimmed
if (!inner) return undefined
const n = Number(inner)
if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) return undefined
return n
}
async function handleStoreError(
error: unknown,
opts: { includeCurrentVersionFor?: string } = {},
): Promise<NextResponse> {
const code = (error as { code?: string })?.code
if (code === 'version_conflict') {
let currentVersion: number | undefined
if (opts.includeCurrentVersionFor) {
try {
const store = await getSceneStore()
const current = await store.load(opts.includeCurrentVersionFor)
currentVersion = current?.version
} catch {
// Best-effort; skip reporting currentVersion on secondary failure.
}
}
return NextResponse.json(
currentVersion === undefined
? { error: 'version_conflict' }
: { error: 'version_conflict', currentVersion },
{ status: 409 },
)
}
if (code === 'not_found') {
return NextResponse.json({ error: 'not_found' }, { status: 404 })
}
if (code === 'too_large') {
return NextResponse.json({ error: 'too_large' }, { status: 413 })
}
if (code === 'invalid') {
return NextResponse.json({ error: 'invalid' }, { status: 400 })
}
const message = error instanceof Error ? error.message : 'unexpected_error'
return NextResponse.json({ error: 'internal_error', message }, { status: 500 })
}