Official Codebase of 3DCodeVerse
Python
graphics lab: build, capture, serve and the sixteen scenes are what remains — session notes, agent cases and provenance tooling are gone
gaoypenge408b152ec40
diff --git a/harness/examples/graphics_lab/README.md b/harness/examples/graphics_lab/README.mdindex 017eb66f..a518ae02 100644--- a/harness/examples/graphics_lab/README.md+++ b/harness/examples/graphics_lab/README.md@@ -1,205 +1,59 @@# Graphics Lab-See the [current maintenance and expansion record](REVIEW_2026-09-23.md),-[earlier refinement](REFINEMENT.md), and-[initial validation and actual model trials](VALIDATION.md) for evidence and limits.--Sixteen executable studies of fire, water, terrain, vegetation,-atmosphere, worked materials and independent shader files, plus three GPT-6 Luna cases.-All images and films come from Three.js scene code;-there are no prerendered backgrounds or generated image assets.+Sixteen hand-composed studies of fire, water, terrain, vegetation, atmosphere,+worked materials and independent shader files, covering the effect modules in+`codeverse3d/languages/scene_threejs/starter/src/lib/`. Every image and film+comes from Three.js scene code rendered through the production scene host; there+are no prerendered backgrounds or generated image assets. It is a development+lab: no run path uses it.From the `harness/` directory:```bash-python examples/graphics_lab/build.py --out /tmp/graphics-lab-v2 --render --video-python examples/graphics_lab/verify_media.py --out /tmp/graphics-lab-v2-node examples/graphics_lab/check.mjs --out /tmp/graphics-lab-v2-node examples/graphics_lab/serve.mjs --out /tmp/graphics-lab-v2+python examples/graphics_lab/build.py --out /tmp/graphics-lab --render --video+node examples/graphics_lab/serve.mjs --out /tmp/graphics-lab```-Open the loopback URL printed by the server. The gallery offers H.264 films,+Open the loopback URL printed by the server. The gallery offers H.264 films,full-resolution stills, and live orbit controls with authored camera presets,-pause and time scrubbing. Everything, including Three.js, is served locally.-Opening `index.html` as a `file:` URL does not load browser ES modules; use the-server. The default output is `examples/graphics_lab/output/` (git-ignored).+pause and time scrubbing. Everything, including Three.js, is served locally;+opening `index.html` as a `file:` URL does not load browser ES modules. The+default output is `examples/graphics_lab/output/` (git-ignored).-`--case fire` selects one case to render again; the gallery still includes all-nineteen entries. Repeat `--case` to select several cases. `--width 1920 --height 1080`-increases capture resolution. `--seconds 6---fps 24` controls the film. Video export requires ffmpeg, either on PATH or-provided by an installed `imageio-ffmpeg` package. No installation happens-automatically. Stills and live exploration need only the harness runtime.+`--case fire` renders one case again (repeat it to select several); the gallery+still lists every case. `--width 1920 --height 1080` raises capture resolution;+`--seconds 6 --fps 24` controls the film. Video export needs ffmpeg on PATH or an+installed `imageio-ffmpeg`. Without `--render`/`--video` the build only stages+source workspaces.-Each scene lives in `scenes/` and implements the normal+Each scene in `scenes/` implements the normal`createScene({THREE, renderer, loaders}) -> {scene, cameras, update}` contract.-The builder stages self-contained workspaces in `<out>/cases/`, using a byte-snapshot of the current shipped `src/lib` modules and all registered scenes.-Independent `.vert`, `.frag` and `.glsl` files under `shaders/` are copied into-every workspace and the published `src/shaders/`, with a separate shader digest-map in the manifest. Their relative paths are preserved. Shader byte changes-receive the same stale-media protection as scene and library changes.-It checks that every scene exists before writing anything. Stills use `runtime_js/render_scene.mjs`;-films use the same scene host, deterministic absolute simulation times and-the same ACES/GTAO/bloom/grade chain. `renders/<case>/metrics.json` and-`<case>.capture.json` record actual execution and renderer information.-`verify_media.py` checks every published/staged source hash, primary scene identity,-encoded-file digest and capture record. It decodes every frame, verifies frame-counts/rates, and compares retained encoding inputs at three times with the-decoded film, including motion where the input frames measurably change. The-first frame also matches its authored-camera still. `capture-plan.json`, when-present, specifies the complete required film/scene/camera set including extras.-Reports and motion contact sheets go in `media-verification/`; pixel change is-not a realism score. Historical captures without input frames/digests require-`--allow-legacy` and are explicitly identified as weaker evidence.--Use a fresh `--out` directory whenever scene or shared library sources change.-Once an output contains media, staging verifies its existing manifest, published-source files, staged workspaces and available capture-time hashes before writing.-A mismatch is refused, including changes to an unselected scene: the builder-cannot attach today's code to yesterday's film. An unchanged-source incremental-run remains supported, for example:--```bash-python examples/graphics_lab/build.py --out /tmp/graphics-lab-v2 --case fire --render --video-```--Staging without `--render` or `--video` creates source workspaces only. A directory-without media may be refreshed freely. Older capture records without source-hashes can only be checked against their retained source manifest; they do not-gain retrospective capture provenance. These checks cover scene/library bytes,-not runtime host revisions. Keep the runtime revision with an archival release.-Existing packages and controlled-comparison snapshots are left untouched.--The manual order is fire, ocean, stream, sand, rocks, meadow, tree, cloud volume,-smoke, ice, waterfall, rain shelter, workshop, campfire/bonfire, structural fire and-external GLSL material. Agent entries A1-A3 are candle-courtyard, coastal creek and garden workbench. The first six retain their original-order and remain the source-and-video package selection. `overview.jpg` uses-three columns and as many rows as the available manual previews require; missing-previews and agent entries are omitted from that contact sheet.--The scenes demonstrate realtime approximations, not a combustion, fluid or-granular physics solver. Ocean reflections use a mean plane; stream refraction-samples the opaque scene and cannot see transparent or offscreen objects; overlapping-transparent fire/glass volumes need careful placement. Sand dunes are static-terrain with animated windborne grains. See each module's JSDoc for limits.--## Library entry points--| Module | Factory | Principal options |-| --- | --- | --- |-| `fire.js` | `makeFire`, `makeCandle` | radius, height, seed, quality; candle wax, wick and drips |-| `firefield.js` | `makeFireField` | emitters, wind, smoke, embers, lighting, occluders, depthResolution, quality |-| `ocean.js` | `makeOceanSurface` | width/depth, waveHeight, wavelength, windDirection, shoreline |-| `stream.js` | `makeStream` | descending path points, width/depth, speed, obstacles, attenuationDistance, reflectionSize, caustics |-| `sand.js` | `makeSandTerrain` | size, duneHeight/duneSpacing, windDirection, rippleSpacing |-| `rock.js` | `makeRock`, `makeRockField` | type, size, seed, moisture, weathering |-| `meadow.js` | `makeMeadow` | size, density, height, heightAt, mask, diversity, seedHeads, wind, shadows |-| `tree.js` | `makeTree`, `makeShrub` | species, height, crownRadius, leafDensity, maxLeaves, leafSegments, autumn, wind |-| `cloudvolume.js` | `makeCloudVolume` | size, coverage, density, wind, sunDirection, quality, seed |-| `smoke.js` | `makeSmoke`, `makeSteam` | height, radius, spread, riseSpeed, wind, density, quality, seed |-| `ice.js` | `makeFracturedIce` | size, thickness, crackDensity, gap, frost, bubbles, heave, seed |-| `waterfall.js` | `makeWaterfall` | width, height, speed, thickness, breakup, foam, spray, quality |-| `paving.js` | `makePaving` | size, stoneSize, pattern, joint, thickness, relief, moisture, seed |--The listed factories return Three.js objects with `userData.update(t, dt)` and-`userData.dispose()`. Coordinates and dimensions are local metres; move the-returned object as a whole. Drive absolute seconds once per frame. Rock is-static; its update hook is intentionally a no-op. Terrain and water sampling-methods return local positions/heights, as documented in the source.--For an existing terrain, pass `ground: false` to `makeMeadow`, and give it the-same `heightAt` function that built the terrain. Grass shadows need a tight-sun frustum and sufficient resolution for centimetre-wide leaves. The runtime-uses `PCFShadowMap`, the filtered shadow type supported by the installed Three.--Background reading for the wind architecture:-[GPU Gems, Rendering Countless Blades of Waving Grass](https://developer.nvidia.com/gpugems/gpugems/part-i-natural-effects/chapter-7-rendering-countless-blades-waving-grass).-The implemented meadow uses actual curved leaf geometry, per-leaf phases and-shared travelling gusts; it does not copy the chapter's texture-card geometry.--Stream optics use [Three's physical transmission](https://threejs.org/docs/pages/MeshPhysicalMaterial.html),-with IOR 1.333 and depth-dependent Beer attenuation. `waterColor` describes the-absorption colour over `attenuationDistance` metres (default 3). Optional-`reflectionSize: 256..2048` adds bank reflections; default 0 uses the environment-map only. Use at most one planar reflector in a scene. The brook study enables-1024-pixel bank reflections. Bed caustics are a bounded ripple-curvature-approximation applied to direct lighting, not a fluid or photon simulation.+The builder stages one self-contained workspace per case in `<out>/cases/`, with a+copy of the current `src/lib` modules and the `.vert`/`.frag`/`.glsl` files under+`shaders/` (relative paths kept). Stills use `runtime_js/render_scene.mjs`; films+(`capture.mjs`) use the same scene host, deterministic absolute simulation times+and the same ACES/GTAO/bloom/grade chain. `renders/<case>/metrics.json` and+`<case>.capture.json` record the renderer and timing. `overview.jpg` is a+three-column contact sheet of the available stills.++The scenes demonstrate realtime approximations, not combustion, fluid or granular+solvers; each module's JSDoc states its limits, and+`codeverse3d/prompts/scene_threejs/effects_catalog.md` is the factory table.## Independent shader filesThe external shader study loads [a vertex shader](shaders/external_shader.vert),[a fragment shader](shaders/external_shader.frag) and[shared GLSL helpers](shaders/external_shader_common.glsl) from async-[scene creation](scenes/external_shader.js). It uses `THREE.FileLoader`,-module-relative URLs and `ShaderMaterial` with `THREE.GLSL3`; no bundler or raw-shader import extension is required. JavaScript owns the geometry, uniforms and-absolute-time update. This is an artistic alloy response with analytic studio-reflections, not measured anodization or scene-wide ray tracing.--For complete API conventions see Three's [ShaderMaterial documentation](https://threejs.org/docs/pages/ShaderMaterial.html)-and [FileLoader documentation](https://threejs.org/docs/pages/FileLoader.html).-Native OpenGL host programs require adaptation to WebGL and GLSL ES.--## Controlled refinement comparison--The retained `output/refinement-baseline/<case>/src` workspaces preserve the first-revision. Historical comparison images and their snapshots remain independent-of the expanded gallery. To produce a new comparison, use a separate output and-a baseline whose shared dependencies support the module revision being compared:--```bash-python examples/graphics_lab/compare.py --baseline /path/to/compatible-baseline --out /tmp/graphics-lab-comparison-python examples/graphics_lab/build.py --out /tmp/graphics-lab-comparison-```--`<out>/comparison.html` provides before/after sliders for ocean, stream, rock and-meadow. Each pair changes exactly one library module; cameras, lighting, scene-source, simulation time and other libraries are byte-identical. Source hashes-and render metrics are linked from the page. The main gallery additionally-contains revised scene dressing. The ignored baseline/output artifacts must be-retained to reproduce this historical comparison on another machine. The browser-checker reads the comparison manifest and verifies its actual image pairs and-slider count; it does not assume a fixed number of comparisons.--## Transfer a source-and-video snapshot--After rendering the gallery, package its first six library studies:--```bash-python examples/graphics_lab/package.py --out /tmp/graphics-lab-v2 --name my_six_studies-```--The script creates an offline video page, six scene modules, their shared-library and external shaders, videos, previews, capture metadata and a verified ZIP-in `<out>/packages`. When available, it checks encoded movie digests and bundles-the retained input PNGs at their original package-relative paths.-It validates published and capture-time source hashes, checks archive integrity-and refuses existing package names. The runtime and npm dependencies are not-bundled. See [REFINEMENT.md](REFINEMENT.md) for retained revision packages.--## Validation+[scene creation](scenes/external_shader.js), with `THREE.FileLoader`,+module-relative URLs and `ShaderMaterial` + `THREE.GLSL3` — the loading pattern the+scene contract (`prompts/scene_threejs/contract.md`) teaches.-The module-specific tests in `tests/scene_runtime/lib/`-cover relevant determinism, topology, sampling, transforms, lifecycle, actual-GPU compilation, and selected final-render animation checks. The shadow-filter-regression test inspects the linked GPU shader so a deprecated enum cannot-silently revert filtering to basic shadows again. Gallery staging regressions in-`tests/graphics/test_graphics_lab_build.py` cover stale-media refusal, unchanged-incremental builds and missing-scene preflight. Visual review of rendered-frames remains necessary; a green compile test is not an aesthetic verdict.+## GLSL recipe studies-`check.mjs` opens the staged gallery in the real GPU browser, decodes each-available film, opens every live scene, switches every authored camera, checks-pause and time scrubbing, reopens the live tab, and cancels a pending boot.-It writes `browser-check.json`, `gallery.png` and each `<case>.live.png`.-Run it after building the output. All example UI, code and documentation must-remain in English.+`build_recipes.py [--video] [--case rain_window]` renders the three fragment+shaders in `glsl_cases/` through the production GL host (`GlHost`), seeding each+with the cookbook recipes it calls exactly as the `graphics` track does. Output+goes to `output/recipes/` with an `index.html` of stills or 144-frame films.-Actual model-generated case runs are stored separately in `output/agent_runs/`.-Their source, prompts, telemetry and renders distinguish agent-produced scenes-from these hand-composed library studies.-The three retained Luna modules live in `agent_cases/`; their provenance and-review history are documented there. Gallery entries A1-A3 identify them as-model cases. All sixteen numbered scenes are manually developed studies.+All example UI, code and documentation stay in English.diff --git a/harness/examples/graphics_lab/REFINEMENT.md b/harness/examples/graphics_lab/REFINEMENT.mddeleted file mode 100644index afd1c536..00000000--- a/harness/examples/graphics_lab/REFINEMENT.md+++ /dev/null@@ -1,112 +0,0 @@-# Graphics Lab refinement — 2026-09-23--This pass responds to visual review of the first gallery, especially water that-looked like a coloured sheet, repeated ocean ridges, regular bank stones and-uniform grass. It changes the shipped library itself as well as selected scene-composition. All assets remain procedural code; no generated image backgrounds-or photographic texture downloads were added.--## Water--The ocean uses 32 directional gravity-wave bands normalized to significant-height Hs, per-fragment analytic slopes, filtered small ripples, dielectric-Fresnel/GGX and roughness-aware reflections. Visible equirectangular sky radiance-and reflected scene objects are handled separately. Debug renders caught and-removed dark trough hatches and purple foam. The ocean study keeps its original-cameras but extends the sea to 1.8 km and uses a longer-period sea state; these-scene changes are excluded from the controlled library comparison.--The stream now uses Three's physical transmission at IOR 1.333. Colour describes-absorption through the graded water column, rather than alpha paint over the-bed. Eleven directional ripple bands replace the regular warped sine pattern.-Stone wakes have shorter, less continuous foam; cobbles sit flatter in the bed.-Direct bed light receives a bounded caustic approximation from the same moving-surface. Optional planar bank reflection is off by default and enabled at 1024-pixels in the brook study. Unsupported offscreen transmission fades smoothly-to the unshifted sample instead of stretching the final screen row.--An independent review also found a curved-channel normal error: the old basis-ignored the derivative of the lateral path offset. CPU and GPU now use the-offset surface derivatives. Regression cases cover tighter bends, nonzero grade-and changing channel width; sampled normals agree with independent position-differences within 0.15 degrees.--The stream remains a kinematic surface. Refraction samples opaque screen-space-geometry, and bank reflection approximates the channel with a mean grade. It-does not solve water/solid collisions, refraction of transparent objects,-overturning breakers or photon transport.--## Rock and meadow--Rock geometry retains fracture edges, independently oriented chipped corners,-recessed sandstone bedding and selective edge wear. Mineral and alteration-detail uses filtered 3D shading. Stream-sized granite was checked separately-because its low-detail silhouettes revealed problems hidden by the hero view.-The matched rock study rises from 195,192 to 509,996 triangles; revised scene-dressing brings the final rock study to 766,060 triangles. Close views remain-visibly procedural rather than scanned geological assets.--Meadow leaves vary by growth form, age and habitat, with arching/twisted blades,-dry fragments and optional sparse geometric seed heads. Leaf count stays at-193,000 in the study. The 579 seed culms add two instanced draws and approximately-6.8% triangles (3.14 million for the complete study). Thin-leaf transmission-obeys the actual shadow map. Seeded geometry and absolute-time updates are-deterministic; whole-renderer PNG replay is not promised to be bit-identical.--## Controlled evidence and transfer packages--`compare.py` renders the retained baseline twice and changes exactly one library-module in the second workspace. Scene source, cameras, lighting, time and other-library modules have identical hashes. The nine camera pairs produce 18 real-GPU stills. `output/comparison.html` exposes four representative pairs with-sliders and links the complete hash/render manifest.--The first transfer package preserves the gallery exactly as it was when-requested: six scene modules, all 50 matching library modules, six six-second-films, a hearth film, previews, capture records and an offline video index.-It has 82 files and a 42.45 MiB ZIP. Its source hashes match the published gallery-manifest and staged workspaces; all seven films decoded, and archive CRC and-extracted-file hashes passed. Subsequent refinement packages use distinct names-so this snapshot is never silently replaced.--No new paid coding-agent runs were made in this refinement. The A1/A2 scene-sources remain the retained Luna outputs; updated gallery rendering uses the-current shared library. Earlier Luna/Gemini trial results remain documented in-[VALIDATION.md](VALIDATION.md).--## Automated checks--**842 tests passed** across scene runtime/library behavior, Three.js rendering,-portability and scene prompts:--```bash-C3D_CACHE_DIR=/tmp/c3d-graphics-refine-v2 python -m pytest tests/scene_runtime tests/threejs_render tests/core/test_portability.py tests/scene_prompts -q -n4-```--The new stream optics test renders a submerged coloured checkerboard twice with-fixed geometry/time and different IOR. It checks actual displacement of colour-boundaries, which an alpha-only overlay cannot produce. Other additions cover-curved-channel CPU/GPU normals, reflector ownership, spectral energy and-environment ownership, rock concavity/topology, and seeded meadow morphology.-One existing Pillow deprecation warning remains.--New video sidecars record the SHA-256 of each staged source module, and capture-fails if those files change during rendering. Packaging validates those hashes-when available; earlier sidecars remain explicitly marked as legacy evidence.--The rebuilt gallery retains 60 stills, eight six-second films and a separate-hearth film, all at 1280×720. All nine capture records match the final staged-source hashes and report zero shader/console errors. Encoded ocean and stream-frames at 0, 2 and 4 seconds were inspected for actual motion.--Browser validation passed all eight scenes, 20 cameras, video decoding,-pause/scrub/tab switching, boot cancellation and all four comparison sliders,-with zero browser errors. Its English-source scan checked 1,695 files; the-final expanded source/document/JSON scan checked 2,014 files, including both-transfer packages, and found no Han characters.--The separate refined transfer package is-`output/packages/graphics_lab_first_six_refined_2026-09-23.zip`: 81 files,-44,711,120 bytes (42.64 MiB), with published/staged/capture-time source validation-and ZIP CRC/extracted-file hash verification. The original requested snapshot-remains unchanged beside it.diff --git a/harness/examples/graphics_lab/REVIEW_2026-09-23.md b/harness/examples/graphics_lab/REVIEW_2026-09-23.mddeleted file mode 100644index ab80d7a6..00000000--- a/harness/examples/graphics_lab/REVIEW_2026-09-23.md+++ /dev/null@@ -1,168 +0,0 @@-# Graphics library maintenance and expansion — September 23, 2026--This record covers the expanded gallery and shared library after the earlier-[water and material refinement](REFINEMENT.md). All examples, shader sources,-comments and gallery controls are English. Images are rendered from scene code;-there are no generated backgrounds or downloaded photographic textures.--## Library changes--All 50 original modules have an explicit disposition in the four family audits.-Forty-seven received visual, numerical, composition or resource-ownership fixes;-`caustics`, `finish` and `ocean` were retained with recorded justification. The-current library has 58 modules and 190 named exports. Seven additions provide-trees/shrubs, bounded volume clouds, smoke/steam, fractured ice, falling water,-paving and shared flame/soot fields. `lifecycle` is the eighth addition, for owned-resource cleanup. The inventory preserves the original 50 source hashes.--Water maintenance corrects transformed reflection planes, nested renderer-state-restoration, attached-object transforms, finite HDR edges and graded stream-bed-sampling. Cloud support no longer regrows against its proxy walls as noise moves.-Vegetation, terrain, rain coverage, walking contact, material normals and borrowed-resource ownership have separate behavioral and actual GPU checks. The rain scene-uses lower-detail background leaves while preserving leaf placement/count; its-tested geometry falls from 20.7 to 12.4 million triangles.--The gallery contains 16 authored studies and three agent cases. The original six-remain first. Additional studies cover trees, clouds, smoke, ice, waterfalls, rain,-worked materials, campfire/bonfire, a burning structure and an independent shader.-Agent provenance distinguishes original Luna CLI output from later delegated-refinements. No new paid model API call was made during this maintenance pass.--## Fire at several scales--[`makeFireField`](../../codeverse3d/languages/scene_threejs/starter/src/lib/firefield.js)-combines up to 16 emitters into one bounded flame/soot volume, with rising embers-and up to four practical lights. An optional depth pass over explicit borrowed-opaque objects terminates rays at visible walls or fuel. Sources share a baked-atlas, avoiding a per-sample loop over every emitter. The original candle and-small-fire API remains available.--[Campfire](scenes/campfire.js) includes close fuel/ember and large open-fire cameras.-[Structural fire](scenes/structural_fire.js) places a shared field through actual-window and roof openings, with whole-house, window and roof views. The examples-use the shipped library, with scene-specific ground, timber and lighting.--Balanced quality uses an approximately 1.49 MB atlas/noise allocation, 80 view-samples and five soot-light samples; high uses approximately 2.49 MB, 128 and-seven. Optional opaque depth adds a pass over the supplied occluders. These are-bounded rendering costs, not isolated frame-rate measurements.--This is prescribed turbulent transport. It does not solve combustion, fuel-consumption, ventilation, structural collapse or fire spread. Bright windows can-saturate and fine ray-march grain remains visible in large wisps. Glass and several-overlapping transparent volumes are not resolved by the opaque-depth pass. The-authored cottage and vegetation remain recognizably procedural.--## Independent GLSL--[The alloy study](scenes/external_shader.js) loads separate-[vertex](shaders/external_shader.vert), [fragment](shaders/external_shader.frag)-and [helper](shaders/external_shader_common.glsl) files using `THREE.FileLoader`-inside asynchronous scene creation. `ShaderMaterial` uses `THREE.GLSL3`;-JavaScript supplies geometry, uniforms and absolute-time updates. The runtime-serves these local files and maps external compiler errors back to source lines.-The gallery builder, capture records and transfer packager preserve their bytes-and SHA-256 values. Direct browser imports of raw shader text need a loader;-desktop OpenGL host programs need adaptation to WebGL and GLSL ES.--The alloy appearance is an artistic analytic studio response. It is not a measured-anodization model or scene-wide ray tracing.--Visual review also retains broader limits: distant mountain geometry is coarse,-some rocks have conspicuously faceted silhouettes, and cloud billows remain-strongly authored. Reflections and transmission improve depth cues but do not-turn the water into a free-surface fluid solver. These are useful executable-effect studies, not a claim of photographic realism across every gallery view.--## Integration and artifact status--The final complete offline suite passed **2,922 tests in 225.65 seconds**, with-one existing Pillow deprecation warning. Ruff passed. Commands and retained logs:--```bash-C3D_CACHE_DIR=/tmp/c3d-graphics-final-integration python -m pytest tests -q -n4-ruff check codeverse3d tests examples/graphics_lab-```--Logs are `/tmp/graphics-seven-hour/offline-final-clean.log` and-`/tmp/graphics-seven-hour/final-ruff-clean.log`. The maintenance checkpoint passed-2,890 tests before the fire/external-shader additions. The first integration-attempt had 2,917 passes and two failures: a closed Chrome target during a cloud-probe, and an over-broad downgrade of an unused shader's static diagnostic.-The isolated cloud module passed all seven tests. The diagnostic now requires-unambiguous source participation in evaluated shader text; 29 focused tests,-including three unused/duplicate-literal regressions, pass. The interrupted-`gallery-v1` capture is retained as a failed attempt, not a release artifact.--The final snapshot is [`output/seven-hour/gallery-v2/`](output/seven-hour/gallery-v2/).-It contains **159 stills across 19 cases and 53 cameras**, with no shader, console-or update errors. All **30 films / 4,320 frames** decoded successfully: 19 primary-views and 11 additional cameras, each six seconds at 24 fps and 1280 by 720.-Every film passed source ownership, encoded digest and three retained input-PNG-checks. All 63 captured source files per case match the manifest. A separate-120-file check binds current library, scene, shader and runtime sources to the-captured snapshot.--The maximum first decoded-frame difference from its still is 4.689/255 mean RGB;-the maximum downsampled difference from a retained encoding input is 1.317/255.-Twenty-seven films have measurable motion at the verifier's anchor-mask threshold-and follow their own changing inputs. Rock, sand and workshop views do not exceed-that threshold; they are not counted as demonstrated motion. These are integrity-checks, not aesthetic scores. Reports and decoded contact sheets are in-[`media-verification/`](output/seven-hour/gallery-v2/media-verification/).--The [browser check](output/seven-hour/gallery-v2/browser-check.json) passed all-19 cases and 53 cameras: actual video playback, orbit-camera selection, pause,-time scrubbing, tab reopening and cancelled scene creation. There were no browser-errors. It checked 4,407 English source/document files before the new transfer-package was created. A separate final-[English scan](output/seven-hour/gallery-v2/verification/english-check.json)-also includes JSON and the extracted transfer packages. Final visual reviews inspected the actual frozen stills,-selected detail views and decoded fire/water/shader contact sheets. Fire samples-at 0/2/4 seconds show changing flame/embers with stable structural occlusion;-this sampled review does not claim to have watched every encoded frame.--Selected test logs and visual-review summaries are retained in-[`verification/`](output/seven-hour/gallery-v2/verification/), with runtime hashes-in [`runtime-source.sha256.json`](output/seven-hour/gallery-v2/runtime-source.sha256.json).-The gallery runs with `node examples/graphics_lab/serve.mjs --out-examples/graphics_lab/output/seven-hour/gallery-v2`; open the printed loopback URL.-Additional films, including `bonfire.mp4`, `window_fire.mp4` and `roof_fire.mp4`,-are in the gallery root; the same authored cameras are available in live mode.--## Transfer package--The new [folder](output/seven-hour/gallery-v2/packages/graphics_lab_first_six_maintained_2026-09-23/)-and [ZIP](output/seven-hour/gallery-v2/packages/graphics_lab_first_six_maintained_2026-09-23.zip)-contain the first six scene modules, 58 matching library modules, three independent-shader files, seven films including the hearth view, six previews, retained-encoding inputs and capture provenance. Open the package's `index.html` directly-to watch offline; running scene code requires the compatible Three.js host.--The ZIP contains **113 files / 74,973,979 bytes (71.50 MiB)**. Published, staged-and captured-source checks, encoded digests, archive CRC and extracted-file hashes-all passed. SHA-256:--```text-26efcebd51c76ba7b1a27eb8fdeea5cab0851ec0b9ef628bfaf556f3ae501098-```--An actual browser opened the extracted package over a `file:` URL without a-server and played all seven six-second, 1280-by-720 videos with zero errors;-the [offline playback report](output/seven-hour/gallery-v2/verification/offline-package-browser.json)-records the result. The final independent artifact audit also rehashed the ZIP-and all payloads, checked 38 relative HTML assets and found no blocking mismatch.-The documentation checks passed all 19 tests after the final integration edits.--Both previously published ZIPs remain byte-identical; no earlier package or-comparison baseline was replaced. The new package contains scene/library/shader-code and media, not runtime binaries or npm dependencies.--The canonical inventory is `output/seven-hour/inventory.json`. Family audits are-[`core`](../../docs/graphics_audit_core.md),-[`weather`](../../docs/graphics_audit_weather.md),-[`life`](../../docs/graphics_audit_life.md) and-[`surfaces`](../../docs/graphics_audit_surfaces.md). Their historical checkpoints-are identified separately from final combined verification. Local `/tmp` render-evidence is not implicitly included in a transfer ZIP.diff --git a/harness/examples/graphics_lab/VALIDATION.md b/harness/examples/graphics_lab/VALIDATION.mddeleted file mode 100644index 5360eea2..00000000--- a/harness/examples/graphics_lab/VALIDATION.md+++ /dev/null@@ -1,94 +0,0 @@-# Graphics Lab validation — 2026-09-22--This records the first gallery revision. See [REFINEMENT.md](REFINEMENT.md) for-the September 23 library refinement, current validation and transfer packages.--## Implementation and integration--Six new modules are in the existing shipped scene library: fire/candles, ocean,-stream, sand, rock and meadow. The effects catalog documents their entry points,-local coordinates and lifecycle. They use the existing Three.js runtime and-post chain. A shared r182 shadow-filter fix switches the renderer to supported-PCF filtering and checks the actual linked fragment program.--## Automated checks--- **834 passed**: scene runtime and library tests, Three.js object rendering,- portability and scene prompt tests. Command:- `C3D_CACHE_DIR=/tmp/c3d-graphics-regression python -m pytest tests/scene_runtime tests/threejs_render tests/core/test_portability.py tests/scene_prompts -q -n 4`.- One existing Pillow deprecation warning; no failed tests.-- After the final planner guidance edit, **36 prompt/skeleton checks passed**:- `python -m pytest tests/scene_prompts tests/scene_runtime/test_skeleton.py -q -n 2`.-- `python -m ruff check codeverse3d tests examples/graphics_lab` and- `git diff --check` passed.-- The browser check opened **8 scenes and 20 authored cameras**, decoded every- gallery film, checked pause/scrub/tab switching and cancelled an asynchronous- scene boot. Zero browser errors. It scanned 1,007 example/staged source and- documentation files for Han characters; none were found. A final broader text- scan also included JSON and JSONL output. See `output/browser-check.json`.--The new regressions cover meaningful failures found during development: closed-rock topology and transformed terrain seating; stable stream downhill grade;-narrow-stream defaults; inverse ocean sampling near a narrow shore; hidden and-removed lighting; caller-owned resource preservation; shader compilation; and-selected final-post image animation/detail checks. These checks do not certify-photographic realism.--## Render artifacts--The retained gallery has **60 authored stills**, eight 6-second H.264 films at-24 FPS and 1280x720, plus a separate hearth film. Captures used the NVIDIA GeForce-RTX 5090 Laptop GPU through ANGLE/D3D12. Per-film `.capture.json` files record-144 rendered frames and zero console/shader errors. `render_ms_mean` is capture-instrumentation, not a certified realtime FPS benchmark.--The six library studies were visually inspected and revised. Actual encoded-frames show visible motion in fire, ocean, stream and meadow. Sand dunes and-rocks are static geometry studies; windborne sand motion is subtle at the wide-camera. The images are rendered from code with no generated bitmap backgrounds.-`output/overview.jpg` is a contact sheet of actual library-study frames.--## Actual coding-agent trials--The retained A1/A2 examples were generated by **GPT-6 Luna through Codex CLI**.-The initial courtyard failed to boot due to an undefined `THREE`; the initial-creek rendered with a raised water/bed ribbon. A second model invocation received-supervisor render feedback and produced revised source. Both revised modules-were copied unchanged into `agent_cases/`, then rendered and browser-tested by-the supervisor. The first invocation's local server bind was sandbox-blocked;-the second allowed sandbox networking for the local renderer. Prompts, hashes,-usage and review limitations are in [the case provenance](agent_cases/README.md).-These are direct CLI usability trials, not full harness plan/judge runs.--Three separate **Gemini full-pipeline runs** used `gemini-cli:gemini-3.7-flash`,-the matching planner, and `gemini:gemini-3.1-pro-preview` as judge. Each requested-one baseline plus one refinement with a 30-minute budget. Repeated provider-503s occurred. Each retained one baseline and ended with `status: budget` before-refinement completed; none passed baseline acceptance:--| Trial | Baseline judge score | Gate errors | Recorded cost (USD) |-| --- | ---: | ---: | ---: |-| Candle alcove | 0.405 | 4 | 1.8948 |-| Coastal cove | 0.120 | 4 | 1.6889 |-| Spring stream | 0.278 | 8 | 1.8372 |--Total recorded Gemini cost: **USD 5.4209**. These are the harness's recorded-provider costs, excluding the separate Codex subscription sessions. Raw runs-remain in `output/agent_runs/`; [the trial summary](agent_cases/gemini-trials.json)-links their records. The scores are model judgments under incomplete execution,-not a controlled comparison with Luna or evidence of the library's quality.--The trials exposed a planning ambiguity: standalone asset generation permits-only Three.js imports, while effects belong in zone/environment code. The final-scene planner explicitly directs those calls to the owning zone and avoids-rebuilding water/flame/grass as duplicate assets. This final prompt correction-has offline checks; it has not been validated by another paid pipeline run.--## Practical limits--These are realtime procedural effects, not combustion, fluid, granular erosion-or photographic asset reconstruction. Ocean reflection uses a mean plane;-stream clarity is approximate; grass density and shadows require an appropriate-budget. Close rock silhouettes, the Luna creek boundary and several large props-still show procedural construction. The six library studies and two agent trials-are labelled separately so curated work is not presented as autonomous output.diff --git a/harness/examples/graphics_lab/agent_cases/README.md b/harness/examples/graphics_lab/agent_cases/README.mddeleted file mode 100644index 5dbb1c3c..00000000--- a/harness/examples/graphics_lab/agent_cases/README.md+++ /dev/null@@ -1,65 +0,0 @@-# GPT-6 Luna usability cases--The original two modules were authored by GPT-6 Luna through Codex CLI in a separate-workspace. The model received the effects catalog, contract and shipped library-source. It was instructed not to read or copy the six hand-authored studies.-The retained source is copied unchanged from the second model invocation.--- [Candle courtyard](luna_candle_courtyard.js)-- [Coastal creek](luna_coastal_creek.js)-- [Initial prompt](prompt.md), [supervisor feedback](feedback.md), [provenance](provenance.json)--The initial courtyard failed to boot because a helper referenced an undefined-`THREE`. The initial creek rendered, but its water/bed ribbon sat above the-terrain. The supervisor rendered the drafts, inspected the images and returned-those concrete failures to the model. In the second invocation the model fixed-the import/scope error, revised lighting and camera framing, and rebuilt the-creek banks from the stream sampler. Both revised scenes produced six real GPU-views at 1280x720, times 0 and 2, with zero console or shader errors.--These are usability trials, not aesthetic gold standards. The creek still has-an overly regular water boundary and sparse sand grass, and the courtyard's-large props and lighting remain visibly procedural. A successful render does-not establish photographic realism. The six library studies offer more carefully-composed views of each effect. Neither these two examples nor the-Gemini trials constitute a controlled comparison of model quality.--The original sources and CLI provenance remain unchanged. The current gallery-uses A1 for the retained courtyard, A2 for the separately reviewed creek-refinement below, and A3 for a new garden case. `build.py` stages and renders them-through the same production host as the library studies, using current shipped-library code. `check.mjs` exercises their live controls and video decoding.-Raw CLI events and draft renders remain under `../output/agent_runs/` (ignored-by git); hashes and prompts above preserve the retained source's provenance.--The first invocation's browser attempt was blocked by its sandbox's localhost-bind policy. The second enabled sandbox network access to use the existing-local renderer, while retaining workspace write restrictions. No API key or new-dependency was provisioned. The CLI's non-interactive workflow is documented in-[official OpenAI documentation](https://learn.chatgpt.com/docs/non-interactive-mode).--## Later delegated-agent cases--The following work used a delegated GPT-6 Luna coding agent in this development-session. It is not an additional vendor-CLI or harness trial, and does not establish-relative model performance.--- A2: [Refined coastal creek](luna_coastal_creek_refined.js),- [provenance and measurements](luna_coastal_creek_refined.provenance.json).- Three review iterations corrected the world/local height conversion, carved- the sand banks from the stream sampler, and replaced tiled pebble materials- with individual rocks. The final triangle-height measurement sampled 41- positions on each bank: maximum bank-to-base-water-grade error was 0.010613 m.- Nine fixed-camera GPU frames at 0, 1.5 and 3 seconds had no console, shader or- update errors. The original `luna_coastal_creek.js` remains available above.-- A3: [Garden workbench](luna_garden_workbench.js),- [provenance](luna_garden_workbench.provenance.json).- Two review iterations revised the workbench and mug to real dimensions,- composed backlit steam, and batched repeated plants and masonry. Nine GPU views- passed; its recorded census is 1,161,394 triangles, 133 meshes and 14,897 instances.--Both cases remain visibly procedural. The creek has a smooth, cool-looking-water ribbon; the garden has stylized planting and terrace geometry, and its-steam is clearest in the close view. The scene source and library hashes in each-new gallery build bind that build's media to its own source snapshot; the earlier-review records describe the exact earlier snapshots in their provenance files.diff --git a/harness/examples/graphics_lab/agent_cases/feedback.md b/harness/examples/graphics_lab/agent_cases/feedback.mddeleted file mode 100644index 23a20328..00000000--- a/harness/examples/graphics_lab/agent_cases/feedback.md+++ /dev/null@@ -1,9 +0,0 @@-Repair and polish the two scene modules already in this workspace. You are GPT-6 Luna in a SECOND independent coding pass following actual supervisor GPU render review. Keep src/lib read-only, do not read/copy any other hand-authored harness examples, and modify only this workspace. All prose/code/comments English. The supplied libraries have been refreshed to the final compatible build. The original source and renders are preserved separately in ../luna_initial/.--Actual first-pass findings:-1. Courtyard DOES NOT BOOT: ReferenceError THREE is not defined at box() line8. You alias the injected THREE as T only inside createScene, while box() uses out-of-scope global THREE. Fix all such references/imports and render it. Compose a true close candle hero (first camera), restrained warm candlelit dusk with realistic light falloff. Check candles actually sit on their tray (current tray top is above candle base), table/material/props look convincing. No clipping or floating props. Do not alter renderer or global exposure. Make sure the fire bowl has solid fuel/logs supporting its flames.-2. Coastal creek boots but visually fails: its entire stream bed is a raised gray ribbon floating far ABOVE the sandy terrain; sand cut follows an approximate hand-coded centerline rather than the actual smooth stream, and upstream ground height never rises to match upstream water. Build the bank from actual stream.userData.sample(u,lateral,0) positions/width/tangent. Terrain must rise alongside the surface, descend below the stream bed inside the channel and make continuous organic banks, never an exposed raised ribbon. Grass is sparse and visibly rectangular; use continuous masking and enough near-camera blades. First camera should frame an attractive close creek composition with no finite terrain slab edges. Extend peripheral ground or choose better camera framing. Driftwood is upright, rotate into a plausible fallen position. Keep sunlit sand under control by choosing darker base material and lighting (no renderer changes). Replace/cover glossy gray obstacle eggs with naturally fractured wet stone at the actual wake positions if possible without changing mechanics.--The previous sandbox denied a local HTTP server bind. This invocation enables sandbox network access so the existing production browser renderer can be used. Use this actual command per scene by temporarily writing src/scene.js to reexport the chosen module:-node /home/yipeng/3dcodeverse/harness/runtime_js/render_scene.mjs --ws /home/yipeng/3dcodeverse/harness/examples/graphics_lab/output/agent_runs/luna_examples --out /home/yipeng/3dcodeverse/harness/examples/graphics_lab/output/agent_runs/luna_examples/renders/CASE --width 1280 --height 720 --times 0,2 --fps-seconds 0 --no-settle-Do not call --help (unsupported). Render and VIEW images with your image tool, fix errors and revise composition until both examples are genuinely useful showcases. The supervisor has attached the first-pass creek screenshots showing the raised bed and empty slab. Update README.md accurately with actual successful checks and remaining limits. Finish within ten minutes if practical. No commits, no dependencies, no API calls, no unrelated work.diff --git a/harness/examples/graphics_lab/agent_cases/gemini-trials.json b/harness/examples/graphics_lab/agent_cases/gemini-trials.jsondeleted file mode 100644index 8143ce14..00000000--- a/harness/examples/graphics_lab/agent_cases/gemini-trials.json+++ /dev/null@@ -1,45 +0,0 @@-{- "date": "2026-09-22",- "protocol": "Full scene pipeline, one baseline plus one requested refinement, 30 minute run budget. Repeated provider 503s occurred; refinement was not completed within budget. These are unsuccessful trials, not passing examples. Scores are recorded judge outputs, not an independent quality comparison. All predate the final planner guidance separating library effects from standalone assets.",- "trials": [- {- "case": "candle_alcove",- "generator": "gemini-cli:gemini-3.7-flash",- "planner": "gemini:gemini-3.7-flash",- "judge": "gemini:gemini-3.1-pro-preview",- "status": "budget",- "completed_rounds": 1,- "baseline_score": 0.405,- "baseline_passed": false,- "baseline_gate_errors": 4,- "cost_usd": 1.8948,- "record": "output/agent_runs/candle_alcove/record.json"- },- {- "case": "coastal_cove",- "generator": "gemini-cli:gemini-3.7-flash",- "planner": "gemini:gemini-3.7-flash",- "judge": "gemini:gemini-3.1-pro-preview",- "status": "budget",- "completed_rounds": 1,- "baseline_score": 0.12,- "baseline_passed": false,- "baseline_gate_errors": 4,- "cost_usd": 1.6889,- "record": "output/agent_runs/coastal_cove/record.json"- },- {- "case": "spring_stream",- "generator": "gemini-cli:gemini-3.7-flash",- "planner": "gemini:gemini-3.7-flash",- "judge": "gemini:gemini-3.1-pro-preview",- "status": "budget",- "completed_rounds": 1,- "baseline_score": 0.278,- "baseline_passed": false,- "baseline_gate_errors": 8,- "cost_usd": 1.8372,- "record": "output/agent_runs/spring_stream/record.json"- }- ]-}diff --git a/harness/examples/graphics_lab/agent_cases/luna_candle_courtyard.js b/harness/examples/graphics_lab/agent_cases/luna_candle_courtyard.jsdeleted file mode 100644index d50ee630..00000000--- a/harness/examples/graphics_lab/agent_cases/luna_candle_courtyard.js+++ /dev/null@@ -1,131 +0,0 @@-import * as THREE from 'three';-import { makeCandle, makeFire } from '../lib/fire.js';-import { sunRig } from '../lib/environment.js';-import { makeSky } from '../lib/sky.js';-import { weatheredWood, cobble, travertine, paintedIron } from '../lib/materials.js';-import { mulberry32 } from '../lib/noise.js';--function box(name, size, material, position, parent, cast = true) {- const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), material);- mesh.name = name; mesh.position.set(...position); mesh.castShadow = cast; mesh.receiveShadow = true;- parent.add(mesh); return mesh;-}--export function createScene({ THREE: T }) {- const scene = new T.Scene();- scene.background = new T.Color(0x22263a);- scene.fog = new T.Fog(0x373347, 17, 48);- const rig = sunRig({ mood: 'golden', azimuth: 232, elevation: 7, bounds: 14,- sunColor: 0xffb27b, fillSky: 0x8b8fc0, fillGround: 0x62504f, intensity: 1.8 });- scene.add(rig.sun, rig.sun.target, rig.fill);- if (rig.sunDisc) scene.add(rig.sunDisc);- scene.environment = rig.envTex;- makeSky(scene, { rig, exposure: 0.25, contrast: 1.2, scale: 120 });-- const courtyard = new T.Group(); courtyard.name = 'CandleCourtyard'; scene.add(courtyard);- const stone = cobble({ color: 0x77716b, scale: 9, repeat: 1.4, variant: 0.52 });- const warmStone = travertine({ color: 0x9a8671, scale: 5, repeat: 1.4, variant: 0.42 });- const wood = weatheredWood({ color: 0x60442f, scale: 7, repeat: 1.1, variant: 0.38 });- const iron = paintedIron({ color: 0x343332, scale: 9, variant: 0.4 });-- // A shallow paved court with a broken, individually articulated perimeter.- box('CourtyardPaving', [12, 0.22, 10], stone, [0, -0.11, 0], courtyard);- const rng = mulberry32(812);- for (let i = 0; i < 34; i++) {- const x = -5.5 + (i % 12) * 0.98 + (rng() - 0.5) * 0.1;- const z = -4.6 + Math.floor(i / 12) * 1.0 + (rng() - 0.5) * 0.1;- box(`PavingJointStone${i}`, [0.91, 0.025, 0.92], i % 4 ? warmStone : stone,- [x, 0.013, z], courtyard, false);- }- // Rear and side walls leave the approach open; the irregular cap stones soften the silhouette.- box('RearGardenWall', [12, 2.35, 0.48], warmStone, [0, 1.17, -5.15], courtyard);- box('LeftGardenWall', [0.48, 2.0, 8.7], stone, [-5.85, 1, -0.35], courtyard);- box('RightGardenWall', [0.48, 1.75, 8.7], stone, [5.85, 0.875, -0.35], courtyard);- for (let i = 0; i < 17; i++) {- const x = -5.65 + i * 0.7;- box(`WallCoping${i}`, [0.68, 0.18, 0.58], i % 3 ? warmStone : stone,- [x, 2.38 + Math.sin(i * 2.1) * 0.035, -5.12], courtyard);- }- // A low timber table, thick top, pegged legs and visible end grain rails.- const table = new T.Group(); table.name = 'WeatheredOakTable'; table.position.set(-0.45, 0, -0.1); courtyard.add(table);- box('TableTop', [1.48, 0.105, 0.78], wood, [0, 0.77, 0], table);- for (let i = 0; i < 5; i++) box(`TablePlank${i}`, [1.44, 0.008, 0.145], wood, [0, 0.828, -0.29 + i * 0.145], table, false);- for (const x of [-0.59, 0.59]) for (const z of [-0.27, 0.27]) {- box(`TrestleLeg${x}_${z}`, [0.095, 0.69, 0.095], wood, [x, 0.38, z], table);- }- box('TableLongApron', [1.18, 0.13, 0.08], wood, [0, 0.63, 0], table);- // Modest candle grouping; candle geometry is authored to real wax dimensions.- const candles = [];- const candleSpecs = [- [-0.34, -0.08, 0.125, 0.029, 0xe7d4ad],- [-0.08, 0.03, 0.158, 0.031, 0xdac59a],- [0.22, -0.04, 0.102, 0.027, 0xeee0c2],- [0.42, 0.11, 0.135, 0.028, 0xe5d1a5],- ];- candleSpecs.forEach(([x, z, h, r, color], i) => {- const candle = makeCandle({ radius: r, height: h, seed: 110 + i * 17, color, lit: true,- flameHeight: 0.047 + (i % 2) * 0.004, quality: 'high', lightIntensity: 0.48 });- candle.name = `BeeswaxCandle${i + 1}`; candle.position.set(x, 0.841, z); table.add(candle); candles.push(candle);- });- const tableLantern = new T.Group(); tableLantern.name = 'CandleTray'; tableLantern.position.set(0.02, 0.833, 0.1); table.add(tableLantern);- const tray = new T.Mesh(new T.CylinderGeometry(0.47, 0.45, 0.008, 48), iron);- tray.name = 'DarkIronTray'; tray.position.y = 0.004; tray.castShadow = true; tableLantern.add(tray);-- // Compact, waist-low iron bowl on a stone plinth: visible coals and one restrained flame.- const bowl = new T.Group(); bowl.name = 'LowFireBowl'; bowl.position.set(2.25, 0, 0.75); courtyard.add(bowl);- const plinth = new T.Mesh(new T.CylinderGeometry(0.36, 0.42, 0.28, 12), warmStone);- plinth.name = 'BowlStoneFoot'; plinth.position.y = 0.14; plinth.castShadow = plinth.receiveShadow = true; bowl.add(plinth);- const bowlMesh = new T.Mesh(new T.LatheGeometry([- new T.Vector2(0.2, 0), new T.Vector2(0.39, 0.08), new T.Vector2(0.49, 0.33),- new T.Vector2(0.46, 0.39), new T.Vector2(0.39, 0.36), new T.Vector2(0.34, 0.20),- ], 48), iron);- bowlMesh.name = 'HammeredBrazier'; bowlMesh.position.y = 0.28; bowlMesh.castShadow = bowlMesh.receiveShadow = true; bowl.add(bowlMesh);- const coals = new T.Mesh(new T.CircleGeometry(0.34, 48), new T.MeshStandardMaterial({- color: 0x472116, emissive: 0x6d2109, emissiveIntensity: 0.7, roughness: 1 }));- coals.name = 'BankedCoals'; coals.rotation.x = -Math.PI / 2; coals.position.y = 0.57; bowl.add(coals);- const fuelMat = new T.MeshStandardMaterial({ color: 0x251913, roughness: 0.96 });- for (let i = 0; i < 3; i++) {- const log = new T.Mesh(new T.CylinderGeometry(0.055, 0.067, 0.52, 9), fuelMat);- log.name = `BrazierFuelLog${i + 1}`;- log.position.set(Math.cos(i * Math.PI / 3) * 0.07, 0.595 + i * 0.035, Math.sin(i * Math.PI / 3) * 0.07);- log.rotation.set(Math.PI / 2 + i * 0.36, i * 0.24, Math.PI / 2 + i * 0.16);- log.castShadow = true; bowl.add(log);- }- const fire = makeFire({ radius: 0.23, height: 0.48, seed: 91, quality: 'high', style: 'campfire', lightIntensity: 2.1 });- fire.name = 'BrazierFlame'; fire.position.y = 0.56; bowl.add(fire);-- // A worn bench and earthen planters anchor the opposite edge without competing with the table.- const bench = new T.Group(); bench.name = 'GardenBench'; bench.position.set(0.15, 0, 2.55); courtyard.add(bench);- box('BenchSeat', [1.65, 0.09, 0.39], wood, [0, 0.46, 0], bench);- for (const x of [-0.62, 0.62]) {- box(`BenchLeg${x}`, [0.10, 0.43, 0.32], warmStone, [x, 0.23, 0], bench);- box(`BenchBackPost${x}`, [0.075, 0.92, 0.075], wood, [x, 0.87, -0.16], bench);- }- box('BenchBack', [1.55, 0.20, 0.09], wood, [0, 0.90, -0.16], bench);- for (const x of [-4.6, 4.55]) {- const pot = new T.Mesh(new T.CylinderGeometry(0.30, 0.23, 0.47, 12, 1, true),- new T.MeshStandardMaterial({ color: 0x7a4d3c, roughness: 0.94, side: T.DoubleSide }));- pot.name = 'TerracottaPlanter'; pot.position.set(x, 0.235, 3.55); pot.castShadow = true; courtyard.add(pot);- const soil = new T.Mesh(new T.CircleGeometry(0.235, 20), new T.MeshStandardMaterial({ color: 0x33251a, roughness: 1 }));- soil.name = 'PlanterSoil'; soil.rotation.x = -Math.PI / 2; soil.position.set(x, 0.47, 3.55); courtyard.add(soil);- for (let j = 0; j < 5; j++) {- const stem = new T.Mesh(new T.CylinderGeometry(0.008, 0.012, 0.42 + (j % 2) * 0.12, 5),- new T.MeshStandardMaterial({ color: 0x52623a, roughness: 1 }));- stem.name = `HerbStem${j}`; stem.position.set(x + (rng() - 0.5) * 0.25, 0.75, 3.55 + (rng() - 0.5) * 0.22); stem.rotation.z = (rng() - 0.5) * 0.4; courtyard.add(stem);- }- }- const fill = new T.PointLight(0xffa34d, 7, 5.5, 2); fill.name = 'BrazierBounce'; fill.position.set(2.2, 1.05, 0.75); courtyard.add(fill);- const candlesLight = new T.PointLight(0xffbc6a, 1.8, 2.7, 2); candlesLight.name = 'CandleClusterBounce'; candlesLight.position.set(-0.45, 1.43, -0.1); table.add(candlesLight);-- const movers = [...candles, fire];- scene.userData.update = (t, dt) => movers.forEach((item) => item.userData.update?.(t, dt));- return {- scene,- cameras: [- { name: 'Establishing', position: [0.05, 1.58, 1.45], lookAt: [0.02, 1.04, 0.02], fov: 43 },- { name: 'CandleDetail', position: [-2.1, 2.0, 1.55], lookAt: [-0.32, 1.02, -0.12], fov: 43 },- { name: 'BrazierAndTable', position: [4.2, 2.0, 4.0], lookAt: [0.7, 0.8, 0.3], fov: 52 },- ],- update(t, dt) { scene.userData.update(t, dt); },- };-}diff --git a/harness/examples/graphics_lab/agent_cases/luna_coastal_creek.js b/harness/examples/graphics_lab/agent_cases/luna_coastal_creek.jsdeleted file mode 100644index 47c72aaf..00000000--- a/harness/examples/graphics_lab/agent_cases/luna_coastal_creek.js+++ /dev/null@@ -1,155 +0,0 @@-import { makeStream } from '../lib/stream.js';-import { makeMeadow } from '../lib/meadow.js';-import { makeSandTerrain } from '../lib/sand.js';-import { makeRock } from '../lib/rock.js';-import { sunRig } from '../lib/environment.js';-import { makeSky } from '../lib/sky.js';-import { mulberry32 } from '../lib/noise.js';-import { cobble } from '../lib/materials.js';--export function createScene({ THREE: T }) {- const scene = new T.Scene();- scene.background = new T.Color(0xaad0e2);- scene.fog = new T.Fog(0xb7d5df, 45, 120);- const rig = sunRig({ mood: 'day', azimuth: 226, elevation: 39, bounds: 26,- sunColor: 0xffedcf, fillSky: 0xb7d9ee, fillGround: 0x8d8767, intensity: 2.65 });- scene.add(rig.sun, rig.sun.target, rig.fill);- if (rig.sunDisc) scene.add(rig.sunDisc);- scene.environment = rig.envTex;- makeSky(scene, { rig, exposure: 0.23, contrast: 1.08, scale: 160 });-- const land = new T.Group(); land.name = 'CoastalCreek'; scene.add(land);- const seed = 4207, rng = mulberry32(seed);- const points = [[0.25, 0.72, -12], [0.95, 0.57, -7], [0.45, 0.34, -1], [-0.72, 0.18, 5], [-0.36, 0.02, 12]];- const sand = makeSandTerrain({ name: 'WindblownSand', size: [40, 44], segments: 192,- duneHeight: 0.21, duneSpacing: 7.4, windDirection: [0.92, 0.38], rippleSpacing: 0.22,- grains: 80, windSpeed: 0.55, seed, color: 0xa88b62 });- sand.position.y = -0.12;- const obstacles = [ { u: 0.22, lateral: -0.5, radius: 0.16 }, { u: 0.53, lateral: 0.45, radius: 0.18 }, { u: 0.78, lateral: -0.25, radius: 0.14 } ];- const stream = makeStream({ name: 'CoastalCreekWater', points, width: 1.52, widthVariation: 0.13,- depth: 0.25, speed: 0.72, roughness: 0.34, segments: 192, widthSegments: 16,- stoneCount: 36, seed: seed + 1, waterColor: 0x5b9992, bedColor: 0x887d62,- obstacles });- stream.name = 'CoastalCreekWater'; land.add(stream);- const suppliedBed = stream.getObjectByName('StreamBed');- if (suppliedBed) suppliedBed.visible = false;- const pathSamples = Array.from({ length: 481 }, (_, i) => {- const u = i / 480, s = stream.userData.sample(u, 0, 0);- return { u, x: s.position.x, z: s.position.z, width: s.width, tx: s.tangent.x, tz: s.tangent.z };- });- const nearestPath = (x, z) => {- let lo = 0, hi = pathSamples.length - 1;- while (hi - lo > 1) { const mid = (lo + hi) >> 1; if (pathSamples[mid].z < z) lo = mid; else hi = mid; }- const a = pathSamples[lo], b = pathSamples[hi];- const f = T.MathUtils.clamp((z - a.z) / (b.z - a.z), 0, 1);- const u = T.MathUtils.lerp(a.u, b.u, f), sample = stream.userData.sample(u, 0, 0);- const best = { x: sample.position.x, z: sample.position.z, width: sample.width,- tx: sample.tangent.x, tz: sample.tangent.z };- const dx = x - best.x, dz = z - best.z;- const acrossX = best.tz, acrossZ = -best.tx;- return { u, width: best.width, lateral: dx * acrossX + dz * acrossZ,- distance: Math.hypot(dx, dz), centerX: best.x, centerZ: best.z };- };- for (let i = 0; i < obstacles.length; i++) {- const obstacle = obstacles[i];- const original = stream.getObjectByName(`StreamObstacle_${i}`);- if (original) original.visible = false;- const sample = stream.userData.sample(obstacle.u, obstacle.lateral, 0);- const rock = makeRock({ type: 'basalt', size: [obstacle.radius * 2.5, obstacle.radius * 1.4, obstacle.radius * 2.2],- seed: seed + 180 + i * 19, detail: 6, moisture: 0.82 });- rock.name = `FracturedWetWakeStone${i + 1}`;- rock.position.copy(sample.position); rock.position.y -= obstacle.radius * 0.34;- rock.rotation.y = rng() * Math.PI * 2; land.add(rock);- }- const groundMesh = sand.children.find((child) => child.isMesh);- const terrain = groundMesh.geometry.attributes.position;- for (let i = 0; i < terrain.count; i++) {- const x = terrain.getX(i), z = terrain.getZ(i), base = terrain.getY(i);- const path = nearestPath(x, z), d = Math.abs(path.lateral) / (path.width * 0.5);- const waterY = stream.userData.sample(path.u, 0, 0).position.y;- const bedY = waterY - 0.25 * (1 - 0.55 * Math.min(1, d) ** 2) + 0.025;- const shelfY = Math.max(base, waterY + 0.055);- let y;- if (d <= 1.40) y = bedY;- else if (d < 1.82) {- const f = T.MathUtils.smoothstep(d, 1.40, 1.82);- y = T.MathUtils.lerp(bedY, shelfY, f);- } else if (d < 4.0) {- const f = T.MathUtils.smoothstep(d, 1.72, 4.0);- y = T.MathUtils.lerp(shelfY, base, f);- } else y = base;- terrain.setY(i, y);- }- terrain.needsUpdate = true; groundMesh.geometry.computeVertexNormals();- sand.userData.update(0); land.add(sand);-- const plantRegions = [];- const grass = makeMeadow({ name: 'ContinuousCoastalGrass', size: [34, 36], height: 0.52, density: 620,- maxBlades: 170000, seed: seed + 20,- heightAt: (x, z) => sand.userData.sampleHeight(x, z),- mask: (x, z) => {- const path = nearestPath(x, z), d = Math.abs(path.lateral) / (path.width * 0.5);- const bank = T.MathUtils.smoothstep(d, 1.55, 2.15);- const windGaps = 0.76 + 0.24 * Math.sin(x * 0.55 + z * 0.31 + 1.2) * Math.sin(z * 0.47 - x * 0.28);- return bank * Math.max(0.28, windGaps);- }, wind: { direction: [0.94, 0.34], strength: 0.48, speed: 1.05 }, ground: false });- grass.position.y = sand.position.y; land.add(grass); plantRegions.push(grass);-- // Sparse dune-edge tufts create a broken transition into the distant shore.- const tuftMat = new T.MeshStandardMaterial({ color: 0x8a9257, roughness: 0.92, side: T.DoubleSide });- for (let i = 0; i < 44; i++) {- const z = -12 + rng() * 24, x = (rng() - 0.5) * 18;- if (Math.abs(nearestPath(x, z).lateral) < 2.1) continue;- const h = 0.24 + rng() * 0.36;- const tuft = new T.Group(); tuft.name = `SeaOatTuft${i}`; tuft.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z), z); land.add(tuft);- for (let j = 0; j < 5; j++) {- const blade = new T.Mesh(new T.PlaneGeometry(0.045, h * (0.68 + rng() * 0.45)), tuftMat);- blade.name = 'OatBlade'; blade.position.y = h * 0.45; blade.rotation.y = j * Math.PI / 5; blade.rotation.z = (rng() - 0.5) * 0.36; tuft.add(blade);- }- }-- // Fractured stones seat against the bank; none is allowed to cover the moving water ribbon.- const rockSpecs = [- [-1.65, -8.5, [0.82, 0.42, 0.66]], [2.2, -5.8, [0.72, 0.37, 0.58]],- [-1.72, -2.4, [0.95, 0.5, 0.72]], [1.7, 0.9, [0.8, 0.43, 0.63]],- [-1.85, 4.2, [0.72, 0.38, 0.56]], [1.25, 7.8, [0.92, 0.5, 0.76]],- [-2.0, 9.8, [0.62, 0.31, 0.52]], [3.4, -9.6, [1.15, 0.56, 0.9]],- ];- rockSpecs.forEach(([x, z, size], i) => {- const rock = makeRock({ type: i % 3 === 0 ? 'sandstone' : 'granite', size,- seed: seed + 80 + i * 13, detail: 5, moisture: 0.12 });- rock.name = `TideWornRock${i + 1}`;- rock.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z) - 0.025, z);- rock.rotation.y = rng() * Math.PI * 2; land.add(rock);- });-- // A few flattened cobbles and a weathered driftwood branch on the dry upper bank.- const pebbleMat = cobble({ color: 0x77776e, scale: 12, variant: 0.46 });- for (let i = 0; i < 16; i++) {- const z = -10 + rng() * 20, side = i % 2 ? 1 : -1;- const path = nearestPath(0, z);- const x = path.centerX + side * (1.15 + rng() * 0.75);- const pebble = new T.Mesh(new T.IcosahedronGeometry(0.12 + rng() * 0.12, 1), pebbleMat);- pebble.name = `CreekPebble${i}`; pebble.scale.set(1.35, 0.48, 0.88);- pebble.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z) + 0.045, z);- pebble.rotation.set(0, rng() * Math.PI, (rng() - 0.5) * 0.18); pebble.castShadow = pebble.receiveShadow = true; land.add(pebble);- }- const driftwood = new T.Mesh(new T.CylinderGeometry(0.075, 0.13, 2.15, 8),- new T.MeshStandardMaterial({ color: 0x655540, roughness: 0.94 }));- driftwood.name = 'SaltBleachedDriftwood'; driftwood.position.set(-5.0, sand.position.y + sand.userData.sampleHeight(-5, -6) + 0.10, -6); driftwood.rotation.z = Math.PI / 2 + 0.14; driftwood.rotation.x = 0.08; driftwood.castShadow = true; land.add(driftwood);-- scene.userData.update = (t, dt) => {- stream.userData.update(t, dt);- sand.userData.update(t, dt);- for (const patch of plantRegions) patch.userData.update(t, dt);- };- return {- scene,- cameras: [- { name: 'Establishing', position: [-3.8, 1.95, 4.3], lookAt: [-0.1, 0.49, -0.65], fov: 41 },- { name: 'Creekside', position: [-4.8, 2.0, 4.7], lookAt: [0.25, 0.32, 0.4], fov: 47 },- { name: 'WaterDetail', position: [3.7, 1.7, -2.2], lookAt: [0.1, 0.34, -3.2], fov: 44 },- ],- update(t, dt) { scene.userData.update(t, dt); },- };-}diff --git a/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.js b/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.jsdeleted file mode 100644index 3dd71aa4..00000000--- a/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.js+++ /dev/null@@ -1,172 +0,0 @@-import { makeStream } from '../lib/stream.js';-import { makeMeadow } from '../lib/meadow.js';-import { makeSandTerrain } from '../lib/sand.js';-import { makeRock } from '../lib/rock.js';-import { sunRig } from '../lib/environment.js';-import { makeSky } from '../lib/sky.js';-import { mulberry32 } from '../lib/noise.js';--export function createScene({ THREE: T }) {- const scene = new T.Scene();- scene.background = new T.Color(0xb8d4dc);- scene.fog = new T.Fog(0xb8d4dc, 62, 145);- const rig = sunRig({ mood: 'day', azimuth: 224, elevation: 34, bounds: 28,- sunColor: 0xffedcf, fillSky: 0xb7d9ee, fillGround: 0x8d8767, intensity: 2.3 });- scene.add(rig.sun, rig.sun.target, rig.fill);- if (rig.sunDisc) scene.add(rig.sunDisc);- scene.environment = rig.envTex;- makeSky(scene, { rig, exposure: 0.28, contrast: 1.04, scale: 170 });-- const land = new T.Group(); land.name = 'SandyCoastalCreek'; scene.add(land);- const seed = 8314, rng = mulberry32(seed);- const points = [- [-1.15, 0.68, -13], [-0.4, 0.53, -8], [0.82, 0.34, -2],- [0.5, 0.19, 4], [-0.85, 0.055, 10], [-0.3, 0.0, 14],- ];- const stream = makeStream({ name: 'ShallowTidalCreek', points, width: 1.25,- widthVariation: 0.18, depth: 0.27, speed: 0.38, roughness: 0.6,- segments: 256, widthSegments: 24, stoneCount: 24, seed: seed + 1,- waterColor: 0x56877e, attenuationDistance: 0.72, bedColor: 0x947d5d,- obstacles: [- { u: 0.26, lateral: -0.43, radius: 0.13 },- { u: 0.57, lateral: 0.43, radius: 0.16 },- { u: 0.82, lateral: -0.38, radius: 0.12 },- ] });- land.add(stream);-- const sand = makeSandTerrain({ name: 'LowWindWorkedDunes', size: [40, 48], segments: 512,- duneHeight: 0.20, duneSpacing: 10.5, windDirection: [0.94, 0.34],- rippleSpacing: 0.24, detailStrength: 0.82, grains: 45, windSpeed: 0.35,- seed, color: 0xb39a73 });- sand.position.y = -0.12;- const ground = sand.children.find((child) => child.isMesh);- const pos = ground.geometry.attributes.position;- const pathSamples = Array.from({ length: 701 }, (_, i) => {- const u = i / 700, s = stream.userData.sample(u, 0, 0);- return { u, x: s.position.x, z: s.position.z };- });- const nearest = (x, z) => {- // The creek runs generally north to south, so a local segment search avoids- // the incorrect straight-across assumption at its two broad bends.- let lo = 0, hi = pathSamples.length - 1;- while (hi - lo > 1) {- const mid = (lo + hi) >> 1;- if (pathSamples[mid].z < z) lo = mid; else hi = mid;- }- let best = pathSamples[lo], bestD = Infinity;- for (let i = Math.max(0, lo - 12); i <= Math.min(pathSamples.length - 1, hi + 12); i++) {- const p = pathSamples[i], dx = x - p.x, dz = z - p.z, d = dx * dx + dz * dz;- if (d < bestD) { bestD = d; best = p; }- }- const s = stream.userData.sample(best.u, 0, 0);- const ax = s.tangent.z, az = -s.tangent.x;- return { u: best.u, lateral: (x - best.x) * ax + (z - best.z) * az,- distance: Math.sqrt(bestD), centerX: best.x, centerZ: best.z };- };-- // Cut a real shallow channel into the terrain. The valley floor follows the- // stream grade and its banks rise to the exact edges of the water ribbon.- for (let i = 0; i < pos.count; i++) {- const x = pos.getX(i), z = pos.getZ(i), duneY = pos.getY(i) + sand.position.y;- const path = nearest(x, z), width = stream.userData.sample(path.u, 0, 0).width;- const half = width * 0.5;- const edge = half;- const d = Math.abs(path.lateral) / edge;- const waterY = stream.userData.sample(path.u, 0, 0).position.y;- const bedY = waterY - 0.27 * Math.pow(1 - Math.min(d, 1), 0.72) - 0.004;- let y;- if (d <= 1) {- y = bedY;- } else if (d < 1.95) {- const t = T.MathUtils.smoothstep(d, 1, 1.95);- y = T.MathUtils.lerp(waterY, Math.max(duneY, waterY + 0.15), t);- } else if (d < 3.1) {- const t = T.MathUtils.smoothstep(d, 1.95, 3.1);- y = T.MathUtils.lerp(Math.max(duneY, waterY + 0.15), duneY, t);- } else {- y = duneY;- }- y += 0.012 * (1 - T.MathUtils.smoothstep(d, 1, 3.1));- // Geometry vertices are local to the offset sand group; all channel- // targets above were derived from the stream's world-space grade.- pos.setY(i, y - sand.position.y);- }- pos.needsUpdate = true;- ground.geometry.computeVertexNormals();- ground.geometry.computeBoundingBox();- ground.geometry.computeBoundingSphere();- sand.userData.update(0);- land.add(sand);-- const grass = makeMeadow({ name: 'SparseSaltGrass', size: [35, 40], height: 0.34,- density: 205, maxBlades: 65000, seed: seed + 20,- heightAt: (x, z) => sand.userData.sampleHeight(x, z),- mask: (x, z) => {- const path = nearest(x, z), d = Math.abs(path.lateral) / 0.625;- const bank = T.MathUtils.smoothstep(d, 1.35, 2.4);- const gaps = 0.54 + 0.46 * Math.sin(x * 0.36 + z * 0.22 + 1.3) * Math.sin(z * 0.31 - x * 0.19);- return bank * Math.max(0.08, gaps);- }, wind: { direction: [0.94, 0.34], strength: 0.34, speed: 0.7 },- diversity: 0.8, dry: 0.26, ground: false });- grass.position.y = sand.position.y;- land.add(grass);-- // Low, separated sea-oat clumps break the grass line on the higher dunes.- const oatMaterial = new T.MeshStandardMaterial({ color: 0x8b8c5a, roughness: 0.94, side: T.DoubleSide });- for (let i = 0; i < 56; i++) {- const z = -15 + rng() * 29, x = (rng() - 0.5) * 20;- if (nearest(x, z).distance < 2.3) continue;- const h = 0.23 + rng() * 0.27;- const tuft = new T.Group(); tuft.name = `SeaOatClump_${i}`;- tuft.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z), z); land.add(tuft);- for (let j = 0; j < 5; j++) {- const blade = new T.Mesh(new T.PlaneGeometry(0.038, h * (0.7 + rng() * 0.35)), oatMaterial);- blade.position.y = h * 0.43; blade.rotation.y = j * Math.PI / 5;- blade.rotation.z = (rng() - 0.5) * 0.27; tuft.add(blade);- }- }-- // Small rounded stones sit on the damp edge; larger broken rocks stay above- // the waterline and are visibly seated in the sloping sand.- const rockSpecs = [- [-1.03, -9.1, [0.58, 0.30, 0.47]], [1.12, -5.1, [0.62, 0.32, 0.48]],- [-1.08, -1.4, [0.67, 0.34, 0.52]], [1.08, 2.4, [0.55, 0.29, 0.46]],- [-1.16, 6.8, [0.6, 0.31, 0.47]], [1.12, 9.8, [0.73, 0.37, 0.59]],- [2.9, -11.5, [0.92, 0.45, 0.78]], [-3.3, 5.1, [0.86, 0.44, 0.71]],- ];- rockSpecs.forEach(([x, z, size], i) => {- const rock = makeRock({ type: i % 3 === 0 ? 'sandstone' : 'granite', size,- seed: seed + 80 + i * 17, detail: 5, moisture: i < 6 ? 0.34 : 0.06, burial: 0.11 });- rock.name = `TideWornBankRock_${i + 1}`;- rock.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z) - 0.005, z);- rock.rotation.y = rng() * Math.PI * 2; land.add(rock);- });- for (let i = 0; i < 24; i++) {- const u = 0.06 + rng() * 0.88, side = i % 2 ? 1 : -1;- const p = stream.userData.sample(u, side, 0);- const offset = 0.12 + rng() * 0.22;- const x = p.position.x + p.tangent.z * side * offset;- const z = p.position.z - p.tangent.x * side * offset;- const sx = 0.18 + rng() * 0.20, sy = 0.10 + rng() * 0.10, sz = 0.15 + rng() * 0.21;- const pebble = makeRock({ type: i % 4 === 0 ? 'sandstone' : 'granite', size: [sx, sy, sz],- seed: seed + 300 + i * 23, detail: 2, weathering: 0.72, moisture: 0.22, burial: 0.22 });- pebble.name = `CreekEdgeStone_${i}`;- pebble.position.set(x, sand.position.y + sand.userData.sampleHeight(x, z), z);- pebble.rotation.y = rng() * Math.PI * 2; land.add(pebble);- }-- scene.userData.update = (t, dt) => {- stream.userData.update(t, dt);- sand.userData.update(t, dt);- grass.userData.update(t, dt);- };- return {- scene,- cameras: [- { name: 'DuneOverview', position: [-5.8, 3.1, 7.2], lookAt: [-0.2, 0.24, -0.6], fov: 43 },- { name: 'Waterline', position: [-2.8, 0.86, 2.7], lookAt: [0.05, 0.27, -2.1], fov: 47 },- { name: 'BendDetail', position: [2.7, 0.95, -3.0], lookAt: [0.05, 0.26, -4.8], fov: 45 },- ],- update(t, dt) { scene.userData.update(t, dt); },- };-}diff --git a/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.provenance.json b/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.provenance.jsondeleted file mode 100644index c335bd03..00000000--- a/harness/examples/graphics_lab/agent_cases/luna_coastal_creek_refined.provenance.json+++ /dev/null@@ -1,33 +0,0 @@-{- "model": "gpt-6-luna",- "authoring_channel": "delegated GPT-6 Luna refinement of the original CodexCLI Luna case; not a new harness or provider-CLI trial",- "review_iteration": 3,- "brief": "Refine the original sandy coastal creek into a plausible shallow channel with a graded bed, irregular contacting banks, proportionate dune vegetation and stones, and clear creekside cameras.",- "modifications": [- "Carved a 512-segment sand terrain channel from the stream's sampled centerline, width and grade, with the supplied stream bed retained under the water.",- "Converted world-space stream and bank heights into the offset sand group's local coordinates; added a small shoreline interpolation correction after measuring the actual triangle sampler.",- "Replaced individually cobble-textured pebble meshes with varied, individually seated makeRock stones, and retained the larger fractured bank rocks.",- "Rendered and reviewed the same establishing, waterline and bend-detail cameras at 0, 1.5 and 3 seconds on the real GPU."- ],- "testing": {- "render_command": "node --import /home/yipeng/3dcodeverse/harness/runtime_js/lib/resolve_three.mjs /home/yipeng/3dcodeverse/harness/runtime_js/render_scene.mjs --ws /tmp/graphics-seven-hour/luna-creek-refinement/staged --out /tmp/graphics-seven-hour/luna-creek-refinement/renders-v3 --times 0,1.5,3 --width 1280 --height 720 --fps-seconds 0 --no-settle --timeout-ms 180000",- "render_result": "9 authored-camera GPU frames rendered on ANGLE/D3D12 (NVIDIA GeForce RTX 5090 Laptop GPU); zero console errors, shader errors, update errors or host warnings.",- "shoreline_measurement": {- "method": "Sampled makeSandTerrain.userData.sampleHeight at both horizontal stream ribbon edges and compared world terrain height with makeStream.userData.sample(u, 0, 0) water grade.",- "samples": 82,- "stream_positions": 41,- "banks": 2,- "height_difference_min_m": -0.010605,- "height_difference_max_m": 0.010613,- "mean_absolute_height_difference_m": 0.005284,- "maximum_absolute_height_difference_m": 0.010613- },- "staging": "Isolated temporary workspace at /tmp/graphics-seven-hour/luna-creek-refinement/staged with copied shipped scene_threejs src/lib modules. Preserved v1 source and renders in /tmp/graphics-seven-hour/luna-creek-refinement/v1; final frames and metrics are in /tmp/graphics-seven-hour/luna-creek-refinement/renders-v3. The original comparison render at /tmp/graphics-seven-hour/integration-preview-1/luna_coastal_creek.png was left unchanged."- },- "library_usability_notes": [- "makeStream.sample(u, lateral, 0) provides the graded centerline and ribbon edge needed to shape terrain along a bend rather than along a fixed world axis.",- "makeSandTerrain.userData.sampleHeight interpolates the actual rendered triangles, allowing bank contact to be measured and stones and plants to be seated against the edited terrain.",- "The sand group is vertically offset, so world-space stream targets must be converted back into local heights before writing terrain vertices."- ],- "visual_limitations": "The result is a stylized procedural coastal creek. The shallow stream remains a smooth kinematic water ribbon and reads somewhat cool and glassy in broad views."-}diff --git a/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.js b/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.jsdeleted file mode 100644index 2fefbcfd..00000000--- a/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.js+++ /dev/null@@ -1,289 +0,0 @@-import { makeSteam } from '../lib/smoke.js';-import { makeTree } from '../lib/tree.js';-import { sunRig } from '../lib/environment.js';-import { makeSky } from '../lib/sky.js';-import { weatheredWood, paintedWood, cobble, granite, terracotta, soil as soilFinish, foliage, paintedIron } from '../lib/materials.js';--export function createScene({ THREE: T }) {- const scene = new T.Scene();- scene.background = new T.Color(0x9bb6bd);- scene.fog = new T.Fog(0xa9bdb9, 24, 62);- const rig = sunRig({ mood: 'day', azimuth: 218, elevation: 14, bounds: 20,- sunColor: 0xffc991, fillSky: 0xa7c2ce, fillGround: 0x827b69, intensity: 2.0 });- scene.add(rig.sun, rig.sun.target, rig.fill);- if (rig.sunDisc) scene.add(rig.sunDisc);- scene.environment = rig.envTex;- makeSky(scene, { rig, exposure: 0.20, contrast: 1.04, scale: 90 });-- const garden = new T.Group(); garden.name = 'GardenWorkbench'; scene.add(garden);- const soilMat = soilFinish({ color: 0x554838, seed: 33, scale: 18, contrast: 0.42, bump: 0.025 });- const gravelMat = cobble({ color: 0x77766c, seed: 17, scale: 22, contrast: 0.38, bump: 0.018 });- const stoneMats = [- cobble({ color: 0x77796e, seed: 41, scale: 16, contrast: 0.32, bump: 0.018 }),- granite({ color: 0x85837a, seed: 62, scale: 18, contrast: 0.36, bump: 0.014 }),- cobble({ color: 0x686e69, seed: 83, scale: 21, contrast: 0.38, bump: 0.018 }),- ];- const mortar = new T.MeshStandardMaterial({ color: 0x403f36, roughness: 1 });- const wood = weatheredWood({ color: 0x927455, seed: 101, scale: 6, contrast: 0.18, bump: 0.0015 });- const sunWood = weatheredWood({ color: 0xa0805b, seed: 119, scale: 6, contrast: 0.20, bump: 0.0015 });- const oldPaint = paintedWood({ color: 0x596153, seed: 129, scale: 6, contrast: 0.15, bump: 0.001 });- const iron = paintedIron({ color: 0x303b39, seed: 5, scale: 10, contrast: 0.22 });- const clay = [0x9d6248, 0x80604a, 0xb27652].map((color, i) => terracotta({ color, seed: 212 + i, scale: 10, contrast: 0.34, bump: 0.006 }));- const leafDark = foliage({ color: 0x435d34, seed: 18, scale: 16, contrast: 0.35 });- const leafMid = foliage({ color: 0x667546, seed: 22, scale: 14, contrast: 0.34 });- const leafLight = foliage({ color: 0x89915b, seed: 25, scale: 17, contrast: 0.34 });-- const box = (name, size, position, material, rotation = [0, 0, 0], parent = garden) => {- const mesh = new T.Mesh(new T.BoxGeometry(...size), material); mesh.name = name;- mesh.position.set(...position); mesh.rotation.set(...rotation);- mesh.castShadow = mesh.receiveShadow = true; parent.add(mesh); return mesh;- };-- // A single, gently uneven garden bed anchors every planted object and the path.- const earth = new T.Mesh(new T.PlaneGeometry(14, 16, 64, 64), soilMat);- earth.name = 'GardenSoil'; earth.rotation.x = -Math.PI / 2; earth.position.set(0, -0.008, -0.15);- earth.receiveShadow = true; garden.add(earth);- const gravel = new T.Mesh(new T.PlaneGeometry(2.35, 8.4), gravelMat);- gravel.name = 'LooseGravelWorkPath'; gravel.rotation.x = -Math.PI / 2; gravel.position.set(0.0, 0.003, 2.2);- gravel.receiveShadow = true; garden.add(gravel);-- // Three distinct retaining walls support successive planted shelves. Small irregular gaps read as dry laid joints.- const wallZ = [-4.25, -2.75, -1.22], deckY = [0.31, 0.49, 0.67];- for (let row = 0; row < wallZ.length; row++) {- const top = deckY[row], front = wallZ[row], bedDepth = 1.25;- box(`MortarCourse_${row}`, [9.65, 0.025, 0.42], [0, top - 0.29, front], mortar);- const courses = stoneMats.map(() => []);- let x = -4.78, i = 0;- while (x < 4.72) {- const width = Math.min(0.54 + ((i * 7 + row * 3) % 5) * 0.105, 4.76 - x);- const h = 0.31 + 0.035 * Math.sin(i * 1.71 + row * 0.9);- const depth = 0.38 + 0.025 * ((i + row) % 3);- const materialIndex = (i + row * 2) % stoneMats.length;- const rotation = [0.008 * Math.sin(i + row), 0.014 * Math.sin(i * 2.3 + row), 0.01 * Math.cos(i * 1.4)];- courses[materialIndex].push({ size: [width - 0.014, h, depth], position: [x + width / 2, top - h / 2, front], rotation });- x += width; i++;- }- const blockGeometry = new T.BoxGeometry(1, 1, 1);- for (let materialIndex = 0; materialIndex < courses.length; materialIndex++) {- const blocks = courses[materialIndex];- if (!blocks.length) continue;- const batch = new T.InstancedMesh(blockGeometry, stoneMats[materialIndex], blocks.length);- batch.name = `DryStoneCourse_${row}_${materialIndex}`;- const dummy = new T.Object3D();- for (let j = 0; j < blocks.length; j++) {- const block = blocks[j]; dummy.position.set(...block.position); dummy.rotation.set(...block.rotation);- dummy.scale.set(...block.size); dummy.updateMatrix(); batch.setMatrixAt(j, dummy.matrix);- }- batch.instanceMatrix.needsUpdate = true; batch.castShadow = batch.receiveShadow = true; garden.add(batch);- }- const shelf = new T.Mesh(new T.BoxGeometry(9.45, 0.11, bedDepth), soilMat);- shelf.name = `RaisedSoilShelf_${row}`; shelf.position.set(0, top - 0.055, front - 0.82);- shelf.receiveShadow = true; garden.add(shelf);- }-- // A weather-softened fence is a useful garden boundary and gives the steam a dark, legible backdrop.- const fenceZ = -1.48, fenceBottom = 0.91;- for (const x of [-1.55, 0, 1.55]) box('FencePost', [0.085, 1.23, 0.085], [x, fenceBottom + 0.615, fenceZ], wood, [0, 0, (x === 0 ? 0.008 : -0.012)]);- for (const y of [1.05, 1.73]) box('FenceRail', [3.12, 0.065, 0.07], [0, y, fenceZ + 0.012], oldPaint);- for (let i = 0; i < 14; i++) {- const x = -1.43 + i * 0.22;- const h = 0.83 + 0.10 * Math.sin(i * 1.76) + 0.06 * Math.sin(i * 0.67 + 1);- const slat = box(`WeatheredPicket_${i}`, [0.126, h, 0.044], [x, fenceBottom + h / 2 + 0.025, fenceZ + 0.065], oldPaint,- [0, 0.008 * Math.sin(i * 2), 0.012 * Math.sin(i * 1.43)]);- slat.geometry.translate(0, -0.025, 0);- }- // Two climbing stems and instanced paired leaves soften the trellis silhouette.- const vineGeometry = new T.SphereGeometry(1, 8, 6);- const vineDark = new T.InstancedMesh(vineGeometry, leafDark, 16); vineDark.name = 'FenceVineLeavesDark';- const vineMid = new T.InstancedMesh(vineGeometry, leafMid, 8); vineMid.name = 'FenceVineLeavesMid';- let vineDarkIndex = 0, vineMidIndex = 0; const vineDummy = new T.Object3D();- for (let vine = 0; vine < 2; vine++) {- const baseX = vine === 0 ? -0.88 : 0.92;- const points = Array.from({ length: 7 }, (_, i) => new T.Vector3(- baseX + 0.095 * Math.sin(i * 0.91 + vine), 0.94 + i * 0.145, fenceZ + 0.112));- const stem = new T.Mesh(new T.TubeGeometry(new T.CatmullRomCurve3(points), 24, 0.006, 5, false),- new T.MeshStandardMaterial({ color: 0x53613e, roughness: 0.96 }));- stem.name = `FenceVineStem_${vine}`; garden.add(stem);- for (let i = 1; i < 7; i++) for (const side of [-1, 1]) {- vineDummy.position.set(points[i].x + side * 0.075, points[i].y + side * 0.022, fenceZ + 0.115);- vineDummy.rotation.set(0, side * 0.45, side * (0.40 + 0.08 * (i % 2)));- vineDummy.scale.set(0.047 * 0.48, 0.047 * 1.22, 0.047 * 0.23); vineDummy.updateMatrix();- if (i % 3) vineDark.setMatrixAt(vineDarkIndex++, vineDummy.matrix); else vineMid.setMatrixAt(vineMidIndex++, vineDummy.matrix);- }- }- vineDark.instanceMatrix.needsUpdate = true; vineMid.instanceMatrix.needsUpdate = true; garden.add(vineDark, vineMid);-- const birch = makeTree({ name: 'FramingBirch', species: 'birch', height: 6.1, crownRadius: 2.55,- seed: 3206, leafDensity: 1.0, leafSize: 0.09, maxLeaves: 16000,- wind: { dir: [0.92, 0.38], strength: 0.32, speed: 0.7 }, shadows: true });- birch.position.set(-5.25, 0, -1.45); garden.add(birch);-- // Bench proportions follow an ordinary potting bench: 1.45 m wide, 0.54 m deep, 0.85 m to the top.- const tableZ = 1.18, topY = 0.85;- const topBoards = [- { z: tableZ - 0.17, width: 0.18 }, { z: tableZ + 0.015, width: 0.18 }, { z: tableZ + 0.20, width: 0.16 },- ];- topBoards.forEach(({ z, width }, i) => box(`BenchtopPlank_${i}`, [1.45, 0.048, width], [0, topY, z], i === 1 ? sunWood : wood));- for (const x of [-0.62, 0.62]) {- for (const z of [tableZ - 0.20, tableZ + 0.20]) box('BenchLeg', [0.058, 0.79, 0.058], [x, 0.435, z], wood);- box('BenchApron', [0.07, 0.13, 0.43], [x, 0.73, tableZ], oldPaint);- }- box('BenchFrontStretcher', [1.16, 0.064, 0.06], [0, 0.34, tableZ + 0.19], wood);- box('LowerSlattedShelf', [1.27, 0.034, 0.43], [0, 0.40, tableZ], sunWood);- for (let i = 0; i < 6; i++) {- const bolt = new T.Mesh(new T.CylinderGeometry(0.008, 0.008, 0.008, 10), iron);- bolt.name = 'BenchJoineryPin'; bolt.rotation.x = Math.PI / 2;- bolt.position.set(i < 3 ? -0.62 : 0.62, 0.78 - (i % 3) * 0.04, tableZ + 0.239); garden.add(bolt);- }- // Soil smudges and small cut marks make the top feel used rather than newly assembled.- const workDust = new T.Mesh(new T.CircleGeometry(0.095, 24), soilMat);- workDust.name = 'PottingSoilSmudge'; workDust.rotation.x = -Math.PI / 2; workDust.scale.set(1.55, 0.56, 1);- workDust.position.set(-0.38, topY + 0.025, tableZ - 0.12); garden.add(workDust);- for (let i = 0; i < 4; i++) {- const scratch = new T.Mesh(new T.BoxGeometry(0.0015, 0.0008, 0.038 + i * 0.006), mortar);- scratch.name = 'BenchWearMark'; scratch.position.set(-0.2 + i * 0.06, topY + 0.025, tableZ + 0.01); scratch.rotation.y = 0.28; garden.add(scratch);- }-- // Small hand trowel laid on the bench, scaled to a real 22 cm garden tool.- const trowel = new T.Group(); trowel.name = 'GardenTrowel'; trowel.position.set(-0.43, topY + 0.026, tableZ + 0.10); trowel.rotation.y = -0.66; garden.add(trowel);- const handle = new T.Mesh(new T.CapsuleGeometry(0.012, 0.105, 4, 8), wood);- handle.name = 'TrowelHandle'; handle.rotation.z = Math.PI / 2; handle.position.x = -0.066; handle.castShadow = true; trowel.add(handle);- const blade = new T.Mesh(new T.SphereGeometry(0.048, 12, 8), paintedIron({ color: 0x78817c, seed: 74, scale: 15, roughness: 0.53, metalness: 0.34 }));- blade.name = 'TrowelBlade'; blade.scale.set(1.25, 0.16, 0.72); blade.position.x = 0.08; blade.castShadow = true; trowel.add(blade);-- // A handmade mug: about 9 cm across and 9.5 cm tall, with a thin rolled rim and a dark tea surface.- const mug = new T.Group(); mug.name = 'MorningMug'; mug.position.set(0.28, topY + 0.024, tableZ - 0.08); garden.add(mug);- const cupProfile = [[0, 0], [0.026, 0], [0.038, 0.006], [0.043, 0.018], [0.046, 0.078],- [0.045, 0.092], [0.039, 0.092], [0.038, 0.078], [0.034, 0.019], [0, 0.014]];- const cup = new T.Mesh(new T.LatheGeometry(cupProfile.map(p => new T.Vector2(...p)), 48),- new T.MeshStandardMaterial({ color: 0xb6b19d, roughness: 0.24, metalness: 0.01 }));- cup.name = 'CeramicCup'; cup.castShadow = cup.receiveShadow = true; mug.add(cup);- const lip = new T.Mesh(new T.TorusGeometry(0.0423, 0.0023, 8, 40), new T.MeshStandardMaterial({ color: 0xd2cdbd, roughness: 0.21 }));- lip.name = 'GlazedRolledRim'; lip.rotation.x = Math.PI / 2; lip.position.y = 0.089; mug.add(lip);- const cupHandle = new T.Mesh(new T.TorusGeometry(0.027, 0.006, 12, 28, Math.PI * 1.72), cup.material);- cupHandle.name = 'CupHandle'; cupHandle.rotation.z = Math.PI * 0.82; cupHandle.position.set(0.047, 0.048, 0); mug.add(cupHandle);- const tea = new T.Mesh(new T.CircleGeometry(0.036, 32), new T.MeshStandardMaterial({ color: 0x39271b, roughness: 0.19 }));- tea.name = 'TeaSurface'; tea.rotation.x = -Math.PI / 2; tea.position.y = 0.079; mug.add(tea);- const steam = makeSteam({ name: 'MugSteam', height: 0.38, radius: 0.040, spread: 0.20,- riseSpeed: 0.16, wind: [0.030, -0.010], density: 13.0, turbulence: 0.50,- dissipation: 1.1, color: 0xf0f0e7, anisotropy: 0.56, quality: 'high', seed: 52 });- steam.name = 'MugSteam'; steam.position.set(0.28, topY + 0.024 + 0.094, tableZ - 0.08); garden.add(steam);- const steamRimLight = new T.PointLight(0xffcc93, 0.8, 0.9, 2);- steamRimLight.name = 'SteamBacklight'; steamRimLight.intensity = 14.0; steamRimLight.distance = 4.0; steamRimLight.position.set(0.31, 1.43, -0.88); garden.add(steamRimLight);--- // Tapered handmade pots, some planted and some recently emptied. Their spacing follows the actual shelves.- const addPot = (name, x, y, z, radius, height, material, plantName = null, type = 0) => {- const group = new T.Group(); group.name = name; group.position.set(x, y, z); garden.add(group);- const profile = [[radius * 0.58, 0], [radius * 0.77, 0.006], [radius * 0.94, height * 0.83],- [radius, height], [radius * 0.82, height], [radius * 0.75, height * 0.82], [radius * 0.62, 0.018], [0, 0.015]];- const vessel = new T.Mesh(new T.LatheGeometry(profile.map(p => new T.Vector2(...p)), 28), material);- vessel.name = 'ThrownClayPot'; vessel.castShadow = vessel.receiveShadow = true; group.add(vessel);- const dirt = new T.Mesh(new T.CircleGeometry(radius * 0.74, 24), soilMat);- dirt.name = 'VisiblePottingSoil'; dirt.rotation.x = -Math.PI / 2; dirt.position.y = height * 0.81; group.add(dirt);- if (plantName) addHerb(plantName, radius, height, type);- function addHerb(herbName, potRadius, potHeight, variety) {- const herbs = new T.Group(); herbs.name = herbName; herbs.position.y = potHeight * 0.78; group.add(herbs);- const count = variety === 2 ? 9 : 6;- const stemGeo = new T.CylinderGeometry(0.003, 0.004, 1, 5);- const stemMat = new T.MeshStandardMaterial({ color: 0x596541, roughness: 0.94 });- const stems = new T.InstancedMesh(stemGeo, stemMat, count); stems.name = 'HerbStems';- const leafRadius = variety === 2 ? 0.026 : 0.034;- const leafGeo = new T.SphereGeometry(1, 7, 5);- const leafMat = variety === 2 ? leafLight : (variety === 1 ? leafMid : leafDark);- const leafCount = count * (variety === 2 ? 2 : 1);- const leaves = new T.InstancedMesh(leafGeo, leafMat, leafCount); leaves.name = 'HerbLeaves';- const dummy = new T.Object3D(); let leafIndex = 0;- for (let i = 0; i < count; i++) {- const angle = i * 2.39996 + variety * 0.57;- const h = (variety === 1 ? 0.18 : 0.22) + (i % 3) * 0.045;- dummy.position.set(Math.cos(angle) * potRadius * 0.23, h * 0.49, Math.sin(angle) * potRadius * 0.23);- dummy.rotation.set(Math.sin(angle) * 0.19, 0, Math.cos(angle) * 0.19); dummy.scale.set(1, h, 1); dummy.updateMatrix(); stems.setMatrixAt(i, dummy.matrix);- const leafY = h * 0.80, leafX = Math.cos(angle) * potRadius * 0.43, leafZ = Math.sin(angle) * potRadius * 0.43;- dummy.position.set(leafX, leafY, leafZ); dummy.rotation.set(0, -angle, Math.cos(angle) * 0.36);- dummy.scale.set(leafRadius * (variety === 2 ? 0.62 : 0.48), leafRadius * (variety === 2 ? 1.5 : 0.8), leafRadius * 0.34);- dummy.updateMatrix(); leaves.setMatrixAt(leafIndex++, dummy.matrix);- if (variety === 2) {- dummy.position.x += Math.cos(angle + 0.35) * 0.025; dummy.position.y -= 0.04; dummy.rotation.y += 1.0;- dummy.updateMatrix(); leaves.setMatrixAt(leafIndex++, dummy.matrix);- }- }- stems.instanceMatrix.needsUpdate = true; leaves.instanceMatrix.needsUpdate = true;- herbs.add(stems, leaves);- }- return group;- };- const shelves = [- { y: deckY[0], z: -5.05, plants: [[-3.8, 0.22, 0.20, 0], [-1.8, 0.17, 0.19, 1], [1.7, 0.25, 0.23, 2], [3.55, 0.18, 0.19, 0]] },- { y: deckY[1], z: -3.5, plants: [[-3.4, 0.20, 0.23, 1], [-0.9, 0.26, 0.22, 2], [2.6, 0.18, 0.20, 0]] },- { y: deckY[2], z: -1.97, plants: [[-3.7, 0.23, 0.20, 0], [-1.55, 0.16, 0.17, 1], [0.55, 0.21, 0.20, 2], [3.45, 0.18, 0.19, 1]] },- ];- shelves.forEach((shelf, row) => shelf.plants.forEach(([x, r, h, variety], i) => {- const z = shelf.z + ((i % 2) ? 0.19 : -0.08);- addPot(`TerracePot_${row}_${i}`, x, shelf.y, z, r, h, clay[(row + i) % clay.length], `GardenHerb_${row}_${i}`, variety);- }));- // A compact rosemary mound sits just behind the mug, giving the low steam a darker, living backdrop.- const rosemary = new T.Group(); rosemary.name = 'RearTerraceRosemary'; rosemary.position.set(-1.37, deckY[2], -1.98); garden.add(rosemary);- const rosemaryStem = new T.Mesh(new T.CylinderGeometry(0.014, 0.021, 0.22, 7), new T.MeshStandardMaterial({ color: 0x5a4935, roughness: 0.95 }));- rosemaryStem.name = 'RosemaryMainStem'; rosemaryStem.position.y = 0.11; rosemary.add(rosemaryStem);- const rosemaryGeometry = new T.SphereGeometry(1, 8, 6);- const rosemaryDark = new T.InstancedMesh(rosemaryGeometry, leafDark, 27); rosemaryDark.name = 'RosemaryNeedlesDark';- const rosemaryLight = new T.InstancedMesh(rosemaryGeometry, leafLight, 7); rosemaryLight.name = 'RosemaryNeedlesLight';- const rosemaryDummy = new T.Object3D(); let rosemaryDarkIndex = 0, rosemaryLightIndex = 0;- for (let i = 0; i < 34; i++) {- const branch = i % 6, side = Math.floor(i / 6), angle = branch * (Math.PI * 2 / 6) + side * 0.31;- const height = 0.075 + (i % 5) * 0.024, radius = 0.042 + side * 0.018;- rosemaryDummy.position.set(Math.cos(angle) * radius, height, Math.sin(angle) * radius);- rosemaryDummy.rotation.set(Math.sin(angle) * 0.58, -angle, Math.cos(angle) * 0.58);- rosemaryDummy.scale.set(0.042 * 0.26, 0.042 * 1.38, 0.042 * 0.22); rosemaryDummy.updateMatrix();- if (i % 5 === 0) rosemaryLight.setMatrixAt(rosemaryLightIndex++, rosemaryDummy.matrix);- else rosemaryDark.setMatrixAt(rosemaryDarkIndex++, rosemaryDummy.matrix);- }- rosemaryDark.instanceMatrix.needsUpdate = true; rosemaryLight.instanceMatrix.needsUpdate = true;- rosemary.add(rosemaryDark, rosemaryLight);- // Shallow seedling flats and an empty pot make the bench look mid-task; a second small pot sits on the lower shelf.- const tray = box('SeedlingTray', [0.28, 0.025, 0.18], [-0.48, topY + 0.027, tableZ - 0.13], oldPaint, [0, -0.11, 0]);- const seedlingPlugs = new T.InstancedMesh(new T.SphereGeometry(0.018, 7, 5), leafMid, 5);- seedlingPlugs.name = 'SeedlingPlugs'; const seedlingDummy = new T.Object3D();- for (let i = 0; i < 5; i++) {- seedlingDummy.position.set(-0.58 + (i % 3) * 0.075, topY + 0.055, tableZ - 0.18 + Math.floor(i / 3) * 0.075);- seedlingDummy.scale.set(1, 1.7, 1); seedlingDummy.updateMatrix(); seedlingPlugs.setMatrixAt(i, seedlingDummy.matrix);- }- seedlingPlugs.instanceMatrix.needsUpdate = true; garden.add(seedlingPlugs);- addPot('LowerShelfHerbPot', -0.36, 0.417, tableZ, 0.074, 0.082, clay[1], 'SparePottedHerb', 1);- addPot('EmptyBenchPot', -0.34, topY + 0.024, tableZ + 0.205, 0.052, 0.067, clay[2], null, 0);-- // Irregular local stone treads curve through the gravel toward the workbench.- const pavers = [- [-0.76, 5.7, 0.66, 0.44, -0.10], [0.22, 4.95, 0.72, 0.46, 0.05], [-0.32, 4.12, 0.62, 0.43, -0.16],- [0.57, 3.33, 0.74, 0.48, 0.13], [0.12, 2.54, 0.58, 0.42, -0.08],- ];- const treadGeometry = new T.BoxGeometry(1, 1, 1);- const treadBatches = stoneMats.map((material) => new T.InstancedMesh(treadGeometry, material, 2));- const treadIndices = [0, 0, 0]; const treadDummy = new T.Object3D();- pavers.forEach(([x, z, w, d, yaw], i) => {- const materialIndex = i % 3, batch = treadBatches[materialIndex], index = treadIndices[materialIndex]++;- treadDummy.position.set(x, 0.03, z); treadDummy.rotation.set(i % 2 ? 0.018 : -0.012, yaw, 0);- treadDummy.scale.set(w, 0.075, d); treadDummy.updateMatrix(); batch.setMatrixAt(index, treadDummy.matrix);- });- treadBatches.forEach((batch, i) => { batch.count = treadIndices[i]; batch.name = `GardenTreads_${i}`; batch.instanceMatrix.needsUpdate = true; batch.castShadow = batch.receiveShadow = true; garden.add(batch); });- const pebbleGeometry = new T.DodecahedronGeometry(0.045, 0);- const pebbleBatches = stoneMats.map((material) => new T.InstancedMesh(pebbleGeometry, material, 3));- for (let i = 0; i < 9; i++) {- const materialIndex = i % 3, batch = pebbleBatches[materialIndex], index = Math.floor(i / 3);- treadDummy.position.set(-1.42 + (i % 3) * 0.16, 0.018, 1.2 + i * 0.42);- treadDummy.rotation.set(0, i * 0.6, 0); treadDummy.scale.set(1.3, 0.54, 0.9); treadDummy.updateMatrix(); batch.setMatrixAt(index, treadDummy.matrix);- }- pebbleBatches.forEach((batch, i) => { batch.name = `PathEdgePebbles_${i}`; batch.instanceMatrix.needsUpdate = true; batch.castShadow = batch.receiveShadow = true; garden.add(batch); });-- const animated = [birch, steam];- return {- scene,- cameras: [- { name: 'WorkbenchGarden', position: [4.6, 2.95, 6.4], lookAt: [0, 1.02, -1.9], fov: 43 },- { name: 'SteamAndCup', position: [0.82, 1.18, 2.10], lookAt: [0.23, 1.02, 1.03], fov: 38 },- { name: 'BirchTerrace', position: [-5.8, 2.85, 5.4], lookAt: [-0.8, 1.05, -2.25], fov: 45 },- ],- update(t) { for (const item of animated) item.userData.update(t); },- };-}diff --git a/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.provenance.json b/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.provenance.jsondeleted file mode 100644index 2325174a..00000000--- a/harness/examples/graphics_lab/agent_cases/luna_garden_workbench.provenance.json+++ /dev/null@@ -1,22 +0,0 @@-{- "model": "gpt-6-luna",- "authoring_channel": "delegated coding agent; not vendor CLI or harness run",- "review_iteration": 2,- "brief": "Early-morning garden workbench with a ceramic mug giving off subtle backlit steam, a birch framing one side, a planted stone terrace and restrained natural materials. Prioritize a convincing scene and readable motion over a feature grid.",- "modifications": [- "Rebuilt the bench and mug to real dimensions (about 1.45 m by 0.54 m and 0.85 m high; mug about 9 cm wide), with weathered wood and procedural stone, soil, clay and foliage materials.",- "Varied the planted pots and terrace stone courses, added mortar gaps and small joinery and wear details, and reframed the close view to keep the steam near the cup against garden structure.",- "Rendered successive review iterations, inspected the wide and close views, and tuned the steam volume and backlight for visible motion while preserving the small mug scale.",- "Batched repeated plants, stones and small path details with InstancedMesh after census review to keep the scene compact."- ],- "testing": {- "command": "node runtime_js/render_scene.mjs --ws /tmp/graphics-seven-hour/luna-workbench --out /tmp/graphics-seven-hour/luna-workbench/renders/final --times 0,1.5,3 --width 1280 --height 720 --fps-seconds 0 --no-settle",- "result": "9 authored-camera GPU frames rendered; zero console errors, shader errors, update errors or host warnings. Scene census: 1,161,394 triangles, 133 meshes, 14,897 instances and 40 materials.",- "staging": "Temporary workspace contains a copy of this scene and a frozen copy of the shipped scene_threejs src/lib modules."- },- "library_usability_notes": [- "At real cup scale, makeSteam is a soft, low-contrast volume against an open dawn sky; the close view, dark garden backing and tuned local backlight are needed to make its motion apparent.",- "The steam volume has no opaque-scene depth integration, so avoid intersecting geometry and overlapping transparent volumes."- ],- "visual_limitations": "The scene remains a stylized procedural garden. The steam reads as a soft, backlit wisp in the close view and is subtle in the wide establishing shot."-}diff --git a/harness/examples/graphics_lab/agent_cases/prompt.md b/harness/examples/graphics_lab/agent_cases/prompt.mddeleted file mode 100644index 4155fa83..00000000--- a/harness/examples/graphics_lab/agent_cases/prompt.md+++ /dev/null@@ -1,8 +0,0 @@-You are an independent coding agent testing a Three.js procedural graphics library. Work only in this workspace. Read effects_catalog.md, contract.md, and actual src/lib module JSDoc before using any factory. Do not read or copy the other hand-authored examples in the parent harness. Keep the supplied src/lib read-only. All generated code, names, comments and prose must be English.--Create TWO complete scene modules at src/scenes/luna_candle_courtyard.js and src/scenes/luna_coastal_creek.js, importing library modules from ../lib/. Each exports createScene({THREE,renderer,loaders}) and returns {scene,cameras:[{name,position,lookAt,fov}],update(t,dt)}. Do not modify renderer settings or postprocessing. Update each moving factory once per frame via userData.update(t,dt). Dimensions in metres, seeded variations, no external assets, images or Blender.--1. An intimate stone courtyard at dusk. A weathered wood table has a small group of realistically sized beeswax candles using makeCandle. Nearby is a restrained fire bowl using makeFire. Detailed believable materials and props, clear close and wide cameras. Candle flames and warm light should have a beautiful photographic composition, not giant featureless primitive props.-2. A bright coastal creek through windblown grass, sand and weathered rocks. Use makeStream, makeMeadow, makeSandTerrain and makeRock, optionally a distant ocean only if it serves the composition. Carve terrain below the channel, align slopes, seat props correctly, avoid water/terrain clipping. Two clear cameras, natural material and organic detail. Do not leave a giant empty plane or rectangular grass slabs.--Use the supplied material/noise/shader/environment helpers as appropriate. Prioritize a polished functioning result. You may render/debug by temporarily writing src/scene.js reexporting each module, then running node /home/yipeng/3dcodeverse/harness/runtime_js/render_scene.mjs --ws YOUR_WORKSPACE --out YOUR_WORKSPACE/renders/CASE --width 1280 --height 720 --times 0,2 --fps-seconds 0 --no-settle. Read render_scene.mjs --help if needed. Inspect the images if your tools permit it, fix runtime failures. Do not modify any other workspace/library. Finish with a concise English README.md describing actual checks, library integration issues and visual limitations. No API calls, commits, new dependencies, or unrelated work. The supervising agent will check and integrate your final source. Aim to finish within ten minutes.diff --git a/harness/examples/graphics_lab/agent_cases/provenance.json b/harness/examples/graphics_lab/agent_cases/provenance.jsondeleted file mode 100644index 319ae8c5..00000000--- a/harness/examples/graphics_lab/agent_cases/provenance.json+++ /dev/null@@ -1,93 +0,0 @@-{- "date": "2026-09-22",- "requested_model": "gpt-6-luna",- "runner": "Codex CLI, independent workspace",- "generation_invocations": 2,- "protocol": "Initial generation, then supervisor render feedback and model revision. Source copied unchanged from the second invocation. Not a controlled model comparison or a full harness plan/judge run.",- "sources": {- "luna_candle_courtyard": {- "initial_sha256": "c62775a3569f11d0c4658b90fec1fe70af26d3b9cfc9265fe77dd0fe8cc99f79",- "retained_sha256": "9e1e6b611fc209edeab03276b8a01b9388a2ffcf8e38c9f5b487ec8b9331cf12"- },- "luna_coastal_creek": {- "initial_sha256": "61843dd04d9ba23e782649d03959f89d5c8fbba75e49f7104e19ed7fba918556",- "retained_sha256": "8ba3e6647b91d4c240dedce45535e23bdc4d8bee514811ab7b9905366e234b91"- }- },- "turns": [- {- "log": "../output/agent_runs/luna_examples/session.jsonl",- "completed": true,- "usage": {- "input_tokens": 1080500,- "cached_input_tokens": 986624,- "cache_write_input_tokens": 0,- "output_tokens": 14554,- "reasoning_output_tokens": 4980- }- },- {- "log": "../output/agent_runs/luna_examples/repair-session.jsonl",- "completed": true,- "usage": {- "input_tokens": 3313742,- "cached_input_tokens": 3207168,- "cache_write_input_tokens": 0,- "output_tokens": 24471,- "reasoning_output_tokens": 12910- }- }- ],- "library_sha256": {- "accumulation.js": "6fdb4449f75132cf6d8e557cea657f4295ba1c08c5a3db17ce8985a6300219e7",- "aging.js": "b5a0f5e7136c94da8723d66dc3ddb692882c28d7e752cd2aa4fbc9681b58d0b7",- "atmosphere.js": "4659d8aebe8d4e75373c2f55ed3877b17ec3e5d2c0db124c87ad4f65c97a3dba",- "building.js": "42080b46ca6eb64aba20fa0f477f26939fc06415ddb61030d30ba24342c825ee",- "canopy.js": "c4bc1791fa38ca5e884af5edb4b6a61b083ef308ab317cd005e97d0e61e0a91a",- "caustics.js": "b8852853776234032b0c1014bbdc0eb0d56e57f34c6ec627349c2bbdea3fe3f7",- "celestial.js": "7b7260fe1ec6890c6e698f01aba206af71f189af84643c986d9c700e54da98a9",- "cloth.js": "e4be1bcba5586d418168e76b9e74c4dad7dd90fbd0dfeda77ab78b45ad4eede1",- "clouds.js": "9e3efd36f28990174e068e4fcb8fa1c268e023eec3af67a8b976bd8f924e7a56",- "damp.js": "fe71562b9f824eeca83d410f07db5283170c75ec57b708e37a1a712dff051486",- "dapple.js": "353acf08b1a2124243d709d8c5cc8482186cef36636def2311fec28fb43675f7",- "environment.js": "5b5c25d028a2f742290c159840dcd3f4292dc8b7b82dbd73b8ab7e1756855569",- "figure.js": "bfeafc699c5e386ff19d0040f2e5598d7653842d2509a0bccee013c2eb527950",- "finish.js": "f5b8b6937b1da011c64490195f3fdc668d1f5ad658a2c59421f2e764ec16e8ce",- "fire.js": "45401761623fe1414063f9c01da1440bec513d20356767230c08f608c414195a",- "flock.js": "920d1e40acf6d8af0515e63fa2854aa302d6048404a7d6d87db579608b40e570",- "flowers.js": "9784465dfbbcd4491694fac3b4bdbe07a3e31b2891f37e605da15d309cb7f3b0",- "foliage_shade.js": "2c4ad45539b733ca8999f5a3d3907218dadd91e7712db8960ea700766153efc0",- "godrays.js": "984078c965f076f9c9bb59ff79eca788f850a288b6581328af01b0cd140a84a3",- "grass.js": "c79a971e71ff09da06e260cf8457d2e75dab3b4365032835e350bbaae884c675",- "instancing.js": "3056ec2877b4f8812898bc9c30aac5cf5cf54284c03ebdd5cca3794ce7a32edf",- "materials.js": "3c7039f63c4796b61154a9cd157460261300f68494622d806dc580d88795837d",- "meadow.js": "2ab3ed685cbfd4e844437e522f198ca7a6db05a58dc277866cdd2f030935a181",- "merge.js": "c479e78422290ee35fac831c2496ef9d5d1c6f6f0287be5aa294cdda6cb386cd",- "neon.js": "d57a0dafe22dc1bce8084c6b9633ea311239bc1a0ff86a9c15f16309362b5bad",- "noise.js": "150a5a5edf06e8653cdd8e74a7fc42ba83c6453a2a846760162b8abdcf90467d",- "ocean.js": "3edf78fd18f7dcb1707ffe2ae9757adab75f1f8627dfbacf010b5319085751e2",- "place.js": "e1c97ebcbf14e3a04fb3acb6ffdca971ca37f39c7a66c888f6823b8b7202f021",- "rain.js": "2bf395659cf79b0860cfb94f85e5980922cec8136500e0c28a5f2d3007e2e63e",- "roadway.js": "48a2c033970cce211bb0958df6ed0f9f7ab0c232f20ac49c52f1ec400551c060",- "rock.js": "2f2b35c43194badc105f0e1eb82b4307e22f5204be1765570bbc398df65f777c",- "sand.js": "6ecc57b46b0b0b155985210499939e4897d03fc213b726ddba442b8a696c153a",- "shader.js": "607004c07cd91b6346eda6cb28b2467ca8bb08dddd646f2208741e0827c75adb",- "signage.js": "031f70ec0420a543a64a4febe34278299c9d34ea2891434965b3a557e9020b15",- "sky.js": "0729b4ea803907ca3e4ba22a8a4e16d7a8d7492df63a2c65dd22788e58af4f97",- "smalllife.js": "d52b561ac2636333d00ac011d67d4d1388f59204755cc7556b0ca8c3b64e97d8",- "strata.js": "aa208ab62bf40d13342448028949368aaa2e5e3b2c8a98ede34f222f4e7bd71a",- "stream.js": "0e476fab53c1df925a559f591223b600b7081502308ba52c9dd5b595a21b31bf",- "submerged.js": "71b7cc71e8832f03fc105c5162176b372c2e52342315866f34610b6abee5b860",- "surface_wear.js": "b24d869fb40f31eff402c68886949e1c2c05f3e876d75a01fbd238eb930f6912",- "terrain.js": "20607158f9286b2c802ec54ad3611a17d39456a6b7b0f19e944e3531f8172a68",- "terrain_shade.js": "4708709264744d610d643aac56023c386075b54a8a77816d6ef713b84c560e77",- "urban.js": "d6b76b6616b53a88350e581606d59f9edce93c764086e3e37fbe93eb4641aa51",- "veils.js": "f9b1ae68d5b510019f6e1779b48098d99ff9443f75c7558f14296bedc3f98597",- "water.js": "ef35be78ea5e943706c4e0988bdb0fa77d9706a270bfc5655d88cf4834f26309",- "watermist.js": "b25fa071ff4ce8e422bd0fe60e8a897d0078d26db3da2106a92038438e608372",- "waterside.js": "2911a46298f6fc7d040ea0e5f8a5b5a179287aad41179d1d3e825b94ee8b2b8c",- "wetground.js": "6f2a68381f005e43b6390287efb7bff76d9d107f0c82df5d1d0c61bb59d0d7f0",- "windows.js": "7f6806b81d028e8d50cd63cc8e7a7dd33ef7f0185c1c08556c561c6c2694dee8",- "woodland.js": "8278f9dcedf878cf7a5e78aa4a61e2146624a1fccbfafadb6e9bb9395a803862"- }-}diff --git a/harness/examples/graphics_lab/build.py b/harness/examples/graphics_lab/build.pyindex 7918bf51..f42b0d1e 100644--- a/harness/examples/graphics_lab/build.py+++ b/harness/examples/graphics_lab/build.py@@ -6,7 +6,6 @@ The default output is ignored by git. No provider calls or external downloads.from __future__ import annotationsimport argparse-import hashlibimport jsonimport shutilimport subprocess@@ -16,7 +15,6 @@ HERE = Path(__file__).resolve().parentHARNESS = HERE.parents[1]LIB = HARNESS / "codeverse3d/languages/scene_threejs/starter/src/lib"SHADER_SUFFIXES = {".glsl", ".vert", ".frag"}-SOURCE_SUFFIXES = {".js", ".mjs", *SHADER_SUFFIXES}CASES = (("fire", "01", "Fire & candlelight", "Volumetric flames · Wax and embers", "flame"),("ocean", "02", "Open water", "Displaced waves · Reflections and whitecaps", "water"),@@ -34,101 +32,9 @@ CASES = (("campfire", "14", "Fire in the clearing", "Campfire and bonfire · Char, embers and rising smoke", "flame"),("structural_fire", "15", "Fire through a structure", "Window and roof flames · Opaque-depth intersections", "flame"),("external_shader", "16", "Light on alloy", "External GLSL · An animated material study", "shader study"),- ("luna_candle_courtyard", "A1", "Candle courtyard", "GPT-6 Luna · Independent agent case", "agent study"),- ("luna_coastal_creek_refined", "A2", "Coastal creek", "GPT-6 Luna · Reviewed agent refinement", "agent study"),- ("luna_garden_workbench", "A3", "Garden workbench", "GPT-6 Luna · Independent agent case", "agent study"),)-def digest(data: bytes) -> str:- return hashlib.sha256(data).hexdigest()---def source_hashes(root: Path, suffixes: set[str] = SOURCE_SUFFIXES) -> dict[str, str]:- return {p.relative_to(root).as_posix(): digest(p.read_bytes())- for p in sorted(root.rglob("*")) if p.is_file() and p.suffix in suffixes}---def workspace_hashes(case: dict, library: dict[str, str],- shaders: dict[str, str] | None = None) -> dict[str, str]:- key = case["id"]- wrapper = f"export {{createScene}} from './scenes/{key}.js';\n"- return {**{f"lib/{name}": value for name, value in library.items()},- **{f"shaders/{name}": value for name, value in (shaders or {}).items()},- f"scenes/{key}.js": case["scene_sha256"], "scene.js": digest(wrapper.encode())}---def has_media(out: Path) -> bool:- """Comparisons/packages carry their own snapshots and are not restaged here."""- if not out.is_dir():- return False- suffixes = {".png", ".jpg", ".jpeg", ".webp", ".mp4", ".webm"}- return any(p.is_file() and (p.suffix.lower() in suffixes or p.name.endswith(".capture.json"))- for p in out.iterdir()) or any(p.is_file() for p in (out / "renders").rglob("*"))---def guard_media(out: Path, manifest: dict) -> None:- """Reject changed or already inconsistent sources before touching old media."""- if not has_media(out):- return-- def stale(reason: str) -> None:- raise ValueError(f"Refusing stale source/media mixture in {out}: {reason}. "- "Choose a new --out directory for changed sources and render/capture there; "- "unchanged incremental --case runs remain supported.")-- published = out / "manifest.json"- if not published.is_file():- stale("existing media has no source manifest")- try:- previous = json.loads(published.read_text(encoding="utf-8"))- old_cases = previous["cases"]- old_library = previous["library_sha256"]- if (not isinstance(old_cases, list) or not all(isinstance(case, dict) for case in old_cases)- or not isinstance(old_library, dict)):- raise ValueError("invalid manifest shape")- except (ValueError, KeyError, TypeError) as exc:- stale(f"the previous manifest cannot be verified ({exc})")- if old_library != manifest["library_sha256"]:- stale("shared library contents changed")- shaders = manifest.get("shader_sha256", {})- if previous.get("shader_sha256", {}) != shaders:- stale("external shader contents changed")- current = {case["id"]: case for case in manifest["cases"]}- for old in old_cases:- key = old.get("id")- if key not in current or old.get("scene_sha256") != current[key]["scene_sha256"]:- stale(f"scene {key!r} changed or was removed")- # Also catch an output previously corrupted by an unsafe restage. Do not- # silently repair its code while leaving its old video in place.- expected_library = manifest["library_sha256"]- actual_library = {p.name: digest(p.read_bytes()) for p in (out / "src/lib").glob("*.js")}- if actual_library != expected_library:- stale("published library files disagree with their manifest")- if source_hashes(out / "src/shaders", SHADER_SUFFIXES) != shaders:- stale("published shader files disagree with their manifest")- for old in old_cases:- key = old["id"]- scene = out / "src/scenes" / f"{key}.js"- if not scene.is_file() or digest(scene.read_bytes()) != current[key]["scene_sha256"]:- stale(f"published scene {key!r} disagrees with its manifest")- workspace = out / "cases" / key / "src"- if workspace.is_dir():- actual = source_hashes(workspace)- if actual != workspace_hashes(current[key], expected_library, shaders):- stale(f"staged workspace {key!r} disagrees with published sources")- expected_workspaces = [workspace_hashes(case, expected_library, shaders) for case in current.values()]- for sidecar in out.glob("*.capture.json"):- try:- capture = json.loads(sidecar.read_text(encoding="utf-8"))- except (ValueError, OSError) as exc:- stale(f"capture record {sidecar.name} cannot be read ({exc})")- if not isinstance(capture, dict):- stale(f"capture record {sidecar.name} is not an object")- if "source_sha256" in capture and capture["source_sha256"] not in expected_workspaces:- stale(f"capture-time sources in {sidecar.name} disagree with current sources")--def write_source_tree(root: Path, files: dict[str, bytes]) -> None:"""Replace generated source only, removing obsolete staged modules as well."""if root.exists():@@ -144,30 +50,21 @@ def stage(out: Path, selected: list[str]) -> list[dict]:unknown = set(selected) - {case[0] for case in CASES}if unknown:raise ValueError(f"Unknown showcase cases: {', '.join(sorted(unknown))}")- # Read a complete snapshot before any output mutation. Concurrent source- # edits cannot make copied workspaces disagree with the recorded hashes.library_files = {p.name: p.read_bytes() for p in sorted(LIB.glob("*.js"))}if not library_files:raise FileNotFoundError(f"Showcase library missing or empty: {LIB}")- library_hashes = {name: digest(data) for name, data in library_files.items()}shader_root = HERE / "shaders"shader_files = {p.relative_to(shader_root).as_posix(): p.read_bytes()for p in sorted(shader_root.rglob("*"))if p.is_file() and p.suffix in SHADER_SUFFIXES}- shader_hashes = {name: digest(data) for name, data in shader_files.items()}cases, sources = [], {}for key, number, title, subtitle, kind in CASES:- source = HERE / ("agent_cases" if number.startswith("A") else "scenes") / f"{key}.js"+ source = HERE / "scenes" / f"{key}.js"if not source.is_file():raise FileNotFoundError(f"Showcase scene missing: {source}")sources[key] = source.read_bytes()cases.append({"id": key, "number": number, "title": title, "subtitle": subtitle,- "kind": kind, "module": f"./src/scenes/{key}.js",- "scene_sha256": digest(sources[key]),- "source_kind": "agent" if number.startswith("A") else "library_study"})- assets = {name: (HERE / name).read_bytes() for name in ("index.html", "viewer.js", "viewer.css")}- manifest = {"cases": cases, "library_sha256": library_hashes, "shader_sha256": shader_hashes}- guard_media(out, manifest)+ "kind": kind, "module": f"./src/scenes/{key}.js"})shared = {**{f"lib/{name}": data for name, data in library_files.items()},**{f"shaders/{name}": data for name, data in shader_files.items()}}write_source_tree(out / "src", {**shared, **{f"scenes/{key}.js": data for key, data in sources.items()}})@@ -177,22 +74,17 @@ def stage(out: Path, selected: list[str]) -> list[dict]:**shared, f"scenes/{key}.js": sources[key],"scene.js": f"export {{createScene}} from './scenes/{key}.js';\n".encode(),})- for name, data in assets.items():- (out / name).write_bytes(data)- if (out / "comparison.html").is_file():- index = out / "index.html"- index.write_text(index.read_text().replace('<!--COMPARISON_LINK-->',- '<p><a href="./comparison.html">Compare library refinements ↗</a></p>'))- (out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False))+ for name in ("index.html", "viewer.js", "viewer.css"):+ (out / name).write_bytes((HERE / name).read_bytes())+ (out / "manifest.json").write_text(json.dumps({"cases": cases}, indent=2, ensure_ascii=False))return [case for case in cases if not selected or case["id"] in selected]def overview(out: Path) -> None:- """A contact sheet of available manual studies, using actual rendered frames."""+ """A contact sheet of the available studies, using actual rendered frames."""from PIL import Image, ImageDraw, ImageFont- studies = [case for case in CASES if case[4] != "agent study"- and (out / f"{case[0]}.png").is_file()]+ studies = [case for case in CASES if (out / f"{case[0]}.png").is_file()]if not studies:returnrows = (len(studies) + 2) // 3diff --git a/harness/examples/graphics_lab/build_recipes.py b/harness/examples/graphics_lab/build_recipes.pyindex 90e376e0..225b863f 100644--- a/harness/examples/graphics_lab/build_recipes.py+++ b/harness/examples/graphics_lab/build_recipes.py@@ -1,12 +1,11 @@"""Render the standalone GLSL recipe studies through the production GL host.python examples/graphics_lab/build_recipes.py [--video] [--case rain_window]-All source dependencies and hashes are retained beside the rendered evidence.+The study shader and the recipes it uses are copied beside the renders."""from __future__ import annotationsimport argparse-import hashlibimport htmlimport jsonimport re@@ -27,7 +26,7 @@ TITLES = {"rain_window": "Rain on glass", "material_light": "Material and movingdef build(out: Path, selected: list[str], video: bool) -> dict:out.mkdir(parents=True, exist_ok=True)known = cookbook_functions(load_text("glsl_shader/cookbook.md"))- manifest = {"source_kind": "authored_recipe_study", "cases": []}+ manifest = {"cases": []}host = GlHost(timeout_s=240)cards = []for key, title in TITLES.items():@@ -68,9 +67,7 @@ def build(out: Path, selected: list[str], video: bool) -> dict:if encoder.wait():raise RuntimeError(f"{key}: video encoder failed")record = {"id": key, "title": title, "renderer": result.renderer, "gpu": result.gpu,- "frames": len(result.frames), "render_ms": result.duration_ms,- "source_sha256": {"shader.frag": hashlib.sha256(source.encode()).hexdigest(),- "recipes.glsl": hashlib.sha256(recipes.encode()).hexdigest()}}+ "frames": len(result.frames), "render_ms": result.duration_ms}manifest["cases"].append(record)media = (f'<video controls loop playsinline poster="{key}/preview.png" src="{key}/film.mp4"></video>'if video else f'<img src="{key}/preview.png" alt="{html.escape(title)}">')@@ -91,7 +88,7 @@ Rendered locally with the production OpenGL host. Source and dependencies are inif __name__ == "__main__":parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--out", type=Path, default=HERE / "output/seven-hour/recipes")+ parser.add_argument("--out", type=Path, default=HERE / "output/recipes")parser.add_argument("--case", action="append", choices=list(TITLES), default=[])parser.add_argument("--video", action="store_true")args = parser.parse_args()diff --git a/harness/examples/graphics_lab/capture.mjs b/harness/examples/graphics_lab/capture.mjsindex 1a83ab0c..85034934 100644--- a/harness/examples/graphics_lab/capture.mjs+++ b/harness/examples/graphics_lab/capture.mjs@@ -4,7 +4,6 @@ import fs from 'node:fs';import path from 'node:path';import {spawn} from 'node:child_process';import {parseArgs} from 'node:util';-import {createHash} from 'node:crypto';import {openHost} from '../../runtime_js/lib/host_page.mjs';const {values:a} = parseArgs({options:{ws:{type:'string'},out:{type:'string'},ffmpeg:{type:'string',default:'ffmpeg'},width:{type:'string',default:'1280'},@@ -19,20 +18,6 @@ for (const size of [Number(a.width), Number(a.height)]) {throw new Error('H.264 width and height must be even integers from 2 to 8192');}}-function sourceHashes() {- const root=path.join(path.resolve(a.ws),'src'), hashes={};- function visit(directory) {- for (const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((x,y)=>x.name.localeCompare(y.name))) {- const file=path.join(directory,entry.name);- if(entry.isDirectory()) visit(file);- else if(entry.isFile() && /\.(?:m?js|glsl|vert|frag)$/.test(entry.name)) {- hashes[path.relative(root,file).split(path.sep).join('/')]=createHash('sha256').update(fs.readFileSync(file)).digest('hex');- }- }- }- visit(root);return hashes;-}-const capturedSource=sourceHashes();const host = await openHost(a.ws,{width:Number(a.width),height:Number(a.height),gpu:'auto',post:true,settle:false,createSceneTimeoutMs:60000});let encoder;@@ -50,22 +35,10 @@ try {encoder.stdin.on('error', error => { encoderError = error; });const done = new Promise(resolve => encoder.once('close', resolve));const timings=[];- const referenceFrames=[];- const referenceIndices=new Set([0,Math.floor(count/3),Math.floor(count*2/3)]);- const referenceDirectory=path.join(path.dirname(path.resolve(a.out)),- 'capture_frames',path.basename(a.out,'.mp4'));- fs.mkdirSync(referenceDirectory,{recursive:true});for (let i=0;i<count;i++) {const frame=await host.page.evaluate((spec,t)=>window.__c3v.renderAt(spec,t),camera,i/fps);timings.push(frame.ms);const png=Buffer.from(frame.dataUrl.split(',')[1],'base64');- if(referenceIndices.has(i)) {- const file=path.join(referenceDirectory,`frame_${String(i).padStart(4,'0')}.png`);- fs.writeFileSync(file,png);- referenceFrames.push({index:i,time_s:i/fps,- path:path.relative(path.dirname(path.resolve(a.out)),file).split(path.sep).join('/'),- sha256:createHash('sha256').update(png).digest('hex')});- }if (encoderError) throw encoderError;await new Promise((resolve, reject) => {encoder.stdin.write(png, error => error ? reject(error) : resolve());@@ -78,16 +51,12 @@ try {if (host.errors.console.length || host.errors.page.length || host.errors.shader_console.length) {throw new Error(JSON.stringify(host.errors));}- if(JSON.stringify(capturedSource)!==JSON.stringify(sourceHashes())) throw new Error('Scene source changed during capture');const summary={ok:true,frames:count,fps,seconds:count/fps,camera:camera.name,gpu:host.gpu,renderer:host.boot.renderer,width:Number(a.width),height:Number(a.height),console_errors:host.errors.console,shader_errors:host.errors.shader_console,- source_sha256:capturedSource,- video_sha256:createHash('sha256').update(fs.readFileSync(a.out)).digest('hex'),- reference_frames:referenceFrames,render_ms_mean:timings.reduce((s,t)=>s+t,0)/count};fs.writeFileSync(a.out.replace(/\.mp4$/i,'.capture.json'),JSON.stringify(summary,null,2));- console.log(JSON.stringify({...summary,source_sha256:undefined,source_files:Object.keys(capturedSource).length}));+ console.log(JSON.stringify(summary));} finally {if (encoder && encoder.exitCode===null) encoder.kill();await host.close();diff --git a/harness/examples/graphics_lab/check.mjs b/harness/examples/graphics_lab/check.mjsdeleted file mode 100644index 17a726f7..00000000--- a/harness/examples/graphics_lab/check.mjs+++ /dev/null@@ -1,152 +0,0 @@-#!/usr/bin/env node-/** Exercise the staged gallery through its real browser controls. */-import fs from 'node:fs';-import path from 'node:path';-import assert from 'node:assert/strict';-import {createRequire} from 'node:module';-import {fileURLToPath} from 'node:url';-import {parseArgs} from 'node:util';-import {launchBrowser} from '../../runtime_js/lib/host_env.mjs';-import {releaseBrowser} from '../../runtime_js/lib/host_page.mjs';-const require = createRequire(import.meta.url);-const {serveDirs} = require('../../runtime_js/serve.cjs');-const here = path.dirname(fileURLToPath(import.meta.url));-const {values} = parseArgs({options: {out: {type: 'string', default: path.join(here, 'output')}}});-const root = path.resolve(values.out);-// Include comments and documentation, not just currently visible UI text.-const sourceExtensions = new Set(['.js', '.mjs', '.py', '.html', '.css', '.md', '.glsl', '.vert', '.frag']);-let englishFilesChecked = 0;-function checkEnglish(directory) {- for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {- if (['.git', 'node_modules', '__pycache__'].includes(entry.name)) continue;- const file = path.join(directory, entry.name);- if (entry.isDirectory()) checkEnglish(file);- else if (entry.isFile() && sourceExtensions.has(path.extname(entry.name))) {- assert(!/\p{Script=Han}/u.test(fs.readFileSync(file, 'utf8')), `Non-English example: ${file}`);- englishFilesChecked++;- }- }-}-checkEnglish(here);-if (!root.startsWith(here + path.sep)) checkEnglish(root);-const server = await serveDirs({root, routes: {- '/': {body: fs.readFileSync(path.join(root, 'index.html'), 'utf8')},- '/favicon.ico': {body: ''},-}});-const launched = await launchBrowser({gpu: 'auto'});-let page;-const errors = [], results = [];-try {- page = await launched.browser.newPage();- await page.setViewport({width: 1440, height: 1000, deviceScaleFactor: 1});- page.on('pageerror', error => errors.push(error.message));- page.on('console', message => {- if (message.type() === 'error') errors.push(message.text());- });- page.on('response', response => {- if (response.status() >= 400) errors.push(`${response.status()} ${response.url()}`);- });- await page.goto(server.base, {waitUntil: 'networkidle0'});- await page.waitForFunction(() => !!window.graphicsLab);- const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json')));- assert.equal(await page.$$eval('.card', cards => cards.length), manifest.cases.length);- assert.equal(await page.evaluate(() => document.documentElement.lang), 'en');- await page.screenshot({path: path.join(root, 'gallery.png'), fullPage: true});-- for (let index = 0; index < manifest.cases.length; index++) {- const item = manifest.cases[index];- console.log(`Checking ${item.id}`);- await page.click(`.card:nth-child(${index + 1})`);- const videoExists = fs.existsSync(path.join(root, `${item.id}.mp4`));- if (videoExists) {- await page.waitForFunction(() => document.querySelector('#video').readyState >= 2);- const video = await page.evaluate(async () => {- const element = document.querySelector('#video');- element.muted = true;- await element.play();- return {width: element.videoWidth, height: element.videoHeight, duration: element.duration};- });- assert(video.width > 0 && video.height > 0 && video.duration > 0);- }- await page.click('#explore');- await page.waitForFunction(() => !!window.graphicsLab.active && !document.querySelector('#status').textContent,- {timeout: 60000});- await page.waitForFunction(() => window.graphicsLab.time > .1);- await page.click('#pause');- const paused = await page.evaluate(() => window.graphicsLab.time);- // Two rendered browser frames must leave simulation time unchanged while paused.- await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));- assert.equal(await page.evaluate(() => window.graphicsLab.time), paused);- await page.$eval('#time', slider => {- slider.value = '2.5';- slider.dispatchEvent(new Event('input', {bubbles: true}));- });- assert.equal(await page.evaluate(() => window.graphicsLab.time), 2.5);- const cameras = await page.$$eval('#camera option', options => options.map(option => option.value));- for (const camera of cameras) {- await page.select('#camera', camera);- await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));- }- await page.select('#camera', '0');- await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));- const screen = await page.$('#canvas');- await screen.screenshot({path: path.join(root, `${item.id}.live.png`)});- const canvasOk = await page.$eval('#canvas', canvas => {- const gl = canvas.getContext('webgl2');- return !!gl && !gl.isContextLost() && canvas.width > 0 && canvas.height > 0;- });- assert(canvasOk, `${item.id}: live WebGL context lost`);- await page.click('#watch');- await page.click('#explore');- await page.waitForFunction(() => window.graphicsLab.time > 2.5);- await page.click('#close');- assert.equal(await page.evaluate(() => !!window.graphicsLab.active), false);- results.push({case: item.id, cameras: cameras.length, video: videoExists, controls: 'pass'});- }- // Cancelling a boot must not resurrect the old scene after returning to the gallery.- await page.evaluate(async () => {- document.querySelector('.card').click();- const loading = window.graphicsLab.explore();- document.querySelector('#close').click();- await loading;- });- assert.equal(await page.evaluate(() => !!window.graphicsLab.active), false);- assert.equal(await page.evaluate(() => /\p{Script=Han}/u.test(document.body.innerText)), false);- let comparisons = 0;- if (fs.existsSync(path.join(root, 'comparison.html'))) {- await page.goto(`${server.base}/comparison.html`, {waitUntil: 'networkidle0'});- await page.waitForFunction(() => [...document.images].every(image => image.complete && image.naturalWidth > 0));- const comparisonManifest = path.join(root, 'comparison', 'manifest.json');- assert(fs.existsSync(comparisonManifest), 'Comparison page has no artifact manifest');- const records = JSON.parse(fs.readFileSync(comparisonManifest, 'utf8'));- assert(Array.isArray(records) && records.length > 0, 'Comparison manifest has no pairs');- const actualPairs = await page.$$eval('.compare', elements => elements.map(element =>- [...element.querySelectorAll('img')].map(image => image.getAttribute('src'))));- comparisons = actualPairs.length;- assert.equal(comparisons, records.length, 'Comparison page and artifact manifest disagree');- for (let index = 0; index < records.length; index++) {- const expected = ['before', 'after'].map(variant => records[index].variants?.[variant]?.image);- assert(expected.every(image => typeof image === 'string'), 'Comparison pair has missing images');- assert.deepEqual(actualPairs[index], expected, `Wrong comparison images for ${records[index].case}`);- for (const relative of expected) {- const image = path.resolve(root, relative);- assert(image.startsWith(root + path.sep) && fs.existsSync(image), `Missing comparison artifact: ${relative}`);- }- }- await page.$$eval('input[type="range"]', inputs => inputs.forEach(input => {- input.value = '27'; input.dispatchEvent(new Event('input', {bubbles: true}));- }));- assert(await page.$$eval('.compare', elements => elements.every(element => element.style.getPropertyValue('--split') === '27%')));- assert.equal(await page.evaluate(() => document.documentElement.lang), 'en');- await page.screenshot({path: path.join(root, 'comparison-page.png'), fullPage: true});- }- assert.deepEqual(errors, []);- const report = {ok: true, gpu: launched.gpu, renderer: launched.renderer,- englishFilesChecked, cases: results, comparisons, errors};- fs.writeFileSync(path.join(root, 'browser-check.json'), JSON.stringify(report, null, 2));- console.log(JSON.stringify(report));-} finally {- await page?.close();- await releaseBrowser(launched);- await server.close();-}diff --git a/harness/examples/graphics_lab/compare.py b/harness/examples/graphics_lab/compare.pydeleted file mode 100644index 0edac75b..00000000--- a/harness/examples/graphics_lab/compare.py+++ /dev/null@@ -1,107 +0,0 @@-"""Render controlled library comparisons from an immutable baseline workspace set.--Each baseline/<case>/src tree is copied twice. Only the named library module is-replaced in the second copy; scene, camera, lighting and all other modules stay-byte-identical. No provider calls or external assets are used.-"""-from __future__ import annotations--import argparse-import hashlib-import json-import shutil-import subprocess-from pathlib import Path--from build import HARNESS, HERE, LIB--CASES = (- ('ocean', 'ocean.js', 'ocean', 'Ocean', 'Directional waves, filtered reflections and broken whitecaps.'),- ('stream', 'stream.js', 'stream', 'Stream', 'Refraction, water-column absorption, ripple lighting and seated cobbles.'),- ('rocks', 'rock.js', 'granite', 'Rock', 'Fracture geometry, recessed weathering and mineral scale.'),- ('meadow', 'meadow.js', 'blades', 'Meadow', 'Leaf growth forms, habitat variation and shadowed transmission.'),-)---def hashes(root: Path) -> dict[str, str]:- return {str(path.relative_to(root)): hashlib.sha256(path.read_bytes()).hexdigest()- for path in sorted(root.rglob('*.js'))}---def main() -> None:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument('--baseline', type=Path, required=True)- parser.add_argument('--out', type=Path, default=HERE / 'output')- args = parser.parse_args()- out = args.out.resolve()- destination = out / 'comparison'- records = []- for key, module, camera, title, note in CASES:- record = {'case': key, 'module': module, 'camera': camera, 'time': 0,- 'title': title, 'note': note, 'variants': {}}- baseline = args.baseline.resolve() / key / 'src'- if not (baseline / 'scene.js').is_file():- raise FileNotFoundError(f'Missing baseline workspace: {baseline}')- for variant in ('before', 'after'):- workspace = destination / 'workspaces' / key / variant- source = workspace / 'src'- if source.exists():- shutil.rmtree(source)- shutil.copytree(baseline, source)- if variant == 'after':- shutil.copy2(LIB / module, source / 'lib' / module)- render = destination / 'renders' / key / variant- print(f'Comparing {key}: {variant}', flush=True)- subprocess.run([- 'node', str(HARNESS / 'runtime_js/render_scene.mjs'),- '--ws', str(workspace), '--out', str(render), '--times', '0',- '--width', '1280', '--height', '720', '--fps-seconds', '0',- '--no-settle', '--timeout-ms', '180000',- ], check=True, cwd=HARNESS, timeout=200)- frame = render / f'{camera}_t0.png'- image = destination / f'{key}-{variant}.png'- shutil.copy2(frame, image)- record['variants'][variant] = {- 'image': str(image.relative_to(out)), 'source_sha256': hashes(source),- 'metrics': str((render / 'metrics.json').relative_to(out)),- }- before = record['variants']['before']['source_sha256']- after = record['variants']['after']['source_sha256']- differences = [name for name in sorted(before.keys() | after.keys()) if before.get(name) != after.get(name)]- if differences != [f'lib/{module}']:- raise ValueError(f'{key}: expected exactly one changed module, found {differences}')- records.append(record)- (destination / 'manifest.json').write_text(json.dumps(records, indent=2))- cards = '\n'.join(f'''<section><h2>{record['title']}</h2><p>{record['note']}</p>-<div class="compare" style="--split:50%">-<img src="{record['variants']['before']['image']}" alt="{record['title']} before refinement">-<img class="after" src="{record['variants']['after']['image']}" alt="{record['title']} after library refinement">-<span class="divider"></span><span class="label old">Before</span><span class="label new">After</span>-</div><label class="control">Reveal refinement <input type="range" min="0" max="100" value="50" aria-label="{record['title']} comparison position"></label>-<p class="detail">Only <code>{record['module']}</code> changed. Camera, scene, lighting and time are identical.-<a href="{record['variants']['before']['image']}">Before image</a> · <a href="{record['variants']['after']['image']}">After image</a></p></section>'''- for record in records)- (out / 'comparison.html').write_text('''<!doctype html>-<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">-<title>Graphics Lab · Refinement comparison</title><style>-*{box-sizing:border-box}body{margin:0;background:#10191c;color:#e5e9de;font:16px/1.5 system-ui,sans-serif}-main{max-width:1280px;margin:auto;padding:36px 24px 80px}a{color:#bdd8bb}h1{font-size:clamp(32px,5vw,64px);line-height:1.1;margin:36px 0 18px}-h2{font-size:28px;margin:0}p{color:#aab8b5;max-width:900px}.intro{margin-bottom:48px}section{margin:0 0 60px}-.compare{position:relative;aspect-ratio:16/9;overflow:hidden;border:1px solid #364244;background:#1e2a2e}-.compare img{position:absolute;inset:0;width:100%;height:100%;object-fit:contain}.after{clip-path:inset(0 0 0 var(--split))}-.divider{position:absolute;left:var(--split);height:100%;width:2px;background:#e5e9de;transform:translateX(-1px)}-.label{position:absolute;top:14px;padding:5px 10px;background:#10191cbb;font-size:13px}.old{left:14px}.new{right:14px}-.control{display:flex;align-items:center;gap:20px;margin-top:16px}input{flex:1;accent-color:#b6d3a7;min-width:80px}.detail{font-size:13px}code{color:#e5e9de}-</style></head><body><main><a href="./">← Graphics Lab</a><div class="intro"><h1>Same scene. Refined library.</h1>-<p>Drag each slider to inspect actual GPU renders. These comparisons isolate the library change; the main gallery also includes revised scene composition. Images use the production renderer and postprocessing, with no painted or generated image layers.</p>-<a href="comparison/manifest.json">Source hashes and render records</a></div>-''' + cards + '''</main><script>-document.querySelectorAll('input').forEach(input=>input.addEventListener('input',()=>{- input.closest('section').querySelector('.compare').style.setProperty('--split',input.value+'%');-}));-</script></body></html>''')- print(f'Comparison: {out / "comparison.html"}')---if __name__ == '__main__':- main()diff --git a/harness/examples/graphics_lab/index.html b/harness/examples/graphics_lab/index.htmlindex 3d7854df..35a5888b 100644--- a/harness/examples/graphics_lab/index.html+++ b/harness/examples/graphics_lab/index.html@@ -5,7 +5,7 @@</head><body><header><a class="brand" href="./">3D CODEVERSE <span>/ GRAPHICS LAB</span></a><span class="edition">MATERIAL & MOTION</span></header><main><section class="intro"><p class="eyebrow">NATURE, MATERIALS & ATMOSPHERE</p><h1>Light. Form. Motion.</h1>-<p>Fire, water, stone, living vegetation and changing weather. Explore library studies and independently authored agent scenes, from cloud banks and waterfalls to intimate material details. Watch the films or step inside each scene.</p><!--COMPARISON_LINK--></section>+<p>Fire, water, stone, living vegetation and changing weather. Explore library studies, from cloud banks and waterfalls to intimate material details. Watch the films or step inside each scene.</p></section><section id="gallery" aria-label="Scene gallery"></section><section id="stage" hidden><div class="stage-heading"><div><p class="eyebrow" id="category"></p><h2 id="title"></h2><p id="subtitle"></p></div><button id="close" class="quiet">Back to gallery ↗</button></div>diff --git a/harness/examples/graphics_lab/package.py b/harness/examples/graphics_lab/package.pydeleted file mode 100644index d8b1d515..00000000--- a/harness/examples/graphics_lab/package.py+++ /dev/null@@ -1,325 +0,0 @@-"""Package six published studies without rebuilding or rendering anything.--python examples/graphics_lab/package.py --out examples/graphics_lab/output --name studies_v2-Existing packages are never overwritten. Uses only the Python standard library.-"""-from __future__ import annotations--import argparse-import hashlib-import html-import json-import math-import re-import shutil-import tempfile-import zipfile-from datetime import UTC, datetime-from pathlib import Path--HERE = Path(__file__).resolve().parent---def digest(path: Path) -> str:- with path.open("rb") as stream:- return hashlib.file_digest(stream, "sha256").hexdigest()---def write_json(path: Path, data: dict) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")---def local_file(root: Path, relative: str) -> Path:- path = (root / relative).resolve()- if not path.is_relative_to(root) or not path.is_file():- raise ValueError(f"Missing or out-of-root published file: {relative}")- return path---def check_hash(path: Path, expected: str) -> None:- if digest(path) != expected:- raise ValueError(f"Published source hash mismatch: {path}")---def capture_record(path: Path, contents: bytes | None = None) -> dict:- record = json.loads(contents if contents is not None else path.read_bytes())- if not record.get("ok") or record.get("console_errors") or record.get("shader_errors"):- raise ValueError(f"Capture did not complete cleanly: {path}")- for field in ("width", "height", "fps", "frames", "seconds"):- value = record.get(field)- if not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:- raise ValueError(f"Invalid capture {field}: {path}")- if not math.isclose(record["frames"] / record["fps"], record["seconds"], abs_tol=0.01):- raise ValueError(f"Capture frame count and duration disagree: {path}")- return record---def verify_capture_sources(out: Path, scene: str, record: dict, libraries: dict,- shaders: dict | None = None) -> dict:- """Prefer the capture-time hashes; older sidecars only identify a camera."""- if "source_sha256" not in record:- return {"mode": "legacy_without_capture_source_hashes", "files_checked": 0}- hashes = record["source_sha256"]- required = {f"lib/{name}" for name in libraries} | {f"scenes/{scene}.js", "scene.js"}- required.update(f"shaders/{name}" for name in (shaders or {}))- if not isinstance(hashes, dict) or not required.issubset(hashes):- raise ValueError(f"Capture source hashes are incomplete: {scene}")- staged = out / "cases" / scene / "src"- for relative, expected in hashes.items():- if staged.is_dir():- check_hash(local_file(staged.resolve(), relative), expected)- elif relative == "scene.js":- wrapper = f"export {{createScene}} from './scenes/{scene}.js';\n"- if hashlib.sha256(wrapper.encode()).hexdigest() != expected:- raise ValueError(f"Cannot verify nonstandard capture entry point without staged workspace: {scene}")- elif relative in required:- check_hash(local_file((out / "src").resolve(), relative), expected)- else:- raise ValueError(f"Cannot verify captured source without staged workspace: {scene}/{relative}")- return {"mode": "capture_source_hashes", "files_checked": len(hashes),- "reference": "staged_workspace" if staged.is_dir() else "published_sources_and_standard_entry"}---def offline_page(cases: list[dict], videos: list[dict]) -> str:- titles = {case["id"]: case["title"] for case in cases}- cards = []- for video in videos:- scene, key, capture = video["origin_scene_id"], video["origin_video_id"], video["capture"]- title = titles[scene] if key == scene else "Extra: Fire at the hearth"- details = f"{capture['width']} × {capture['height']} · {capture['fps']} fps · {capture['seconds']} seconds"- cards.append(- f'<article><h2>{html.escape(title)}</h2>'- f'<video controls playsinline preload="metadata" poster="previews/{scene}.png">'- f'<source src="videos/{key}.mp4" type="video/mp4"></video>'- f'<p>{details}</p><nav><a href="videos/{key}.mp4" download>Download video</a>'- f'<a href="src/scenes/{scene}.js">Scene source</a>'- f'<a href="previews/{scene}.png">Preview</a></nav></article>'- )- return """<!doctype html><html lang="en"><head><meta charset="utf-8">-<meta name="viewport" content="width=device-width,initial-scale=1">-<title>Graphics Lab: Six Published Studies</title><style>-*{box-sizing:border-box}body{margin:0;background:#101716;color:#edf0e9;font:16px/1.6 system-ui,sans-serif}-header,main,footer{max-width:1320px;margin:auto;padding:32px}h1{font-size:clamp(32px,5vw,60px);line-height:1.1}-main{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,430px),1fr));gap:26px}-article{background:#18211f;border:1px solid #34443b;border-radius:14px;overflow:hidden}-h2{font-size:20px;font-weight:550;margin:18px 20px}video{width:100%;display:block;aspect-ratio:16/9;background:#060908}-article p,nav{padding:0 20px}p,footer{color:#b6c5bb}nav{display:flex;flex-wrap:wrap;gap:20px;padding-bottom:22px}-a{color:#d2e2ae;text-underline-offset:4px}</style></head><body><header>-<h1>Six studies in light and nature.</h1><p>The first six published manual library studies, with existing-films and source code. Open this page directly to watch offline.</p><a href="README.md">Package notes</a>- · <a href="manifest.json">Source and capture manifest</a></header><main>""" + "".join(cards) + """</main>-<footer>The video page needs no server, JavaScript or network access. Executing the Three.js scenes-requires a compatible runtime; see <a href="README.md">README.md</a>.</footer></body></html>-"""---def readme(cases: list[dict], library_count: int) -> str:- table = "\n".join(- f"| {c['id']} | `src/scenes/{c['id']}.js` | `videos/{c['id']}.mp4` | `previews/{c['id']}.png` |"- for c in cases- )- return f"""# Graphics Lab: first six published studies--This package is a snapshot of the supplied gallery's first six manual library studies.-Scene code and all {library_count} shared library modules are byte-for-byte copies of that gallery,-validated against its published manifest. Films and previews are existing gallery assets.-Later gallery changes are excluded. No source rebuild, rendering, dependency download or model-call occurs during packaging.--## Watch offline--Open `index.html` directly in a browser using a `file://` URL. The video page needs no installation,-server, JavaScript or network access. MP4 files in `videos/` can be uploaded individually.-If included, `hearth.mp4` is a second camera from the fire scene.-Original resolution, duration, frame rate and renderer records are in `provenance/captures/`.--| ID | Scene code | Film | Preview |-| --- | --- | --- | --- |-{table}--## Run the scene source--Scenes export `createScene({{ THREE, renderer, loaders }})`, returning the scene, authored cameras-and update function. `src/scene.js` selects fire by default; change its export path to another ID.-Keep `src/scenes/` beside `src/lib/` and `src/shaders/` (when present) so relative imports resolve.--Executing the code requires Three.js r182 (`three` 0.182.x), WebGL 2, ES module resolution for-`three` and `three/addons/`, and a compatible scene host. The original harness uses Node.js 20.6+-and Chromium through Puppeteer. Its host configures sRGB output, ACES tone mapping, filtered-shadows and a post-processing chain including ambient occlusion, bloom and grading. Another-host can produce a different appearance. Runtime code and npm dependencies are not bundled.--## Provenance and integrity--`manifest.json` records SHA-256 and size for every payload file except itself, plus original-scene/video IDs and capture records. `provenance/published_selection.json` preserves expected-scene/library hashes, the original published manifest digest, and staged-workspace comparisons-where those workspaces exist. The packager verifies the ZIP CRC and every extracted file hash.--When a capture sidecar includes `source_sha256`, every recorded source hash is verified against-the retained capture workspace. If that workspace is absent, the published scene/library files-and the standard generated entry point are checked instead. Mismatches stop packaging.-Per-video `source_verification` records the evidence used. Legacy sidecars without source hashes-are explicitly marked: for those films, published/staged source agreement is not a direct-source-to-video hash binding. Capture records are not a new playback or aesthetic evaluation.-When present, the encoded MP4 digest and retained input-frame hashes are also checked.-Input frames keep their original paths under `capture_frames/`; paths recorded in original-capture metadata resolve from this package's root, not from `provenance/captures/`.--The package excludes model-run records, credentials, environment files and `node_modules`.-The offline video page is independent of the Three.js runtime.-"""---def build_package(out: Path, name: str) -> dict:- out = out.resolve()- if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", name):- raise ValueError("Package name must be one folder name using letters, digits, '.', '_' or '-'")- packages = out / "packages"- destination, archive = packages / name, packages / f"{name}.zip"- if destination.exists() or archive.exists():- raise FileExistsError(f"Package already exists; choose a new --name: {destination}")- published_file = local_file(out, "manifest.json")- published_hash = digest(published_file)- published = json.loads(published_file.read_text(encoding="utf-8"))- cases = published["cases"][:6]- if len(cases) != 6 or any(c.get("source_kind") != "library_study" for c in cases):- raise ValueError("The first six published cases must be manual library studies")- ids = [case["id"] for case in cases]- if len(set(ids)) != 6 or "fire" not in ids or any(not re.fullmatch(r"[a-z0-9_]+", i) for i in ids):- raise ValueError("Scene IDs must be unique safe filenames and include fire")- libraries = published["library_sha256"]- shaders = published.get("shader_sha256", {})- actual = {p.name for p in (out / "src/lib").iterdir() if p.is_file()}- if not libraries or actual != set(libraries):- raise ValueError("Published library files and manifest entries disagree")- packages.mkdir(parents=True, exist_ok=True)- with tempfile.TemporaryDirectory(prefix=".package-", dir=packages) as temp:- work = Path(temp) / name- work.mkdir()- origins, checks, videos = {}, [], []-- def copy(source: Path, relative: str, expected: str | None = None) -> None:- expected = expected or digest(source)- target = work / relative- target.parent.mkdir(parents=True, exist_ok=True)- shutil.copy2(source, target)- check_hash(target, expected)- origins[relative] = source.relative_to(out).as_posix()-- for filename, expected in sorted(libraries.items()):- if Path(filename).name != filename or not filename.endswith(".js"):- raise ValueError(f"Invalid shared library filename: {filename}")- copy(local_file(out, f"src/lib/{filename}"), f"src/lib/{filename}", expected)- for filename, expected in sorted(shaders.items()):- if (Path(filename).is_absolute() or ".." in Path(filename).parts- or Path(filename).suffix not in {".glsl", ".vert", ".frag"}):- raise ValueError(f"Invalid external shader filename: {filename}")- copy(local_file(out, f"src/shaders/{filename}"), f"src/shaders/{filename}", expected)- for case in cases:- key = case["id"]- copy(local_file(out, case["module"]), f"src/scenes/{key}.js", case["scene_sha256"])- preview = local_file(out, f"{key}.png")- with preview.open("rb") as stream:- if stream.read(8) != b"\x89PNG\r\n\x1a\n":- raise ValueError(f"Preview is not a PNG: {preview}")- copy(preview, f"previews/{key}.png")- staged = out / "cases" / key / "src"- if staged.exists():- check_hash(staged / "scenes" / f"{key}.js", case["scene_sha256"])- for filename, expected in libraries.items():- check_hash(staged / "lib" / filename, expected)- for filename, expected in shaders.items():- check_hash(staged / "shaders" / filename, expected)- checks.append({"scene_id": key, "published_hash_matches": True,- "staged_workspace_present": staged.exists(),- "staged_library_files_checked": len(libraries) if staged.exists() else 0,- "staged_shader_files_checked": len(shaders) if staged.exists() else 0})- video_ids = [(key, key) for key in ids]- if (out / "hearth.mp4").exists():- video_ids.append(("fire", "hearth"))- for scene, key in video_ids:- source = local_file(out, f"{key}.mp4")- with source.open("rb") as stream:- if stream.read(12)[4:8] != b"ftyp":- raise ValueError(f"Video is not an MP4 container: {source}")- capture = local_file(out, f"{key}.capture.json")- capture_bytes = capture.read_bytes()- capture_digest = hashlib.sha256(capture_bytes).hexdigest()- record = capture_record(capture, capture_bytes)- verification = verify_capture_sources(out, scene, record, libraries, shaders)- video_digest = record.get("video_sha256") or digest(source)- if record.get("video_sha256"):- check_hash(source, video_digest)- verification["encoded_digest_checked"] = True- references = record.get("reference_frames", [])- for reference in references:- relative = reference["path"]- if (Path(relative).is_absolute() or ".." in Path(relative).parts- or not relative.startswith("capture_frames/") or not relative.endswith(".png")):- raise ValueError(f"Invalid retained input frame path: {relative}")- copy(local_file(out, relative), relative, reference["sha256"])- verification["retained_input_frames_checked"] = len(references)- copy(source, f"videos/{key}.mp4", video_digest)- copy(capture, f"provenance/captures/{key}.capture.json", capture_digest)- videos.append({"video": f"videos/{key}.mp4", "origin_scene_id": scene,- "origin_video_id": key, "capture": record,- "source_verification": verification})- (work / "src/scene.js").write_text("export { createScene } from './scenes/fire.js';\n", encoding="utf-8")- (work / "README.md").write_text(readme(cases, len(libraries)), encoding="utf-8")- (work / "index.html").write_text(offline_page(cases, videos), encoding="utf-8")- provenance = {"published_manifest_sha256": published_hash, "selected_cases": cases,- "library_sha256": libraries, "shader_sha256": shaders, "source_checks": checks}- write_json(work / "provenance/published_selection.json", provenance)- files = {}- for file in sorted(work.rglob("*")):- if not file.is_file():- continue- relative = file.relative_to(work).as_posix()- if file.suffix in {".js", ".html", ".md", ".glsl", ".vert", ".frag"} and re.search(r"[\u3400-\u9fff]", file.read_text(encoding="utf-8")):- raise ValueError(f"Example text must be English: {relative}")- files[relative] = {"sha256": digest(file), "bytes": file.stat().st_size,- "origin": origins.get(relative, "Generated package metadata or offline viewer")}- manifest = {"package_name": name, "created_utc": datetime.now(UTC).isoformat(),- "default_scene_id": "fire", "shared_library_count": len(libraries),- "published_manifest_sha256": published_hash, "scenes": cases,- "videos": videos, "source_checks": checks,- "integrity_scope": "All payload files except manifest.json itself", "files": files}- write_json(work / "manifest.json", manifest)- check_hash(published_file, published_hash)- expected_files = {p.relative_to(work).as_posix(): digest(p) for p in work.rglob("*") if p.is_file()}- temporary_zip = Path(temp) / f"{name}.zip"- with zipfile.ZipFile(temporary_zip, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as zipped:- for relative in sorted(expected_files):- zipped.write(work / relative, f"{name}/{relative}")- with zipfile.ZipFile(temporary_zip) as zipped:- expected_names = {f"{name}/{relative}" for relative in expected_files}- if zipped.testzip() is not None or set(zipped.namelist()) != expected_names:- raise ValueError("ZIP CRC or file list verification failed")- extracted = Path(temp) / "verify"- zipped.extractall(extracted)- for relative, expected in expected_files.items():- check_hash(extracted / name / relative, expected)- if destination.exists() or archive.exists():- raise FileExistsError(f"Package appeared during packaging: {destination}")- work.rename(destination)- temporary_zip.rename(archive)- return {"folder": str(destination), "zip": str(archive), "files": len(expected_files),- "zip_bytes": archive.stat().st_size, "zip_sha256": digest(archive),- "source_manifest": "pass", "zip_crc_and_extracted_hashes": "pass"}---def main() -> None:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--out", type=Path, default=HERE / "output", help="Existing published gallery root")- parser.add_argument("--name", required=True, help="New folder/ZIP name under <out>/packages")- args = parser.parse_args()- try:- print(json.dumps(build_package(args.out, args.name), indent=2))- except (OSError, ValueError, KeyError, TypeError) as error:- parser.exit(1, f"Package failed: {error}\n")---if __name__ == "__main__":- main()diff --git a/harness/examples/graphics_lab/verify_media.py b/harness/examples/graphics_lab/verify_media.pydeleted file mode 100644index 0aac340d..00000000--- a/harness/examples/graphics_lab/verify_media.py+++ /dev/null@@ -1,200 +0,0 @@-"""Decode every gallery film and check its retained scene/source correspondence.--From harness/: python examples/graphics_lab/verify_media.py --out /path/to/gallery-Motion statistics describe decoded pixels; they are not an aesthetic score.-"""-from __future__ import annotations--import argparse-import hashlib-import json-from pathlib import Path--import imageio_ffmpeg-import numpy as np-from PIL import Image, ImageDraw---def sha256(path: Path) -> str:- return hashlib.sha256(path.read_bytes()).hexdigest()---def verify(out: Path, *, allow_legacy: bool = False) -> dict:- manifest = json.loads((out / "manifest.json").read_text())- libraries = manifest["library_sha256"]- actual = {p.name: sha256(p) for p in (out / "src/lib").glob("*.js")}- if actual != libraries:- raise ValueError("Published library does not match the source manifest")- shaders = manifest.get("shader_sha256", {})- shader_root = out / "src/shaders"- actual = {p.relative_to(shader_root).as_posix(): sha256(p)- for p in shader_root.rglob("*")- if p.is_file() and p.suffix in {".glsl", ".vert", ".frag"}}- if actual != shaders:- raise ValueError("Published shaders do not match the source manifest")- expected_sources = {}- for case in manifest["cases"]:- key = case["id"]- scene = out / "src/scenes" / f"{key}.js"- if sha256(scene) != case["scene_sha256"]:- raise ValueError(f"Published scene does not match its manifest: {key}")- workspace = out / "cases" / key / "src"- wanted = {f"lib/{name}": value for name, value in libraries.items()}- wanted.update({f"shaders/{name}": value for name, value in shaders.items()})- wanted[f"scenes/{key}.js"] = case["scene_sha256"]- wanted["scene.js"] = hashlib.sha256(- f"export {{createScene}} from './scenes/{key}.js';\n".encode()).hexdigest()- actual = {p.relative_to(workspace).as_posix(): sha256(p)- for p in workspace.rglob("*")- if p.is_file() and p.suffix in {".js", ".mjs", ".glsl", ".vert", ".frag"}}- if actual != wanted:- raise ValueError(f"Staged workspace does not match published source: {key}")- expected_sources[key] = wanted- if not (out / f"{key}.mp4").is_file():- raise ValueError(f"Missing gallery film: {key}")-- plan_file = out / "capture-plan.json"- planned = {}- if plan_file.is_file():- entries = json.loads(plan_file.read_text())["films"]- planned = {item["file"]: item for item in entries}- if len(planned) != len(entries) or set(planned) != {p.name for p in out.glob("*.mp4")}:- raise ValueError("Movie files do not match the complete capture plan")- evidence = out / "media-verification"- evidence.mkdir(exist_ok=True)- reports = []- for film in sorted(out.glob("*.mp4")):- capture = json.loads(film.with_suffix(".capture.json").read_text())- owners = [key for key, source in expected_sources.items()- if capture.get("source_sha256") == source]- if len(owners) != 1:- raise ValueError(f"Film has no unique matching source snapshot: {film.name}")- if not capture.get("ok") or capture.get("console_errors") or capture.get("shader_errors"):- raise ValueError(f"Capture reported errors: {film.name}")- key = owners[0]- if film.stem in expected_sources and key != film.stem:- raise ValueError(f"Primary gallery film belongs to another scene: {film.name}: {key}")- if film.name in planned:- wanted = planned[film.name]- if key != wanted["scene"] or any(capture[field] != wanted[field]- for field in ["camera", "fps", "frames"]):- raise ValueError(f"Capture differs from its declared plan: {film.name}")- video_hash = sha256(film)- references = capture.get("reference_frames", [])- legacy = not capture.get("video_sha256") or not references- if legacy and not allow_legacy:- raise ValueError(f"Capture lacks encoded-file/anchor evidence: {film.name}; "- "use --allow-legacy only for historical movies")- if capture.get("video_sha256") and capture["video_sha256"] != video_hash:- raise ValueError(f"Encoded movie differs from its capture digest: {film.name}")- anchors = {}- for reference in references:- file = (out / reference["path"]).resolve()- if not file.is_relative_to(out) or sha256(file) != reference["sha256"]:- raise ValueError(f"Invalid retained input frame: {film.name}")- index = reference["index"]- if (not isinstance(index, int) or index < 0 or index >= capture["frames"]- or index in anchors or abs(reference["time_s"] - index / capture["fps"]) > 1e-8):- raise ValueError(f"Invalid retained frame index/time: {film.name}")- anchors[index] = Image.open(file).convert("RGB")- if not legacy and set(anchors) != {0, capture["frames"] // 3, 2 * capture["frames"] // 3}:- raise ValueError(f"Capture reference frames are incomplete: {film.name}")- first_input = (np.asarray(anchors[0].resize((160, 90)), dtype=np.float32)- if 0 in anchors else None)- views = json.loads((out / "renders" / key / "views.json").read_text())- stills = [view for view in views- if view["name"] == capture["camera"] and view["time_s"] == 0]- if len(stills) != 1:- raise ValueError(f"Film has no matching time-zero camera still: {film.name}")- still = Image.open(out / "renders" / key / stills[0]["path"]).convert("RGB")- frames = imageio_ffmpeg.read_frames(str(film), pix_fmt="rgb24")- metadata = next(frames)- width, height = metadata["size"]- if (width, height) != (capture["width"], capture["height"]):- raise ValueError(f"Encoded dimensions differ from capture: {film.name}")- if abs(metadata["fps"] - capture["fps"]) > .01:- raise ValueError(f"Encoded frame rate differs from capture: {film.name}")- selected = {0, capture["frames"] // 3, 2 * capture["frames"] // 3}- tiles, previous, motion, first_error, count = [], None, [], None, 0- anchor_errors = {}- motion_matches = {}- try:- for count, raw in enumerate(frames, 1):- pixels = np.frombuffer(raw, dtype=np.uint8).reshape(height, width, 3)- if count == 1:- if still.size != (width, height):- raise ValueError(f"Matching still has different dimensions: {film.name}")- first_error = float(np.abs(pixels.astype(np.float32)- - np.asarray(still, dtype=np.float32)).mean())- if first_error > 6:- raise ValueError(f"First decoded frame differs from its scene still: "- f"{film.name}: {first_error:.3f}/255")- image = Image.fromarray(pixels)- small = np.asarray(image.resize((160, 90)), dtype=np.float32)- if count - 1 in anchors:- anchor = anchors[count - 1]- if anchor.size != (width, height):- raise ValueError(f"Retained frame dimensions differ: {film.name}")- intended = np.asarray(anchor.resize((160, 90)), dtype=np.float32)- error = float(np.abs(small - intended).mean())- # Downsampling removes fine chroma-subsampling differences,- # while retaining the scene's changing forms and lighting.- if error > 1.5:- raise ValueError(f"Encoded frame {count - 1} differs from its input: "- f"{film.name}: {error:.3f}/255")- anchor_errors[count - 1] = error- moving = np.max(np.abs(intended - first_input), axis=2) > 4- if count > 1 and int(moving.sum()) >= 16:- own_error = float(np.abs(small[moving] - intended[moving]).mean())- frozen_error = float(np.abs(small[moving] - first_input[moving]).mean())- if own_error + .1 >= frozen_error:- raise ValueError(f"Encoded frame does not follow captured motion: "- f"{film.name}: frame {count - 1}")- motion_matches[count - 1] = {"changed_pixels": int(moving.sum()),- "intended_frame_error": own_error,- "first_frame_error": frozen_error}- if previous is not None:- motion.append(float(np.abs(small - previous).mean()))- previous = small- if count - 1 in selected:- tiles.append((image.resize((640, 360)), (count - 1) / capture["fps"]))- finally:- frames.close()- if count != capture["frames"]:- raise ValueError(f"Decoded frame count differs: {film.name}: "- f"{count} versus {capture['frames']}")- sheet = Image.new("RGB", (640 * len(tiles), 396), (18, 23, 27))- draw = ImageDraw.Draw(sheet)- for i, (tile, time) in enumerate(tiles):- sheet.paste(tile, (640 * i, 36))- draw.text((640 * i + 12, 12), f"{film.stem} / {capture['camera']} / {time:.2f}s",- fill="white")- sheet.save(evidence / f"{film.stem}.jpg", quality=94)- reports.append({"film": film.name, "scene": key, "camera": capture["camera"],- "sha256": video_hash, "frames_decoded": count,- "capture_binding": "legacy_source_only" if legacy else "encoded_digest_and_input_frames",- "input_frame_rgb_mae_255_at_160x90": anchor_errors,- "motion_correspondence_at_160x90": motion_matches,- "fps": metadata["fps"], "size": [width, height],- "first_frame_rgb_mae_255": first_error,- "adjacent_frame_mean_rgb_mae_255_at_160x90": float(np.mean(motion))- if motion else 0, "source_files_checked": len(expected_sources[key])})- print(f"Verified {film.name}: {count} frames, source {key}, "- f"first-frame error {first_error:.3f}/255", flush=True)- report = {"ok": True, "manifest_sha256": sha256(out / "manifest.json"),- "library_modules": len(libraries), "external_shader_files": len(shaders),- "gallery_cases": len(expected_sources),- "films": reports,- "limitations": "Pixel motion includes compression and rendering changes. Static "- "studies may have zero motion; these statistics do not certify visual realism."}- (evidence / "report.json").write_text(json.dumps(report, indent=2) + "\n")- return report---if __name__ == "__main__":- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--out", type=Path, required=True)- parser.add_argument("--allow-legacy", action="store_true",- help="Allow historical sidecars without encoded-file digests or retained input frames")- args = parser.parse_args()- verify(args.out.resolve(), allow_legacy=args.allow_legacy)diff --git a/harness/examples/graphics_lab/viewer.js b/harness/examples/graphics_lab/viewer.jsindex 57f64ede..1ebf066e 100644--- a/harness/examples/graphics_lab/viewer.js+++ b/harness/examples/graphics_lab/viewer.js@@ -242,9 +242,3 @@ function frame(now) {}requestAnimationFrame(frame);-// Diagnostics used by the browser smoke test.-window.graphicsLab = {- open, explore,- get active() { return bundle?.result; },- get time() { return time; },-};diff --git a/harness/tests/graphics/test_graphics_lab_build.py b/harness/tests/graphics/test_graphics_lab_build.pydeleted file mode 100644index ea71715e..00000000--- a/harness/tests/graphics/test_graphics_lab_build.py+++ /dev/null@@ -1,146 +0,0 @@-"""A gallery restage must never relabel old media with different source code."""-from __future__ import annotations--import importlib.util-import json-from pathlib import Path--import pytest--BUILDER = Path(__file__).resolve().parents[2] / "examples/graphics_lab/build.py"-spec = importlib.util.spec_from_file_location("graphics_lab_builder", BUILDER)-build = importlib.util.module_from_spec(spec)-spec.loader.exec_module(build)---def studio(tmp_path: Path, monkeypatch):- source, library, out = tmp_path / "studio", tmp_path / "lib", tmp_path / "out"- (source / "scenes").mkdir(parents=True)- library.mkdir()- (library / "shader.js").write_text("export const version = 1;\n")- for key in ("one", "two"):- (source / "scenes" / f"{key}.js").write_text(f"export const scene = '{key}';\n")- for name in ("index.html", "viewer.js", "viewer.css"):- (source / name).write_text("<!--COMPARISON_LINK-->" if name == "index.html" else "")- monkeypatch.setattr(build, "HERE", source)- monkeypatch.setattr(build, "LIB", library)- monkeypatch.setattr(build, "CASES", tuple((key, str(i), key, "Study", "life")- for i, key in enumerate(("one", "two"), 1)))- return source, library, out---def file_snapshot(root: Path) -> dict[str, bytes]:- return {p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()}--[email protected]("capture_hashes", [False, True])-def test_unchanged_selected_rebuild_preserves_other_media(studio, capture_hashes):- _, _, out = studio- cases = build.stage(out, [])- (out / "two.mp4").write_bytes(b"previous film")- record = {"ok": True}- if capture_hashes:- manifest = json.loads((out / "manifest.json").read_text())- record["source_sha256"] = build.workspace_hashes(cases[1], manifest["library_sha256"])- (out / "two.capture.json").write_text(json.dumps(record))- before = file_snapshot(out)- selected = build.stage(out, ["one"])- assert [case["id"] for case in selected] == ["one"]- assert file_snapshot(out) == before--[email protected]("change", ["library", "unselected_scene"])-def test_changed_sources_refuse_before_mutating_old_media(studio, change):- source, library, out = studio- build.stage(out, [])- (out / "two.mp4").write_bytes(b"previous film")- target = library / "shader.js" if change == "library" else source / "scenes/two.js"- target.write_text("export const changed = true;\n")- before = file_snapshot(out)- with pytest.raises(ValueError, match="new --out"):- build.stage(out, ["one"])- assert file_snapshot(out) == before---def test_capture_hashes_catch_an_already_mislabelled_video(studio):- _, library, out = studio- cases = build.stage(out, [])- old_manifest = json.loads((out / "manifest.json").read_text())- captured = build.workspace_hashes(cases[1], old_manifest["library_sha256"])- # Simulate the former unsafe builder: newer source/manifest with an old film.- (library / "shader.js").write_text("export const version = 2;\n")- build.stage(out, [])- (out / "two.mp4").write_bytes(b"older film")- (out / "two.capture.json").write_text(json.dumps({"ok": True, "source_sha256": captured}))- before = file_snapshot(out)- with pytest.raises(ValueError, match="capture-time sources"):- build.stage(out, ["one"])- assert file_snapshot(out) == before---def test_missing_case_fails_without_partial_output(studio):- source, _, out = studio- (source / "scenes/two.js").unlink()- with pytest.raises(FileNotFoundError, match="Showcase scene missing"):- build.stage(out, ["one"])- assert not out.exists()---def test_unversioned_media_cannot_acquire_new_source_labels(studio):- _, _, out = studio- out.mkdir()- (out / "one.png").write_bytes(b"unknown old still")- before = file_snapshot(out)- with pytest.raises(ValueError, match="no source manifest"):- build.stage(out, [])- assert file_snapshot(out) == before---def test_source_only_refresh_removes_obsolete_modules(studio):- _, library, out = studio- (library / "obsolete.js").write_text("export const old = true;\n")- build.stage(out, [])- (library / "obsolete.js").unlink()- (library / "new.js").write_text("export const current = true;\n")- build.stage(out, [])- assert not list(out.rglob("obsolete.js"))- assert len(list(out.rglob("new.js"))) == 3--[email protected]("suffix", [".glsl", ".vert", ".frag"])-def test_external_shader_bytes_are_staged_and_guarded(studio, suffix):- source, _, out = studio- shader = source / "shaders/nested" / f"surface{suffix}"- shader.parent.mkdir(parents=True)- shader.write_text("// Independent shader source\nvoid main() {}\n")- cases = build.stage(out, [])- manifest = json.loads((out / "manifest.json").read_text())- shader_key = f"nested/surface{suffix}"- assert manifest["shader_sha256"] == {shader_key: build.digest(shader.read_bytes())}- for root in [out / "src", out / "cases/one/src", out / "cases/two/src"]:- assert (root / "shaders" / shader_key).read_bytes() == shader.read_bytes()- captured = build.workspace_hashes(cases[1], manifest["library_sha256"], manifest["shader_sha256"])- (out / "two.mp4").write_bytes(b"previous film")- (out / "two.capture.json").write_text(json.dumps({"ok": True, "source_sha256": captured}))- before = file_snapshot(out)- build.stage(out, ["one"])- assert file_snapshot(out) == before- shader.write_text("// Changed optical response\nvoid main() {}\n")- with pytest.raises(ValueError, match="external shader contents changed"):- build.stage(out, ["one"])- assert file_snapshot(out) == before--[email protected]("where", ["src", "cases/two/src"])-def test_corrupted_published_or_staged_shader_refuses_restage(studio, where):- source, _, out = studio- (source / "shaders").mkdir()- (source / "shaders/surface.frag").write_text("void main() {}\n")- build.stage(out, [])- (out / "two.mp4").write_bytes(b"previous film")- (out / where / "shaders/surface.frag").write_text("// Unrecorded shader change\n")- before = file_snapshot(out)- with pytest.raises(ValueError, match="disagree"):- build.stage(out, ["one"])- assert file_snapshot(out) == beforediff --git a/harness/tests/graphics/test_graphics_lab_lifecycle.py b/harness/tests/graphics/test_graphics_lab_lifecycle.pydeleted file mode 100644index 87ae259c..00000000--- a/harness/tests/graphics/test_graphics_lab_lifecycle.py+++ /dev/null@@ -1,139 +0,0 @@-"""The live viewer respects effect ownership and releases failed scene contexts."""-from __future__ import annotations--import json-from pathlib import Path--import pytest--from tests.scene_runtime.conftest import needs_browser, run_node_json--pytestmark = [pytest.mark.node, needs_browser]-LAB = Path(__file__).resolve().parents[2] / "examples/graphics_lab"--FIXTURE = """-import * as THREE from 'three';-export async function makeScene(kind,{renderer}) {- const stats=window.cleanupStats={};- const count=key=>stats[key]=(stats[key]||0)+1;- const track=(resource,key)=>{resource.addEventListener('dispose',()=>count(key));return resource;};- const originalDispose=renderer.dispose.bind(renderer);- renderer.dispose=()=>{count('renderer');originalDispose();if(kind==='throwing')throw Error('Renderer cleanup failure');};- const originalLoss=renderer.forceContextLoss.bind(renderer);- renderer.forceContextLoss=()=>{count('context');originalLoss();};- const canvas=renderer.domElement,originalRemove=canvas.remove.bind(canvas);- canvas.remove=()=>{count('canvas');originalRemove();};- const scene=new THREE.Scene();- const geometry=track(new THREE.BoxGeometry(),'geometry');- const material=track(new THREE.MeshBasicMaterial({color:0x558899}),'material');- const mesh=new THREE.Mesh(geometry,material);scene.add(mesh);- const result={scene,cameras:[{name:'Study',position:[2,2,4],lookAt:[0,0,0]}],update(){}};- if(kind==='authoritative') {- mesh.userData.dispose=()=>count('childDisposer');- const borrowed=track(new THREE.BoxGeometry(),'borrowedGeometry');- mesh.add(new THREE.Mesh(borrowed,track(new THREE.MeshBasicMaterial(),'borrowedMaterial')));- result.dispose=()=>{count('sceneDisposer');geometry.dispose();material.dispose();};- } else if(kind.startsWith('fallback')) {- const owner=new THREE.Group();scene.add(owner);owner.add(mesh);- owner.userData.dispose=()=>{count('ownerDisposer');geometry.dispose();material.dispose();- if(kind==='fallback_failure')throw Error('Effect cleanup failure');};- mesh.userData.dispose=()=>count('nestedDisposer');- mesh.add(new THREE.Mesh(track(new THREE.BoxGeometry(),'borrowedGeometry'),- track(new THREE.MeshBasicMaterial(),'borrowedMaterial')));- // A managed resource also used by an unmanaged sibling must not be freed twice.- scene.add(new THREE.Mesh(geometry,material));- const looseGeometry=track(new THREE.BoxGeometry(),'looseGeometry');- const looseMaterial=track(new THREE.MeshBasicMaterial(),'looseMaterial');- const texture=track(new THREE.DataTexture(new Uint8Array([255,255,255,255]),1,1),'texture');texture.needsUpdate=true;- looseMaterial.map=texture;- const loose=new THREE.InstancedMesh(looseGeometry,looseMaterial,1);track(loose,'instances');- loose.customDepthMaterial=track(new THREE.MeshDepthMaterial(),'depthMaterial');- loose.customDistanceMaterial=track(new THREE.MeshDistanceMaterial(),'distanceMaterial');scene.add(loose);- scene.add(new THREE.Mesh(looseGeometry,looseMaterial));- const cached=track(new THREE.MeshBasicMaterial(),'cachedMaterial');cached.userData.shared=true;- scene.add(new THREE.Mesh(looseGeometry,cached));- } else if(kind==='throwing'||kind==='invalid') {- result.dispose=()=>{count('sceneDisposer');throw Error('Owned cleanup failure');};- if(kind==='invalid')result.scene=null;- } else if(kind==='cancelled') {- result.dispose=()=>{count('sceneDisposer');geometry.dispose();material.dispose();};- await new Promise(resolve=>{window.resolveScene=resolve;});- }- return result;-}-"""---def test_live_cleanup_ownership_failures_and_pending_cancellation(tmp_path: Path):- for name in ("index.html", "viewer.js", "viewer.css"):- (tmp_path / name).write_bytes((LAB / name).read_bytes())- cases = []- for kind in ("authoritative", "fallback", "fallback_failure", "throwing", "invalid", "cancelled"):- (tmp_path / f"{kind}.js").write_text(- "import {makeScene} from './fixture.js';\n"- f"export const createScene=options=>makeScene('{kind}',options);\n"- )- cases.append({"id": kind, "title": kind, "subtitle": "Cleanup study",- "kind": "test", "number": "01", "module": f"./{kind}.js"})- (tmp_path / "fixture.js").write_text(FIXTURE)- (tmp_path / "manifest.json").write_text(json.dumps({"cases": cases}))- result = run_node_json("""-import fs from 'node:fs';-import assert from 'node:assert/strict';-import {launchBrowser,serveDirs} from './lib/host_env.mjs';-import {releaseBrowser} from './lib/host_page.mjs';-const root=ROOT;-const server=await serveDirs({root,routes:{'/':{body:fs.readFileSync(root+'/index.html','utf8')}}});-const launched=await launchBrowser({gpu:'auto'});-let page;-try {- page=await launched.browser.newPage();- const errors=[],warnings=[];- page.on('pageerror',e=>errors.push(e.message));- page.on('console',m=>{if(m.type()==='warn'&&m.text().includes('cleanup failed'))warnings.push(m.text());});- await page.goto(server.base,{waitUntil:'networkidle0'});- await page.waitForFunction(()=>!!window.graphicsLab);- const snapshots={};- for(const kind of ['authoritative','fallback','fallback_failure','throwing','invalid','cancelled']) {- await page.evaluate(async kind=>{- const item=(await (await fetch('./manifest.json')).json()).cases.find(item=>item.id===kind);- window.graphicsLab.open(item);- window.pendingBoot=window.graphicsLab.explore();- },kind);- if(kind==='cancelled') {- await page.waitForFunction(()=>typeof window.resolveScene==='function');- await page.click('#close');- await page.evaluate(async()=>{window.resolveScene();await window.pendingBoot;});- } else {- await page.evaluate(()=>window.pendingBoot);- if(kind==='invalid') {- await page.$eval('#video',e=>e.dispatchEvent(new Event('error')));- assert.match(await page.$eval('#status',e=>e.textContent),/Scene does not implement the scene contract/);- }- else assert(await page.evaluate(()=>!!window.graphicsLab.active),kind+' did not boot');- await page.click('#close');- }- snapshots[kind]=await page.evaluate(()=>({...window.cleanupStats,active:!!window.graphicsLab.active,canvasCount:document.querySelectorAll('#live canvas').length}));- }- assert.deepEqual(errors,[]);- for(const stats of Object.values(snapshots)) {- assert.equal(stats.renderer,1);assert.equal(stats.context,1);assert.equal(stats.canvas,1);- assert.equal(stats.active,false);assert.equal(stats.canvasCount,0);- }- const a=snapshots.authoritative;- assert.equal(a.sceneDisposer,1);assert.equal(a.geometry,1);assert.equal(a.material,1);- assert.equal(a.childDisposer,undefined);assert.equal(a.borrowedGeometry,undefined);assert.equal(a.borrowedMaterial,undefined);- for(const f of [snapshots.fallback,snapshots.fallback_failure]) {- for(const key of ['ownerDisposer','geometry','material','looseGeometry','looseMaterial','instances','depthMaterial','distanceMaterial'])assert.equal(f[key],1,key);- for(const key of ['nestedDisposer','borrowedGeometry','borrowedMaterial','cachedMaterial','texture'])assert.equal(f[key],undefined,key);- }- assert.equal(snapshots.throwing.sceneDisposer,1);assert.equal(snapshots.invalid.sceneDisposer,1);- assert.equal(snapshots.cancelled.sceneDisposer,1);- assert.equal(warnings.length,3);- console.log(JSON.stringify({snapshots,warnings:warnings.length,errors}));-} finally {- await page?.close();await releaseBrowser(launched);await server.close();-}-""".replace("ROOT", json.dumps(str(tmp_path))), timeout=120)- assert len(result["snapshots"]) == 6- assert result["errors"] == []diff --git a/harness/tests/graphics/test_graphics_lab_media.py b/harness/tests/graphics/test_graphics_lab_media.pydeleted file mode 100644index 96f99da2..00000000--- a/harness/tests/graphics/test_graphics_lab_media.py+++ /dev/null@@ -1,180 +0,0 @@-"""Check that exported media retains its source, camera and animation evidence."""-from __future__ import annotations--import hashlib-import importlib.util-import json-import shutil-from pathlib import Path--import numpy as np-import pytest-from PIL import Image--ffmpeg = pytest.importorskip("imageio_ffmpeg")-HERE = Path(__file__).resolve().parents[2] / "examples/graphics_lab"---def load_module(name):- spec = importlib.util.spec_from_file_location(f"graphics_lab_{name}", HERE / f"{name}.py")- module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)- return module---build, verify, package = [load_module(name) for name in ["build", "verify_media", "package"]]---def write_json(path, value):- path.write_text(json.dumps(value))---def encode(path, frames):- writer = ffmpeg.write_frames(str(path), (96, 64), fps=3, codec="libx264",- output_params=["-crf", "18"], macro_block_size=1)- writer.send(None)- try:- for frame in frames:- writer.send(frame)- finally:- writer.close()---def gallery(tmp_path, monkeypatch):- source, library, out = tmp_path / "source", tmp_path / "lib", tmp_path / "out"- (source / "scenes").mkdir(parents=True)- (source / "shaders").mkdir()- library.mkdir()- (library / "shader.js").write_text("export const scale = 1;\n")- (source / "scenes/smoke.js").write_text("export const kind = 'smoke';\n")- for suffix in ["glsl", "vert", "frag"]:- (source / "shaders" / f"surface.{suffix}").write_text("void main() {}\n")- for name in ["index.html", "viewer.js", "viewer.css"]:- (source / name).write_text("")- monkeypatch.setattr(build, "HERE", source)- monkeypatch.setattr(build, "LIB", library)- monkeypatch.setattr(build, "CASES", (("smoke", "01", "Smoke", "Study", "air"),))- case = build.stage(out, [])[0]- manifest = json.loads((out / "manifest.json").read_text())- frames, references = [], []- (out / "capture_frames/smoke").mkdir(parents=True)- for index in range(9):- pixels = np.full((64, 96, 3), [25, 30, 35], dtype=np.uint8)- x = 8 + index * 6- pixels[21:38, x:x+17] = [190, 110, 55]- frames.append(pixels)- if index in [0, 3, 6]:- file = out / "capture_frames/smoke" / f"frame_{index}.png"- Image.fromarray(pixels).save(file)- references.append({"index": index, "time_s": index / 3,- "path": file.relative_to(out).as_posix(),- "sha256": verify.sha256(file)})- encode(out / "smoke.mp4", frames)- renders = out / "renders/smoke"- renders.mkdir(parents=True)- Image.fromarray(frames[0]).save(renders / "main_t0.png")- shutil.copy2(renders / "main_t0.png", out / "smoke.png")- write_json(renders / "views.json", [{"name": "main", "time_s": 0, "path": "main_t0.png"}])- record = {"ok": True, "console_errors": [], "shader_errors": [], "camera": "main",- "width": 96, "height": 64, "fps": 3, "frames": 9, "seconds": 3,- "source_sha256": build.workspace_hashes(case, manifest["library_sha256"],- manifest["shader_sha256"]),- "video_sha256": verify.sha256(out / "smoke.mp4"), "reference_frames": references}- write_json(out / "smoke.capture.json", record)- write_json(out / "capture-plan.json", {"films": [- {"file": "smoke.mp4", "scene": "smoke", "camera": "main", "fps": 3, "frames": 9}]})- return out, frames---def test_decoded_animation_matches_retained_inputs_and_external_sources(gallery):- out, _ = gallery- report = verify.verify(out)- assert report["external_shader_files"] == 3- film = report["films"][0]- assert film["frames_decoded"] == 9- assert set(film["motion_correspondence_at_160x90"]) == {3, 6}- assert film["capture_binding"] == "encoded_digest_and_input_frames"--[email protected]("change, message", [- ("frozen", "differs from its input|does not follow captured motion"),- ("encoded_bytes", "differs from its capture digest"),- ("missing_camera", "complete capture plan"),- ("fragment", "Published shaders"),- ("legacy", "lacks encoded-file/anchor evidence"),-])-def test_mislabelled_or_incomplete_media_is_rejected(gallery, change, message):- out, frames = gallery- record = json.loads((out / "smoke.capture.json").read_text())- if change == "frozen":- encode(out / "smoke.mp4", [frames[0]] * 9)- record["video_sha256"] = verify.sha256(out / "smoke.mp4")- write_json(out / "smoke.capture.json", record)- elif change == "encoded_bytes":- with (out / "smoke.mp4").open("ab") as stream:- stream.write(b"changed")- elif change == "fragment":- (out / "src/shaders/surface.frag").write_text("// Changed after capture\n")- elif change == "legacy":- record.pop("reference_frames")- record.pop("video_sha256")- write_json(out / "smoke.capture.json", record)- else:- plan = json.loads((out / "capture-plan.json").read_text())- plan["films"].append({**plan["films"][0], "file": "smoke_close.mp4"})- write_json(out / "capture-plan.json", plan)- with pytest.raises(ValueError, match=message):- verify.verify(out)---def six_studies(gallery):- out, _ = gallery- manifest = json.loads((out / "manifest.json").read_text())- template = manifest["cases"][0]- record = json.loads((out / "smoke.capture.json").read_text())- manifest["cases"] = []- for key in ["fire", "ocean", "stream", "sand", "rocks", "meadow"]:- scene = f"export const kind = '{key}';\n".encode()- case = {**template, "id": key, "module": f"./src/scenes/{key}.js",- "scene_sha256": hashlib.sha256(scene).hexdigest()}- manifest["cases"].append(case)- (out / f"src/scenes/{key}.js").write_bytes(scene)- shutil.copy2(out / "smoke.mp4", out / f"{key}.mp4")- shutil.copy2(out / "smoke.png", out / f"{key}.png")- write_json(out / f"{key}.capture.json", {**record, "source_sha256":- build.workspace_hashes(case, manifest["library_sha256"], manifest["shader_sha256"])})- write_json(out / "manifest.json", manifest)- return out, record---def test_transfer_package_keeps_shader_and_capture_inputs(gallery):- out, record = six_studies(gallery)- result = package.build_package(out, "transfer")- folder = Path(result["folder"])- for suffix in ["glsl", "vert", "frag"]:- assert (folder / f"src/shaders/surface.{suffix}").read_bytes() == b"void main() {}\n"- for reference in record["reference_frames"]:- assert verify.sha256(folder / reference["path"]) == reference["sha256"]- assert result["zip_crc_and_extracted_hashes"] == "pass"- with pytest.raises(FileExistsError):- package.build_package(out, "transfer")--[email protected]("changed", ["fire.mp4", "fire.capture.json"])-def test_concurrent_recapture_cannot_change_verified_package_bytes(gallery, monkeypatch, changed):- out, _ = six_studies(gallery)- original_copy = shutil.copy2- changed_source = out / changed-- def mutate_before_copy(source, target):- if source == changed_source:- with source.open("ab") as stream:- stream.write(b"changed during packaging")- return original_copy(source, target)-- monkeypatch.setattr(package.shutil, "copy2", mutate_before_copy)- with pytest.raises(ValueError, match="hash mismatch"):- package.build_package(out, "inconsistent")- assert not (out / "packages/inconsistent.zip").exists()- assert not (out / "packages/inconsistent").exists()