3D engine that AI agents drive
Support atomic agent topology edits and retained GPU resources
Nguyen Xuan And09caffa2219
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d2475bd9..5aa84c21 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Add atomic agent commands for creating, removing and rebinding nodes and shared resources, with bounded checkpoint geometry ownership.+- Reconcile rigid untextured renderer topology while retaining unchanged batches and sharing immutable geometry buffers across draws.- Add source-checkout MCP tools with strict scene schemas, persistent CPU/GPU previews and bounded PNG responses.- Keep renderer sessions alive across edits and close owned browser resources when the MCP connection ends.- Add optional agent scene sessions with stable IDs, shared geometry, revision checks, atomic edits and bounded checkpoints.diff --git a/README.md b/README.mdindex 46efed5a..76cccb13 100644--- a/README.md+++ b/README.md@@ -126,12 +126,13 @@ The repository includes two reusable Codex skills.The current source includes [agent scene sessions](docs/agent-scene.md), newer than npm `0.4.1`.Agents can author JSON recipes, inspect object bounds, submit atomic edits and restore bounded checkpoints.-The optional addon retains renderer-facing parts and geometry across supported edits.+Agents can add or remove nodes and shared resources in the same revisioned command stream.+The optional addon retains unchanged parts and geometry across supported edits.The source [MCP server](docs/mcp.md) connects these sessions to a persistent browser renderer.Agents receive PNG previews and structured scene metadata through ten stdio tools.Run `node scripts/mcp-server.mjs --backend gpu --memory 192` from a checkout with project dependencies and a local Chrome installation.-Dynamic node creation, asset ingestion and persistent video jobs remain implementation work.+Asset ingestion, animation authoring and persistent video jobs remain implementation work.## Checks and performancediff --git a/ROADMAP.md b/ROADMAP.mdindex b1a25006..3f40714e 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -22,10 +22,10 @@ This document separates shipping capabilities from work in progress. Performance## Next-The current source, after npm `0.4.1`, includes fixed-topology agent scenes with stable IDs, atomic revisioned edits and checkpoints.+The current source, after npm `0.4.1`, includes agent scenes with stable IDs, atomic resource/node edits and checkpoints.Its stdio MCP server supplies ten schema-backed tools and persistent CPU/GPU image previews.-1. Extend agent sessions with dynamic node and resource creation while preserving bounded allocation, replay and undo.+1. Extend agent sessions to ingest validated local assets with stable IDs, bounded allocation, replay and undo.2. Extend MCP visual feedback with bounded multi-angle and absolute animation-time previews, plus persistent authored lighting and effect controls.3. Persistent render jobs with progress, cancellation, explicit CPU/GPU budgets and deterministic image and video export.4. Geometry, rig and asset diagnostics that help agents correct intersections, invalid transforms and unsupported materials.diff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex 5f769fb9..4f54fbc3 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -117,36 +117,84 @@ Each successful application increments the revision once, including a command thStale revisions and invalid commands leave canonical state, published matrices, materials, and the revision unchanged.Every command in a batch stages before any command publishes.+Commands run sequentially against a private candidate recipe.+Final resource references and hierarchy must be valid before publication.+| Operation | Fields || --- | --- |-| `set-node` | `id`, optional `translation`, `rotation`, `scale`, `parent`, `label` |+| `set-node` | `id`, optional `translation`, `rotation`, `scale`, `parent`, `label`, `geometry`, `material` || `set-material` | `id`, optional `color`, `metallic`, `roughness`, `emission`, `emissiveColor` || `set-camera` | Optional `eye`, `target`, `up`, `fov`, `near`, `far` directly on the command |+| `add-geometry` | `geometry`, containing a complete geometry record |+| `remove-geometry` | `id` |+| `add-material` | `material`, containing a complete material record |+| `remove-material` | `id` |+| `add-node` | `node`, containing a complete node record |+| `remove-node` | `id`, optional boolean `recursive`, default `false` |-Node membership and resource definitions remain fixed.Reparenting changes hierarchy while preserving each node's local transform.-Adding or removing nodes, changing geometry, and changing material tags require a new session.+Commands can add or remove nodes and resources.+Adding a duplicate ID or removing a missing ID fails.+Resource removal can precede rebinding or dependent node removal in the same batch.+The final recipe must contain every resource and parent referenced by surviving nodes.+Mesh nodes require both geometry and material IDs in the final recipe.++Nonrecursive removal rejects a node that has children at that command's position in the batch.+Child removal or reparenting must precede nonrecursive parent removal.+Recursive removal explicitly removes that node and its entire current subtree.+Node removal leaves geometry and materials intact until explicit resource removal.+Changing a geometry definition or material tag requires removing and adding its resource record.+Direct `set-material` commands still reject tag changes.The session copies input recipes and commands.`exportRecipe()` and `camera` return detached JSON snapshots.Published material objects are frozen and expose immutable arrays through retained getters.-Renderer parts, matrices, geometries, and material objects retain their identities across successful edits and restores.Material reads do not allocate arrays or scan resource collections.+Surviving nodes retain their part and matrix identities when geometry and material bindings retain their resource identities.+Rebinding replaces the part and its matrix.+Removing and adding the same node ID also replaces its part.++Geometry identity survives when its ID and complete definition match an active or checkpoint resource.+Object key order does not affect that comparison.+Omitted parameters and explicit defaults remain distinct definitions.+A changed definition creates new immutable geometry and replaces parts bound to that resource.+Multiple nodes referencing the same resource ID share its geometry.++`parts` returns a frozen current list.+The list retains its identity while its ordered part identities remain unchanged.+Transform, material value, camera, and group-only edits can retain the list.+Removed parts leave the current list and are no longer renderer update targets.+Removed material handles remain readable with their last committed snapshot.+`parts` is a privileged renderer adapter surface.Its geometry typed arrays follow the engine's immutable geometry contract and must never change or detach.-The session does not duplicate geometry buffers or regenerate geometry during transactions.+The session does not duplicate geometry buffers or regenerate unchanged geometry during transactions.Writes to retained matrices cannot poison the private recipe or inspection transforms.A successful transaction overwrites those matrices from canonical state.Detached matrices reject publication before canonical state changes.An agent adapter must expose JSON commands and snapshots rather than renderer typed arrays.+`topologyRevision` starts at zero and increments only when ordered part identities or membership change.+Restore follows the same rule.+Failed transactions leave both revisions unchanged.+Unused resource or group-only edits do not increment `topologyRevision`.+Renderer adapters can compare it to choose topology replacement or retained instance updates.+The session does not replace renderer GPU resources itself.+`checkpoint()` returns an opaque, frozen handle that belongs to its session.Checkpoint snapshots are private and cannot change through the handle.+Checkpoints retain recipe snapshots and references to their geometry, material handles, and parts.+Restore reuses those resources without regenerating geometry.+Unchanged active parts take priority when their bindings still match.+Otherwise, restore can recover the checkpoint's original part and matrix identities.+`restore(handle, { expectedRevision })` applies the same atomic validation and increments the revision.Released and foreign handles fail.`releaseCheckpoint(handle)` frees its slot and does not change the scene revision.+Released geometry references leave session ownership unless the active scene or another checkpoint still needs them.+There is no separate unbounded geometry history cache.## Budgets and inspection@@ -159,23 +207,32 @@ The optional second constructor argument overrides the following positive intege| `maxDepth` | `256`, counting a root as depth one || `maxGeometries` | `256` || `maxMaterials` | `256` |-| `maxVertices` | `250000`, summed across unique geometries |+| `maxVertices` | `250000`, across unique active, checkpoint, and staged geometry allocations || `maxGeometryBytes` | `33554432` || `maxOperations` | `256`, per application || `maxCheckpoints` | `8` || `maxRecipeBytes` | `1048576`, also used for each command batch |-Preflight sums conservative vertex counts before any geometry generation.+Preflight accounts for peak geometry ownership before generating any new resource.+It counts each unique active or checkpoint allocation once, using actual vertices and typed array bytes.+New resources contribute their conservative vertex and byte bounds.Its byte bound uses 56 bytes per vertex for eight floats and at most six Uint32 indices.Actual generated geometry bytes must also fit the budget.-Byte counts include position, normal, UV, and index typed arrays across unique geometries.-They exclude JavaScript object overhead, temporary generator allocations, transaction matrices, checkpoints, and renderer GPU memory.+Atomic replacement retains the old active geometry until the candidate commits, so both allocations count during preflight.+A single replacement can fail even when the final geometry fits alone.+Checkpoint sharing does not duplicate geometry bytes.+Unused active resources still count until explicitly removed.+Releasing checkpoints can free ownership for later additions.++Byte counts include position, normal, UV, and index typed arrays across unique owned geometry allocations.+They exclude JavaScript objects, temporary generator allocations, transaction matrices, checkpoint recipes, and renderer GPU memory.+External renderer adapters can retain removed arrays beyond the session's ownership accounting.The JSON budget uses conservative UTF-8 traversal accounting and also checks serialized JSON size.Normalization can increase serialized size, so normalized recipes also pass the JSON budget.Each checkpoint stores at most one normalized recipe within that limit.-`inspect({ ids, limit, includeBounds })` returns compact JSON with the current revision, global counts, and selected node records.+`inspect({ ids, limit, includeBounds })` returns JSON with both revisions, global counts, and selected node records.Its default limit is 64, capped by `maxNodes`.Requested IDs must exist.@@ -183,6 +240,9 @@ Requested IDs must exist.Global counts include nodes, render parts, unique geometries, materials, and unique geometry vertices.`geometryBytes` reports actual unique typed array bytes.`estimatedGeometryBytes` reports the conservative preflight bound.++Those fields describe active resources, including unused resources.+`residentGeometryBytes` and `residentGeometryVertices` include unique active and checkpoint allocations.Inspection does not report GPU timing or renderer allocation.With `includeBounds: true`, each mesh record includes `{ min, max }` from every transformed geometry vertex.@@ -198,5 +258,12 @@ They describe the authored mesh surface without shader effects or displacement.| Validate JSON recipes and typed commands | Bounded inputs, private ownership, atomic batches, and reproducible snapshots | A deliberately limited geometry and editing vocabulary |The addon uses validated JSON because ownership and atomic editing form its public contract.-A future MCP adapter can translate tool calls into this API without placing transport logic inside the scene session.+The separate [source MCP adapter](mcp.md) translates tool calls into this API without placing transport logic inside the scene session.This version does not claim Blender feature parity.++| Geometry ownership design | Benefit | Cost |+| --- | --- | --- |+| Regenerate the full scene after every command | Simple replacement ownership | Repeated geometry allocation and lost renderer identities |+| Retain immutable resource records in active state and bounded checkpoints | Shared geometry, replay, stable parts, and peak allocation preflight | Explicit staging and checkpoint ownership accounting |++The addon retains immutable resource records because topology editing must preserve unaffected geometry and renderer handles.diff --git a/docs/guide.md b/docs/guide.mdindex 985e22f1..d43ac900 100644--- a/docs/guide.md+++ b/docs/guide.md@@ -408,6 +408,11 @@ The addon accepts JSON recipes with stable object IDs, shared geometry and materEdits use an expected revision and commit as one batch. Checkpoints restore the supported scene state.The session keeps existing renderer-facing parts and matrices for transform, material and camera edits.+Agents can build from an empty recipe with `add-geometry`, `add-material` and `add-node` commands.+Explicit removal and rebinding use the same atomic batch contract.+Checkpoints retain shared geometry under the session budget. Release unused snapshots before increasing scene detail.+The preview reconciles rigid, untextured topology while keeping unchanged geometry buffers and draw batches.+The CPU addon owns recipe state. The separate Node MCP server connects it to browser rendering. Background render jobs remain unsupported.Give the agent this guide and the matching repository skill. Start with a scene brief: focal subject, visual references, camera, output size, required interaction, GPU/CPU backend and memory budget. Read the matching scene recipe and run the smallest trial first.diff --git a/docs/mcp.md b/docs/mcp.mdindex 6f0f0e8e..d5a4a2cf 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -93,7 +93,22 @@ Inspect or export the recipe before retrying. Context loss still permits recipeThe recipe uses `format: '67js.scene'` and `schemaVersion: 1`.Supported geometry types are `box`, `cylinder`, `sphere`, `torus`, `lathe`, `extrude`, and `tube`.Geometry fields remain flat inside each geometry record.-Operations use `set-node`, `set-material`, or `set-camera`, with fields directly on each command.+Set operations use `set-node`, `set-material`, or `set-camera`, with fields directly on each command.+`set-node` can rebind a mesh to another geometry/material pair.++Build from an empty recipe by adding resources and nodes in one revisioned batch:++```js+[+ { type: 'add-geometry', geometry: { id: 'cube', type: 'box', bevel: 0.04 } },+ { type: 'add-material', material: { id: 'paint', color: [0.2, 0.6, 0.8] } },+ { type: 'add-node', node: { id: 'mesh', geometry: 'cube', material: 'paint' } }+]+```++Use `remove-node`, `remove-geometry` and `remove-material` with an `id` to remove entries.+References must resolve after the complete batch. Removing a parent leaves its children unchanged unless `recursive: true` removes its subtree.+Reparent or remove those children before the parent removal command to avoid rejection.The [scene contract](agent-scene.md) defines the geometry fields, transforms, materials, and atomic validation rules.## Limits@@ -124,10 +139,18 @@ An oversized PNG response returns an error. Request a smaller preview rather thaBrowser evaluations have a 30-second deadline. A timeout closes the preview browser and makes the runtime unavailable.Camera matrices must remain finite at every supported preview aspect ratio, from 1:16 to 16:1.-Group and mesh membership, geometry definitions, and material tags remain fixed after creation.-Adding nodes or changing geometry requires a new scene.+Geometry resources remain immutable. Remove an unused definition and add its replacement in one batch, or add a new resource ID and rebind its nodes.+Checkpoints retain their resource handles for exact restoration. Active, checkpoint and staged geometry share a bounded allocation budget.+Release unused checkpoints to free that ownership before adding detail.-The tools expose no arbitrary JavaScript execution, URLs, file access, asset ingestion, or render jobs.+The preview reconciles rigid, untextured parts while retaining shader programs, render targets and shared geometry buffers.+Unchanged draw batches remain allocated. Changed instance groups receive new instance buffers. Retired buffers are released.++Staging must fit alongside the current render allocations, so a replacement can fail its GPU budget even when the final scene alone fits.+The committed revision and separate render failure remain visible in that case.+Request a smaller `scene_look` to release large frame targets before retrying reconciliation.++The tools expose no arbitrary JavaScript execution, URLs, file access, asset ingestion, animation authoring, or render jobs.The transport supplies a visual feedback loop, but visual quality still depends on the authored scene and image assessment.MCP support does not establish Blender feature parity.@@ -143,4 +166,9 @@ These tests do not prove browser launch, GPU rendering, or final visual quality.Run `node scripts/smoke-mcp.mjs gpu modern` for a native browser test through real stdio tools.Run `node scripts/smoke-mcp.mjs cpu legacy` for the software backend and legacy protocol negotiation.Each checks landscape and portrait PNGs, stale revision rejection, exact PNG restoration, session disposal, and process cleanup.+They build the scene from empty through tool calls, add and remove geometry, and restore the scene after all mesh resources were removed.The scripts save images and metadata under `artifacts/`. They use one isolated browser and close it when finished.++Run `node scripts/smoke-agent-topology.mjs` to inspect native GPU allocations during a shared-geometry addition and restoration.+Its staging-budget failure must allocate no buffers and retain the previous rendered frame.+Use `node scripts/smoke-agent-topology.mjs cpu` for software rendering. Both modes also verify recovery through a smaller CPU preview under a 32 MiB budget.diff --git a/package.json b/package.jsonindex 54e73af7..20834e0a 100644--- a/package.json+++ b/package.json@@ -83,6 +83,7 @@"smoke:package": "node scripts/smoke-package.mjs","mcp": "node scripts/mcp-server.mjs","smoke:mcp": "node scripts/smoke-mcp.mjs",+ "smoke:agent-topology": "node scripts/smoke-agent-topology.mjs","smoke:enhancements": "node scripts/smoke-enhancements.mjs","smoke:site": "node scripts/smoke-site.mjs","publish:ci": "node scripts/publish-ci.mjs"diff --git a/public/llms.txt b/public/llms.txtindex c3ddc098..6897a7f1 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -19,7 +19,15 @@ Read `/mcp.md` before configuring it. Start with `scene_capabilities`, create aCheckpoint, apply small revisioned batches, then use `scene_look` to assess the actual PNG.Restore failed experiments and release unused checkpoints. Export the recipe and dispose the scene when finished.The runtime keeps one browser scene alive, serializes calls, caps PNG responses and releases resources on stdin EOF.-It exposes no arbitrary code, file access, asset providers, dynamic node creation or video jobs.++Use `add-geometry`, `add-material` and `add-node` records to build a scene from an empty recipe.+Use explicit removal commands and `set-node` geometry/material fields to rebind meshes. Final batch references must resolve.+Removing a parent requires `recursive: true` or reparenting/removing its children in the same batch.++Active, checkpoint and staged geometry share a budget. Release unused checkpoints before increasing detail.+Topology changes reconcile rigid, untextured GPU parts. Geometry stays immutable and surviving shared buffers remain allocated.++It exposes no arbitrary code, file access, asset providers, animation authoring or video jobs.- [Release metadata](https://67js.codepawl.com/release.json): package name, version, publication status, install command, module URL and commit.- [Complete plain-text guide](https://67js.codepawl.com/guide.md): renderer, parts, materials, cameras, animation, lifecycle, export and troubleshooting.diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex e8ad07b1..40e847d7 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -49,6 +49,9 @@ function renderInfo(renderer) {height: canvas.height,samples: renderer.capabilities.samples,hdr: renderer.capabilities.hdr,+ geometryBuffers: renderer.geometryBuffers?.size ?? 0,+ gpuBuffers: renderer.buffers?.length ?? 0,+ drawBatches: renderer.batches?.length ?? 0,};}@@ -56,8 +59,15 @@ function draw(record) {if (record.renderer.context.isContextLost()) {throw new Error('The render context was lost. Export the recipe and dispose this session.');}+ // Shrink the existing target first so a smaller look can recover a staging-budget failure.record.renderer.resize();- record.renderer.updateParts(record.scene.parts);+ if (record.rendererTopology !== record.scene.topologyRevision) {+ record.renderer.replaceParts(record.scene.parts);+ record.rendererTopology = record.scene.topologyRevision;+ record.renderer.resize();+ } else {+ record.renderer.updateParts(record.scene.parts);+ }record.renderer.render({ ...record.scene.camera, effects });const error = record.renderer.context.getError();if (error !== 0) {@@ -71,6 +81,7 @@ function status(record) {return {sessionId: record.sessionId,revision: record.scene.revision,+ topologyRevision: record.scene.topologyRevision,inspection: record.scene.inspect(),render,};@@ -109,7 +120,7 @@ window.__agentPreview = {samples: backend === 'cpu' ? 1 : 4,memoryBudgetMiB,});- const record = { scene, renderer, sessionId, checkpoints: new Map() };+ const record = { scene, renderer, sessionId, checkpoints: new Map(), rendererTopology: scene.topologyRevision };draw(record);const result = status(record);if (backend === 'gpu' && /swiftshader|llvmpipe|software/i.test(result.render.graphics)) {@@ -139,10 +150,12 @@ window.__agentPreview = {look({ sessionId }) {const record = requireSession(sessionId);draw(record);+ const render = renderInfo(record.renderer);+ record.lastRender = render;return {data: canvas.toDataURL('image/png').split(',')[1],mimeType: 'image/png',- metadata: { sessionId, revision: record.scene.revision, ...renderInfo(record.renderer) },+ metadata: { sessionId, revision: record.scene.revision, topologyRevision: record.scene.topologyRevision, ...render },};},checkpoint({ sessionId, checkpointId }) {diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex 062421f7..290c9480 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -176,7 +176,7 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memopreview: { backend, memoryBudgetMiB: memory, maximumWidth: 1024, maximumHeight: 1024, maximumImageBytes: MAXIMUM_IMAGE_BYTES, maximumActiveScenes: 1, maximumQueuedCalls: MAXIMUM_QUEUED_CALLS, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS },phase: closing && phase !== 'closed' ? 'closing' : phase,availableIn: 'source after npm 0.4.1',- unsupported: ['dynamic node creation', 'asset providers', 'arbitrary code execution', 'animation authoring', 'video jobs'],+ unsupported: ['asset providers', 'arbitrary code execution', 'animation authoring', 'video jobs'],};},create({ recipe }) {diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex c9e2c58c..5db3f6a3 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -24,6 +24,7 @@ const nodeFields = {rotation: quaternion.optional().describe('Nonzero local XYZW quaternion. The backend normalizes it.'),scale: z.tuple([positive, positive, positive]).optional().describe('Positive local XYZ scale.'),};+const nodeRecord = z.strictObject({ id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields });const materialFields = {color: color.optional().describe('Linear RGB base color, each component between zero and one.'),metallic: unit.optional(),@@ -53,13 +54,19 @@ const recipe = z.strictObject({schemaVersion: z.literal(1),geometries: z.array(geometry).max(256),materials: z.array(z.strictObject({ id: identifier, tag: z.enum(['surface', 'unlit']).optional(), ...materialFields })).max(256),- nodes: z.array(z.strictObject({ id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields })).max(4096),+ nodes: z.array(nodeRecord).max(4096),camera: z.strictObject(cameraFields).optional(),}).describe('Bounded scene recipe. Backend validates references, mesh resource pairs, hierarchy, geometry budgets and camera consistency.');const operation = z.discriminatedUnion('type', [- z.strictObject({ type: z.literal('set-node'), id: identifier, ...nodeFields }),+ z.strictObject({ type: z.literal('set-node'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields }),z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }),z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),+ z.strictObject({ type: z.literal('add-node'), node: nodeRecord }),+ z.strictObject({ type: z.literal('remove-node'), id: identifier, recursive: z.boolean().optional().describe('Remove descendants too. Defaults to false; dangling children reject the batch.') }),+ z.strictObject({ type: z.literal('add-geometry'), geometry }),+ z.strictObject({ type: z.literal('remove-geometry'), id: identifier }),+ z.strictObject({ type: z.literal('add-material'), material: z.strictObject({ id: identifier, tag: z.enum(['surface', 'unlit']).optional(), ...materialFields }) }),+ z.strictObject({ type: z.literal('remove-material'), id: identifier }),]);const sessionFields = { sessionId: z.uuid().describe('Session UUID returned by scene_create.') };const checkpointFields = { ...sessionFields, checkpointId: z.uuid().describe('Checkpoint UUID returned by scene_checkpoint for this session.') };@@ -73,7 +80,7 @@ function jsonResult(value) {export function createAgentMcpServer(runtime, { version = '0.4.1' } = {}) {const server = new McpServer({ name: '67js-scene', version }, {- instructions: 'Start with scene_capabilities, then scene_create and scene_inspect. Before editing, save a scene_checkpoint. Apply small batches with the current expectedRevision and check committed, revision and renderSucceeded. A committed edit can have a separate renderError; do not retry it with an old revision. Use scene_look to judge the rendered image. Restore failed experiments or release unused checkpoints. Export the final recipe and dispose the scene when finished. Resources and node membership are fixed. No arbitrary JavaScript, URLs, files or jobs are exposed.',+ instructions: 'Start with scene_capabilities, then scene_create and scene_inspect. Before editing, save a scene_checkpoint. Apply small batches with the current expectedRevision and check committed, revision and renderSucceeded. Add nodes and shared geometry/material resources through explicit commands; references must resolve in the final batch. Removing a parent requires recursive:true or removing/reparenting its children. A committed edit can have a separate renderError; do not retry it with an old revision. Use scene_look to judge the rendered image. Restore failed experiments or release unused checkpoints. Export the final recipe and dispose the scene when finished. No arbitrary JavaScript, URLs, files or jobs are exposed.',});let closePromise;server.server.onclose = () => {@@ -96,7 +103,7 @@ export function createAgentMcpServer(runtime, { version = '0.4.1' } = {}) {register('scene_capabilities', 'Read supported recipe features and runtime budgets before authoring. Does not launch a browser.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.capabilities()));register('scene_create', 'Create the single active render scene from a JSON recipe. Dispose an existing scene first.', z.strictObject({ recipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.create(argumentsValue)));register('scene_inspect', 'Read revision, counts and selected nodes. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));- register('scene_apply', 'Atomically apply one small command batch. Successful batches increment revision once. Geometry and node membership remain fixed.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Commands with flat fields. All commands validate before publication.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));+ register('scene_apply', 'Atomically edit transforms, camera, materials or scene membership. Add immutable geometry and shared materials; remove unused resources explicitly. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Set commands use flat fields; add commands contain node, geometry or material records. Final references and budgets validate before publication.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));register('scene_look', 'Render the active scene as a bounded PNG image for visual assessment.', z.strictObject({ ...sessionFields, width: z.number().int().min(64).max(1024).default(768).describe('PNG width in pixels.'), height: z.number().int().min(64).max(1024).default(512).describe('PNG height in pixels.') }), readOnly, async argumentsValue => {const { data, mimeType, metadata } = await runtime.look(argumentsValue);return { content: [{ type: 'image', data, mimeType }, { type: 'text', text: JSON.stringify(metadata) }], structuredContent: metadata };diff --git a/scripts/smoke-agent-topology.mjs b/scripts/smoke-agent-topology.mjsnew file mode 100644index 00000000..02701d67--- /dev/null+++ b/scripts/smoke-agent-topology.mjs@@ -0,0 +1,161 @@+import assert from 'node:assert/strict';+import { mkdir, writeFile } from 'node:fs/promises';+import { constants, setPriority } from 'node:os';+import { createServer } from 'vite';+import { chromium } from 'playwright';+import { createAgentPreviewFixture } from './agent-preview-fixture.mjs';+import { createAgentRuntime } from './agent-runtime.mjs';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const backend = process.argv[2] ?? 'gpu';+assert.ok(['gpu', 'cpu'].includes(backend));+await mkdir('artifacts', { recursive: true });+const fixture = createAgentPreviewFixture();+const harness = `<!doctype html><html><head><style>html,body{margin:0;height:100%;background:#182126}canvas{width:100vw;height:100vh;display:block}</style></head><body><canvas></canvas><script type="module">+import {createAgentScene} from '/src/agent-scene.js';+import {Renderer67} from '/src/renderer.js';+const recipe=${JSON.stringify(fixture)};+const session=createAgentScene({...recipe,geometries:[],materials:[],nodes:[]});+const renderer=new Renderer67(document.querySelector('canvas'),session.parts,{ground:false,hdr:true,samples:4,pixelRatio:1,memoryBudgetMiB:192});+const counters={buffers:0,arrays:0,textures:0,framebuffers:0,renderbuffers:0,staticUploads:0,dynamicUploads:0};+const liveBuffers=new Set();+const context=renderer.context;+for(const [method,field] of [['createBuffer','buffers'],['createVertexArray','arrays'],['createTexture','textures'],['createFramebuffer','framebuffers'],['createRenderbuffer','renderbuffers']]) {+ const original=context[method].bind(context);+ context[method]=(...parameters)=>{+ counters[field]++;+ const result=original(...parameters);+ if(method==='createBuffer') liveBuffers.add(result);+ return result;+ };+}+const originalDelete=context.deleteBuffer.bind(context);+context.deleteBuffer=buffer=>{+ liveBuffers.delete(buffer);+ return originalDelete(buffer);+};+const originalUpload=context.bufferData.bind(context);+context.bufferData=(target,data,usage)=>{+ counters[usage===context.STATIC_DRAW?'staticUploads':'dynamicUploads']++;+ return originalUpload(target,data,usage);+};+function draw() {+ renderer.resize();+ renderer.updateParts(session.parts);+ renderer.render({...session.camera,effects:{bloom:{strength:0.12,threshold:1,radius:1},grain:0,vignette:0}});+}+function pixels() {+ const data=new Uint8Array(context.drawingBufferWidth*context.drawingBufferHeight*4);+ context.readPixels(0,0,context.drawingBufferWidth,context.drawingBufferHeight,context.RGBA,context.UNSIGNED_BYTE,data);+ return data;+}+session.apply([...recipe.geometries.map(geometry=>({type:'add-geometry',geometry})),...recipe.materials.map(material=>({type:'add-material',material})),...recipe.nodes.map(node=>({type:'add-node',node}))],{expectedRevision:0});+renderer.replaceParts(session.parts);+draw();+window.__topology={recipe,session,renderer,draw,pixels,counters,liveBuffers};+</script></body></html>`;+await writeFile('artifacts/agent-topology-harness.html', harness);+const server = await createServer({ server: { host: '127.0.0.1', port: 0 }, logLevel: 'silent' });+let browser;+try {+ await server.listen();+ const port = server.httpServer.address().port;+ const args = ['--enable-webgl', '--ignore-gpu-blocklist', '--disable-renderer-backgrounding'];+ if (backend === 'cpu') args.push('--use-angle=swiftshader', '--enable-unsafe-swiftshader');+ browser = await chromium.launch({ executablePath: 'C:/Program Files/Google/Chrome/Application/chrome.exe', headless: true, args });+ const page = await browser.newPage({ viewport: { width: 960, height: 540 } });+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.goto(`http://127.0.0.1:${port}/artifacts/agent-topology-harness.html`);+ await page.waitForFunction(() => window.__topology);+ await page.screenshot({ path: 'artifacts/agent-topology-built.png' });+ const result = await page.evaluate(() => {+ const { session, renderer, draw, pixels, counters, liveBuffers } = window.__topology;+ draw();+ const before = pixels();+ const checkpoint = session.checkpoint();+ const geometryBuffers = renderer.geometryBuffers.get(session.parts.find(part => part.name === 'fin-0').geometry);+ const originalBuffers = [...geometryBuffers.values()];+ const firstCounters = { ...counters };+ session.apply([{ type: 'add-node', node: { id: 'extra-fin', geometry: 'fin', material: 'brass', translation: [-0.9, 0.8, 0.1], scale: [0.5, 0.5, 0.5] } }], { expectedRevision: session.revision });+ renderer.replaceParts(session.parts);+ draw();+ const after = pixels();+ const added = Object.fromEntries(Object.entries(counters).map(([key, count]) => [key, count - firstCounters[key]]));+ const sharedBuffersRetained = originalBuffers.every(buffer => liveBuffers.has(buffer));+ let changedChannels = 0;+ for (let index = 0; index < before.length; index++) {+ if (before[index] !== after[index]) changedChannels++;+ }+ session.restore(checkpoint, { expectedRevision: session.revision });+ renderer.replaceParts(session.parts);+ draw();+ const restored = pixels();+ const exactRestore = restored.every((value, index) => value === before[index]);+ session.releaseCheckpoint(checkpoint);+ const previousBatches = [...renderer.batches];+ const previousBudget = renderer.memoryBudgetMiB;+ renderer.memoryBudgetMiB = renderer.memoryPlan.estimatedBytes / 1048576;+ const staged = { ...session.parts[0], name: 'budget-probe' };+ const allocationCount = counters.buffers;+ let budgetRejected = false;+ try {+ renderer.replaceParts([...session.parts, staged]);+ } catch (error) {+ budgetRejected = /staged replacement/.test(error.message);+ }+ renderer.memoryBudgetMiB = previousBudget;+ const noFailedAllocations = counters.buffers === allocationCount;+ const previousBatchesRetained = previousBatches.every((batch, index) => batch === renderer.batches[index]);+ draw();+ const afterRejected = pixels();+ const failureFrameRetained = afterRejected.every((value, index) => value === before[index]);+ const debug = renderer.context.getExtension('WEBGL_debug_renderer_info');+ const graphics = renderer.context.getParameter(debug.UNMASKED_RENDERER_WEBGL);+ const glError = renderer.context.getError();+ window.__topology.finalImage = document.querySelector('canvas').toDataURL('image/png');+ const estimatedBytes = renderer.memoryPlan.estimatedBytes;+ renderer.dispose();+ return { changedChannels, added, sharedBuffersRetained, exactRestore, budgetRejected, noFailedAllocations, previousBatchesRetained, failureFrameRetained, liveBuffers: liveBuffers.size, graphics, glError, estimatedBytes };+ });+ assert.deepEqual(errors, []);+ assert.match(result.graphics, backend === 'gpu' ? /NVIDIA/ : /SwiftShader/);+ assert.ok(result.changedChannels > 1000);+ assert.deepEqual(result.added, { buffers: 1, arrays: 1, textures: 0, framebuffers: 0, renderbuffers: 0, staticUploads: 0, dynamicUploads: 1 });+ for (const field of ['sharedBuffersRetained', 'exactRestore', 'budgetRejected', 'noFailedAllocations', 'previousBatchesRetained', 'failureFrameRetained']) assert.equal(result[field], true, field);+ assert.equal(result.liveBuffers, 0);+ assert.equal(result.glError, 0);+ const data = await page.evaluate(() => window.__topology.finalImage);+ await writeFile('artifacts/agent-topology-restored.png', Buffer.from(data.split(',')[1], 'base64'));+ await writeFile(`artifacts/agent-topology-${backend}.json`, JSON.stringify(result, null, 2));+ console.log(JSON.stringify(result));+} finally {+ await browser?.close();+ await server.close();+}++// A smaller look must recover an already committed edit whose GPU staging budget failed.+const runtime = createAgentRuntime({ backend: 'cpu', memory: 32 });+try {+ const initial = await runtime.create({ recipe: { ...fixture, geometries: [], materials: [], nodes: [] } });+ const { sessionId } = initial;+ await runtime.look({ sessionId, width: 1024, height: 1024 });+ const edited = await runtime.apply({ sessionId, expectedRevision: 0, operations: [+ ...fixture.geometries.map(geometry => ({ type: 'add-geometry', geometry })),+ ...fixture.materials.map(material => ({ type: 'add-material', material })),+ ...fixture.nodes.map(node => ({ type: 'add-node', node })),+ ] });+ assert.equal(edited.committed, true);+ assert.equal(edited.revision, 1);+ assert.equal(edited.renderSucceeded, false);+ assert.match(edited.renderError, /staged replacement/);+ const recovered = await runtime.look({ sessionId, width: 128, height: 128 });+ assert.equal(recovered.metadata.revision, 1);+ assert.equal(recovered.metadata.geometryBuffers, 7);+ assert.equal(recovered.metadata.width, 128);+ assert.ok(recovered.metadata.estimatedBytes < 32 * 1048576);+ assert.equal((await runtime.inspect({ sessionId })).counts.parts, 19);+ console.log(JSON.stringify({ stagingRecovery: true, revision: 1, preview: [128, 128], budgetMiB: 32 }));+} finally {+ await runtime.close();+}diff --git a/scripts/smoke-mcp.mjs b/scripts/smoke-mcp.mjsindex 06f4cd27..ff51335c 100644--- a/scripts/smoke-mcp.mjs+++ b/scripts/smoke-mcp.mjs@@ -56,23 +56,31 @@ try {assert.equal(listing.tools.length, 10);const capabilities = (await call('scene_capabilities')).structuredContent;assert.equal(capabilities.phase, 'idle');- const created = (await call('scene_create', { recipe: createAgentPreviewFixture() })).structuredContent;- const { sessionId } = created;+ const fixture = createAgentPreviewFixture();+ const empty = (await call('scene_create', { recipe: { ...fixture, geometries: [], materials: [], nodes: [] } })).structuredContent;+ const { sessionId } = empty;+ assert.equal(empty.inspection.counts.parts, 0);+ const created = (await call('scene_apply', { sessionId, expectedRevision: 0, operations: [+ ...fixture.geometries.map(geometry => ({ type: 'add-geometry', geometry })),+ ...fixture.materials.map(material => ({ type: 'add-material', material })),+ ...fixture.nodes.map(node => ({ type: 'add-node', node })),+ ] })).structuredContent;+ assert.equal(created.renderSucceeded, true);assert.equal(created.inspection.counts.parts, 19);assert.equal(created.inspection.counts.geometries, 7);- assert.equal(created.revision, 0);+ assert.equal(created.revision, 1);assert.match(created.render.graphics, backend === 'gpu' ? /NVIDIA/i : /SwiftShader/i);const before = await look(sessionId, 'before');const checkpoint = (await call('scene_checkpoint', { sessionId })).structuredContent;const edited = (await call('scene_apply', {- sessionId, expectedRevision: 0,+ sessionId, expectedRevision: 1,operations: [{ type: 'set-node', id: 'lamp', translation: [0.18, 0.82, 0] },{ type: 'set-node', id: 'glow', scale: [0.34, 0.3, 0.34], translation: [0, 0.75, 0] },{ type: 'set-material', id: 'light', color: [0.9, 0.28, 0.04], emissiveColor: [0.9, 0.28, 0.04] },],})).structuredContent;- assert.equal(edited.revision, 1);+ assert.equal(edited.revision, 2);assert.equal(edited.committed, true);assert.equal(edited.renderSucceeded, true);const after = await look(sessionId, 'after');@@ -82,21 +90,45 @@ try {} });assert.equal(stale.isError, true);const inspection = (await call('scene_inspect', { sessionId, ids: ['lamp', 'glow'], includeBounds: true })).structuredContent;- assert.equal(inspection.revision, 1);+ assert.equal(inspection.revision, 2);assert.equal(inspection.nodes.length, 2);assert.ok(inspection.nodes[1].bounds);- const restoredStatus = (await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: 1 })).structuredContent;+ const restoredStatus = (await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: 2 })).structuredContent;assert.equal(restoredStatus.committed, true);assert.equal(restoredStatus.renderSucceeded, true);const restored = await look(sessionId, 'restored');assert.deepEqual(restored.bytes, before.bytes);+ const enlarged = (await call('scene_apply', { sessionId, expectedRevision: 3, operations: [+ { type: 'add-geometry', geometry: { id: 'ornament', type: 'sphere', segments: 24, rings: 16 } },+ { type: 'add-material', material: { id: 'ruby', color: [0.8, 0.04, 0.06], metallic: 0.6, roughness: 0.2 } },+ { type: 'add-node', node: { id: 'ornament', geometry: 'ornament', material: 'ruby', translation: [-1.2, 0.8, 0], scale: [0.28, 0.28, 0.28] } },+ ] })).structuredContent;+ assert.equal(enlarged.renderSucceeded, true);+ assert.equal(enlarged.inspection.counts.parts, 20);+ assert.equal(enlarged.render.geometryBuffers, 8);+ const topology = await look(sessionId, 'topology');+ assert.notDeepEqual(topology.bytes, before.bytes);+ await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: 4 });+ const topologyRestored = await look(sessionId, 'topology-restored');+ assert.deepEqual(topologyRestored.bytes, before.bytes);+ assert.equal(topologyRestored.metadata.geometryBuffers, 7);+ const removed = (await call('scene_apply', { sessionId, expectedRevision: 5, operations: [+ { type: 'remove-node', id: 'lamp', recursive: true },+ ...fixture.geometries.map(geometry => ({ type: 'remove-geometry', id: geometry.id })),+ ...fixture.materials.map(material => ({ type: 'remove-material', id: material.id })),+ ] })).structuredContent;+ assert.equal(removed.renderSucceeded, true);+ assert.equal(removed.inspection.counts.parts, 0);+ assert.equal(removed.render.gpuBuffers, 0);+ await call('scene_restore', { sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: 6 });+ assert.deepEqual((await look(sessionId, 'recreated')).bytes, before.bytes);await call('scene_release_checkpoint', { sessionId, checkpointId: checkpoint.checkpointId });const exported = (await call('scene_export_recipe', { sessionId })).structuredContent;- assert.equal(exported.revision, 2);+ assert.equal(exported.revision, 7);assert.deepEqual(exported.recipe.nodes.find(node => node.id === 'lamp').translation, [0, 0.82, 0]);await writeFile(`artifacts/mcp-${backend}-${era}-recipe.json`, JSON.stringify(exported.recipe, null, 2));const portrait = await look(sessionId, 'portrait', 540, 960);- await call('scene_apply', { sessionId, expectedRevision: 2, operations: [+ await call('scene_apply', { sessionId, expectedRevision: 7, operations: [{ type: 'set-camera', eye: [0, 5.5, 0], target: [0, 1.06, 0], up: [0, 0, -1] },] });await look(sessionId, 'top', 540, 960);@@ -109,7 +141,8 @@ try {assert.notEqual(replacement.sessionId, sessionId);await call('scene_dispose', { sessionId: replacement.sessionId });report = { backend, era, tools: listing.tools.length, parts: created.inspection.counts.parts, geometryBytes: created.inspection.geometryBytes,- graphics: created.render.graphics, before: before.metadata, portrait: portrait.metadata, restorePngExact: true, staleRevisionRejected: true };+ graphics: created.render.graphics, before: before.metadata, portrait: portrait.metadata, restorePngExact: true, staleRevisionRejected: true,+ builtFromEmpty: true, topologyRestoreExact: true, disposedGeometryBuffers: true };} finally {await client.close();}diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex d15e4096..521064b7 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -145,6 +145,18 @@ if (${!published}) {agentScene.restore(agentCheckpoint, { expectedRevision: agentScene.revision });assert.equal(agentPart.matrix[12], 0);agentScene.releaseCheckpoint(agentCheckpoint);+ const dynamicCheckpoint = agentScene.checkpoint();+ agentScene.apply([+ { type: 'add-geometry', geometry: { id: 'ball', type: 'sphere', segments: 12, rings: 8 } },+ { type: 'add-node', node: { id: 'ball', geometry: 'ball', material: 'paint', translation: [1, 0, 0] } },+ ], { expectedRevision: agentScene.revision });+ assert.equal(agentScene.parts.length, 2);+ assert.equal(agentScene.parts[0], agentPart);+ assert.equal(agentScene.topologyRevision, 1);+ agentScene.restore(dynamicCheckpoint, { expectedRevision: agentScene.revision });+ assert.equal(agentScene.parts.length, 1);+ assert.equal(agentScene.parts[0], agentPart);+ agentScene.releaseCheckpoint(dynamicCheckpoint);}const parts = createModel();assert.equal(parts.length, 574);diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex b5cda096..35cf7b15 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -134,20 +134,23 @@ The surface-attachment addon is included in npm `0.4.1`.Agent authoring uses `createAgentScene(recipe, limits)` from `67js/addons/agent-scene`.This addon is available in source after npm `0.4.1`; it is not included in that published package.-Read `docs/agent-scene.md` for schema version one and its fixed resource topology.+Read `docs/agent-scene.md` for schema version one, immutable resources and atomic topology commands.Start with capabilities and bounded inspection. Edit stable IDs through one `apply` batch with the current `expectedRevision`.Checkpoint before uncertain changes, inspect and render the result, then restore or release the checkpoint.-Call `renderer.updateParts(session.parts)` after successful edits, then render the detached `session.camera` snapshot.+For rigid, untextured scenes, compare `session.topologyRevision` with the uploaded revision after successful edits.+Call `renderer.replaceParts(session.parts)` for changed topology or `renderer.updateParts(session.parts)` for retained parts, then render the detached camera.+Use add/remove commands for nodes and shared resources, and `set-node` geometry/material fields for rebinding.+Release unused checkpoints before increasing detail; active, checkpoint and staged geometry share a peak allocation budget.Keep JSON commands and snapshots exposed to agents; retained matrices and immutable geometry belong to the renderer adapter.Do not inspect all vertex bounds in a frame loop. Memory estimates cover unique geometry arrays, not total RAM or VRAM.-The scene addon does not implement MCP transport, dynamic node creation, asset search, or render jobs.+The scene addon does not implement MCP transport, asset search, animation authoring, or render jobs.For a configured MCP client, use the separate source-only server documented in `docs/mcp.md`.Call `scene_capabilities`, create one JSON scene, inspect IDs, checkpoint, apply a small batch, and assess `scene_look` PNG content.Use the revision returned by each committed apply or restore. A response with `committed: true` and `renderSucceeded: false` still advances revision.Inspect or export the canonical recipe after a render failure; do not retry the edit with its old revision.The server retains one renderer, bounds image dimensions and payloads, and closes its browser on stdio EOF.-Export the recipe before disposal. Dynamic nodes, asset ingestion, animation authoring and video jobs remain unsupported by these tools.+Export the recipe before disposal. Asset ingestion, animation authoring and video jobs remain unsupported by these tools.`cameraView('front' | 'right' | 'top')` returns an orthographic camera with the correct up vector.`fitOrthographicHeight(bounds, view, aspect)` frames both model width and height.diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 2d0f9f81..6551febc 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -10,16 +10,28 @@ const DEFAULT_LIMITS = Object.freeze({maxOperations: 256, maxCheckpoints: 8, maxRecipeBytes: 1024 * 1024,});const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 });-const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label'];+const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material'];const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor'];const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);+const ADDITION_FIELDS = Object.freeze({+ 'add-geometry': ['geometries', 'geometry'],+ 'add-material': ['materials', 'material'],+ 'add-node': ['nodes', 'node'],+});+const REMOVAL_FIELDS = Object.freeze({+ 'remove-geometry': 'geometries',+ 'remove-material': 'materials',+});export const AGENT_SCENE_CAPABILITIES = Object.freeze({format: '67js.scene', schemaVersion: 1,geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube']),- operations: Object.freeze(['set-node', 'set-material', 'set-camera']),+ operations: Object.freeze([+ 'set-node', 'set-material', 'set-camera', 'add-node', 'remove-node',+ 'add-geometry', 'remove-geometry', 'add-material', 'remove-material',+ ]),materialTags: Object.freeze(['surface', 'unlit']),- fixedResources: true, checkpoints: true, positiveScaleOnly: true,+ fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,});function knownKeys(value, allowed, label) {@@ -208,7 +220,9 @@ function nodeFrom(value) {translation: vector(defaultValue(value.translation, [0, 0, 0]), 3, 'translation'),rotation: vector(defaultValue(value.rotation, [0, 0, 0, 1]), 4, 'rotation'),scale: vector(defaultValue(value.scale, [1, 1, 1]), 3, 'scale') };- if (result.parent !== null) identifier(result.parent);+ if (result.parent !== null) {+ identifier(result.parent);+ }if (result.label !== undefined && (typeof result.label !== 'string' || result.label.length > 256)) {throw new TypeError('label must be a string of at most 256 characters.');}@@ -241,7 +255,9 @@ function cameraFrom(value = {}) {throw new RangeError('Camera up must be nonzero.');}result.up = result.up.map(component => component / upLength);- for (const field of ['fov', 'near', 'far']) finite(result[field], field);+ for (const field of ['fov', 'near', 'far']) {+ finite(result[field], field);+ }if (Math.fround(result.fov) <= 0 || Math.fround(result.fov) >= 180 || Math.fround(result.near) <= 0 || Math.fround(result.far) <= Math.fround(result.near)) {throw new RangeError('Camera needs 0 < fov < 180 and 0 < near < far at Float32 precision.');}@@ -250,9 +266,9 @@ function cameraFrom(value = {}) {}const direction = result.target.map((component, axis) => component - result.eye[axis]);const directionLength = Math.hypot(...direction);- const unit = direction.map(component => component / directionLength);- const crossLength = Math.hypot(unit[1] * result.up[2] - unit[2] * result.up[1],- unit[2] * result.up[0] - unit[0] * result.up[2], unit[0] * result.up[1] - unit[1] * result.up[0]);+ const unitDirection = direction.map(component => component / directionLength);+ const crossLength = Math.hypot(unitDirection[1] * result.up[2] - unitDirection[2] * result.up[1],+ unitDirection[2] * result.up[0] - unitDirection[0] * result.up[2], unitDirection[0] * result.up[1] - unitDirection[1] * result.up[0]);if (Math.fround(crossLength) === 0) {throw new RangeError('Camera up must not be collinear with the view direction.');}@@ -287,18 +303,27 @@ function geometryEstimate(value) {if (!Array.isArray(input) || input.length < minimum || input.length > 4096) {throw new RangeError('Geometry point count exceeds its limit.');}- for (const point of input) vector(point, size, 'geometry point');+ for (const point of input) {+ vector(point, size, 'geometry point');+ }return input.length;}for (const field of GEOMETRY_FIELDS[value.type]) {- if (value[field] !== undefined && !['profile', 'contour', 'holes', 'path', 'closed'].includes(field)) finite(value[field], field);+ if (value[field] !== undefined && !['profile', 'contour', 'holes', 'path', 'closed'].includes(field)) {+ finite(value[field], field);+ }}switch (value.type) {- case 'box': return value.bevel === 0 ? 24 : 6 * (2 * detail('subdivisions', 6, 1, 128) + 2) ** 2;- case 'cylinder': return (detail('segments', 80, 3, 2048) + 1) * 2 * (detail('bevelSegments', 6, 1, 128) + 1) + 2 * ((value.segments ?? 80) + 2);- case 'sphere': return (detail('segments', 64, 3, 2048) + 1) * (detail('rings', 40, 2, 2048) + 1);- case 'torus': return (detail('segments', 96, 3, 2048) + 1) * (detail('sides', 24, 3, 128) + 1) + 2 * ((value.sides ?? 24) + 2);- case 'lathe': return (detail('segments', 64, 3, 2048) + 1) * points(value.profile, 2, 2);+ case 'box':+ return value.bevel === 0 ? 24 : 6 * (2 * detail('subdivisions', 6, 1, 128) + 2) ** 2;+ case 'cylinder':+ return (detail('segments', 80, 3, 2048) + 1) * 2 * (detail('bevelSegments', 6, 1, 128) + 1) + 2 * ((value.segments ?? 80) + 2);+ case 'sphere':+ return (detail('segments', 64, 3, 2048) + 1) * (detail('rings', 40, 2, 2048) + 1);+ case 'torus':+ return (detail('segments', 96, 3, 2048) + 1) * (detail('sides', 24, 3, 128) + 1) + 2 * ((value.sides ?? 24) + 2);+ case 'lathe':+ return (detail('segments', 64, 3, 2048) + 1) * points(value.profile, 2, 2);case 'tube':points(value.path, 3, value.closed ? 3 : 2);if (value.closed !== undefined && typeof value.closed !== 'boolean') {@@ -322,13 +347,20 @@ function geometryEstimate(value) {function generateGeometry(value, maxVertices) {switch (value.type) {- case 'box': return box(value.bevel, value.subdivisions);- case 'cylinder': return cylinder(value.segments, value.bevel, value.bevelSegments);- case 'sphere': return sphere(value.segments, value.rings);- case 'torus': return torus(value.tubeRadius, value.segments, value.sides, value.arc, value.start);- case 'lathe': return lathe(value.profile, { ...value, maxVertices });- case 'extrude': return extrude(value.contour, { ...value, maxVertices });- case 'tube': return tube(value.path, { ...value, maxVertices });+ case 'box':+ return box(value.bevel, value.subdivisions);+ case 'cylinder':+ return cylinder(value.segments, value.bevel, value.bevelSegments);+ case 'sphere':+ return sphere(value.segments, value.rings);+ case 'torus':+ return torus(value.tubeRadius, value.segments, value.sides, value.arc, value.start);+ case 'lathe':+ return lathe(value.profile, { ...value, maxVertices });+ case 'extrude':+ return extrude(value.contour, { ...value, maxVertices });+ case 'tube':+ return tube(value.path, { ...value, maxVertices });}}@@ -336,7 +368,7 @@ function compile(recipe, geometries, localBounds, limits) {const materials = new Map(recipe.materials.map(material => [material.id, material]));const graph = createSceneGraph(recipe.nodes.map(node => {if (node.geometry !== undefined && (!geometries.has(node.geometry) || !materials.has(node.material))) {- throw new RangeError(`Node ${node.id} references an unknown resource.`);+ throw new RangeError(`Unknown resource referenced by node ${node.id}.`);}return { name: node.id, parent: node.parent,matrix: mat4.fromRotationTranslationScale(mat4.create(), node.rotation, node.translation, node.scale),@@ -380,60 +412,233 @@ function boundsFor(geometry, matrix) {return { min: minimum, max: maximum };}-/** A bounded CPU authoring session. Render adapters must treat geometry as immutable. */-export function createAgentScene(input, inputLimits = {}) {- const limits = resolveLimits(inputLimits);+function normalizeRecipe(input, limits) {let recipe = copiedJson(input, limits.maxRecipeBytes);knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'camera'], 'recipe');if (recipe.format !== '67js.scene' || recipe.schemaVersion !== 1) {throw new RangeError('Expected 67js.scene schemaVersion 1.');}- recipe.geometries = resources(recipe.geometries, limits.maxGeometries, 'geometries', value => value);+ recipe.geometries = resources(recipe.geometries, limits.maxGeometries, 'geometries', value => {+ geometryEstimate(value);+ const definition = { id: value.id, type: value.type };+ for (const field of GEOMETRY_FIELDS[value.type]) {+ if (Object.hasOwn(value, field)) {+ definition[field] = value[field];+ }+ }+ return definition;+ });recipe.materials = resources(recipe.materials, limits.maxMaterials, 'materials', materialFrom);recipe.nodes = resources(recipe.nodes, limits.maxNodes, 'nodes', nodeFrom);recipe.camera = cameraFrom(recipe.camera);- const estimatedVertices = recipe.geometries.reduce((total, value) => total + geometryEstimate(value), 0);- // Every supported generator uses at most six Uint32 indices per vertex and eight floats per vertex.- const estimatedGeometryBytes = estimatedVertices * 56;- if (estimatedVertices > limits.maxVertices || estimatedGeometryBytes > limits.maxGeometryBytes) {- throw new RangeError('Geometry preflight exceeds maxVertices or maxGeometryBytes. Reduce detail.');- }recipe = copiedJson(recipe, limits.maxRecipeBytes);- const geometries = new Map(recipe.geometries.map(value => [value.id, Object.freeze(generateGeometry(value, Math.min(limits.maxVertices, 1_000_000)))]));- const localBounds = new Map([...geometries.values()].map(geometry => [geometry, boundsFor(geometry, mat4.create())]));- let graph = compile(recipe, geometries, localBounds, limits);- const geometryBytes = [...geometries.values()].reduce((total, geometry) => total + Object.values(geometry).reduce((sum, array) => sum + array.byteLength, 0), 0);- const vertices = [...geometries.values()].reduce((total, geometry) => total + geometry.positions.length / 3, 0);- if (vertices > limits.maxVertices || geometryBytes > limits.maxGeometryBytes) {- throw new RangeError('Generated geometry exceeds its budget.');+ return recipe;+}++function geometryStats(records) {+ let vertices = 0;+ let geometryBytes = 0;+ let estimatedGeometryBytes = 0;+ for (const record of records) {+ vertices += record.vertices;+ geometryBytes += record.geometryBytes;+ estimatedGeometryBytes += record.estimatedVertices * 56;+ }+ return { vertices, geometryBytes, estimatedGeometryBytes };+}++function materialHandle(snapshot) {+ const holder = { snapshot };+ const output = {};+ for (const field of ['tag', ...MATERIAL_FIELDS]) {+ Object.defineProperty(output, field, {+ enumerable: true,+ get() {+ return holder.snapshot[field];+ },+ });+ }+ return { holder, output: Object.freeze(output) };+}++function immutableMaterial(snapshot) {+ for (const field of ['color', 'emissiveColor']) {+ if (snapshot[field]) {+ Object.freeze(snapshot[field]);+ }+ }+ return Object.freeze(snapshot);+}++function retainedMatrices(parts) {+ for (const part of parts) {+ if (part.matrix.length !== 16 || part.matrix.byteLength !== 64) {+ throw new RangeError('Retained render matrices must not be detached.');+ }}+}++function removeNode(candidate, operation) {+ knownKeys(operation, ['type', 'id', 'recursive'], 'operation');+ identifier(operation.id);+ const recursive = operation.recursive === undefined ? false : operation.recursive;+ if (typeof recursive !== 'boolean') {+ throw new TypeError('recursive must be boolean.');+ }+ if (!candidate.nodes.some(node => node.id === operation.id)) {+ throw new RangeError(`Operation ID was not found: ${operation.id}.`);+ }+ const children = new Map();+ for (const node of candidate.nodes) {+ const siblings = children.get(node.parent) ?? [];+ siblings.push(node.id);+ children.set(node.parent, siblings);+ }+ if (!recursive && (children.get(operation.id)?.length ?? 0) > 0) {+ throw new RangeError('Nonrecursive removal cannot remove a node with children. Remove children first or use recursive.');+ }+ const removed = new Set([operation.id]);+ const pending = [operation.id];+ if (recursive) {+ for (let cursor = 0; cursor < pending.length; cursor++) {+ for (const child of children.get(pending[cursor]) ?? []) {+ if (!removed.has(child)) {+ removed.add(child);+ pending.push(child);+ }+ }+ }+ }+ candidate.nodes = candidate.nodes.filter(node => !removed.has(node.id));+ return removed;+}++/** A bounded CPU authoring session. Render adapters must treat geometry as immutable. */+export function createAgentScene(input, inputLimits = {}) {+ const limits = resolveLimits(inputLimits);+ let state = null;let revision = 0;+ let topologyRevision = 0;const checkpoints = new Map();- let currentMaterials = new Map();- function snapshotsFor(materials) {- return new Map(materials.map(material => {- for (const field of ['color', 'emissiveColor']) {- if (material[field]) {- Object.freeze(material[field]);++ function ownedGeometryRecords() {+ const records = new Set(state?.geometryRecords.values() ?? []);+ for (const checkpoint of checkpoints.values()) {+ for (const record of checkpoint.geometryRecords.values()) {+ records.add(record);+ }+ }+ return records;+ }++ function stage(inputRecipe, preferred = null, removedNodes = new Set(), removedMaterials = new Set()) {+ const recipe = normalizeRecipe(inputRecipe, limits);+ if (state) {+ retainedMatrices(state.parts);+ }+ const ownedRecords = ownedGeometryRecords();+ const availableRecords = new Map();+ for (const record of ownedRecords) {+ availableRecords.set(record.signature, record);+ }+ const plans = recipe.geometries.map(definition => {+ const signature = JSON.stringify(definition);+ const preferredRecord = preferred?.geometryRecords.get(definition.id);+ const activeRecord = state?.geometryRecords.get(definition.id);+ const existing = [preferredRecord, activeRecord, availableRecords.get(signature)]+ .find(record => record?.signature === signature);+ return { definition, signature, existing, estimatedVertices: geometryEstimate(definition) };+ });+ const residentStats = geometryStats(ownedRecords);+ const pendingPlans = plans.filter(plan => !plan.existing);+ const pendingVertices = pendingPlans.reduce((total, plan) => total + plan.estimatedVertices, 0);+ if (residentStats.vertices + pendingVertices > limits.maxVertices ||+ residentStats.geometryBytes + pendingVertices * 56 > limits.maxGeometryBytes) {+ throw new RangeError('Geometry preflight exceeds peak maxVertices or maxGeometryBytes across active, checkpoint, and staged resources. Reduce detail or release checkpoints.');+ }++ // Validate references, hierarchy and matrix arithmetic before generating any new resource.+ const placeholders = new Map();+ const placeholderBounds = new Map();+ for (const plan of plans) {+ const geometry = plan.existing?.geometry ?? Object.freeze({});+ placeholders.set(plan.definition.id, geometry);+ placeholderBounds.set(geometry, plan.existing?.bounds ?? { min: [0, 0, 0], max: [0, 0, 0] });+ }+ compile(recipe, placeholders, placeholderBounds, limits);++ const geometryRecords = new Map();+ for (const plan of plans) {+ let record = plan.existing;+ if (!record) {+ const geometry = Object.freeze(generateGeometry(plan.definition, Math.min(limits.maxVertices, 1_000_000)));+ const geometryBytes = Object.values(geometry).reduce((total, array) => total + array.byteLength, 0);+ const vertices = geometry.positions.length / 3;+ if (vertices > plan.estimatedVertices || geometryBytes > plan.estimatedVertices * 56) {+ throw new RangeError('Generated geometry exceeds its conservative preflight bound.');}+ record = Object.freeze({+ signature: plan.signature, geometry,+ bounds: boundsFor(geometry, mat4.create()),+ vertices, geometryBytes, estimatedVertices: plan.estimatedVertices,+ });}- return [material.id, material];- }));- }- currentMaterials = snapshotsFor(recipe.materials);- const materialOutputs = new Map(recipe.materials.map(material => {- const output = {};- for (const field of ['tag', ...MATERIAL_FIELDS]) {- Object.defineProperty(output, field, { enumerable: true, get() {- return currentMaterials.get(material.id)[field];- } });- }- return [material.id, Object.freeze(output)];- }));- const parts = Object.freeze(recipe.nodes.filter(node => node.geometry !== undefined).map(node => Object.freeze({- name: node.id, geometry: geometries.get(node.geometry), material: materialOutputs.get(node.material),- matrix: new Float32Array(graph.getNode(node.id).worldMatrix),- })));+ geometryRecords.set(plan.definition.id, record);+ }+ const geometries = new Map([...geometryRecords].map(([id, record]) => [id, record.geometry]));+ const localBounds = new Map([...geometryRecords.values()].map(record => [record.geometry, record.bounds]));+ const graph = compile(recipe, geometries, localBounds, limits);+ const materialHandles = new Map();+ const materialUpdates = [];+ for (const material of recipe.materials) {+ const snapshot = immutableMaterial(material);+ const preferredHandle = preferred?.materialHandles.get(material.id);+ const activeHandle = removedMaterials.has(material.id) ? null : state?.materialHandles.get(material.id);+ const existing = [preferredHandle, activeHandle].find(handle => handle?.holder.snapshot.tag === material.tag);+ const handle = existing ?? materialHandle(snapshot);+ materialHandles.set(material.id, handle);+ materialUpdates.push({ holder: handle.holder, snapshot });+ }+ const activeParts = new Map(state?.parts.map(part => [part.name, part]) ?? []);+ const preferredParts = new Map(preferred?.parts.map(part => [part.name, part]) ?? []);+ const nextParts = recipe.nodes.filter(node => node.geometry !== undefined).map(node => {+ const geometry = geometries.get(node.geometry);+ const material = materialHandles.get(node.material).output;+ const activePart = removedNodes.has(node.id) ? null : activeParts.get(node.id);+ const existing = [activePart, preferredParts.get(node.id)]+ .find(part => part?.geometry === geometry && part.material === material);+ return existing ?? Object.freeze({+ name: node.id, geometry, material,+ matrix: new Float32Array(graph.getNode(node.id).worldMatrix),+ });+ });+ retainedMatrices(nextParts);+ const sameParts = state && state.parts.length === nextParts.length &&+ state.parts.every((part, index) => part === nextParts[index]);+ return {+ recipe, geometryRecords, geometries, graph, materialHandles, materialUpdates,+ parts: sameParts ? state.parts : Object.freeze(nextParts),+ topologyChanged: Boolean(state && !sameParts),+ stats: geometryStats(geometryRecords.values()),+ };+ }++ function commit(stagedState, incrementRevision) {+ for (const part of stagedState.parts) {+ Float32Array.prototype.set.call(part.matrix, stagedState.graph.getNode(part.name).worldMatrix);+ }+ for (const update of stagedState.materialUpdates) {+ update.holder.snapshot = update.snapshot;+ }+ if (stagedState.topologyChanged) {+ topologyRevision++;+ }+ state = stagedState;+ if (incrementRevision) {+ revision++;+ }+ return revision;+ }function expected(options) {knownKeys(options, ['expectedRevision'], 'transaction options');@@ -441,38 +646,25 @@ export function createAgentScene(input, inputLimits = {}) {throw new RangeError('expectedRevision must match the current revision.');}}- function publish(candidate) {- candidate = copiedJson(candidate, limits.maxRecipeBytes);- candidate.nodes = candidate.nodes.map(nodeFrom);- candidate.materials = candidate.materials.map(materialFrom);- candidate.camera = cameraFrom(candidate.camera);- candidate = copiedJson(candidate, limits.maxRecipeBytes);- const staged = compile(candidate, geometries, localBounds, limits);- const stagedMaterials = snapshotsFor(candidate.materials);- for (const part of parts) {- if (part.matrix.length !== 16 || part.matrix.byteLength !== 64) {- throw new RangeError('Retained render matrices must not be detached.');- }- }- recipe = candidate;- currentMaterials = stagedMaterials;- graph = staged;- for (const part of parts) {- part.matrix.set(graph.getNode(part.name).worldMatrix);- }- revision++;- return revision;- }++ commit(stage(input), false);return Object.freeze({- parts, capabilities: AGENT_SCENE_CAPABILITIES, limits,+ capabilities: AGENT_SCENE_CAPABILITIES,+ limits,+ get parts() {+ return state.parts;+ },get revision() {return revision;},+ get topologyRevision() {+ return topologyRevision;+ },get camera() {- return structuredClone(recipe.camera);+ return structuredClone(state.recipe.camera);},exportRecipe() {- return structuredClone(recipe);+ return structuredClone(state.recipe);},apply(inputOperations, options = {}) {expected(options);@@ -480,8 +672,49 @@ export function createAgentScene(input, inputLimits = {}) {throw new RangeError('operations must contain 1 to maxOperations commands.');}const operations = copiedJson(inputOperations, limits.maxRecipeBytes);- const candidate = structuredClone(recipe);+ const candidate = structuredClone(state.recipe);+ const removedNodes = new Set();+ const removedMaterials = new Set();for (const operation of operations) {+ const addition = Object.hasOwn(ADDITION_FIELDS, operation.type) ? ADDITION_FIELDS[operation.type] : null;+ if (addition) {+ const [collection, field] = addition;+ knownKeys(operation, ['type', field], 'operation');+ const record = operation[field];+ identifier(record?.id);+ if (operation.type === 'add-geometry') {+ geometryEstimate(record);+ } else if (operation.type === 'add-material') {+ materialFrom(record);+ } else {+ nodeFrom(record);+ }+ if (candidate[collection].some(existing => existing.id === record.id)) {+ throw new RangeError(`Duplicate ${collection} ID: ${record.id}.`);+ }+ candidate[collection].push(record);+ continue;+ }+ if (operation.type === 'remove-node') {+ for (const id of removeNode(candidate, operation)) {+ removedNodes.add(id);+ }+ continue;+ }+ const removal = Object.hasOwn(REMOVAL_FIELDS, operation.type) ? REMOVAL_FIELDS[operation.type] : null;+ if (removal) {+ knownKeys(operation, ['type', 'id'], 'operation');+ identifier(operation.id);+ const index = candidate[removal].findIndex(record => record.id === operation.id);+ if (index < 0) {+ throw new RangeError(`Operation ID was not found: ${operation.id}.`);+ }+ candidate[removal].splice(index, 1);+ if (operation.type === 'remove-material') {+ removedMaterials.add(operation.id);+ }+ continue;+ }let target;let fields;if (operation.type === 'set-node') {@@ -506,7 +739,7 @@ export function createAgentScene(input, inputLimits = {}) {}}}- return publish(candidate);+ return commit(stage(candidate, null, removedNodes, removedMaterials), true);},inspect(options = {}) {knownKeys(options, ['ids', 'limit', 'includeBounds'], 'inspection');@@ -517,39 +750,62 @@ export function createAgentScene(input, inputLimits = {}) {if (options.ids !== undefined && (!Array.isArray(options.ids) || options.ids.length > limits.maxNodes)) {throw new RangeError('Inspection IDs exceed maxNodes.');}- const selected = options.ids === undefined ? recipe.nodes : options.ids.map(id => {+ const selected = options.ids === undefined ? state.recipe.nodes : options.ids.map(id => {identifier(id);- const node = recipe.nodes.find(value => value.id === id);+ const node = state.recipe.nodes.find(value => value.id === id);if (!node) {throw new RangeError(`Inspection ID was not found: ${id}.`);}return node;});const nodes = selected.slice(0, maximum).map(node => {- const geometry = geometries.get(node.geometry);- const result = { id: node.id, label: node.label ?? node.id, parent: node.parent,+ const geometry = state.geometries.get(node.geometry);+ const result = {+ id: node.id, label: node.label ?? node.id, parent: node.parent,geometry: node.geometry ?? null, material: node.material ?? null,- vertices: geometry ? geometry.positions.length / 3 : 0, triangles: geometry ? geometry.indices.length / 3 : 0 };- if (options.includeBounds) result.bounds = geometry ? boundsFor(geometry, graph.getNode(node.id).worldMatrix) : null;+ vertices: geometry ? geometry.positions.length / 3 : 0,+ triangles: geometry ? geometry.indices.length / 3 : 0,+ };+ if (options.includeBounds) {+ result.bounds = geometry ? boundsFor(geometry, state.graph.getNode(node.id).worldMatrix) : null;+ }return result;});- return { revision, counts: { nodes: recipe.nodes.length, parts: parts.length, geometries: geometries.size, materials: recipe.materials.length, vertices },- geometryBytes, estimatedGeometryBytes, nodes, truncated: selected.length > nodes.length };+ const resident = geometryStats(ownedGeometryRecords());+ return {+ revision, topologyRevision,+ counts: {+ nodes: state.recipe.nodes.length, parts: state.parts.length,+ geometries: state.geometries.size, materials: state.recipe.materials.length,+ vertices: state.stats.vertices,+ },+ geometryBytes: state.stats.geometryBytes,+ estimatedGeometryBytes: state.stats.estimatedGeometryBytes,+ residentGeometryBytes: resident.geometryBytes,+ residentGeometryVertices: resident.vertices,+ nodes, truncated: selected.length > nodes.length,+ };},checkpoint() {if (checkpoints.size >= limits.maxCheckpoints) {throw new RangeError('Checkpoint budget exhausted. Release a checkpoint.');}const handle = Object.freeze({});- checkpoints.set(handle, structuredClone(recipe));+ checkpoints.set(handle, {+ recipe: structuredClone(state.recipe),+ geometryRecords: new Map(state.geometryRecords),+ materialHandles: new Map(state.materialHandles),+ parts: state.parts,+ });return handle;},restore(handle, options = {}) {expected(options);- if (!checkpoints.has(handle)) {+ const checkpoint = checkpoints.get(handle);+ if (!checkpoint) {throw new RangeError('Unknown or released checkpoint.');}- return publish(checkpoints.get(handle));+ return commit(stage(checkpoint.recipe, checkpoint), true);},releaseCheckpoint(handle) {if (!checkpoints.delete(handle)) {diff --git a/src/renderer.js b/src/renderer.jsindex db4dc590..c935639b 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -1,7 +1,7 @@import { mat4, mat3 } from 'gl-matrix';import { vertexShader, fragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';import { fullscreenVertex, postFragment, skyFragment, bloomFragment } from './post.js';-import { planRenderSize, estimateTextureBytes } from './budget.js';+import { planRenderSize, estimateTextureBytes, estimateFrameBytes } from './budget.js';import { applyProjection } from './camera.js';import { resolveEffects } from './effects.js';import { createLightingState, updateLightingState } from './lighting.js';@@ -175,6 +175,29 @@ function sampleCount(context, format, requested) {return Math.max(0, ...colorCounts.filter(count => count <= requested && depthCounts.includes(count)));}+function geometryBufferBytes(geometry) {+ return ['positions', 'normals', 'uvs', 'colors', 'indices'].reduce((total, field) => total + (geometry[field]?.byteLength ?? 0), 0);+}++function validateReplacementGeometry(geometry) {+ const vertexCount = geometry.positions?.length / 3;+ if (!(geometry.positions instanceof Float32Array) || !Number.isInteger(vertexCount) || vertexCount < 1 ||+ !(geometry.normals instanceof Float32Array) || geometry.normals.length !== vertexCount * 3 ||+ !(geometry.indices instanceof Uint32Array) || geometry.indices.length < 3 || geometry.indices.length % 3 !== 0) {+ throw new TypeError('Replacement geometry needs matching Float32 positions/normals and Uint32 triangles.');+ }+ for (const [field, count] of [['positions', 3], ['normals', 3], ['uvs', 2], ['colors', 3]]) {+ const values = geometry[field];+ if (!values && ['uvs', 'colors'].includes(field)) continue;+ if (!(values instanceof Float32Array) || values.length !== vertexCount * count || !values.every(Number.isFinite)) {+ throw new TypeError(`Replacement ${field} must contain finite matching Float32 data.`);+ }+ }+ if (!geometry.indices.every(index => index < vertexCount)) {+ throw new RangeError('Replacement triangle indices must address existing vertices.');+ }+}+export class Renderer67 {constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {} } = {}) {this.canvas = canvas;@@ -199,6 +222,9 @@ export class Renderer67 {this.multisampleSamples = benchmark ? 0 : sampleCount(this.context, this.hdr ? this.context.RGBA16F : this.context.RGBA8, Math.min(samples, this.context.getParameter(this.context.MAX_SAMPLES)));this.capabilities = { hdr: this.hdr, hdrRequested: Boolean(hdr), hdrFallbackReason: hdr && !this.hdr ? benchmark ? 'HDR is disabled in benchmark mode' : 'EXT_color_buffer_float is unavailable' : null, samples: this.multisampleSamples };this.geometryBytes = 0;+ this.geometryBuffers = new Map();+ this.batching = batching;+ this.groundPart = ground ? groundPart() : null;this.buffers = [];this.batches = [];this.partLocations = new Map();@@ -211,7 +237,7 @@ export class Renderer67 {this.textures = new Map();this.textureBytes = 4;this.shadowsDirty = true;- const groups = groupParts(ground ? [...parts, groundPart()] : parts, batching);+ const groups = groupParts(this.groundPart ? [...parts, this.groundPart] : parts, batching);const textureLimit = this.context.getParameter(this.context.MAX_TEXTURE_SIZE);this.hasSkins = groups.some(group => group[0].skin);this.hasMorphs = groups.some(group => group[0].morph);@@ -354,17 +380,39 @@ export class Renderer67 {uploadBatch(parts) {const context = this.context;- const geometry = parts[0].geometry;const vertexArray = context.createVertexArray();+ try {+ return this.uploadBatchData(parts, vertexArray);+ } catch (error) {+ context.bindVertexArray(null);+ context.deleteVertexArray(vertexArray);+ throw error;+ }+ }++ uploadBatchData(parts, vertexArray) {+ const context = this.context;+ const geometry = parts[0].geometry;context.bindVertexArray(vertexArray);- for (const [location, data] of [[0, geometry.positions], [1, geometry.normals]]) {- this.uploadBuffer(context.ARRAY_BUFFER, data);+ let geometryBuffers = this.geometryBuffers.get(geometry);+ if (!geometryBuffers) {+ geometryBuffers = new Map();+ for (const field of ['positions', 'normals', 'uvs', 'colors', 'indices']) {+ if (geometry[field]) {+ const target = field === 'indices' ? context.ELEMENT_ARRAY_BUFFER : context.ARRAY_BUFFER;+ geometryBuffers.set(field, this.uploadBuffer(target, geometry[field]));+ }+ }+ this.geometryBuffers.set(geometry, geometryBuffers);+ }+ for (const [location, field] of [[0, 'positions'], [1, 'normals']]) {+ context.bindBuffer(context.ARRAY_BUFFER, geometryBuffers.get(field));context.enableVertexAttribArray(location);context.vertexAttribPointer(location, 3, context.FLOAT, false, 0, 0);}if (geometry.uvs) {if (geometry.uvs.length !== geometry.positions.length / 3 * 2) throw new Error('Geometry UV count must match the vertex count.');- this.uploadBuffer(context.ARRAY_BUFFER, geometry.uvs);+ context.bindBuffer(context.ARRAY_BUFFER, geometryBuffers.get('uvs'));context.enableVertexAttribArray(13);context.vertexAttribPointer(13, 2, context.FLOAT, false, 0, 0);} else {@@ -374,14 +422,14 @@ export class Renderer67 {}if (geometry.colors) {if (geometry.colors.length !== geometry.positions.length) throw new Error('Geometry colors must contain RGB for every vertex.');- this.uploadBuffer(context.ARRAY_BUFFER, geometry.colors);+ context.bindBuffer(context.ARRAY_BUFFER, geometryBuffers.get('colors'));context.enableVertexAttribArray(14);context.vertexAttribPointer(14, 3, context.FLOAT, false, 0, 0);} else {context.disableVertexAttribArray(14);context.vertexAttrib3f(14, 1, 1, 1);}- this.uploadBuffer(context.ELEMENT_ARRAY_BUFFER, geometry.indices);+ context.bindBuffer(context.ELEMENT_ARRAY_BUFFER, geometryBuffers.get('indices'));const stride = INSTANCE_STRIDE;const instanceData = new Float32Array(parts.length * stride);const normalMatrix = mat3.create();@@ -407,11 +455,116 @@ export class Renderer67 {const morph = parts[0].morph ?? null;const morphTexture = morph ? this.createMorphTexture(geometry, morph) : null;const morphWeights = morph ? new Float32Array(morph.weights) : null;- const batch = { vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: parts[0].castShadow !== false };+ const batch = { parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: parts[0].castShadow !== false };parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));return batch;}+ /** Reconcile immutable rigid, untextured geometry without rebuilding programs or render targets. */+ replaceParts(parts) {+ if (!Array.isArray(parts) || new Set(parts).size !== parts.length) {+ throw new TypeError('Scene parts must be an array with distinct object identities.');+ }+ for (const location of this.partLocations.values()) {+ if (location.skin || location.morph || location.morphTargets || location.skinIndices || location.mapState.slice(0, 5).some(Boolean)) {+ throw new Error('replaceParts currently requires an existing rigid, untextured scene.');+ }+ }+ for (const part of parts) {+ if (part.skin || part.morph || part.geometry.morphTargets || part.geometry.skinIndices || hasMaterialMap(part.material)) {+ throw new Error('replaceParts currently requires rigid, untextured parts.');+ }+ }+ const renderParts = this.groundPart ? [...parts, this.groundPart] : parts;+ const groups = groupParts(renderParts, this.batching);+ const geometries = new Set(renderParts.map(part => part.geometry));+ for (const geometry of geometries) {+ validateReplacementGeometry(geometry);+ }+ const retained = new Set();+ const replacements = groups.map(group => {+ const first = group[0];+ const location = this.partLocations.get(first);+ const batch = location?.batch;+ const mapState = materialMapState(first.material);+ const sameParts = batch?.parts.length === group.length && batch.parts.every((part, index) => part === group[index]);+ const sameState = location?.geometry === first.geometry && batch?.castShadow === (first.castShadow !== false) &&+ batch.floor === (first.material.tag === 'floor') &&+ batch.mapState.every((value, index) => value === mapState[index]);+ if (sameParts && sameState) {+ retained.add(batch);+ return { group, batch };+ }+ return { group, batch: null };+ });+ const newGeometryBytes = [...geometries].filter(geometry => !this.geometryBuffers.has(geometry)).reduce((total, geometry) => total + geometryBufferBytes(geometry), 0);+ const newInstanceBytes = replacements.filter(item => !item.batch).reduce((total, item) => total + item.group.length * INSTANCE_STRIDE * 4, 0);+ const frameBytes = estimateFrameBytes(this.canvas.width, this.canvas.height, this.samples, 2048, { hdr: this.hdr, bloom: !this.benchmark, depth: this.depth });+ const peakBytes = frameBytes + this.textureBytes + this.geometryBytes + newGeometryBytes + newInstanceBytes;+ if (peakBytes > this.memoryBudgetMiB * 1024 * 1024) {+ throw new RangeError('Memory budget cannot hold the current scene and staged replacement buffers.');+ }+ const previousLocations = this.partLocations;+ const previousBuffers = [...this.buffers];+ const previousGeometryBytes = this.geometryBytes;+ const previousGeometryBuffers = new Map(this.geometryBuffers);+ const stagedLocations = new Map();+ const stagedBatches = [];+ this.partLocations = stagedLocations;+ try {+ for (const item of replacements) {+ if (item.batch) {+ stagedBatches.push(item.batch);+ for (const part of item.group) {+ stagedLocations.set(part, previousLocations.get(part));+ }+ } else {+ stagedBatches.push(this.uploadBatch(item.group));+ }+ }+ const error = this.context.getError();+ if (error !== 0) {+ throw new Error(`WebGL replacement allocation failed with error ${error}.`);+ }+ } catch (error) {+ for (const batch of stagedBatches) {+ if (!retained.has(batch)) this.context.deleteVertexArray(batch.vertexArray);+ }+ for (const buffer of this.buffers.slice(previousBuffers.length)) {+ this.context.deleteBuffer(buffer);+ }+ this.context.bindVertexArray(null);+ this.buffers = previousBuffers;+ this.geometryBytes = previousGeometryBytes;+ this.geometryBuffers = previousGeometryBuffers;+ this.partLocations = previousLocations;+ throw error;+ }+ const releasedBuffers = new Set();+ for (const batch of this.batches) {+ if (!retained.has(batch)) {+ this.context.deleteVertexArray(batch.vertexArray);+ releasedBuffers.add(batch.instanceBuffer);+ }+ }+ for (const [geometry, buffers] of this.geometryBuffers) {+ if (!geometries.has(geometry)) {+ for (const buffer of buffers.values()) releasedBuffers.add(buffer);+ this.geometryBuffers.delete(geometry);+ }+ }+ for (const buffer of releasedBuffers) this.context.deleteBuffer(buffer);+ this.buffers = this.buffers.filter(buffer => !releasedBuffers.has(buffer));+ this.geometryBytes = [...geometries].reduce((total, geometry) => total + geometryBufferBytes(geometry), 0) + renderParts.length * INSTANCE_STRIDE * 4;+ this.batches = stagedBatches;+ this.partCount = parts.length;+ this.triangles = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);+ this.updateBatches.clear();+ this.shadowsDirty = true;+ this.updateParts(renderParts);+ return parts.length;+ }+createSkinTexture(cache, identity, matrices, groupSize) {if (cache.has(identity)) return cache.get(identity);const context = this.context;@@ -867,6 +1020,7 @@ export class Renderer67 {this.releaseFrameTargets();this.batches.forEach((batch) => this.context.deleteVertexArray(batch.vertexArray));this.buffers.forEach((buffer) => this.context.deleteBuffer(buffer));+ this.geometryBuffers?.clear();this.context.deleteTexture(this.shadowTexture);this.context.deleteFramebuffer(this.shadowFramebuffer);this.context.deleteProgram(this.program);diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.jsindex b88bc3bf..5c317d27 100644--- a/tests/agent-preview.test.js+++ b/tests/agent-preview.test.js@@ -11,6 +11,8 @@ const source = (await readFile(new URL('../scripts/agent-preview-browser.js', imfunction previewHarness() {let renderError = 0;let lost = false;+ let replacementError = false;+ let replacementCount = 0;const canvas = { width: 768, height: 512 };class FaultInjectedRenderer {memoryPlan = { estimatedBytes: 1024 };@@ -23,6 +25,10 @@ function previewHarness() {};resize() {}updateParts() {}+ replaceParts() {+ if (replacementError) throw new Error('Injected replacement allocation failure');+ replacementCount++;+ }render() {}dispose() {}}@@ -40,6 +46,8 @@ function previewHarness() {preview: context.window.__agentPreview,injectError: value => { renderError = value; },loseContext: () => { lost = true; },+ rejectReplacement: value => { replacementError = value; },+ replacementCount: () => replacementCount,};}@@ -64,6 +72,33 @@ test('preview rejects a camera that overflows at a permitted aspect before commiassert.deepEqual(preview.exportRecipe({ sessionId: 'scene' }).recipe.nodes[0].translation, [0, 0, 0]);});+test('topology driver failure discloses committed recipe and retries reconciliation with the current revision', () => {+ const harness = previewHarness();+ const sessionId = 'test-topology';+ harness.preview.create({ recipe: recipe(), sessionId, memoryBudgetMiB: 192, backend: 'cpu' });+ const checkpoint = harness.preview.checkpoint({ sessionId, checkpointId: 'initial' });+ harness.rejectReplacement(true);+ const added = harness.preview.apply({ sessionId, expectedRevision: 0, operations: [+ { type: 'add-node', node: { id: 'second', geometry: 'cube', material: 'paint', translation: [2, 0, 0] } },+ ] });+ assert.equal(added.committed, true);+ assert.equal(added.revision, 1);+ assert.equal(added.renderSucceeded, false);+ assert.match(added.renderError, /allocation failure/);+ assert.equal(harness.preview.inspect({ sessionId }).counts.parts, 2);+ assert.equal(harness.replacementCount(), 0);+ harness.rejectReplacement(false);+ const recovered = harness.preview.apply({ sessionId, expectedRevision: 1, operations: [+ { type: 'set-material', id: 'paint', color: [0.3, 0.6, 0.8] },+ ] });+ assert.equal(recovered.renderSucceeded, true);+ assert.equal(harness.replacementCount(), 1);+ const restored = harness.preview.restore({ sessionId, checkpointId: checkpoint.checkpointId, expectedRevision: 2 });+ assert.equal(restored.renderSucceeded, true);+ assert.equal(harness.preview.inspect({ sessionId }).counts.parts, 1);+ assert.equal(harness.replacementCount(), 2);+});+test('driver errors disclose committed revision and context loss preserves recipe recovery', () => {const harness = previewHarness();const { preview } = harness;diff --git a/tests/agent-scene.test.js b/tests/agent-scene.test.jsindex fd650347..503de813 100644--- a/tests/agent-scene.test.js+++ b/tests/agent-scene.test.js@@ -69,7 +69,9 @@ test('shared resources and retained renderer identities survive apply and restorassert.equal(parts[0].matrix[12], 4);assert.deepEqual(parts[0].material.color, [0.2, 0.4, 0.6]);parts.forEach((part, index) => {- [part, part.matrix, part.geometry, part.material].forEach((value, component) => assert.equal(value, identities[index][component]));+ [part, part.matrix, part.geometry, part.material].forEach((value, component) => {+ assert.equal(value, identities[index][component]);+ });});assert.equal(parts[0].material.color, parts[0].material.color);assert.equal(session.parts, parts);@@ -117,11 +119,15 @@ test('hierarchy and actual vertex bounds agree with an independent double precisconst world = root.multiply(child);const minimum = [Infinity, Infinity, Infinity];const maximum = [-Infinity, -Infinity, -Infinity];- for (const x of [-0.5, 0.5]) for (const y of [-0.5, 0.5]) for (const z of [-0.5, 0.5]) {- const point = new Vector3(x, y, z).applyMatrix4(world).toArray();- for (let axis = 0; axis < 3; axis++) {- minimum[axis] = Math.min(minimum[axis], point[axis]);- maximum[axis] = Math.max(maximum[axis], point[axis]);+ for (const x of [-0.5, 0.5]) {+ for (const y of [-0.5, 0.5]) {+ for (const z of [-0.5, 0.5]) {+ const point = new Vector3(x, y, z).applyMatrix4(world).toArray();+ for (let axis = 0; axis < 3; axis++) {+ minimum[axis] = Math.min(minimum[axis], point[axis]);+ maximum[axis] = Math.max(maximum[axis], point[axis]);+ }+ }}}const actual = session.inspect({ ids: ['child'], includeBounds: true }).nodes[0].bounds;@@ -265,6 +271,253 @@ test('all seven generators remain within conservative aggregate vertex and byteassert.ok(inspection.geometryBytes <= inspection.estimatedGeometryBytes);assert.ok(inspection.nodes.every(node => node.bounds.min.every(Number.isFinite)));assert.deepEqual(createAgentScene(session.exportRecipe()).inspect(), session.inspect());- assert.throws(() => session.apply([{ type: 'set-node', id: 'box', geometry: 'sphere' }], { expectedRevision: 0 }), /Unknown/);- assert.throws(() => session.apply([{ type: 'set-material', id: 'material', tag: 'unlit' }], { expectedRevision: 0 }), /Unknown/);+ const originalBox = session.parts[0];+ session.apply([{ type: 'set-node', id: 'box', geometry: 'sphere' }], { expectedRevision: 0 });+ assert.notEqual(session.parts[0], originalBox);+ assert.equal(session.parts[0].geometry, session.parts[2].geometry);+ assert.equal(session.topologyRevision, 1);+ assert.throws(() => session.apply([{ type: 'set-material', id: 'material', tag: 'unlit' }], { expectedRevision: 1 }), /Unknown/);+});++function emptyRecipe() {+ return { format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [] };+}++test('topology can grow from an empty session while sharing resources and preserving existing part identities', () => {+ const session = createAgentScene(emptyRecipe());+ const emptyParts = session.parts;+ assert.equal(session.topologyRevision, 0);+ assert.equal(session.capabilities.fixedResources, false);+ assert.equal(session.capabilities.dynamicTopology, true);+ session.apply([+ { type: 'add-node', node: { id: 'first', parent: 'group', geometry: 'cube', material: 'red' } },+ { type: 'add-node', node: { id: 'group' } },+ { type: 'add-material', material: { id: 'red', color: [1, 0, 0] } },+ { type: 'add-geometry', geometry: { id: 'cube', type: 'box', bevel: 0 } },+ ], { expectedRevision: 0 });+ assert.notEqual(session.parts, emptyParts);+ assert.equal(session.revision, 1);+ assert.equal(session.topologyRevision, 1);+ const first = session.parts[0];+ session.apply([{ type: 'add-node', node: { id: 'second', geometry: 'cube', material: 'red' } }], { expectedRevision: 1 });+ assert.equal(session.parts[0], first);+ assert.equal(session.parts[1].geometry, first.geometry);+ assert.equal(session.parts[1].material, first.material);+ assert.equal(session.topologyRevision, 2);+ const retainedList = session.parts;+ session.apply([+ { type: 'set-node', id: 'group', translation: [3, 0, 0] },+ { type: 'set-material', id: 'red', roughness: 0.2 },+ { type: 'set-camera', fov: 60 },+ { type: 'add-node', node: { id: 'unused-group' } },+ ], { expectedRevision: 2 });+ assert.equal(session.parts, retainedList);+ assert.equal(first.matrix[12], 3);+ assert.equal(first.material.roughness, 0.2);+ assert.equal(session.topologyRevision, 2);+});++test('topology failures roll back recipes, geometry, materials, matrices and both revisions', () => {+ const session = createAgentScene(recipe());+ const before = session.exportRecipe();+ const parts = session.parts;+ const matrices = parts.map(part => Array.from(part.matrix));+ const invalidBatches = [+ [{ type: 'remove-geometry', id: 'box' }],+ [{ type: 'remove-material', id: 'finish' }],+ [{ type: 'add-node', node: { id: 'cycle', parent: 'child' } }, { type: 'set-node', id: 'root', parent: 'cycle' }],+ [{ type: 'add-node', node: { id: 'mesh', geometry: 'box' } }],+ [{ type: 'add-node', node: { id: 'mesh', geometry: 'missing', material: 'finish' } }],+ [{ type: 'add-node', node: { id: 'mesh', parent: 'missing' } }],+ [{ type: 'add-geometry', geometry: { id: 'box', type: 'sphere' } }],+ [{ type: 'add-material', material: { id: 'finish' } }],+ [{ type: 'add-node', node: { id: 'root' } }],+ [{ type: 'remove-node', id: 'missing' }],+ [{ type: 'remove-geometry', id: 'missing' }],+ [{ type: 'remove-material', id: 'missing' }],+ [{ type: 'add-geometry', geometry: { id: 'invalid', type: 'box', bevel: 2 } }],+ [{ type: 'add-material', material: { id: 'invalid', roughness: 2 } }],+ [{ type: 'add-geometry', geometry: { id: 'huge', type: 'sphere', segments: 2048, rings: 2048 } }],+ [{ type: 'remove-node', id: 'root', recursive: 'true' }],+ [{ type: 'remove-node', id: 'other', extra: true }],+ [{ type: 'add-node', node: { id: 'mesh' }, extra: true }],+ [{ type: 'add-node', node: { id: 'mesh', extra: true } }],+ ];+ for (const operations of invalidBatches) {+ assert.throws(() => session.apply([+ { type: 'set-material', id: 'finish', color: [1, 0, 0] },+ { type: 'set-node', id: 'root', translation: [8, 0, 0] },+ ...operations,+ ], { expectedRevision: 0 }));+ assert.deepEqual(session.exportRecipe(), before);+ assert.equal(session.parts, parts);+ assert.deepEqual(parts.map(part => Array.from(part.matrix)), matrices);+ assert.deepEqual(parts[0].material.color, [0.2, 0.4, 0.6]);+ assert.equal(session.revision, 0);+ assert.equal(session.topologyRevision, 0);+ }+ session.apply([{ type: 'remove-node', id: 'other' }], { expectedRevision: 0 });+ assert.equal(session.parts[0], parts[0]);+ assert.equal(session.topologyRevision, 1);+});++test('node deletion distinguishes nonrecursive rejection from explicit subtree removal', () => {+ const input = recipe();+ input.nodes.push({ id: 'grandchild', parent: 'child', geometry: 'box', material: 'finish' });+ const session = createAgentScene(input);+ assert.throws(() => session.apply([+ { type: 'remove-node', id: 'root' }, { type: 'remove-node', id: 'child', recursive: true },+ ], { expectedRevision: 0 }), /Nonrecursive/);+ session.apply([{ type: 'remove-node', id: 'root', recursive: true }], { expectedRevision: 0 });+ assert.deepEqual(session.exportRecipe().nodes.map(node => node.id), ['other']);+ assert.deepEqual(session.parts.map(part => part.name), ['other']);+ assert.equal(session.inspect().counts.geometries, 1);+ session.apply([+ { type: 'remove-node', id: 'other' },+ { type: 'remove-material', id: 'finish' },+ { type: 'remove-geometry', id: 'box' },+ ], { expectedRevision: 1 });+ assert.equal(session.parts.length, 0);+ assert.equal(session.inspect().residentGeometryBytes, 0);+});++test('resource removal and node rebinding resolve final references after sequential commands', () => {+ const session = createAgentScene(recipe());+ const oldParts = session.parts;+ session.apply([+ { type: 'remove-geometry', id: 'box' },+ { type: 'remove-material', id: 'finish' },+ { type: 'add-geometry', geometry: { id: 'sphere', type: 'sphere', segments: 8, rings: 4 } },+ { type: 'add-material', material: { id: 'green', color: [0, 1, 0] } },+ { type: 'set-node', id: 'child', geometry: 'sphere', material: 'green' },+ { type: 'set-node', id: 'other', geometry: 'sphere', material: 'green' },+ ], { expectedRevision: 0 });+ assert.notEqual(session.parts[0], oldParts[0]);+ assert.notEqual(session.parts[0].matrix, oldParts[0].matrix);+ assert.equal(session.parts[0].geometry, session.parts[1].geometry);+ assert.equal(session.parts[0].material, session.parts[1].material);+ assert.equal(session.topologyRevision, 1);+ assert.deepEqual(oldParts[0].material.color, [0.2, 0.4, 0.6]);+ session.apply([{ type: 'set-node', id: 'root', geometry: 'sphere', material: 'green' }], { expectedRevision: 1 });+ assert.equal(session.parts.length, 3);+ assert.equal(session.parts[0].name, 'child');+});++test('unchanged definitions reuse geometry while changed definitions replace bound parts', () => {+ const session = createAgentScene(recipe());+ const originalParts = session.parts;+ session.apply([+ { type: 'remove-geometry', id: 'box' },+ { type: 'add-geometry', geometry: { bevel: 0, type: 'box', id: 'box' } },+ ], { expectedRevision: 0 });+ assert.equal(session.parts, originalParts);+ assert.equal(session.topologyRevision, 0);+ session.apply([+ { type: 'remove-geometry', id: 'box' },+ { type: 'add-geometry', geometry: { id: 'box', type: 'sphere', segments: 8, rings: 4 } },+ ], { expectedRevision: 1 });+ assert.notEqual(session.parts[0].geometry, originalParts[0].geometry);+ assert.notEqual(session.parts[0], originalParts[0]);+ assert.equal(session.parts[0].geometry, session.parts[1].geometry);+ assert.equal(session.topologyRevision, 1);+});++test('checkpoints restore removed geometry and parts with bounded private retained identities', () => {+ const session = createAgentScene(recipe());+ const originalParts = session.parts;+ const checkpoint = session.checkpoint();+ session.apply([+ { type: 'remove-node', id: 'root', recursive: true },+ { type: 'remove-node', id: 'other' },+ { type: 'remove-geometry', id: 'box' },+ { type: 'remove-material', id: 'finish' },+ ], { expectedRevision: 0 });+ assert.equal(session.parts.length, 0);+ assert.equal(session.inspect().geometryBytes, 0);+ assert.equal(session.inspect().residentGeometryBytes, 720);+ session.restore(checkpoint, { expectedRevision: 1 });+ assert.equal(session.parts[0], originalParts[0]);+ assert.equal(session.parts[1], originalParts[1]);+ assert.equal(session.topologyRevision, 2);+ const restoredList = session.parts;+ session.restore(checkpoint, { expectedRevision: 2 });+ assert.equal(session.parts, restoredList);+ assert.equal(session.topologyRevision, 2);+ session.releaseCheckpoint(checkpoint);+ assert.equal(session.inspect().residentGeometryBytes, 720);+});++test('peak geometry budgets count checkpoint ownership and free it on release', () => {+ const session = createAgentScene(recipe(), { maxVertices: 24, maxGeometryBytes: 1344 });+ const originalParts = session.parts;+ const firstCheckpoint = session.checkpoint();+ const secondCheckpoint = session.checkpoint();+ assert.equal(session.inspect().residentGeometryVertices, 24);+ session.apply([+ { type: 'remove-node', id: 'root', recursive: true }, { type: 'remove-node', id: 'other' },+ { type: 'remove-geometry', id: 'box' }, { type: 'remove-material', id: 'finish' },+ ], { expectedRevision: 0 });+ const add = [{ type: 'add-geometry', geometry: { id: 'new', type: 'box', bevel: 0 } }];+ assert.throws(() => session.apply(add, { expectedRevision: 1 }), /peak/);+ assert.equal(session.revision, 1);+ session.releaseCheckpoint(firstCheckpoint);+ assert.throws(() => session.apply(add, { expectedRevision: 1 }), /peak/);+ session.restore(secondCheckpoint, { expectedRevision: 1 });+ assert.equal(session.parts[0], originalParts[0]);+ session.apply([+ { type: 'remove-node', id: 'root', recursive: true }, { type: 'remove-node', id: 'other' },+ { type: 'remove-geometry', id: 'box' }, { type: 'remove-material', id: 'finish' },+ ], { expectedRevision: 2 });+ session.releaseCheckpoint(secondCheckpoint);+ assert.equal(session.inspect().residentGeometryBytes, 0);+ session.apply(add, { expectedRevision: 3 });+ assert.equal(session.inspect().geometryBytes, 720);+ assert.equal(session.topologyRevision, 3);+});++test('atomic replacement budgets include old active resources until commit', () => {+ const session = createAgentScene(recipe(), { maxGeometryBytes: 1344 });+ assert.throws(() => session.apply([+ { type: 'remove-geometry', id: 'box' },+ { type: 'add-geometry', geometry: { id: 'box', type: 'box', bevel: 0, subdivisions: 1 } },+ ], { expectedRevision: 0 }), /peak/);+ assert.equal(session.revision, 0);+ assert.equal(session.topologyRevision, 0);+ assert.equal(session.inspect().geometryBytes, 720);+});++test('new topology enforces world geometry overflow and depth before publishing', () => {+ const session = createAgentScene(emptyRecipe(), { maxDepth: 1 });+ const emptyParts = session.parts;+ assert.throws(() => session.apply([+ { type: 'add-node', node: { id: 'root' } },+ { type: 'add-node', node: { id: 'child', parent: 'root' } },+ ], { expectedRevision: 0 }), /maxDepth/);+ assert.throws(() => session.apply([+ { type: 'add-geometry', geometry: { id: 'huge', type: 'lathe', profile: [[1e30, -1], [1e30, 1]], segments: 8 } },+ { type: 'add-material', material: { id: 'finish' } },+ { type: 'add-node', node: { id: 'mesh', geometry: 'huge', material: 'finish', scale: [1e30, 1, 1] } },+ ], { expectedRevision: 0 }), /world geometry bounds/);+ assert.equal(session.parts, emptyParts);+ assert.equal(session.revision, 0);+ assert.equal(session.topologyRevision, 0);+});++test('topology rejects stale revisions and detached active or checkpoint matrices atomically', () => {+ const session = createAgentScene(recipe());+ const checkpoint = session.checkpoint();+ const oldParts = session.parts;+ session.apply([{ type: 'remove-node', id: 'other' }], { expectedRevision: 0 });+ assert.throws(() => session.apply([{ type: 'remove-node', id: 'child' }], { expectedRevision: 0 }), /expectedRevision/);+ structuredClone(oldParts[1].matrix.buffer, { transfer: [oldParts[1].matrix.buffer] });+ const before = session.exportRecipe();+ const parts = session.parts;+ assert.throws(() => session.restore(checkpoint, { expectedRevision: 1 }), /detached/);+ assert.deepEqual(session.exportRecipe(), before);+ assert.equal(session.parts, parts);+ assert.equal(session.topologyRevision, 1);+ structuredClone(parts[0].matrix.buffer, { transfer: [parts[0].matrix.buffer] });+ assert.throws(() => session.apply([{ type: 'remove-node', id: 'child' }], { expectedRevision: 1 }), /detached/);+ assert.deepEqual(session.exportRecipe(), before);+ assert.equal(session.revision, 1);});diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.jsindex f362a0d5..7be8e074 100644--- a/tests/mcp-tools.test.js+++ b/tests/mcp-tools.test.js@@ -195,3 +195,26 @@ test('SDK stdio EOF closes the runtime without launching a scene', async () => {input.destroy();output.destroy();});++test('SDK dynamic batches create resources, reject dangling edits, and restore scene membership', async context => {+ const { client, sessionId } = await connect(context);+ const call = (name, argumentsValue) => client.callTool({ name, arguments: argumentsValue });+ await call('scene_create', { recipe: { format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [] } });+ const initial = (await call('scene_checkpoint', { sessionId })).structuredContent;+ const added = await call('scene_apply', { sessionId, expectedRevision: 0, operations: [+ { type: 'add-geometry', geometry: { id: 'cube', type: 'box' } },+ { type: 'add-material', material: { id: 'paint', color: [0.2, 0.6, 0.8] } },+ { type: 'add-node', node: { id: 'group' } },+ { type: 'add-node', node: { id: 'mesh', parent: 'group', geometry: 'cube', material: 'paint' } },+ ] });+ assert.equal(added.isError, undefined);+ assert.equal(added.structuredContent.inspection.counts.parts, 1);+ const invalid = await call('scene_apply', { sessionId, expectedRevision: 1, operations: [{ type: 'remove-geometry', id: 'cube' }] });+ assert.equal(invalid.isError, true);+ const inspected = (await call('scene_inspect', { sessionId })).structuredContent;+ assert.equal(inspected.revision, 1);+ assert.equal(inspected.counts.geometries, 1);+ const restored = await call('scene_restore', { sessionId, checkpointId: initial.checkpointId, expectedRevision: 1 });+ assert.equal(restored.structuredContent.inspection.counts.parts, 0);+ assert.equal(restored.structuredContent.inspection.counts.geometries, 0);+});diff --git a/tests/renderer-topology.test.js b/tests/renderer-topology.test.jsnew file mode 100644index 00000000..d30374da--- /dev/null+++ b/tests/renderer-topology.test.js@@ -0,0 +1,163 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { mat4 } from 'gl-matrix';+import { box, sphere } from '../src/geometry.js';+import { Renderer67 } from '../src/renderer.js';++function part(name, geometry) {+ return { name, geometry, matrix: mat4.create(), material: { tag: 'surface', color: [0.5, 0.6, 0.7], metallic: 0, roughness: 0.5 } };+}++function allocationRenderer() {+ const renderer = Object.create(Renderer67.prototype);+ const liveBuffers = new Set();+ const liveArrays = new Set();+ const uploads = [];+ let driverError = 0;+ let throwingUpload = false;+ renderer.context = {+ ARRAY_BUFFER: 34962, ELEMENT_ARRAY_BUFFER: 34963, STATIC_DRAW: 35044, DYNAMIC_DRAW: 35048, FLOAT: 5126,+ createBuffer() {+ const buffer = {};+ liveBuffers.add(buffer);+ return buffer;+ },+ deleteBuffer(buffer) { liveBuffers.delete(buffer); },+ createVertexArray() {+ const array = {};+ liveArrays.add(array);+ return array;+ },+ deleteVertexArray(array) { liveArrays.delete(array); },+ bindBuffer() {}, bindVertexArray() {}, enableVertexAttribArray() {}, disableVertexAttribArray() {},+ vertexAttribPointer() {}, vertexAttribDivisor() {}, vertexAttrib2f() {}, vertexAttrib3f() {},+ bufferData(target, data, usage) {+ if (throwingUpload) throw new Error('Injected upload exception');+ uploads.push({ target, data, usage });+ },+ bufferSubData() {},+ getError() {+ const error = driverError;+ driverError = 0;+ return error;+ },+ };+ renderer.canvas = { width: 64, height: 64 };+ renderer.multisampleSamples = 0;+ renderer.memoryBudgetMiB = 64;+ renderer.textureBytes = 4;+ renderer.geometryBytes = 0;+ renderer.geometryBuffers = new Map();+ renderer.batching = true;+ renderer.groundPart = null;+ renderer.buffers = [];+ renderer.batches = [];+ renderer.partLocations = new Map();+ renderer.updateBatches = new Set();+ renderer.updateSkins = new Set();+ renderer.updateMorphs = new Set();+ renderer.createTexture = () => null;+ return { renderer, liveBuffers, liveArrays, uploads,+ failDriver() { driverError = 1285; },+ failUpload(value) { throwingUpload = value; },+ };+}++test('topology reconciliation reuses geometry uploads and unchanged batches, and releases removed geometry', () => {+ const state = allocationRenderer();+ const geometry = box();+ const first = part('first', geometry);+ state.renderer.replaceParts([first]);+ const originalBuffers = [...state.renderer.geometryBuffers.get(geometry).values()];+ assert.equal(state.uploads.length, 4);+ const unchangedBatch = state.renderer.batches[0];+ state.renderer.replaceParts([first]);+ assert.equal(state.renderer.batches[0], unchangedBatch);+ assert.equal(state.uploads.length, 4);+ first.matrix[12] = 5;+ first.material.color[0] = 0.9;+ first.material.tag = 'unlit';+ state.renderer.replaceParts([first]);+ assert.equal(state.renderer.batches[0], unchangedBatch);+ assert.equal(unchangedBatch.instanceData[12], 5);+ assert.ok(Math.abs(unchangedBatch.instanceData[25] - 0.9) < 1e-6);+ assert.equal(unchangedBatch.instanceData[31], 10);+ assert.equal(state.uploads.length, 4);+ const second = part('second', geometry);+ state.renderer.replaceParts([first, second]);+ assert.equal(state.uploads.length, 5, 'Only the resized instance array is uploaded');+ assert.deepEqual([...state.renderer.geometryBuffers.get(geometry).values()], originalBuffers);+ assert.equal(state.liveBuffers.size, 4);+ assert.equal(state.liveArrays.size, 1);+ const third = part('third', sphere(12, 8));+ const retainedBatch = state.renderer.batches[0];+ state.renderer.replaceParts([first, second, third]);+ assert.equal(state.renderer.batches[0], retainedBatch);+ state.renderer.replaceParts([third]);+ assert.equal(state.renderer.geometryBuffers.has(geometry), false);+ for (const buffer of originalBuffers) assert.equal(state.liveBuffers.has(buffer), false);+ assert.equal(state.renderer.partLocations.has(first), false);+ assert.equal(state.renderer.partCount, 1);+ state.renderer.replaceParts([]);+ assert.equal(state.liveBuffers.size, 0);+ assert.equal(state.liveArrays.size, 0);+ assert.equal(state.renderer.geometryBytes, 0);+});++test('invalid geometry and peak staging budgets reject before allocation and preserve the previous scene', () => {+ const state = allocationRenderer();+ const first = part('first', box());+ state.renderer.replaceParts([first]);+ const batch = state.renderer.batches[0];+ const allocations = state.uploads.length;+ const invalid = part('invalid', box());+ invalid.geometry.indices[0] = invalid.geometry.positions.length;+ assert.throws(() => state.renderer.replaceParts([first, invalid]), /indices/);+ assert.equal(state.uploads.length, allocations);+ state.renderer.memoryBudgetMiB = 16;+ assert.throws(() => state.renderer.replaceParts([first, part('new', sphere(24, 16))]), /staged/);+ assert.equal(state.renderer.batches[0], batch);+ assert.equal(state.uploads.length, allocations);+});++test('driver errors and throwing uploads clean staged resources without retiring the working renderer', () => {+ const state = allocationRenderer();+ const first = part('first', box());+ state.renderer.replaceParts([first]);+ const batch = state.renderer.batches[0];+ const buffers = [...state.liveBuffers];+ const candidate = part('candidate', sphere(12, 8));+ state.failDriver();+ assert.throws(() => state.renderer.replaceParts([first, candidate]), /1285/);+ assert.equal(state.renderer.batches[0], batch);+ assert.deepEqual([...state.liveBuffers], buffers);+ assert.equal(state.liveArrays.size, 1);+ assert.equal(state.renderer.geometryBuffers.has(candidate.geometry), false);+ state.failUpload(true);+ assert.throws(() => state.renderer.replaceParts([first, candidate]), /Injected/);+ assert.deepEqual([...state.liveBuffers], buffers);+ assert.equal(state.liveArrays.size, 1);+ state.failUpload(false);+ state.renderer.replaceParts([first, candidate]);+ assert.equal(state.renderer.partCount, 2);+ assert.equal(state.renderer.batches[0], batch);+});++test('committed uploaded resource ownership rejects replacement even when callers mutate live handles', () => {+ const state = allocationRenderer();+ const first = part('first', box());+ state.renderer.replaceParts([first]);+ const location = state.renderer.partLocations.get(first);+ const originalBatch = state.renderer.batches[0];+ const allocations = state.uploads.length;+ location.mapState[0] = { image: {} };+ first.material.map = undefined;+ assert.throws(() => state.renderer.replaceParts([]), /existing rigid/);+ assert.equal(state.renderer.batches[0], originalBatch);+ assert.equal(state.uploads.length, allocations);+ location.mapState[0] = null;+ location.skin = { jointMatrices: new Float32Array(16) };+ first.skin = undefined;+ assert.throws(() => state.renderer.replaceParts([]), /existing rigid/);+ assert.equal(state.renderer.partCount, 1);+});