3D engine that AI agents drive
Add branches and labelled review images to the agent tools
Nguyen Xuan Ana4477e2f2cf0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 053f8484..2a7a607b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Add branches and labelled images to the agent tools (part of issue #67, no new tool). `scene_apply` with a `branch` name runs the operations on a scratch copy and stores the result in a snapshot store that holds one copy per distinct recipe (8 branches), leaving the scene, its revision and its checkpoints untouched. `scene_review` shots take a `branch` and render it in a private scene; `scene_restore` with `branch` keeps one. `labels: true` on `scene_look` and `scene_review` draws part names, material tags and mesh lint problems on the image and returns them as JSON with pixel positions. Branch names are bounded (`^[a-z][a-z0-9_-]{0,23}$`). The tool-schema budget rose by 800 bytes in total (150 for `scene_apply`). `npm run smoke:agent-branches` drives it through MCP on SwiftShader.+- Add a bounded material node graph (issue #50): material `pattern` of `type: "graph"` bakes noise, voronoi, wave, checker, gradient, ramp, maths and `uv` nodes on the CPU into base colour, roughness, metallic, emission and height (a normal map, so bump). The graph is data, never shader text; nodes, depth, ramp stops, texture size and work are checked before any pixel is computed. Add `mapping: "uv"` to every pattern so it follows `uv_unwrap` UVs instead of box projection; the emissive map now box-maps like the other maps. The 11 presets bake the same bytes as before. Covered in the MCP schema, `scene_capabilities` (`materialGraph`, `materialMappings`), GLB export, `docs/agent-scene.md`, `docs/material-maps.md` and the `brick-graph` reference scene.- Add `decimate`, `remesh` and generated levels of detail (issue #40). `decimate` (a `ratio` of triangles) is a quadric edge collapse of our own that keeps open boundaries, the borders between tags and the tags themselves; it measured 0.25 to 0.85 of the Hausdorff error of meshoptimizer 1.3.0 on the same meshes and adds no dependency, but takes about 2.5 s on 100k triangles where meshoptimizer takes 0.09 s. `remesh` (`voxelSize` or `resolution`, at most 192 per side and 4,194,304 cells, checked before allocation) builds a closed quad surface from a BVH signed distance with surface nets. Both are edits and stack nodes, in the MCP schemas, and load on demand with the mesh code. `generateMeshLods`, `generateGeometryLods` and `generateAssetLods` (also in `67js/addons/mesh`) return levels with a measured error for runtime selection (issue #37). Four decimate and two remesh cases join the Blender comparison, compared by volume, area and Hausdorff distance because face counts differ.diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.jsonindex 93612b60..6afa0d4d 100644--- a/bench/tool-cost-budgets.json+++ b/bench/tool-cost-budgets.json@@ -1,9 +1,9 @@{- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; was 373388 schema bytes before shared IDs and recipe references",- "schemaTotalBytes": 189900,+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); was 373388 schema bytes before shared IDs and recipe references",+ "schemaTotalBytes": 190700,"schemaToolBytes": {"scene_create": 60900,- "scene_apply": 47400,+ "scene_apply": 47550,"mesh_edit": 34000,"scene_create_asset": 19750,"mesh_stack": 11500diff --git a/docs/agent-review.md b/docs/agent-review.mdindex 66af85e7..970c5f18 100644--- a/docs/agent-review.md+++ b/docs/agent-review.md@@ -64,6 +64,19 @@ These samples require authored motion. Nonlooping motion holds its endpoint afte`rendererTime` controls shader animation independently and defaults to zero.Camera fields override only the private shot camera. They do not author tracks or edit the source camera.+## Compare branches and read labels++A shot can name a branch made by `scene_apply` with `branch`. The branch renders in its own private scene, so one review compares variants without a restore, a revision or a look per variant:++```json+{ "sessionId": "<scene UUID>", "expectedRevision": 3, "labels": true,+ "shots": [{ "branch": "warm" }, { "branch": "cool" }, { "label": "Now" }] }+```++Shots of the same branch share one private scene. Each shot reports `branch` and `branchStale`, true when the scene changed after the fork. Branch shots cannot sample an imported clip.++`labels: true`, on `scene_review` and on `scene_look`, draws the node name, a material tag other than `surface` and the mesh lint problems (in orange) at each visible part's bounds centre. The same list returns as JSON, `labels: [{ id, name, tag, faceTags, problems, x, y }]`, with `x` and `y` in the pixels of that image or shot. At most 24 parts are labelled; hidden parts are left out. Names are cut to printable ASCII. Imported assets get names and tags but no lint.+## Budgets and ownership| Limit | Value |diff --git a/docs/mcp.md b/docs/mcp.mdindex d26b2441..cc91a362 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -77,8 +77,9 @@ Closing stdin or sending `SIGINT` or `SIGTERM` closes the runtime and releases i6. Call `scene_look` to assess the rendered image.7. Call `scene_restore` with the current revision if the experiment fails.8. Call `scene_release_checkpoint` when you no longer need the saved state.-9. Call `scene_export_recipe` to retain the canonical recipe.-10. Call `scene_dispose` to release the scene before creating another one.+9. To try variants, call `scene_apply` once per variant with a `branch` name (the scene stays as it is), compare them with one `scene_review` that has a `branch` per shot, then call `scene_restore` with the winning `branch` to keep it.+10. Call `scene_export_recipe` to retain the canonical recipe.+11. Call `scene_dispose` to release the scene before creating another one.`scene_create`, `scene_apply`, and `scene_restore` return the session ID, current revision, inspection, and render status.`scene_checkpoint` returns a checkpoint UUID scoped to its session UUID.@@ -105,10 +106,10 @@ Inspect or export the recipe before retrying. Context loss still permits recipe| `mesh_inspect` | `sessionId`, optional `geometries` (up to 16 IDs) | Per geometry: polygon counts, face sizes, parts, face tags, bounds and lint problems with fixes || `mesh_edit` | `sessionId`, `expectedRevision`, `geometry`, `edits`, optional `replace` | Updated revision, render status and the mesh report with per-edit results || `mesh_stack` | `sessionId`, `expectedRevision`, `geometry`, optional `stack`, `apply` | Updated revision, render status and the mesh report with per-node results |-| `scene_look` | `sessionId`, optional `width`, `height`, `motionTime` | PNG image and metadata |-| `scene_review` | `sessionId`, `expectedRevision`, `shots`, optional `width`, `height` | Labeled PNG grid and metadata from an isolated snapshot |+| `scene_look` | `sessionId`, optional `width`, `height`, `motionTime`, `labels` | PNG image and metadata |+| `scene_review` | `sessionId`, `expectedRevision`, `shots` (each with an optional `branch`), optional `width`, `height`, `labels` | Labeled PNG grid and metadata from an isolated snapshot || `scene_checkpoint` | `sessionId` | Checkpoint ID, session ID, and revision |-| `scene_restore` | `sessionId`, `checkpointId`, `expectedRevision` | Updated revision, inspection, and render status |+| `scene_restore` | `sessionId`, `expectedRevision`, and a `checkpointId` or a `branch` | Updated revision, inspection, and render status || `scene_release_checkpoint` | `sessionId`, `checkpointId` | Release confirmation || `scene_export_recipe` | `sessionId` | Canonical recipe and revision || `scene_export_glb` | `sessionId`, optional `clip`, `motionTime`, `maxTextureSize` | A GLB file under `<jobs>/exports/` with a server-chosen name: path, bytes, SHA-256. See [GLB export](export-glb.md) |@@ -139,6 +140,8 @@ Imported clip sampling remains available through `set-animation`.`scene_review` compares up to four cameras or motion samples without changing the source recipe, revision or preview pose.Each shot starts from the authored base pose. The [review guide](agent-review.md) describes separate clocks, dimensions and resource limits.+`scene_apply` with a `branch` name forks instead of editing: the operations run on a scratch copy and the result is stored as that branch, so the scene, its revision and its checkpoints stay as they are. Branches are named with lowercase letters, digits, `_` and `-` (at most 24 characters); up to eight can exist, and branches that end in the same recipe share one snapshot. `scene_restore` with `branch` replays that branch's operations on the scene as one revision and drops every branch; it fails if the scene changed since the fork. Procedural scenes only. See the [review guide](agent-review.md#compare-branches-and-read-labels).+`set-node` can rebind a mesh to another geometry/material pair.The recipe also accepts [authored lighting, fog, effects and shadow coverage](agent-look.md).diff --git a/docs/parity.md b/docs/parity.mdindex bfd05810..f54dd37f 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -246,4 +246,4 @@ The goal also needs this work, and no page in the Blender manual covers it.| Rendering backend | missing | WebGL2 only. WebGPU is not evaluated. | #56 || Terrain and navigation | partial | Terrain with 4 splat layers and no holes. There is no navmesh. | #64 || Tool cost and errors | partial | Lint and errors exist. No budget limits schema size, and not every error is checked. | #65, #66 |-| Branches and labelled images | missing | 8 checkpoints and unlabelled images. | #67 |+| Branches and labelled images | partial | `scene_apply` `branch` forks a variant over a deduplicated snapshot store (8 branches, scene and revision untouched), `scene_review` shots take a `branch`, `scene_restore` `branch` keeps one. `labels: true` on `scene_look` and `scene_review` prints part names, tags and lint problems and returns them with pixel positions. Procedural scenes only; no suite task yet measures calls. | #67 |diff --git a/package.json b/package.jsonindex 320d26b4..aefff6c6 100644--- a/package.json+++ b/package.json@@ -108,6 +108,7 @@"smoke:character": "node scripts/smoke-character.mjs","smoke:agent-character": "node scripts/smoke-agent-character.mjs","smoke:agent-review": "node scripts/smoke-agent-review.mjs",+ "smoke:agent-branches": "node scripts/smoke-agent-branches.mjs","parity": "node scripts/parity-report.mjs","reference": "node bench/reference/run.mjs","size": "node scripts/measure-size.mjs",diff --git a/public/llms.txt b/public/llms.txtindex 08e7da70..ec936696 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -12,6 +12,7 @@ Version `0.6.0` adds asynchronous snapshot render jobs. Read `/agent-render-jobsVersion `0.8.0` adds imported source-node overrides and motion. Read `/agent-character-motion.md` for joint IDs, layering and pose ownership.+Variants: `scene_apply` with a `branch` name forks without editing, `scene_review` shots take a `branch`, `scene_restore` with `branch` keeps one; `labels: true` on `scene_look` and `scene_review` prints and returns part names and lint with pixel positions.Version `0.9.0` adds `scene_review`. Read `/agent-review.md` for a labeled PNG grid of up to four views or poses.Review uses an isolated snapshot with separate camera and clock settings. It preserves the source revision and preview pose.diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex b6c4d037..7049ed9f 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -9,6 +9,7 @@ import { exportGlb } from '../src/export.js';import { weightTracksFromGltfAnimation } from '../src/export-skeleton.js';import { clipFromGltfAnimation } from '../src/skeleton-pose.js';import { sessionProblem } from '../src/agent-errors.js';+import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../src/agent-branches.js';let active = null;let canvas = document.querySelector('canvas');@@ -144,6 +145,18 @@ function mutationStatus(record) {}}+// Draw the part labels onto a copy of the frame, so the preview canvas itself stays unmarked.+function labeledPng(labels) {+ if (!labels) return canvas.toDataURL('image/png').split(',')[1];+ const composed = document.createElement('canvas');+ composed.width = canvas.width;+ composed.height = canvas.height;+ const context = composed.getContext('2d');+ context.drawImage(canvas, 0, 0);+ paintLabels(context, labels, 0, 0);+ return composed.toDataURL('image/png').split(',')[1];+}+function resetCanvas() {canvas.getContext('webgl2')?.getExtension('WEBGL_lose_context')?.loseContext();const replacement = document.createElement('canvas');@@ -174,7 +187,7 @@ function createPreview(scene, { sessionId, memoryBudgetMiB, backend }, asset) {try {renderer = initializeRenderer(scene, { memoryBudgetMiB, backend });const record = { scene, renderer, asset, sessionId, options: { memoryBudgetMiB, backend },- checkpoints: new Map(), rendererTopology: scene.topologyRevision, rendererTextured: hasPatternTextures(scene.parts) };+ checkpoints: new Map(), branches: createBranchStore(), rendererTopology: scene.topologyRevision, rendererTextured: hasPatternTextures(scene.parts) };draw(record);const result = status(record);if (backend === 'gpu' && /swiftshader|llvmpipe|software/i.test(result.render.graphics)) {@@ -262,18 +275,79 @@ function bytesToBase64(bytes) {return btoa(binary);}+// The review grid outlives the private scenes drawn into it, because each branch in a review is its own scene.+let reviewGrid;++function projectToScreen(matrix, point, width, height) {+ const [x, y, z] = point;+ const clipX = matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12];+ const clipY = matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13];+ const clipW = matrix[3] * x + matrix[7] * y + matrix[11] * z + matrix[15];+ if (!(clipW > 0)) return null;+ const normalizedX = clipX / clipW;+ const normalizedY = clipY / clipW;+ if (Math.abs(normalizedX) > 1 || Math.abs(normalizedY) > 1) return null;+ return { x: Math.round((normalizedX * 0.5 + 0.5) * width), y: Math.round((1 - (normalizedY * 0.5 + 0.5)) * height) };+}++function meshProblemsByGeometry(scene, geometryIds) {+ const result = new Map();+ if (typeof scene.inspectMeshes !== 'function' || geometryIds.length === 0) return result;+ const { meshes } = scene.inspectMeshes({ geometries: geometryIds.slice(0, 16) });+ for (const mesh of meshes) {+ const faceTags = Array.isArray(mesh.tags) ? mesh.tags : Object.keys(mesh.tags ?? {});+ result.set(mesh.geometry, { problems: mesh.problems.map(problem => problem.kind), faceTags: faceTags.slice(0, 6) });+ }+ return result;+}++/** Name, material tag, face tags and lint problems of the visible parts, with the pixel they project to. */+function collectLabels(scene, camera, width, height) {+ const nodes = scene.inspect({ includeBounds: true }).nodes.filter(node => node.bounds);+ const materialTags = new Map(scene.exportRecipe().materials.map(material => [material.id, material.tag]));+ const view = mat4.lookAt(mat4.create(), camera.eye, camera.target, camera.up);+ const matrix = mat4.multiply(mat4.create(), applyProjection(mat4.create(), camera, width / height), view);+ const geometryIds = [...new Set(nodes.map(node => node.geometry))];+ const meshInfo = meshProblemsByGeometry(scene, geometryIds);+ const labels = [];+ for (const node of nodes) {+ const center = [0, 1, 2].map(axis => (node.bounds.min[axis] + node.bounds.max[axis]) / 2);+ const position = projectToScreen(matrix, center, width, height);+ if (!position || labels.length >= BRANCH_LIMITS.maximumLabels) continue;+ const mesh = meshInfo.get(node.geometry);+ labels.push({ id: node.id, name: printableLabel(node.label), tag: materialTags.get(node.material) ?? null,+ faceTags: mesh?.faceTags ?? [], problems: mesh?.problems ?? [], x: position.x, y: position.y });+ }+ return labels;+}++function paintLabels(context, labels, offsetX, offsetY) {+ context.font = '11px sans-serif';+ context.textBaseline = 'middle';+ for (const label of labels) {+ const text = [label.name, label.tag === 'surface' ? null : label.tag,...(label.problems.length ? [`! ${label.problems.join(',')}`] : [])].filter(Boolean).join(' ');+ const x = offsetX + label.x;+ const y = offsetY + label.y;+ context.fillStyle = label.problems.length ? '#ff8a65' : '#ffe082';+ context.fillRect(x - 2, y - 2, 4, 4);+ context.lineWidth = 3;+ context.strokeStyle = 'rgba(16,20,22,0.85)';+ context.strokeText(text, x + 5, y);+ context.fillText(text, x + 5, y);+ }+}+window.__agentPreview = {- reviewBegin({ sessionId, width, height }) {- const record = requireSession(sessionId);- record.reviewGrid = document.createElement('canvas');- record.reviewGrid.width = width;- record.reviewGrid.height = height;- const context = record.reviewGrid.getContext('2d');+ reviewBegin({ width, height }) {+ reviewGrid = document.createElement('canvas');+ reviewGrid.width = width;+ reviewGrid.height = height;+ const context = reviewGrid.getContext('2d');context.fillStyle = '#202428';context.fillRect(0, 0, width, height);return { width, height };},- reviewShot({ sessionId, shot, index, width, height, columns }) {+ reviewShot({ sessionId, shot, index, width, height, columns, labels: withLabels = false }) {const record = requireSession(sessionId);const recipe = record.scene.exportRecipe();const animation = shot.animation ?? recipe.animation ?? null;@@ -289,7 +363,7 @@ window.__agentPreview = {draw(record, shot.rendererTime, camera);const render = renderInfo(record.renderer);if (render.width < 64 || render.height < 64) throw new Error('Render budget reduced review below its minimum output size.');- const context = record.reviewGrid.getContext('2d');+ const context = reviewGrid.getContext('2d');const x = index % columns * width;const y = Math.floor(index / columns) * (height + 24);context.drawImage(canvas, x, y + 24, width, height);@@ -297,13 +371,14 @@ window.__agentPreview = {context.font = '12px sans-serif';context.textBaseline = 'middle';context.fillText(shot.label.replace(/[\r\n\t]/g, ' '), x + 8, y + 12, width - 16);+ const labels = withLabels ? collectLabels(record.scene, camera, width, height) : undefined;+ if (labels) paintLabels(context, labels, x, y + 24);return { label: shot.label, camera, animation: record.asset ? animation : null,motionTime: record.scene.motionTime ?? null, rendererTime: shot.rendererTime,- requestedWidth: width, requestedHeight: height, ...render };+ requestedWidth: width, requestedHeight: height, ...render, ...(labels ? { labels } : {}) };},- reviewResult({ sessionId }) {- const record = requireSession(sessionId);- return { data: record.reviewGrid.toDataURL('image/png').split(',')[1], mimeType: 'image/png' };+ reviewResult() {+ return { data: reviewGrid.toDataURL('image/png').split(',')[1], mimeType: 'image/png' };},snapshot({ sessionId, expectedRevision }) {const record = requireSession(sessionId);@@ -421,7 +496,7 @@ window.__agentPreview = {const [mesh] = record.scene.inspectMeshes({ geometries: [geometry] }).meshes;return { ...status, mesh };},- look({ sessionId, motionTime }) {+ look({ sessionId, motionTime, labels: withLabels = false }) {const record = requireSession(sessionId);if (motionTime !== undefined) {if (typeof record.scene.sampleMotion !== 'function') {@@ -432,11 +507,12 @@ window.__agentPreview = {draw(record);const render = renderInfo(record.renderer);record.lastRender = render;+ const labels = withLabels ? collectLabels(record.scene, record.scene.camera, canvas.width, canvas.height) : undefined;return {- data: canvas.toDataURL('image/png').split(',')[1],+ data: labeledPng(labels),mimeType: 'image/png',metadata: { sessionId, revision: record.scene.revision, topologyRevision: record.scene.topologyRevision,- motionTime: record.scene.motionTime ?? null, ...render },+ motionTime: record.scene.motionTime ?? null, ...render, ...(labels ? { labels } : {}) },};},checkpoint({ sessionId, checkpointId }) {@@ -466,6 +542,37 @@ window.__agentPreview = {record.checkpoints.delete(checkpointId);return { sessionId, checkpointId, released: true };},+ /** Apply operations to a scratch copy and store the result as a branch. The source scene and its revision stay as they are. */+ branchApply({ sessionId, name, operations, expectedRevision }) {+ return afterMeshBooleans(operations, () => {+ const record = requireSession(sessionId);+ if (record.asset) throw new TypeError('Branches support procedural recipe scenes.');+ if (record.scene.revision !== expectedRevision) throw new Error('Stale revision for branch.');+ const baseRecipe = record.scene.exportRecipe();+ const scratch = createAgentScene(baseRecipe);+ validatePreviewCamera(candidateCamera(record, operations));+ scratch.apply(operations, { expectedRevision: scratch.revision });+ const { shared } = record.branches.fork(name, { recipe: scratch.exportRecipe(), baseRecipe, operations, baseRevision: expectedRevision });+ return { sessionId, branch: name, sourceRevision: record.scene.revision, shared,+ branches: record.branches.names(), snapshots: record.branches.snapshotCount() };+ });+ },+ branchRecipe({ sessionId, name }) {+ const record = requireSession(sessionId);+ const branch = record.branches.get(name);+ return { recipe: branch.recipe, stale: branch.baseKey !== JSON.stringify(record.scene.exportRecipe()) };+ },+ /** Keep one branch: replay its operations on the live scene (one revision), then drop every branch. */+ keepBranch({ sessionId, name, expectedRevision }) {+ const record = requireSession(sessionId);+ const branch = record.branches.get(name);+ if (branch.baseKey !== JSON.stringify(record.scene.exportRecipe())) {+ throw new Error(`The scene changed since branch ${name} was forked. Fork it again from the current revision.`);+ }+ const status = this.applyLoaded({ sessionId, operations: branch.operations, expectedRevision });+ record.branches.clear();+ return { ...status, kept: name };+ },exportRecipe({ sessionId }) {const record = requireSession(sessionId);return { sessionId, revision: record.scene.revision, recipe: record.scene.exportRecipe() };@@ -489,6 +596,7 @@ window.__agentPreview = {record.asset?.dispose();}record.checkpoints.clear();+ record.branches.clear();active = null;return { sessionId, disposed: true };},diff --git a/scripts/agent-review.mjs b/scripts/agent-review.mjsindex ca483f40..81683391 100644--- a/scripts/agent-review.mjs+++ b/scripts/agent-review.mjs@@ -1,3 +1,5 @@+import { validateBranchName } from '../src/agent-branches.js';+export const REVIEW_LIMITS = Object.freeze({ minimumShots: 1, maximumShots: 4,minimumDimension: 64, maximumDimension: 480, defaultWidth: 384, defaultHeight: 384,labelHeight: 24, maximumLabelLength: 48, maximumGridWidth: 960, maximumGridHeight: 1008,@@ -17,9 +19,20 @@ function clock(value, name) {return value;}+/** Shots of one scene render together: the source scene, or one branch each. */+function groupShotsByBranch(shots) {+ const groups = new Map();+ for (const [index, shot] of shots.entries()) {+ if (!groups.has(shot.branch)) groups.set(shot.branch, { branch: shot.branch, shotIndexes: [] });+ groups.get(shot.branch).shotIndexes.push(index);+ }+ return [...groups.values()];+}+/** Validate before leasing the source renderer. Camera relationships use the sampled pose. */export function normalizeReview(input) {- fields(input, ['sessionId', 'expectedRevision', 'width', 'height', 'shots'], 'review');+ fields(input, ['sessionId', 'expectedRevision', 'width', 'height', 'shots', 'labels'], 'review');+ if (input.labels !== undefined && typeof input.labels !== 'boolean') throw new TypeError('Review labels must be boolean.');if (typeof input.sessionId !== 'string' || !Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0) {throw new TypeError('Review requires a sessionId and a safe nonnegative expectedRevision.');}@@ -32,7 +45,11 @@ export function normalizeReview(input) {throw new RangeError('Review requires one to four shots.');}const shots = input.shots.map((shot, index) => {- fields(shot, ['label', 'camera', 'animation', 'motionTime', 'rendererTime'], 'shot');+ fields(shot, ['label', 'camera', 'animation', 'motionTime', 'rendererTime', 'branch'], 'shot');+ if (shot.branch !== undefined) {+ validateBranchName(shot.branch);+ if (shot.animation !== undefined) throw new TypeError('A branch shot cannot sample an imported animation.');+ }if (shot.label !== undefined && (typeof shot.label !== 'string' || shot.label.length > 48)) {throw new TypeError('Shot label must be a string of at most 48 characters.');}@@ -53,12 +70,16 @@ export function normalizeReview(input) {}const motionTime = shot.motionTime ?? null;if (motionTime !== null) clock(motionTime, 'Motion time');- return { label: shot.label ?? `View ${index + 1}`,+ return { label: shot.label ?? shot.branch ?? `View ${index + 1}`,+ ...(shot.branch === undefined ? {} : { branch: shot.branch }),...(shot.camera === undefined ? {} : { camera: structuredClone(shot.camera) }),...(shot.animation === undefined ? {} : { animation: structuredClone(shot.animation) }),motionTime, rendererTime: clock(shot.rendererTime === undefined ? 0 : shot.rendererTime, 'Renderer time') };});const columns = shots.length > 1 ? 2 : 1;- return { sessionId: input.sessionId, expectedRevision: input.expectedRevision, width, height, shots,+ const groups = groupShotsByBranch(shots);+ return { sessionId: input.sessionId, expectedRevision: input.expectedRevision, width, height, shots, groups,+ branchNames: [...new Set(shots.flatMap(shot => shot.branch === undefined ? [] : [shot.branch]))],+ labels: input.labels === true,gridWidth: width * columns, gridHeight: (height + REVIEW_LIMITS.labelHeight) * Math.ceil(shots.length / columns), columns };}diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex 9129ac93..91d14100 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -11,6 +11,7 @@ import { createAgentRenderJobs, EXPORT_DIRECTORY_NAME } from './agent-render-jobimport { createFrameEncoder } from './frame-encoder.mjs';import { isPreviewHost } from './preview-host.mjs';import { normalizeReview, REVIEW_LIMITS } from './agent-review.mjs';+import { BRANCH_LIMITS, validateBranchName } from '../src/agent-branches.js';import { sessionProblem } from '../src/agent-errors.js';const SCENE_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;@@ -372,7 +373,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 },review: { ...REVIEW_LIMITS, backend, memoryBudgetMiB: memory, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS,totalTimeoutMs: EVALUATION_TIMEOUT_MS,- sourcePreserved: true, defaultMotionTime: null, defaultRendererTime: 0 },+ sourcePreserved: true, defaultMotionTime: null, defaultRendererTime: 0, branches: BRANCH_LIMITS },phase: closing && phase !== 'closed' ? 'closing' : phase,availableIn: packageMetadata.version,assets: {@@ -437,6 +438,10 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memoapply(input) {return enqueue(async () => {await requirePreviewRenderer();+ if (input.branch !== undefined) {+ const { branch, ...rest } = input;+ return invoke('branchApply', { ...rest, name: validateBranchName(branch) });+ }return invoke('apply', input);});},@@ -451,7 +456,8 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo}await page.setViewportSize({ width, height });const result = await invoke('look', { sessionId: input.sessionId,- ...(input.motionTime !== undefined ? { motionTime: input.motionTime } : {}) });+ ...(input.motionTime !== undefined ? { motionTime: input.motionTime } : {}),+ ...(input.labels ? { labels: true } : {}) });if (Buffer.byteLength(result.data, 'base64') > MAXIMUM_IMAGE_BYTES) {throw new Error('The PNG exceeds the 1 MiB image response budget. Request a smaller preview.');}@@ -475,8 +481,12 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memoawait requirePreviewRenderer();requireSession(settings.sessionId);const snapshot = await invoke('snapshot', settings);+ const branchRecipes = new Map();+ for (const name of settings.branchNames) {+ branchRecipes.set(name, await invoke('branchRecipe', { sessionId: settings.sessionId, name }));+ }const assetBytes = snapshot.recipe.format === '67js.asset' ? await (await catalog()).read(snapshot.recipe.assetId) : undefined;- const privateSessionId = randomUUID();+ let privateSessionId;const started = performance.now();let suspended = false;let privateCreated = false;@@ -527,26 +537,31 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memoreviewPage.setDefaultTimeout(15000);await reviewPage.goto(origin);await reviewPage.waitForFunction(() => Boolean(window.__agentPreview));- await reviewEvaluate(assetBytes ? 'createAsset' : 'create', { sessionId: privateSessionId,- recipe: snapshot.recipe, memoryBudgetMiB: memory, backend,- ...(assetBytes ? { data: assetBytes.toString('base64') } : {}) });- privateCreated = true;- await reviewEvaluate('reviewBegin', { sessionId: privateSessionId,- width: settings.gridWidth, height: settings.gridHeight });+ await reviewEvaluate('reviewBegin', { width: settings.gridWidth, height: settings.gridHeight });session = await reviewPage.context().newCDPSession(reviewPage);const shots = [];let peakBrowserHeap = 0;let peakNodeBytes = 0;- for (const [index, shot] of settings.shots.entries()) {- const rendered = await reviewEvaluate('reviewShot', { sessionId: privateSessionId, shot, index,- width: settings.width, height: settings.height, columns: settings.columns });- if (backend === 'cpu' && !/swiftshader/i.test(rendered.graphics)) throw new Error('CPU review did not select SwiftShader.');- peakNodeBytes = Math.max(peakNodeBytes, process.memoryUsage().rss);- peakBrowserHeap = Math.max(peakBrowserHeap, (await session.send('Runtime.getHeapUsage')).usedSize);- if (peakNodeBytes > 512 * 1024 ** 2 || peakBrowserHeap > 256 * 1024 ** 2) {- throw new Error('Review exceeded its Node RSS or sampled browser heap guard.');+ for (const group of settings.groups) {+ const branchRecipe = group.branch === undefined ? undefined : branchRecipes.get(group.branch);+ privateSessionId = randomUUID();+ await reviewEvaluate(branchRecipe || !assetBytes ? 'create' : 'createAsset', { sessionId: privateSessionId,+ recipe: branchRecipe ? branchRecipe.recipe : snapshot.recipe, memoryBudgetMiB: memory, backend,+ ...(!branchRecipe && assetBytes ? { data: assetBytes.toString('base64') } : {}) });+ privateCreated = true;+ for (const index of group.shotIndexes) {+ const rendered = await reviewEvaluate('reviewShot', { sessionId: privateSessionId, shot: settings.shots[index], index,+ width: settings.width, height: settings.height, columns: settings.columns, labels: settings.labels });+ if (backend === 'cpu' && !/swiftshader/i.test(rendered.graphics)) throw new Error('CPU review did not select SwiftShader.');+ peakNodeBytes = Math.max(peakNodeBytes, process.memoryUsage().rss);+ peakBrowserHeap = Math.max(peakBrowserHeap, (await session.send('Runtime.getHeapUsage')).usedSize);+ if (peakNodeBytes > 512 * 1024 ** 2 || peakBrowserHeap > 256 * 1024 ** 2) {+ throw new Error('Review exceeded its Node RSS or sampled browser heap guard.');+ }+ shots[index] = { ...rendered, ...(group.branch === undefined ? {} : { branch: group.branch, branchStale: branchRecipe.stale }) };}- shots.push(rendered);+ await reviewEvaluate('dispose', { sessionId: privateSessionId });+ privateCreated = false;}const result = await reviewEvaluate('reviewResult', { sessionId: privateSessionId });if (Buffer.byteLength(result.data, 'base64') > MAXIMUM_IMAGE_BYTES) throw new Error('The review PNG exceeds the 1 MiB image response budget. Request smaller shots.');@@ -592,6 +607,10 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memorestore(input) {return enqueue(async () => {await requirePreviewRenderer();+ if (input.branch !== undefined) {+ return invoke('keepBranch', { sessionId: input.sessionId, name: validateBranchName(input.branch), expectedRevision: input.expectedRevision });+ }+ if (input.checkpointId === undefined) throw new TypeError('Restore needs a checkpointId or a branch.');return invoke('restore', input);});},diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 5e6bc698..d6c5959a 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -1,3 +1,4 @@+import { BRANCH_NAME_PATTERN } from '../src/agent-branches.js';import { McpServer } from '@modelcontextprotocol/server';import { serveStdio, StdioServerTransport } from '@modelcontextprotocol/server/stdio';import * as z from 'zod/v4';@@ -515,6 +516,8 @@ const operation = z.discriminatedUnion('type', [z.strictObject({ type: z.literal('add-material'), material: z.strictObject({ id: identifier, tag: materialTag, ...materialFields }) }),z.strictObject({ type: z.literal('remove-material'), id: identifier }),]);+const branchName = z.string().regex(BRANCH_NAME_PATTERN).describe('Branch name, up to 24 characters.');+const labelsFlag = z.boolean().optional().describe('Draw part names, tags and lint problems on the image; returned with pixel positions.');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.') };const expectedRevision = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).describe('Current revision returned by create, inspect, apply or restore. Stale edits fail atomically.');@@ -545,7 +548,7 @@ function jsonResult(value) {export function createAgentMcpServer(runtime, { version = packageMetadata.version } = {}) {const server = new McpServer({ name: '67js-scene', version }, {- instructions: 'Start with scene_capabilities. Create a procedural recipe with scene_create, or select a configured GLB digest from scene_asset_catalog and use scene_create_asset. Inspect stable IDs and save a checkpoint before editing. 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 actual image, or scene_review with the current expectedRevision to compare independent camera and motion samples in one grid while preserving the source pose. When jobs are configured, scene_render_submit captures an immutable snapshot. Poll scene_render_status, cancel when needed, and retrieve verified local artifact metadata with scene_render_result after completion. Preview rendering and edits pause during a job; source revision and checkpoints survive. Release outputs with scene_render_release. Export the final recipe and dispose the scene when finished. No arbitrary JavaScript, remote URLs or caller-selected output paths are exposed.',+ instructions: 'Start with scene_capabilities. Create a procedural recipe with scene_create, or select a configured GLB digest from scene_asset_catalog and use scene_create_asset. Inspect stable IDs and save a checkpoint before editing. 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. To try variants, give scene_apply a branch name for each (the scene stays put), compare them in one scene_review with a branch per shot, then keep the best with scene_restore and its branch. Pass labels: true to scene_look or scene_review to match part names to the image. Use scene_look to judge the actual image, or scene_review with the current expectedRevision to compare independent camera and motion samples in one grid while preserving the source pose. When jobs are configured, scene_render_submit captures an immutable snapshot. Poll scene_render_status, cancel when needed, and retrieve verified local artifact metadata with scene_render_result after completion. Preview rendering and edits pause during a job; source revision and checkpoints survive. Release outputs with scene_render_release. Export the final recipe and dispose the scene when finished. No arbitrary JavaScript, remote URLs or caller-selected output paths are exposed.',});let closePromise;server.server.onclose = () => {@@ -572,8 +575,8 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioregister('mesh_inspect', 'Check recipe geometries as polygon meshes: vertex, edge and face counts, triangles/quads/n-gons, connected and closed parts, face tags (top, bottom, side, left, right, front, back), bounds, and lint problems (non-manifold, inconsistent winding, inverted, degenerate, open, loose) with a suggested fix each. Procedural scenes only. Read-only and cached per geometry.', z.strictObject({ ...sessionFields, geometry: identifier.optional().describe('One geometry ID to check, as in mesh_edit.'), geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit both to check the first 16 geometries.') }), readOnly, async ({ geometry: geometryId, geometries, ...rest }) => jsonResult(await runtime.inspectMeshes({ ...rest, ...(geometries || geometryId ? { geometries: [...(geometries ?? []), ...(geometryId ? [geometryId] : [])] } : {}) })));register('mesh_edit', 'Append edits to a recipe mesh geometry (or replace its edit log), atomically like scene_apply: extrude, inset, delete, flip, translate with proportional falloff, merge by distance, tag, loop cut, bevel, mirror, array, solidify, UV unwrap, set_position and displace driven by field expressions (math, noise, attributes; also a {"field":expr} selection rule), and booleans (union, difference, intersect) with a primitive cutter. Edits that select no faces or break limits fail without changing the scene. Returns the new revision, render status and the mesh report with per-edit results (faces selected, tags created, size after).', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), edits: meshEdits.min(1), replace: z.boolean().optional().describe('Replace the whole edit log instead of appending.') }), edit, async argumentsValue => jsonResult(await runtime.editMesh(argumentsValue)));register('mesh_stack', 'Set the non-destructive modifier stack of a recipe mesh geometry (mirror, array, solidify, bevel, uv_unwrap, subdivide, set_position, displace, decimate, remesh), evaluated after its edits with each prefix cached, so changing a late node is cheap. apply: n moves the first n nodes into the edit log, as Blender\'s Apply modifier. Atomic like scene_apply. Returns the revision, render status and mesh report with per-node results.', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), stack: meshStack.optional().describe('The whole new stack. Omit to keep the current stack (for example with apply).'), apply: z.number().int().min(0).max(16).optional() }), edit, async argumentsValue => jsonResult(await runtime.setMeshStack(argumentsValue)));- register('scene_apply', 'Atomically edit transforms, look, camera or materials. Procedural scenes support membership and set-motion authoring. Imported assets support set-root, set-asset-node, set-motion and absolute set-animation sampling. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Node/material/camera/root/animation commands use flat fields. Motion, look patches and add commands contain nested records. Backend validates each scene mode before publication.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));- register('scene_look', 'Render the active scene as a bounded PNG. Optional authored motionTime seeks without changing revision; null restores the authored base pose. Omit to retain the last preview pose.', z.strictObject({ ...sessionFields, motionTime: z.number().min(0).max(3600).nullable().optional(), 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 => {+ register('scene_apply', 'Atomically edit transforms, look, camera or materials. Procedural scenes support membership and set-motion authoring. Imported assets support set-root, set-asset-node, set-motion and absolute set-animation sampling. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Node/material/camera/root/animation commands use flat fields. Motion, look patches and add commands contain nested records. Backend validates each scene mode before publication.'), branch: branchName.optional().describe('Fork: store the result as this branch (up to 8), leaving the scene unchanged.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));+ register('scene_look', 'Render the active scene as a bounded PNG, optionally with part labels. Optional authored motionTime seeks without changing revision; null restores the authored base pose. Omit to retain the last preview pose.', z.strictObject({ ...sessionFields, motionTime: z.number().min(0).max(3600).nullable().optional(), 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.'), labels: labelsFlag }), 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 };});@@ -581,8 +584,10 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio...sessionFields, expectedRevision,width: z.number().int().min(64).max(480).default(384),height: z.number().int().min(64).max(480).default(384),+ labels: labelsFlag,shots: z.array(z.strictObject({label: z.string().max(48).optional(),+ branch: branchName.optional().describe('Render this scene_apply branch.'),camera: z.strictObject(cameraFields).optional(),animation: z.strictObject({ clip: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), time: z.number().min(0).max(3600) }).optional(),motionTime: z.number().min(0).max(3600).nullable().optional(),@@ -593,7 +598,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioreturn { content: [{ type: 'image', data, mimeType }, { type: 'text', text: JSON.stringify(metadata) }], structuredContent: metadata };});register('scene_checkpoint', 'Save a private recipe snapshot. Up to eight checkpoints can be retained per session.', z.strictObject(sessionFields), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.checkpoint(argumentsValue)));- register('scene_restore', 'Restore a checkpoint atomically using the current revision. The checkpoint remains available and revision increments.', z.strictObject({ ...checkpointFields, expectedRevision }), edit, async argumentsValue => jsonResult(await runtime.restore(argumentsValue)));+ register('scene_restore', 'Restore a checkpoint atomically using the current revision. The checkpoint remains available and revision increments. With branch instead of checkpointId, keep that branch (one revision) and drop all branches.', z.strictObject({ ...sessionFields, checkpointId: checkpointFields.checkpointId.optional(), branch: branchName.optional(), expectedRevision }), edit, async argumentsValue => jsonResult(await runtime.restore(argumentsValue)));register('scene_release_checkpoint', 'Release one checkpoint slot. Released or foreign checkpoints fail.', z.strictObject(checkpointFields), edit, async argumentsValue => jsonResult(await runtime.releaseCheckpoint(argumentsValue)));register('scene_export_recipe', 'Read a detached canonical JSON recipe for reproduction.', z.strictObject(sessionFields), readOnly, async argumentsValue => jsonResult(await runtime.exportRecipe(argumentsValue)));register('scene_export_glb', 'Write the active scene as a GLB file in the configured jobs folder, under a server-chosen name (the result has the path, byte count and SHA-256). Needs --jobs. Exports the current pose with pattern and imported textures, skins, morph weights and IK as posed; motionTime seeks authored motion first. For an imported asset, clip adds that source clip (translation, rotation, scale and morph weight tracks) on the source skeleton, which needs no animation, node overrides or motion in the scene. At most eight files are kept, oldest removed first; the GLB is at most 32 MiB.', z.strictObject({ ...sessionFields, clip: z.number().int().min(0).max(255).optional().describe('Imported assets only: index of the source clip to write.'), motionTime: z.number().min(0).max(3600).optional().describe('Seek authored motion (and IK) to this time before exporting. Leaves the preview there, like scene_look.'), maxTextureSize: z.number().int().min(1).max(4096).optional().describe('Largest texture side in pixels. Defaults to 2048.') }), edit, async argumentsValue => jsonResult(await runtime.exportGlb(argumentsValue)));diff --git a/scripts/smoke-agent-branches.mjs b/scripts/smoke-agent-branches.mjsnew file mode 100644index 00000000..c69ac274--- /dev/null+++ b/scripts/smoke-agent-branches.mjs@@ -0,0 +1,111 @@+import assert from 'node:assert/strict';+import { mkdtemp, writeFile } from 'node:fs/promises';+import { tmpdir, constants, setPriority } from 'node:os';+import { join, resolve } from 'node:path';+import { spawnSync } from 'node:child_process';+import { Client } from '@modelcontextprotocol/client';+import { PatientStdioClientTransport } from './patient-stdio-transport.mjs';+import { createAgentPreviewFixture } from './agent-preview-fixture.mjs';++// Drives the installed MCP server on SwiftShader: branches, a branch review and labels, through real tool calls.+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const directory = await mkdtemp(join(tmpdir(), '67js-branches-proof-'));+const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');+const transport = new PatientStdioClientTransport({ command: process.execPath,+ args: [cli, '--backend', 'cpu', '--memory', '96'], cwd: directory, stderr: 'pipe' });+const client = new Client({ name: '67js-branches-proof', version: '1' });++async function call(name, argumentsValue) {+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 60000 });+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);+ return result;+}++async function rejected(name, argumentsValue) {+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 60000 });+ assert.equal(result.isError, true, `${name} must reject ${JSON.stringify(argumentsValue).slice(0, 80)}`);+}++function imageBytes(result) {+ return Buffer.from(result.content.find(item => item.type === 'image').data, 'base64');+}++function decodedPixels(bytes, crop) {+ const decoded = spawnSync('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', 'pipe:0',+ ...(crop ? ['-vf', crop] : []), '-frames:v', '1', '-f', 'rawvideo', '-pix_fmt', 'rgba', 'pipe:1'],+ { input: bytes, windowsHide: true, maxBuffer: 16 * 1024 * 1024 });+ assert.equal(decoded.status, 0, decoded.stderr.toString());+ return decoded.stdout;+}++function recolor(color) {+ return [{ type: 'set-material', id: 'light', color, emissiveColor: color }];+}++try {+ await client.connect(transport);+ const created = (await call('scene_create', { recipe: createAgentPreviewFixture() })).structuredContent;+ const sessionId = created.sessionId;+ const settings = { sessionId, expectedRevision: 0 };+ const sourceBefore = decodedPixels(imageBytes(await call('scene_look', { sessionId, width: 256, height: 256 })));+ const checkpoint = (await call('scene_checkpoint', { sessionId })).structuredContent;+ const recipeBefore = (await call('scene_export_recipe', { sessionId })).structuredContent.recipe;++ const variants = { warm: [1, 0.3, 0.1], cool: [0.1, 0.4, 1], twin: [0.1, 0.4, 1] };+ const forks = {};+ for (const [name, color] of Object.entries(variants)) {+ forks[name] = (await call('scene_apply', { ...settings, branch: name, operations: recolor(color) })).structuredContent;+ }+ assert.equal(forks.twin.shared, true, 'identical recipes share one snapshot');+ assert.equal(forks.twin.snapshots, 2);+ assert.equal(forks.twin.sourceRevision, 0, 'a fork does not consume a revision');++ const review = await call('scene_review', { ...settings, width: 256, height: 256, labels: true,+ shots: [{ branch: 'warm' }, { branch: 'cool' }, { label: 'Source' }, { branch: 'twin', label: 'Twin' }] });+ const shots = review.structuredContent.shots;+ assert.deepEqual(shots.map(shot => shot.branch), ['warm', 'cool', undefined, 'twin']);+ const grid = imageBytes(review);+ if (process.env.BRANCH_SMOKE_IMAGE) await writeFile(process.env.BRANCH_SMOKE_IMAGE, grid);+ const warmShot = decodedPixels(grid, 'crop=256:256:0:24');+ const coolShot = decodedPixels(grid, 'crop=256:256:256:24');+ const sourceShot = decodedPixels(grid, 'crop=256:256:0:304');+ assert.notDeepEqual(warmShot, coolShot, 'branches render different scenes');+ assert.notDeepEqual(warmShot, sourceShot);+ for (const shot of shots) {+ assert.ok(shot.labels.length > 0 && shot.labels.length <= 24);+ for (const label of shot.labels) {+ assert.ok(label.x >= 0 && label.x <= 256 && label.y >= 0 && label.y <= 256, 'label inside the shot');+ assert.equal(typeof label.id, 'string');+ }+ }++ const afterReview = (await call('scene_inspect', { sessionId })).structuredContent;+ assert.equal(afterReview.revision, 0, 'review and branches leave the revision alone');+ assert.deepEqual((await call('scene_export_recipe', { sessionId })).structuredContent.recipe, recipeBefore);+ assert.deepEqual(decodedPixels(imageBytes(await call('scene_look', { sessionId, width: 256, height: 256 }))), sourceBefore,+ 'the source image is identical after branching and review');++ const labelled = await call('scene_look', { sessionId, width: 384, height: 384, labels: true });+ assert.ok(labelled.structuredContent.labels.length > 0);+ assert.notDeepEqual(decodedPixels(imageBytes(labelled)), decodedPixels(imageBytes(await call('scene_look', { sessionId, width: 384, height: 384 }))));++ for (const hostile of ['', 'Warm', '1warm', 'a'.repeat(25), '../x', 'a b', 'a\nb', 'http://example.com/x', '__proto__ ', 'a;rm']) {+ await rejected('scene_apply', { ...settings, branch: hostile, operations: recolor([1, 1, 1]) });+ await rejected('scene_review', { ...settings, shots: [{ branch: hostile }] });+ await rejected('scene_restore', { sessionId, expectedRevision: 0, branch: hostile });+ }+ await rejected('scene_review', { ...settings, shots: [{ branch: 'missing' }] });+ await rejected('scene_review', { ...settings, labels: 'yes', shots: [{ label: 'x' }] });+ await rejected('scene_restore', { sessionId, expectedRevision: 0 });++ const kept = (await call('scene_restore', { sessionId, expectedRevision: 0, branch: 'cool' })).structuredContent;+ assert.equal(kept.revision, 1);+ assert.equal(kept.kept, 'cool');+ await rejected('scene_review', { sessionId, expectedRevision: 1, shots: [{ branch: 'warm' }] });+ const restored = (await call('scene_restore', { sessionId, expectedRevision: 1, checkpointId: checkpoint.checkpointId })).structuredContent;+ assert.equal(restored.revision, 2);+ await call('scene_dispose', { sessionId });+ console.log('Branch smoke passed: fork, shared snapshot, review, labels, keep, hostile names.');+} finally {+ await client.close().catch(() => {});+}diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex 1870369f..a8738552 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -47,6 +47,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.- Things that fall, pile up or rest on an authored mesh (dropped objects, a ball in a bowl, a trigger zone) use the recipe `physics` section: bodies on root node IDs, `shape: 'trimesh'` on a fixed body so objects follow the mesh, `sensor: true` for triggers, `layer` and `collidesWith` for masks. Seek with `motionTime` like motion, and read `physics` from `scene_inspect` (resting times, contacts, sensor events) instead of guessing from a picture. Needs the optional peer `@dimforge/rapier3d-compat`; bodies bound to bones for ragdolls are not supported. See "Recipe physics" in the checkout's `docs/physics.md`.- Agent procedural animation uses `docs/agent-motion.md` from release `0.7.0`. Author recipe tracks, then seek through `sampleMotion` or MCP `motionTime`.- Agent imported character motion uses `docs/agent-character-motion.md` from release `0.8.0`. Inspect source joints before authoring local tracks.+- To pick between variants, fork each with `scene_apply` and a `branch` name (the scene and revision stay put), compare them in one `scene_review` with a `branch` per shot, then keep the winner with `scene_restore` and its `branch`. Add `labels: true` to `scene_look` or `scene_review` to match node names and lint problems to what the image shows. Docs: `docs/agent-review.md`.- Agent comparisons use `scene_review` from release `0.9.0`. Read `docs/agent-review.md` for isolated views and independent pose samples.- An image or video export uses `render-67js-media`.- A GLB for Blender or another tool uses `scene_export_glb` (needs `--jobs`): it returns a file path under the jobs folder, takes no path of its own. Plain call for the current pose with textures, skins and IK; `motionTime` to pose authored motion first; `clip` on an unposed imported asset for its source animation. See `docs/export-glb.md`.diff --git a/src/agent-branches.js b/src/agent-branches.jsnew file mode 100644index 00000000..96b24730--- /dev/null+++ b/src/agent-branches.js@@ -0,0 +1,70 @@+// Branches are named variants of the scene an agent is editing. A branch records the operations that made it and the+// recipe they produce. Recipes are stored once per distinct content, so three branches that end in the same recipe cost+// one snapshot. This module holds plain data only: it must stay free of engine imports so the MCP server can share it.++export const BRANCH_LIMITS = Object.freeze({ maximumBranches: 8, maximumNameLength: 24, maximumLabels: 24 });++export const BRANCH_NAME_PATTERN = /^[a-z][a-z0-9_-]{0,23}$/;++export function validateBranchName(name) {+ if (typeof name !== 'string' || !BRANCH_NAME_PATTERN.test(name)) {+ throw new TypeError('A branch name starts with a lowercase letter and has at most 24 lowercase letters, digits, underscores or hyphens.');+ }+ return name;+}++/** Keep only printable text that fits a drawn label, so a hostile node ID cannot break the overlay. */+export function printableLabel(text, maximumLength = 32) {+ return String(text).replace(/[^\x20-\x7e]/g, '?').slice(0, maximumLength);+}++export function createBranchStore() {+ const snapshots = new Map();+ const branches = new Map();++ function referencedKeys() {+ return new Set([...branches.values()].map(branch => branch.recipeKey));+ }++ function pruneSnapshots() {+ const referenced = referencedKeys();+ for (const key of snapshots.keys()) {+ if (!referenced.has(key)) snapshots.delete(key);+ }+ }++ return {+ /** Store a branch. Returns whether its recipe was already held by another branch. */+ fork(name, { recipe, baseRecipe, operations, baseRevision }) {+ validateBranchName(name);+ if (!branches.has(name) && branches.size >= BRANCH_LIMITS.maximumBranches) {+ throw new RangeError(`At most ${BRANCH_LIMITS.maximumBranches} branches can exist. Keep one, or reuse a name to replace it.`);+ }+ const recipeKey = JSON.stringify(recipe);+ const shared = [...branches.entries()].some(([otherName, other]) => otherName !== name && other.recipeKey === recipeKey);+ branches.set(name, { recipeKey, baseKey: JSON.stringify(baseRecipe), operations: structuredClone(operations), baseRevision });+ if (!snapshots.has(recipeKey)) snapshots.set(recipeKey, recipe);+ pruneSnapshots();+ return { shared };+ },+ get(name) {+ validateBranchName(name);+ const branch = branches.get(name);+ if (!branch) {+ throw new RangeError(`Unknown branch: ${name}. Known branches: ${[...branches.keys()].join(', ') || 'none'}.`);+ }+ return { recipe: structuredClone(snapshots.get(branch.recipeKey)), baseKey: branch.baseKey,+ operations: structuredClone(branch.operations), baseRevision: branch.baseRevision };+ },+ names() {+ return [...branches.keys()];+ },+ snapshotCount() {+ return snapshots.size;+ },+ clear() {+ branches.clear();+ snapshots.clear();+ },+ };+}diff --git a/tests/agent-branches-live.test.js b/tests/agent-branches-live.test.jsnew file mode 100644index 00000000..564a824b--- /dev/null+++ b/tests/agent-branches-live.test.js@@ -0,0 +1,20 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { existsSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';++// Runs the real MCP server on SwiftShader: branches and review leave the revision, recipe and source image untouched.+// It needs the prepared preview bundle (npm run prepare:release) and ffmpeg to decode PNGs, so it skips without them.+const preview = fileURLToPath(new URL('../build/mcp/preview.js', import.meta.url));+const smoke = fileURLToPath(new URL('../scripts/smoke-agent-branches.mjs', import.meta.url));+const hasFfmpeg = spawnSync('ffmpeg', ['-version'], { windowsHide: true }).status === 0;++test('live MCP branches do not consume revisions or change the scene being edited', {+ skip: !existsSync(preview) || !hasFfmpeg ? 'needs build/mcp (prepare:release) and ffmpeg' : false,+ timeout: 240000,+}, () => {+ const result = spawnSync(process.execPath, [smoke], { encoding: 'utf8', windowsHide: true, timeout: 230000 });+ assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`);+ assert.match(result.stdout, /Branch smoke passed/);+});diff --git a/tests/agent-branches.test.js b/tests/agent-branches.test.jsnew file mode 100644index 00000000..997ff2dc--- /dev/null+++ b/tests/agent-branches.test.js@@ -0,0 +1,74 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { BRANCH_LIMITS, createBranchStore, printableLabel, validateBranchName } from '../src/agent-branches.js';+import { normalizeReview } from '../scripts/agent-review.mjs';++const hostileNames = ['', 'Warm', '1warm', 'a'.repeat(25), '../x', 'a b', 'a\nb', 'https://example.com/x', '__proto__ ', 'a;rm', 'é', 7, null, {}];++function forkInput(recipeId, baseId = 'base') {+ return { recipe: { id: recipeId }, baseRecipe: { id: baseId }, operations: [{ type: 'set-material', id: recipeId }], baseRevision: 0 };+}++test('branch names are bounded identifiers and hostile text is refused', () => {+ for (const name of ['a', 'warm', 'variant-2', 'long_name_with_24_chars']) assert.equal(validateBranchName(name), name);+ for (const name of hostileNames) assert.throws(() => validateBranchName(name), TypeError, String(name));+});++test('branches with the same recipe share one snapshot and unused snapshots are pruned', () => {+ const store = createBranchStore();+ assert.equal(store.fork('one', forkInput('red')).shared, false);+ assert.equal(store.fork('two', forkInput('red')).shared, true);+ assert.equal(store.fork('three', forkInput('blue')).shared, false);+ assert.equal(store.snapshotCount(), 2);+ store.fork('two', forkInput('blue'));+ store.fork('one', forkInput('blue'));+ assert.equal(store.snapshotCount(), 1);+ assert.deepEqual(store.names(), ['one', 'two', 'three']);+});++test('branch reads return copies, so a caller cannot edit stored recipes', () => {+ const store = createBranchStore();+ store.fork('one', forkInput('red'));+ store.get('one').recipe.id = 'changed';+ store.get('one').operations.length = 0;+ assert.equal(store.get('one').recipe.id, 'red');+ assert.equal(store.get('one').operations.length, 1);+});++test('the branch count is capped, a name can be reused at the cap, and unknown names fail clearly', () => {+ const store = createBranchStore();+ for (let index = 0; index < BRANCH_LIMITS.maximumBranches; index++) store.fork(`b${index}`, forkInput(`r${index}`));+ assert.throws(() => store.fork('extra', forkInput('x')), /At most 8 branches/);+ store.fork('b0', forkInput('replacement'));+ assert.throws(() => store.get('missing'), /Unknown branch: missing/);+ assert.throws(() => store.get('Bad Name'), TypeError);+ store.clear();+ assert.deepEqual(store.names(), []);+ assert.equal(store.snapshotCount(), 0);+});++test('label text is reduced to short printable ASCII', () => {+ assert.equal(printableLabel('lamp\nbody\u0000'), 'lamp?body??');+ assert.equal(printableLabel('x'.repeat(100)).length, 32);+});++test('review groups shots by branch and keeps the source shots together', () => {+ const normalized = normalizeReview({ sessionId: 's', expectedRevision: 0, labels: true,+ shots: [{ branch: 'warm' }, {}, { branch: 'cool', label: 'Cool' }, { branch: 'warm', camera: { eye: [1, 2, 3] } }] });+ assert.equal(normalized.labels, true);+ assert.deepEqual(normalized.branchNames, ['warm', 'cool']);+ assert.deepEqual(normalized.groups, [+ { branch: 'warm', shotIndexes: [0, 3] }, { branch: undefined, shotIndexes: [1] }, { branch: 'cool', shotIndexes: [2] }]);+ assert.equal(normalized.shots[0].label, 'warm');+ assert.equal(normalized.shots[2].label, 'Cool');+ assert.equal(normalizeReview({ sessionId: 's', expectedRevision: 0, shots: [{}] }).labels, false);+});++test('review rejects hostile branch names and branch shots that sample an imported clip', () => {+ const base = { sessionId: 's', expectedRevision: 0 };+ for (const name of hostileNames.filter(name => name !== undefined)) {+ assert.throws(() => normalizeReview({ ...base, shots: [{ branch: name }] }), TypeError, String(name));+ }+ assert.throws(() => normalizeReview({ ...base, shots: [{ branch: 'warm', animation: { clip: 0, time: 0 } }] }), /imported animation/);+ assert.throws(() => normalizeReview({ ...base, labels: 'yes', shots: [{}] }), /labels must be boolean/);+});diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.jsindex dfc1bab7..f35be166 100644--- a/tests/agent-preview.test.js+++ b/tests/agent-preview.test.js@@ -8,6 +8,7 @@ import { applyProjection } from '../src/camera.js';import { resolveAgentShadow, agentEnvironmentMap } from '../src/agent-look.js';import { createAgentAssetScene } from '../src/agent-asset.js';import { parseGltf } from '../src/gltf.js';+import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../src/agent-branches.js';import { skinnedStripAsset } from './fixtures/skinned-strip.js';const source = (await readFile(new URL('../scripts/agent-preview-browser.js', import.meta.url), 'utf8')).replace(/^import .+;\r?$/gm, '');@@ -69,7 +70,7 @@ function previewHarness() {setManifoldModuleLoader: () => {},needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader: () => {},parseGltf, Uint8Array, atob,- applyProjection, mat4, resolveAgentShadow, agentEnvironmentMap,+ applyProjection, mat4, resolveAgentShadow, agentEnvironmentMap, BRANCH_LIMITS, createBranchStore, printableLabel,Renderer67: FaultInjectedRenderer,});// Evaluate only trusted repository adapter code; inject the driver boundary for failure cases.diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.jsindex 6e9f2910..e901888a 100644--- a/tests/agent-runtime.test.js+++ b/tests/agent-runtime.test.js@@ -8,6 +8,7 @@ import { randomUUID } from 'node:crypto';import { createContext, Script } from 'node:vm';import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS } from '../src/agent-scene-capabilities.js';import { normalizeReview, REVIEW_LIMITS } from '../scripts/agent-review.mjs';+import { BRANCH_LIMITS, validateBranchName } from '../src/agent-branches.js';test('runtime reports real scene capabilities without launching a browser and closes idempotently', async () => {const runtime = createAgentRuntime({ backend: 'cpu', memory: 64 });@@ -96,7 +97,7 @@ async function reviewRuntimeHarness({ failShot, blockShot = false, oversize = faconst context = createContext({ createServer, randomUUID, existsSync: () => true,readFile: async () => '', packageMetadata: { version: 'test' },createRequire: () => ({ resolve: () => { throw new Error('no peer in tests'); } }),- AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, normalizeReview, REVIEW_LIMITS, isPreviewHost,+ AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, normalizeReview, REVIEW_LIMITS, isPreviewHost, BRANCH_LIMITS, validateBranchName,chromium: { launch: async () => browser }, URL, Buffer, process, performance, setTimeout, clearTimeout,});new Script(`${source}\nglobalThis.runtime = createAgentRuntime({ backend: 'cpu' });`).runInContext(context);diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.jsindex ba49150a..876dc49b 100644--- a/tests/mcp-tools.test.js+++ b/tests/mcp-tools.test.js@@ -206,6 +206,31 @@ test('review SDK exposes one image and rejects unknown or unbounded shot fieldsassert.equal(calls(), before);});+test('branch names and labels are bounded in every tool schema and rejected before dispatch', async context => {+ const { client, sessionId, calls } = await connect(context);+ await client.callTool({ name: 'scene_create', arguments: { recipe: recipe() } });+ const { tools } = await client.listTools();+ const schema = name => tools.find(tool => tool.name === name).inputSchema;+ assert.equal(tools.length, 22, 'branches add fields, not tools');+ const pattern = '^[a-z][a-z0-9_-]{0,23}$';+ assert.equal(schema('scene_apply').properties.branch.pattern, pattern);+ assert.equal(schema('scene_restore').properties.branch.pattern, pattern);+ assert.equal(schema('scene_review').properties.shots.items.properties.branch.pattern, pattern);+ assert.equal(schema('scene_look').properties.labels.type, 'boolean');+ assert.equal(schema('scene_review').properties.labels.type, 'boolean');+ assert.ok(!schema('scene_restore').required.includes('checkpointId'));+ const operations = [{ type: 'set-material', id: 'light', color: [1, 1, 1] }];+ const before = calls();+ for (const hostile of ['', 'Warm', '1warm', 'a'.repeat(25), '../x', 'a b', 'a\nb', 'https://example.com/x', '__proto__ ', 'a;rm', 7, null]) {+ await rejected(client, 'scene_apply', { sessionId, expectedRevision: 0, branch: hostile, operations });+ await rejected(client, 'scene_review', { sessionId, expectedRevision: 0, shots: [{ branch: hostile }] });+ await rejected(client, 'scene_restore', { sessionId, expectedRevision: 0, branch: hostile });+ }+ await rejected(client, 'scene_look', { sessionId, labels: 'yes' });+ await rejected(client, 'scene_review', { sessionId, expectedRevision: 0, labels: 1, shots: [{}] });+ assert.equal(calls(), before);+});+test('SDK rejects unknown fields, missing revisions, invalid vectors and oversized inputs before runtime dispatch', async context => {const boundary = await connect(context);const { client, sessionId } = boundary;