Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.
JavaScript 3d3d-assets3d-modelingagent-skillsagent-toolsai-agentsasset-pipelinecligame-assetsglbgltfmcpmcp-servermodel-context-protocolprocedural-generationprocedural-modelingtext-to-3dthreejstypescript
feat: scaffold @kiln/engine — lean carve-out from pixel-forge core/kiln
Matt Kissinger287ab8a299ce
diff --git a/.gitignore b/.gitignorenew file mode 100644index 00000000..f4f85e76--- /dev/null+++ b/.gitignore@@ -0,0 +1,11 @@+node_modules/+dist/+coverage/+*.tsbuildinfo+*.log+.DS_Store+.env+.env.*+!.env.example+.localdata/+tmp/diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 00000000..afa99cda--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,42 @@+# Changelog++All notable changes to `@kiln/engine`. This is a **private** package; semver is tracked+for the consuming app's lockfile + tarball provenance, not public npm releases.++## [0.1.0] — 2026-06-23++Initial extraction of the Kiln 3D engine from `pixel-forge/packages/core/src/kiln`+(source `d396c10`), file history preserved via `git subtree split`.++### Included (the reachable runtime closure of agent/render/palette/views/arena)+- `agent/` Strands agent loop · `arena/` ranking math · `render.ts` GLB bake/grade/optimize/snap/composeScene+- `primitives.ts` · `solids.ts` (CSG) · `ops.ts` · `gears.ts` · `uv.ts`/`uv-shapes.ts` · `textures.ts`+- `validation.ts` (AST) · `inspect.ts` · `metrics.ts` · `palette.ts`/`palette-snap.ts`+- `list-primitives.ts` · `prompt.ts`/`prompt-api.ts` · `tools/registry.ts` · `views/` (CPU rasterizer + PNG)++### Removed vs pixel-forge core/kiln (what makes it lean)+- TIJ pipeline modules `imposter/`, `fbx-ingest/`, `sprite-atlas/`, `retex/`,+ `photogrammetry/`, `lod/` — the only modules pulling in Playwright + the heavier+ image path.+- Legacy single-shot `generate.ts` (Studio uses the agent path) and the entangled root+ `index.ts` barrel (Studio consumes subpaths, not the barrel).+- Dropped deps: `@anthropic-ai/*`, `@ai-sdk/{anthropic,google,openai}`, `@google/genai`,+ `openai`, `@fal-ai/client`, Vercel `ai`, `playwright`, `meshoptimizer`, `xatlas-three`,+ `@pixel-forge/shared`.++### Retained runtime deps (lazy-loaded)+- `sharp` — texture decode in `loadTexture` (`await import('sharp')`).+- `xatlasjs` — UV atlas in `autoUnwrap` (`await import('xatlasjs/dist/node/...')`).++### Tests+- 38 source test files ported. Live agent tests gated behind `KILN_SPIKE_LIVE=1`+ (off in CI). Dropped: the 6 OUT-module test suites, `deps-smoke` (old dep set), and+ `spike`/`top-level-generate` (tested the deleted barrel `generate()` wrapper).++### Follow-ups (deliberately deferred from WS0 — see ../plan/03-standards-harness.md)+- Tighten `tsconfig` (`exactOptionalPropertyTypes`); currently mirrors pixel-forge core+ for a zero-drift green typecheck.+- Add Biome lint config.+- Consider `tsup` `dist` build + Vitest golden-image render harness (engine ships TS+ source today for drop-in parity with how Studio consumes core).+- Rename the live-test gate `KILN_SPIKE_LIVE` → `KILN_LIVE`.diff --git a/LICENSE b/LICENSEnew file mode 100644index 00000000..f2bfd501--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Matthew Kissinger++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 00000000..5326d214--- /dev/null+++ b/README.md@@ -0,0 +1,57 @@+# @kiln/engine++The **Kiln 3D engine** — a sentence in, a game-ready GLB out. A model-agnostic+Strands agent loop drives a tool surface (`list → validate → render → screenshot →+finalize`) over a primitive/CSG library, a deterministic pure-CPU rasterizer that+lets the model *see* its asset, and post-bake grading (instanceability, palette+consolidation). Plus a Bradley-Terry pairwise **arena** for ranking.++Extracted from the `pixel-forge` monorepo (`packages/core/src/kiln`) as a lean,+self-contained package: **no Playwright, no 2D image SDKs, no FBX/imposter/LOD+pipeline** — just the text-to-GLB engine Kiln Studio runs in production.++> **Private package.** Not published to npm. Consumed by the `kiln-studio` app via a+> path-link locally and a committed tarball in CI/Docker. See `../plan/`.++## Install++```bash+bun install+bun run typecheck # tsc --noEmit+bun run test # bun test (offline; live agent tests gated behind KILN_SPIKE_LIVE=1)+```++## Subpath exports++The engine ships TypeScript source (Bun/tsx transpile on the fly); consume by subpath:++| Import | What |+|---|---|+| `@kiln/engine/agent` | the Strands agent loop, model factory, tool surface, edit buffer, unified-diff |+| `@kiln/engine/render` | GLB build + serialize, `grade`/`optimize`/`snap`, `composeScene` (the core bake) |+| `@kiln/engine/palette` | canonical `OPTIMIZED_PALETTE` + directive (pure data, browser-safe) |+| `@kiln/engine/views` | the pure-CPU six-view rasterizer + `node:zlib` PNG encoder (`kiln_screenshot`) |+| `@kiln/engine/arena` | Bradley-Terry + adaptive pairwise sampling (pure math) |+| `@kiln/engine/validation` | structural validator + AST analysis (acorn) |+| `@kiln/engine/primitives` | the 70+ primitive/helper registry |+| `@kiln/engine/prompt`, `/prompt-api`, `/list-primitives` | system-prompt generation + catalog |+| `@kiln/engine/metrics`, `/inspect` | instanceability grade + scene-structure analysis |++## Dependencies++Runtime: `three`, `@gltf-transform/*`, `manifold-3d` (CSG, WASM), `three-subdivide`,+`acorn`/`acorn-walk`, `zod`, `@openrouter/ai-sdk-provider`, plus lazy-loaded `sharp`+(texture decode) and `xatlasjs` (UV atlas). The agent stack —+`@strands-agents/sdk` + `@ai-sdk/provider` — is an **optional peer**: install it only+when you use `@kiln/engine/agent`.++## Determinism++Render/rasterizer compute paths are deterministic — no `Date.now()` / `Math.random()` —+so six-view output is byte-reproducible (the basis for golden-image tests). Inject+seeds/timestamps at the boundary.++## Provenance++Initial extraction from `pixel-forge@d396c10`, file history preserved via+`git subtree split`. See `CHANGELOG.md`.diff --git a/bun.lock b/bun.locknew file mode 100644index 00000000..dc80ec47--- /dev/null+++ b/bun.lock@@ -0,0 +1,575 @@+{+ "lockfileVersion": 1,+ "configVersion": 1,+ "workspaces": {+ "": {+ "name": "@kiln/engine",+ "dependencies": {+ "@gltf-transform/core": "^4.4.0",+ "@gltf-transform/functions": "^4.4.0",+ "@openrouter/ai-sdk-provider": "^2.9.1",+ "@types/three": "^0.184.1",+ "acorn": "^8.17.0",+ "acorn-walk": "^8.3.5",+ "manifold-3d": "^3.5.1",+ "sharp": "^0.34.5",+ "three": "0.184.0",+ "three-subdivide": "^1.1.5",+ "xatlasjs": "^0.2.0",+ "zod": "^4.4.3",+ },+ "devDependencies": {+ "@ai-sdk/provider": "^3.0.10",+ "@anthropic-ai/sdk": "^0.104.1",+ "@aws-sdk/client-bedrock-runtime": "^3.1075.0",+ "@google/genai": "^2.8.0",+ "@strands-agents/sdk": "^1.4.0",+ "@types/bun": "^1.3.14",+ "ai": "^6.0.202",+ "openai": "^6.42.0",+ "typescript": "^6.0.3",+ },+ "peerDependencies": {+ "@ai-sdk/provider": "^3.0.0",+ "@strands-agents/sdk": "^1.4.0",+ },+ "optionalPeers": [+ "@ai-sdk/provider",+ "@strands-agents/sdk",+ ],+ },+ },+ "packages": {+ "@ai-sdk/gateway": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.30", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-PfUkQp01EihEyNM6e+nexXmVANiY5KcHMui/MmaHsC4KVVQYh/MwPeOsD3bTPu63e581BKO+AwaPPNmD4x943A=="],++ "@ai-sdk/provider": ["@ai-sdk/[email protected]", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-Q3BZ27qfpYqnCYGvE3vt+Qi6LGOF9R5Nmzn+9JoM1lCRsD9mYaIhfJLkSunN48nfGXJ6n+XNV0J/XVpqGQl7Dw=="],++ "@ai-sdk/provider-utils": ["@ai-sdk/[email protected]", "", { "dependencies": { "@ai-sdk/provider": "3.0.10", "@standard-schema/spec": "^1.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-VO7I+vPffqI5sMnPoUq5DCSqKIgQIk/naJWRdQVpz2ma2zoprC/lqiJiUEl2s6DfvTD76TbhD3q39ROjlA6rGw=="],++ "@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-s1wEVDAtEwkS7Ajgep6PZKJLFqybRkmD3Byz+iVVsSpbDY0gjROXE9aOft6V3PMqynn3NTcycV5whga9tCzmKA=="],++ "@aws-crypto/crc32": ["@aws-crypto/[email protected]", "", { "dependencies": { "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "tslib": "^2.6.2" } }, "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg=="],++ "@aws-crypto/sha256-browser": ["@aws-crypto/[email protected]", "", { "dependencies": { "@aws-crypto/sha256-js": "^5.2.0", "@aws-crypto/supports-web-crypto": "^5.2.0", "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "@aws-sdk/util-locate-window": "^3.0.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw=="],++ "@aws-crypto/sha256-js": ["@aws-crypto/[email protected]", "", { "dependencies": { "@aws-crypto/util": "^5.2.0", "@aws-sdk/types": "^3.222.0", "tslib": "^2.6.2" } }, "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA=="],++ "@aws-crypto/supports-web-crypto": ["@aws-crypto/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg=="],++ "@aws-crypto/util": ["@aws-crypto/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.222.0", "@smithy/util-utf8": "^2.0.0", "tslib": "^2.6.2" } }, "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ=="],++ "@aws-sdk/client-bedrock-runtime": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.23", "@aws-sdk/credential-provider-node": "^3.972.58", "@aws-sdk/eventstream-handler-node": "^3.972.22", "@aws-sdk/middleware-eventstream": "^3.972.18", "@aws-sdk/middleware-websocket": "^3.972.31", "@aws-sdk/token-providers": "3.1075.0", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/fetch-http-handler": "^5.4.6", "@smithy/node-http-handler": "^4.7.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-LDGtNMOxnMz0dw9q+8z0f/X+Soj8OyiYg5zPcqToLh6H9/HHlazogFj7PXqFLOhnvhCqyAvKVAC1ZrL0RX418g=="],++ "@aws-sdk/core": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.973.13", "@aws-sdk/xml-builder": "^3.972.31", "@aws/lambda-invoke-store": "^0.2.2", "@smithy/core": "^3.24.6", "@smithy/signature-v4": "^5.4.6", "@smithy/types": "^4.14.3", "bowser": "^2.11.0", "tslib": "^2.6.2" } }, "sha512-MiWR/uWjxjFXGzrE0Ghc5lWxUxzHsUWFhV+OX7M4cR9SrmrnZs6TXavnCWnzzdwJeFri34xQo81rvGNzK3c4BQ=="],++ "@aws-sdk/credential-provider-env": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.974.23", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-liB3yQNHCM9k/gu/w36XHMKPluT7HTlnGUhRbBGSISDQkcr/Sy1zsZabiuvQj8WG5yW573u9RehrBvvnIQ9OEQ=="],++ "@aws-sdk/credential-provider-http": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.974.23", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/fetch-http-handler": "^5.4.6", "@smithy/node-http-handler": "^4.7.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-XET0H2oofciJ5lMRWNIvRjAP7Q3wv2XT+JtJJEdhPWUMwe3TvQ9qcxonpu7vXmNngncvFpi4E2It+Tamas/naA=="],++ "@aws-sdk/credential-provider-ini": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.974.23", "@aws-sdk/credential-provider-env": "^3.972.49", "@aws-sdk/credential-provider-http": "^3.972.51", "@aws-sdk/credential-provider-login": "^3.972.55", "@aws-sdk/credential-provider-process": "^3.972.49", "@aws-sdk/credential-provider-sso": "^3.972.55", "@aws-sdk/credential-provider-web-identity": "^3.972.55", "@aws-sdk/nested-clients": "^3.997.23", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/credential-provider-imds": "^4.3.7", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-IAmc61hbgQiHht9U3x0tnRwz0lzdwOwD/i9voRgdJrKamF+JtmrBOsW9GwB7mfFonNWOWL4qARWYrF8veEMe3w=="],++ "@aws-sdk/credential-provider-login": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.974.23", "@aws-sdk/nested-clients": "^3.997.23", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-hBBkANo3cDn+h2qxxzER4a+J8JCO9o9Z/YYmU7iky6AcaarX5RRdRcHNC6SLdwY0vAXQygn6soUbDqPn3GghaA=="],++ "@aws-sdk/credential-provider-node": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.49", "@aws-sdk/credential-provider-http": "^3.972.51", "@aws-sdk/credential-provider-ini": "^3.972.56", "@aws-sdk/credential-provider-process": "^3.972.49", "@aws-sdk/credential-provider-sso": "^3.972.55", "@aws-sdk/credential-provider-web-identity": "^3.972.55", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/credential-provider-imds": "^4.3.7", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-OyCLVmSI7pZO8hxwNVX6pXhTVlJqRBTp+ijdEfJSUj0RyjHnF602OfAarOzGq6wkGodeFkYBt8MmJ6A6ycRgWw=="],++ "@aws-sdk/credential-provider-process": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.974.23", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-C8h36lBuC/RnBSsjlO+dn6xZm3KbAl5vpJaVPAfQnMmz2/OISmKOc8XZcqMQgO2ADwBYNRMM6Kf3vz9G/TulMQ=="],++ "@aws-sdk/credential-provider-sso": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.974.23", "@aws-sdk/nested-clients": "^3.997.23", "@aws-sdk/token-providers": "3.1074.0", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-1FkOz74Ea5QGS9jtIoXp55T/IkSS3spv+nLTT07fRY/+T5xmEOqaYBVIaEmX4zTNvbV6g2lrtlaVKWEoNyJt3w=="],++ "@aws-sdk/credential-provider-web-identity": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.974.23", "@aws-sdk/nested-clients": "^3.997.23", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-g2BoECD1q01kTPByi56+VLVvdWDzMkKIcr77qixpqH0okw2t0U5CoPv+6S8v/D1Y2Wa6QKKtn6XAtDzP+Kfpvg=="],++ "@aws-sdk/eventstream-handler-node": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-tqPJv0dz4+O0hWGm1a6YekcMZyPhDFs/zH73Von7icaVT5n0Jqvm86typ3jRrG+qoUdPhALOnboRLTmnWQTlYQ=="],++ "@aws-sdk/middleware-eventstream": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-OHpk8YoZi3yexPq8aFt1vN1IxA2zLKvsIR5GpWYylX/ve6kQmY7wxHNSFy/D3t2apMZ16rs76Co4dJWcDyIk3A=="],++ "@aws-sdk/middleware-websocket": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.974.23", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/fetch-http-handler": "^5.4.6", "@smithy/signature-v4": "^5.4.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-ps1rumU1LybSFHaW9dTDgkhCMJLVaedEY78kKSzUDDY+b9974/g6aiaYYA0U9WV0oL4CJCJrVWG+EZ/qr4or7g=="],++ "@aws-sdk/nested-clients": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-crypto/sha256-browser": "5.2.0", "@aws-crypto/sha256-js": "5.2.0", "@aws-sdk/core": "^3.974.23", "@aws-sdk/signature-v4-multi-region": "^3.996.35", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/fetch-http-handler": "^5.4.6", "@smithy/node-http-handler": "^4.7.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-gO93ZPsI2bxeFZD42f1/qjDw6FAZkNZcKRO94LIiT03fzOmcJ9e/tunxjVjA1Rl69ClmVJzz8H3G9CdKef10PA=="],++ "@aws-sdk/signature-v4-multi-region": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/types": "^3.973.13", "@smithy/signature-v4": "^5.4.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-6L/VWs+Wch2stHemCGTmUNqKLMzURxQDK5boNG3Jn3kAOp71meDUuS5sbObpEvFxHDq0uWeSLFDNSYsjNt+Dlg=="],++ "@aws-sdk/token-providers": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.974.23", "@aws-sdk/nested-clients": "^3.997.23", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-SsunyegDXq68TaN5Iut8ElErGIAA6DeuKPKd5/v0lpSmZBI7ZKOC5OALyi1MRHsl/cuO/zHkJL3vKnNHdGaI+Q=="],++ "@aws-sdk/types": ["@aws-sdk/[email protected]", "", { "dependencies": { "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-pEHZqRkAlHfnfAU9tK+WpKv/gBNjGJrHMgA3A0iYRGyswBS2t0pfez+lWlwktb3Bqa0ovh7w/QJTFwp3fDxLNg=="],++ "@aws-sdk/util-locate-window": ["@aws-sdk/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-uUbMs1cBZPafD0ohUj6EwNf0fPZ534NvBxHox4hjX+0Rxq5paSYUem7+hi833pYrzrcnBATKIYpR02MDXT5M9g=="],++ "@aws-sdk/xml-builder": ["@aws-sdk/[email protected]", "", { "dependencies": { "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-SzE4Pgyl+hDF+BuyuzxUSpwnuUu9lJuO1YGgteG89/4Qv0+2IQiVQqdbPV32IozLvXWQChPQcdkk/sKvb1QHiQ=="],++ "@aws/lambda-invoke-store": ["@aws/[email protected]", "", {}, "sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ=="],++ "@babel/runtime": ["@babel/[email protected]", "", {}, "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw=="],++ "@dimforge/rapier3d-compat": ["@dimforge/[email protected]", "", {}, "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="],++ "@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="],++ "@gltf-transform/core": ["@gltf-transform/[email protected]", "", { "dependencies": { "property-graph": "^4.1.0" } }, "sha512-cOPxOhHFFz5hwmix+li1+Nnq5qMV/QD3fTCsVlApxxFACtFdjkt2R/juseD4gvZ7D2c/yl6OilKH0pvI735YyQ=="],++ "@gltf-transform/extensions": ["@gltf-transform/[email protected]", "", { "dependencies": { "@gltf-transform/core": "^4.4.0", "ktx-parse": "^1.1.0" } }, "sha512-ZwEgFkkqnUR7d4m6roK9BycxxdoqJNtVyo7w5ShJ9syKBoQiXw2QrTSLwXaUAImSrEIl9Jh/wZTtvSVyviQuXg=="],++ "@gltf-transform/functions": ["@gltf-transform/[email protected]", "", { "dependencies": { "@gltf-transform/core": "^4.4.0", "@gltf-transform/extensions": "^4.4.0", "ktx-parse": "^1.1.0", "ndarray": "^1.0.19", "ndarray-lanczos": "^0.3.0", "ndarray-pixels": "^5.0.1" } }, "sha512-CaSTAVAd2NXNWsxdgvq090rKHqy7AQlcNWV4ec7xtQyS8WEv3S3gVN27ikWmdB8nWEsXUbOIDhtPMLbXI6xDJg=="],++ "@google/genai": ["@google/[email protected]", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"] }, "sha512-3DRdSJ0LaKFig3FNGeRDn9BQxtjZm2qr0hNH2d771LKcG0HvUYddlN0LPdSp8XU7Ekb04i9q3+tt64uYqavUdw=="],++ "@hono/node-server": ["@hono/[email protected]", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],++ "@img/colour": ["@img/[email protected]", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],++ "@img/sharp-darwin-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.2.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w=="],++ "@img/sharp-darwin-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.2.4" }, "os": "darwin", "cpu": "x64" }, "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw=="],++ "@img/sharp-libvips-darwin-arm64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g=="],++ "@img/sharp-libvips-darwin-x64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg=="],++ "@img/sharp-libvips-linux-arm": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A=="],++ "@img/sharp-libvips-linux-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw=="],++ "@img/sharp-libvips-linux-ppc64": ["@img/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA=="],++ "@img/sharp-libvips-linux-riscv64": ["@img/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA=="],++ "@img/sharp-libvips-linux-s390x": ["@img/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ=="],++ "@img/sharp-libvips-linux-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw=="],++ "@img/sharp-libvips-linuxmusl-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw=="],++ "@img/sharp-libvips-linuxmusl-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg=="],++ "@img/sharp-linux-arm": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.2.4" }, "os": "linux", "cpu": "arm" }, "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw=="],++ "@img/sharp-linux-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64" }, "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg=="],++ "@img/sharp-linux-ppc64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.2.4" }, "os": "linux", "cpu": "ppc64" }, "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA=="],++ "@img/sharp-linux-riscv64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.2.4" }, "os": "linux", "cpu": "none" }, "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw=="],++ "@img/sharp-linux-s390x": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.2.4" }, "os": "linux", "cpu": "s390x" }, "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg=="],++ "@img/sharp-linux-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.2.4" }, "os": "linux", "cpu": "x64" }, "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ=="],++ "@img/sharp-linuxmusl-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64" }, "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg=="],++ "@img/sharp-linuxmusl-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.2.4" }, "os": "linux", "cpu": "x64" }, "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q=="],++ "@img/sharp-wasm32": ["@img/[email protected]", "", { "dependencies": { "@emnapi/runtime": "^1.7.0" }, "cpu": "none" }, "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw=="],++ "@img/sharp-win32-arm64": ["@img/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g=="],++ "@img/sharp-win32-ia32": ["@img/[email protected]", "", { "os": "win32", "cpu": "ia32" }, "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg=="],++ "@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],++ "@jridgewell/resolve-uri": ["@jridgewell/[email protected]", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],++ "@jridgewell/sourcemap-codec": ["@jridgewell/[email protected]", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],++ "@jridgewell/trace-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],++ "@jscadui/3mf-export": ["@jscadui/[email protected]", "", {}, "sha512-y5vZktqCjyi7wA38zqNlLIdZUIRZoOO9vCjLzwmL4bR0hk7B/Zm1IeffzJPFe1vFc0C1IEv3hm8caDv3doRk9g=="],++ "@modelcontextprotocol/sdk": ["@modelcontextprotocol/[email protected]", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],++ "@nodable/entities": ["@nodable/[email protected]", "", {}, "sha512-9uGyhaQavEUMC8AIddIjau4NsnsXhou+j5sBAGojCM1oxmQpVKTWR/9JxABD6UAv12vpIms55fPZKFQEhG6uBg=="],++ "@openrouter/ai-sdk-provider": ["@openrouter/[email protected]", "", { "peerDependencies": { "ai": "^6.0.0", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-okgq07Vdkro4CB5INbfhwa0e6VR1HS7sidNcfHN/MeXLJvX1JmQCff/vem6tcxwT9r1avyFrXSlfv9B28D/Pag=="],++ "@opentelemetry/api": ["@opentelemetry/[email protected]", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="],++ "@protobufjs/aspromise": ["@protobufjs/[email protected]", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],++ "@protobufjs/base64": ["@protobufjs/[email protected]", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="],++ "@protobufjs/codegen": ["@protobufjs/[email protected]", "", {}, "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g=="],++ "@protobufjs/eventemitter": ["@protobufjs/[email protected]", "", {}, "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg=="],++ "@protobufjs/fetch": ["@protobufjs/[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1" } }, "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw=="],++ "@protobufjs/float": ["@protobufjs/[email protected]", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="],++ "@protobufjs/path": ["@protobufjs/[email protected]", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="],++ "@protobufjs/pool": ["@protobufjs/[email protected]", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="],++ "@protobufjs/utf8": ["@protobufjs/[email protected]", "", {}, "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg=="],++ "@smithy/core": ["@smithy/[email protected]", "", { "dependencies": { "@aws-crypto/crc32": "5.2.0", "@smithy/types": "^4.15.0", "tslib": "^2.6.2" } }, "sha512-mLUktFAn+Pa2agl1J7VgtYNFWCX8/b4GMJSK1hCu4YCvtBfM6F8Os3EP4ry+DFFlXOf3wyvlgXhuUdFoy52D3g=="],++ "@smithy/credential-provider-imds": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/core": "^3.26.0", "@smithy/types": "^4.15.0", "tslib": "^2.6.2" } }, "sha512-18UMDMyrAbDcpmL1gLUA7ww0fRTcdCrSjSJOi2Sbld+tVjwD/pW+OAwjlScFLR7vvBnhZrIPQ7kVuTf1mnJLug=="],++ "@smithy/fetch-http-handler": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/core": "^3.26.0", "@smithy/types": "^4.15.0", "tslib": "^2.6.2" } }, "sha512-Ei/UK/QMhq0rKaMqGPlOAkE2yS9DZeYmZdk1RAKc3vp3zxgleZHZyBLlZv8yLsxljX4svCRuMTD6u3LLIcU4Bg=="],++ "@smithy/is-array-buffer": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA=="],++ "@smithy/node-http-handler": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/core": "^3.26.0", "@smithy/types": "^4.15.0", "tslib": "^2.6.2" } }, "sha512-wfl1uwrAqMH9/pi4kqBo5LBcFwrJLxuDLqL7p7qNcJIFcyZDUc6pzhYk4CYv+DP7fIUpQCZumwNnkhPKS52osQ=="],++ "@smithy/signature-v4": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/core": "^3.26.0", "@smithy/types": "^4.15.0", "tslib": "^2.6.2" } }, "sha512-7xHpmPY4rt0IOmeAA8EfjgEH8isT+587TCdy9H6a7d4OMi5CQ0oEHhWllunvPu4j4Cq0vTFwdxXN/kABWPjdyA=="],++ "@smithy/types": ["@smithy/[email protected]", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-Z5TAOxygoFvybJV3igo5SloFflSokHx2hu1eFA+DxDTcn+FtKxUSui+rbTRG1pAafMA888Z3MVvCWUuvCrTXjg=="],++ "@smithy/util-buffer-from": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/is-array-buffer": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA=="],++ "@smithy/util-utf8": ["@smithy/[email protected]", "", { "dependencies": { "@smithy/util-buffer-from": "^2.2.0", "tslib": "^2.6.2" } }, "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A=="],++ "@stablelib/base64": ["@stablelib/[email protected]", "", {}, "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ=="],++ "@standard-schema/spec": ["@standard-schema/[email protected]", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],++ "@strands-agents/sdk": ["@strands-agents/[email protected]", "", { "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.1037.0", "@types/json-schema": "^7.0.15", "uuid": "^14.0.0", "yaml": "^2.8.3" }, "peerDependencies": { "@a2a-js/sdk": "^0.3.10", "@ai-sdk/provider": "^3.0.0", "@anthropic-ai/sdk": "^0.92.0", "@aws-sdk/client-bedrock-agent": "^3.943.0", "@aws-sdk/client-bedrock-agent-runtime": "^3.943.0", "@aws-sdk/client-s3": "^3.943.0", "@aws/bedrock-token-generator": "^1.1.0", "@cedar-policy/cedar-wasm": "^4.0.0", "@cedar-policy/mcp-schema-generator-wasm": "^0.6.0", "@google/genai": "^1.40.0", "@modelcontextprotocol/sdk": "^1.25.2", "@opentelemetry/api": "^1.9.0", "@opentelemetry/exporter-metrics-otlp-http": "^0.214.0", "@opentelemetry/exporter-trace-otlp-http": "^0.214.0", "@opentelemetry/resources": "^2.6.1", "@opentelemetry/sdk-metrics": "^2.6.1", "@opentelemetry/sdk-trace-base": "^2.6.1", "@opentelemetry/sdk-trace-node": "^2.6.1", "@smithy/types": "^4.0.0", "express": "^5.1.0", "openai": "^6.7.0", "zod": "^4.1.12" }, "optionalPeers": ["@a2a-js/sdk", "@ai-sdk/provider", "@anthropic-ai/sdk", "@aws-sdk/client-bedrock-agent", "@aws-sdk/client-bedrock-agent-runtime", "@aws-sdk/client-s3", "@aws/bedrock-token-generator", "@cedar-policy/cedar-wasm", "@cedar-policy/mcp-schema-generator-wasm", "@google/genai", "@opentelemetry/exporter-metrics-otlp-http", "@opentelemetry/exporter-trace-otlp-http", "@opentelemetry/resources", "@opentelemetry/sdk-metrics", "@opentelemetry/sdk-trace-base", "@opentelemetry/sdk-trace-node", "@smithy/types", "express", "openai"] }, "sha512-tvmDHkgO7oPe8G0c3bmnTiSetb/Iden4DdSh/maRyLqDZj7uLIeS7whwrk654yM7EOYgo6p0/ewEItMbS+7m+A=="],++ "@tweenjs/tween.js": ["@tweenjs/[email protected]", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="],++ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],++ "@types/json-schema": ["@types/[email protected]", "", {}, "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA=="],++ "@types/ndarray": ["@types/[email protected]", "", {}, "sha512-oANmFZMnFQvb219SSBIhI1Ih/r4CvHDOzkWyJS/XRqkMrGH5/kaPSA1hQhdIBzouaE+5KpE/f5ylI9cujmckQg=="],++ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-vf2YFi1iY9lHGwNJMs01biZFbKJkrZR1T6/MlzjhJLPdntOHLhTrDSnSVcdtvjihi4VQNlrFRIxLsDBlQpAipA=="],++ "@types/retry": ["@types/[email protected]", "", {}, "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA=="],++ "@types/stats.js": ["@types/[email protected]", "", {}, "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA=="],++ "@types/three": ["@types/[email protected]", "", { "dependencies": { "@dimforge/rapier3d-compat": "~0.12.0", "@tweenjs/tween.js": "~23.1.3", "@types/stats.js": "*", "@types/webxr": ">=0.5.17", "fflate": "~0.8.2", "meshoptimizer": "~1.1.1" } }, "sha512-6q4VdiqVsrTRqmk62/BnlcAvIrnDM0zf2ZDVKI5kZiniWrSaOHaQzmbp+BNzoggc/8tgW412pL//wZIxu2PPTA=="],++ "@types/webxr": ["@types/[email protected]", "", {}, "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg=="],++ "@vercel/oidc": ["@vercel/[email protected]", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="],++ "accepts": ["[email protected]", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],++ "acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg=="],++ "acorn-walk": ["[email protected]", "", { "dependencies": { "acorn": "^8.11.0" } }, "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw=="],++ "agent-base": ["[email protected]", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],++ "ai": ["[email protected]", "", { "dependencies": { "@ai-sdk/gateway": "3.0.134", "@ai-sdk/provider": "3.0.10", "@ai-sdk/provider-utils": "4.0.30", "@opentelemetry/api": "^1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-NE7uErmxOe+i77BPT1+AhW4wr7xzilbQLsKVmvGEyil5AjaF6C/m92hlPI4Xwtnv5n77D/29bizwcR27/S/gSQ=="],++ "ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],++ "ajv-formats": ["[email protected]", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],++ "anynum": ["[email protected]", "", {}, "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A=="],++ "base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],++ "bignumber.js": ["[email protected]", "", {}, "sha512-Ko0uX15oIUS7wJ3Rb30Fs6SkVbLmPBAKdlm7q9+ak9bbIeFf0MwuBsQV6z7+X768/cHsfg+WlysDWJcmthjsjQ=="],++ "body-parser": ["[email protected]", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="],++ "bowser": ["[email protected]", "", {}, "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg=="],++ "buffer-equal-constant-time": ["[email protected]", "", {}, "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="],++ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],++ "bytes": ["[email protected]", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],++ "call-bind-apply-helpers": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],++ "call-bound": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],++ "comlink": ["[email protected]", "", {}, "sha512-OxGdvBmJuNKSCMO4NTl1L47VRp6xn2wG4F/2hYzB6tiCb709otOxtEYCSvK80PtjODfXXZu8ds+Nw5kVCjqd2g=="],++ "commander": ["[email protected]", "", {}, "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw=="],++ "content-disposition": ["[email protected]", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],++ "content-type": ["[email protected]", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],++ "convert-source-map": ["[email protected]", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],++ "cookie": ["[email protected]", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],++ "cookie-signature": ["[email protected]", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],++ "cors": ["[email protected]", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],++ "cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],++ "cwise-compiler": ["[email protected]", "", { "dependencies": { "uniq": "^1.0.0" } }, "sha512-WXlK/m+Di8DMMcCjcWr4i+XzcQra9eCdXIJrgh4TUgh0pIS/yJduLxS9JgefsHJ/YVLdgPtXm9r62W92MvanEQ=="],++ "data-uri-to-buffer": ["[email protected]", "", {}, "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A=="],++ "debug": ["[email protected]", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],++ "depd": ["[email protected]", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],++ "detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],++ "dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],++ "ecdsa-sig-formatter": ["[email protected]", "", { "dependencies": { "safe-buffer": "^5.0.1" } }, "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ=="],++ "ee-first": ["[email protected]", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],++ "encodeurl": ["[email protected]", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],++ "es-define-property": ["[email protected]", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],++ "es-errors": ["[email protected]", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],++ "es-object-atoms": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="],++ "esbuild-wasm": ["[email protected]", "", { "bin": { "esbuild": "bin/esbuild" } }, "sha512-1k03e2/tGz+sLz3/xzoZmUsIqtaGIvJa8k4UqUeqCUry83nHmlxQYZUUES0WBFUYilSQUf7nDUGAciIIklljSg=="],++ "escape-html": ["[email protected]", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],++ "etag": ["[email protected]", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],++ "eventsource": ["[email protected]", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],++ "eventsource-parser": ["[email protected]", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="],++ "express": ["[email protected]", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],++ "express-rate-limit": ["[email protected]", "", { "dependencies": { "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A=="],++ "extend": ["[email protected]", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],++ "fast-deep-equal": ["[email protected]", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],++ "fast-sha256": ["[email protected]", "", {}, "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ=="],++ "fast-uri": ["[email protected]", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="],++ "fast-xml-builder": ["[email protected]", "", { "dependencies": { "path-expression-matcher": "^1.5.0", "xml-naming": "^0.1.0" } }, "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q=="],++ "fast-xml-parser": ["[email protected]", "", { "dependencies": { "@nodable/entities": "^2.2.0", "fast-xml-builder": "^1.2.0", "is-unsafe": "^1.0.1", "path-expression-matcher": "^1.5.0", "strnum": "^2.4.1", "xml-naming": "^0.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-brCNCeScma/kqa54J4PIDriSSSLssRkuYaUCpvHJulGc3HGI/xxKUCTDcYkAdqJsyb//ydpbxecjC3hB9+tb/g=="],++ "fetch-blob": ["[email protected]", "", { "dependencies": { "node-domexception": "^1.0.0", "web-streams-polyfill": "^3.0.3" } }, "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ=="],++ "fflate": ["[email protected]", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="],++ "finalhandler": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],++ "formdata-polyfill": ["[email protected]", "", { "dependencies": { "fetch-blob": "^3.1.2" } }, "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g=="],++ "forwarded": ["[email protected]", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],++ "fresh": ["[email protected]", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],++ "function-bind": ["[email protected]", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],++ "gaxios": ["[email protected]", "", { "dependencies": { "extend": "^3.0.2", "https-proxy-agent": "^7.0.1", "node-fetch": "^3.3.2" } }, "sha512-5FZy72Rh8LhtjmvDrKkI+lVhrsQrVKVsItxMoDm5mNQE+xR0WVIIs+jzPSJgBvKVsLi24fZhXJIsNI0bihDzFg=="],++ "gcp-metadata": ["[email protected]", "", { "dependencies": { "gaxios": "^7.0.0", "google-logging-utils": "^1.0.0", "json-bigint": "^1.0.0" } }, "sha512-zV/5HKTfCeKWnxG0Dmrw51hEWFGfcF2xiXqcA3+J90WDuP0SvoiSO5ORvcBsifmx/FoIjgQN3oNOGaQ5PhLFkg=="],++ "get-intrinsic": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],++ "get-proto": ["[email protected]", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],++ "google-auth-library": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.0", "ecdsa-sig-formatter": "^1.0.11", "gaxios": "^7.1.4", "gcp-metadata": "8.1.2", "google-logging-utils": "1.1.3", "jws": "^4.0.0" } }, "sha512-QpTAbNJ36TliZLx3TTtahR8HG0hN9RllL1e3FymOvQSIKK8JmgV58H924ub2wa2DsS3ANjjP1Aw1N+Ramc8hqQ=="],++ "google-logging-utils": ["[email protected]", "", {}, "sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA=="],++ "gopd": ["[email protected]", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],++ "has-symbols": ["[email protected]", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],++ "hasown": ["[email protected]", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],++ "hono": ["[email protected]", "", {}, "sha512-1yrb/+w6HWQJrUCLkJ2IF5jNIPvvFkblV5RNOYl6bV+OA6p9GLcMpHFFGTosSvHvcAUibuUukRqhlYI4z32C7Q=="],++ "http-errors": ["[email protected]", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],++ "https-proxy-agent": ["[email protected]", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="],++ "iconv-lite": ["[email protected]", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],++ "inherits": ["[email protected]", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],++ "iota-array": ["[email protected]", "", {}, "sha512-pZ2xT+LOHckCatGQ3DcG/a+QuEqvoxqkiL7tvE8nn3uuu+f6i1TtpB5/FtWFbxUuVr5PZCx8KskuGatbJDXOWA=="],++ "ip-address": ["[email protected]", "", {}, "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA=="],++ "ipaddr.js": ["[email protected]", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],++ "is-buffer": ["[email protected]", "", {}, "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="],++ "is-promise": ["[email protected]", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],++ "is-unsafe": ["[email protected]", "", {}, "sha512-CLK2+VdgERgD96EYm5lUQssZYlRg2tkZnbsxZoacmSiRxiFJ4Nk4SzjCl+Ur+v3kXIY9dTIdb3IH22y1mZ56LA=="],++ "isexe": ["[email protected]", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],++ "jose": ["[email protected]", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="],++ "json-bigint": ["[email protected]", "", { "dependencies": { "bignumber.js": "^9.0.0" } }, "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ=="],++ "json-schema": ["[email protected]", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="],++ "json-schema-to-ts": ["[email protected]", "", { "dependencies": { "@babel/runtime": "^7.18.3", "ts-algebra": "^2.0.0" } }, "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g=="],++ "json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],++ "json-schema-typed": ["[email protected]", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],++ "jwa": ["[email protected]", "", { "dependencies": { "buffer-equal-constant-time": "^1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg=="],++ "jws": ["[email protected]", "", { "dependencies": { "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA=="],++ "ktx-parse": ["[email protected]", "", {}, "sha512-mKp3y+FaYgR7mXWAbyyzpa/r1zDWeaunH+INJO4fou3hb45XuNSwar+7llrRyvpMWafxSIi99RNFJ05MHedaJQ=="],++ "long": ["[email protected]", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],++ "magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],++ "manifold-3d": ["[email protected]", "", { "dependencies": { "@gltf-transform/core": "^4.2.0", "@gltf-transform/extensions": "^4.2.0", "@gltf-transform/functions": "^4.2.0", "@jridgewell/resolve-uri": "^3.1.2", "@jridgewell/trace-mapping": "^0.3.31", "@jscadui/3mf-export": "^0.5.0", "commander": "^13.1.0", "convert-source-map": "^2.0.0", "fast-xml-parser": "^5.4.2", "fflate": "^0.8.0", "magic-string": "^0.30.21" }, "peerDependencies": { "esbuild-wasm": "^0.27.3" }, "bin": { "manifold-cad": "bin/manifold-cad" } }, "sha512-/+m6kxYMMhnPutcQ5oSmFJiJ+gyP/0fmuUCb9Qeaunvecm/bfqogKYDDJarsnWiFioSMtKheF+lGmSlnYCik9g=="],++ "math-intrinsics": ["[email protected]", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],++ "media-typer": ["[email protected]", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],++ "merge-descriptors": ["[email protected]", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],++ "meshoptimizer": ["[email protected]", "", {}, "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g=="],++ "mime-db": ["[email protected]", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],++ "mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],++ "ms": ["[email protected]", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],++ "ndarray": ["[email protected]", "", { "dependencies": { "iota-array": "^1.0.0", "is-buffer": "^1.0.2" } }, "sha512-B4JHA4vdyZU30ELBw3g7/p9bZupyew5a7tX1Y/gGeF2hafrPaQZhgrGQfsvgfYbgdFZjYwuEcnaobeM/WMW+HQ=="],++ "ndarray-lanczos": ["[email protected]", "", { "dependencies": { "@types/ndarray": "^1.0.11", "ndarray": "^1.0.19" } }, "sha512-5kBmmG3Zvyj77qxIAC4QFLKuYdDIBJwCG+DukT6jQHNa1Ft74/hPH1z5mbQXeHBt8yvGPBGVrr3wEOdJPYYZYg=="],++ "ndarray-ops": ["[email protected]", "", { "dependencies": { "cwise-compiler": "^1.0.0" } }, "sha512-BppWAFRjMYF7N/r6Ie51q6D4fs0iiGmeXIACKY66fLpnwIui3Wc3CXiD/30mgLbDjPpSLrsqcp3Z62+IcHZsDw=="],++ "ndarray-pixels": ["[email protected]", "", { "dependencies": { "@types/ndarray": "^1.0.14", "ndarray": "^1.0.19", "ndarray-ops": "^1.2.2", "sharp": "^0.34.0" } }, "sha512-IBtrpefpqlI8SPDCGjXk4v5NV5z7r3JSuCbfuEEXaM0vrOJtNGgYUa4C3Lt5H+qWdYF4BCPVFsnXhNC7QvZwkw=="],++ "negotiator": ["[email protected]", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],++ "node-domexception": ["[email protected]", "", {}, "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ=="],++ "node-fetch": ["[email protected]", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="],++ "object-assign": ["[email protected]", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],++ "object-inspect": ["[email protected]", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],++ "on-finished": ["[email protected]", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],++ "once": ["[email protected]", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],++ "openai": ["[email protected]", "", { "peerDependencies": { "ws": "^8.18.0", "zod": "^3.25 || ^4.0" }, "optionalPeers": ["ws", "zod"] }, "sha512-09/gH+8jH0RgUwsgWHAaxsKGRT5zVZ95IaJUnqAWj6XejIBmnFRwq2WUIF37VtDEsmGrtPmvCs5+yBSeZGWvkA=="],++ "p-retry": ["[email protected]", "", { "dependencies": { "@types/retry": "0.12.0", "retry": "^0.13.1" } }, "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ=="],++ "parseurl": ["[email protected]", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],++ "path-expression-matcher": ["[email protected]", "", {}, "sha512-h7bxdzhHk8Knyc4Tj+jMaa7fEEoUJy7p1qtbVgkYg1Uhpe5Np5VuGXCRZnkZvU+Q42M1vStt0ifa3ueykRJPmQ=="],++ "path-key": ["[email protected]", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],++ "path-to-regexp": ["[email protected]", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="],++ "pkce-challenge": ["[email protected]", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],++ "property-graph": ["[email protected]", "", {}, "sha512-AvPcP7XECNWy4LGmFQ77k7un4lSKM4eS29PTvW4ck95uYeLxXPWJM7hLuBqK91FaHqCcgJvIUCuNJjjxKE7VKQ=="],++ "protobufjs": ["[email protected]", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" } }, "sha512-RJJPTTpvFfHcWLkIa2JFWK4XvtSzS0yEWDmunqHXli1h3JlkbcQZXDZdcWxv+JK3Xsl5/UFDPZ0iGm7DAengYw=="],++ "proxy-addr": ["[email protected]", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],++ "qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw=="],++ "range-parser": ["[email protected]", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="],++ "raw-body": ["[email protected]", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],++ "require-from-string": ["[email protected]", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],++ "retry": ["[email protected]", "", {}, "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg=="],++ "router": ["[email protected]", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],++ "safe-buffer": ["[email protected]", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],++ "safer-buffer": ["[email protected]", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],++ "semver": ["[email protected]", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],++ "send": ["[email protected]", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],++ "serve-static": ["[email protected]", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],++ "setprototypeof": ["[email protected]", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],++ "sharp": ["[email protected]", "", { "dependencies": { "@img/colour": "^1.0.0", "detect-libc": "^2.1.2", "semver": "^7.7.3" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.34.5", "@img/sharp-darwin-x64": "0.34.5", "@img/sharp-libvips-darwin-arm64": "1.2.4", "@img/sharp-libvips-darwin-x64": "1.2.4", "@img/sharp-libvips-linux-arm": "1.2.4", "@img/sharp-libvips-linux-arm64": "1.2.4", "@img/sharp-libvips-linux-ppc64": "1.2.4", "@img/sharp-libvips-linux-riscv64": "1.2.4", "@img/sharp-libvips-linux-s390x": "1.2.4", "@img/sharp-libvips-linux-x64": "1.2.4", "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", "@img/sharp-libvips-linuxmusl-x64": "1.2.4", "@img/sharp-linux-arm": "0.34.5", "@img/sharp-linux-arm64": "0.34.5", "@img/sharp-linux-ppc64": "0.34.5", "@img/sharp-linux-riscv64": "0.34.5", "@img/sharp-linux-s390x": "0.34.5", "@img/sharp-linux-x64": "0.34.5", "@img/sharp-linuxmusl-arm64": "0.34.5", "@img/sharp-linuxmusl-x64": "0.34.5", "@img/sharp-wasm32": "0.34.5", "@img/sharp-win32-arm64": "0.34.5", "@img/sharp-win32-ia32": "0.34.5", "@img/sharp-win32-x64": "0.34.5" } }, "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg=="],++ "shebang-command": ["[email protected]", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],++ "shebang-regex": ["[email protected]", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],++ "side-channel": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4", "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ=="],++ "side-channel-list": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="],++ "side-channel-map": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="],++ "side-channel-weakmap": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],++ "standardwebhooks": ["[email protected]", "", { "dependencies": { "@stablelib/base64": "^1.0.0", "fast-sha256": "^1.3.0" } }, "sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg=="],++ "statuses": ["[email protected]", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],++ "strnum": ["[email protected]", "", { "dependencies": { "anynum": "^1.0.1" } }, "sha512-M9eUSMT2dCB2cTNPG7UYj6KuK7RJR2SN2+yCV/fTW3xzTCS6EaGZ5pSMgDIjB7r8zSfTGk+dvvn9rTjpVS9Mwg=="],++ "three": ["[email protected]", "", {}, "sha512-wtTRjG92pM5eUg/KuUnHsqSAlPM296brTOcLgMRqEeylYTh/CdtvKUvCyyCQTzFuStieWxvZb8mVTMvdPyUpxg=="],++ "three-subdivide": ["[email protected]", "", { "peerDependencies": { "three": ">= 0.125.0" } }, "sha512-eEWMevrsHIMnC1xbsZSQZIB8QBr8XeXZhTSAdYrLm3ZC/yTdR4ocOZ2Qi+gEyPJFOt3iirQ+SQR0jCamk7e6FQ=="],++ "toidentifier": ["[email protected]", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],++ "ts-algebra": ["[email protected]", "", {}, "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw=="],++ "tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],++ "type-is": ["[email protected]", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="],++ "typescript": ["[email protected]", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="],++ "undici-types": ["[email protected]", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="],++ "uniq": ["[email protected]", "", {}, "sha512-Gw+zz50YNKPDKXs+9d+aKAjVwpjNwqzvNpLigIruT4HA9lMZNdMqs9x07kKHB/L9WRzqp4+DlTU5s4wG2esdoA=="],++ "unpipe": ["[email protected]", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],++ "uuid": ["[email protected]", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew=="],++ "vary": ["[email protected]", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],++ "web-streams-polyfill": ["[email protected]", "", {}, "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="],++ "which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],++ "wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],++ "ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g=="],++ "xatlasjs": ["[email protected]", "", { "optionalDependencies": { "comlink": "^4.3.1" } }, "sha512-3YxdpuDY4X2Kjn/Zm2c5648x/hYAP/X5YIx7nc1ify65kroSX+CFyzkhbBkIq9RDpjhA2prPRyhJZzYPUE1WgQ=="],++ "xml-naming": ["[email protected]", "", {}, "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw=="],++ "yaml": ["[email protected]", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],++ "zod": ["[email protected]", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],++ "zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],++ "@aws-sdk/credential-provider-sso/@aws-sdk/token-providers": ["@aws-sdk/[email protected]", "", { "dependencies": { "@aws-sdk/core": "^3.974.23", "@aws-sdk/nested-clients": "^3.997.23", "@aws-sdk/types": "^3.973.13", "@smithy/core": "^3.24.6", "@smithy/types": "^4.14.3", "tslib": "^2.6.2" } }, "sha512-pv80IzgGW4RnXWtft692chZOM9i6PhebVsLCcnaM4dBEPZva2fE6FXAHs76G7Rc7s3yGyX/68G0nZMrUy+Vmpg=="],++ "body-parser/content-type": ["[email protected]", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],++ "type-is/content-type": ["[email protected]", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],+ }+}diff --git a/package.json b/package.jsonnew file mode 100644index 00000000..e7bd6f12--- /dev/null+++ b/package.json@@ -0,0 +1,75 @@+{+ "name": "@kiln/engine",+ "private": true,+ "version": "0.1.0",+ "description": "Kiln 3D engine — text-to-GLB codegen agent loop, deterministic CPU render/rasterizer, primitive/CSG library, palette + instanceability grading, and pairwise ranking arena. Extracted from pixel-forge.",+ "license": "MIT",+ "author": "Matthew Kissinger",+ "type": "module",+ "exports": {+ "./agent": "./src/agent/index.ts",+ "./arena": "./src/arena/index.ts",+ "./render": "./src/render.ts",+ "./palette": "./src/palette.ts",+ "./views": "./src/views/index.ts",+ "./validation": "./src/validation.ts",+ "./primitives": "./src/primitives.ts",+ "./prompt": "./src/prompt.ts",+ "./prompt-api": "./src/prompt-api.ts",+ "./list-primitives": "./src/list-primitives.ts",+ "./metrics": "./src/metrics.ts",+ "./inspect": "./src/inspect.ts"+ },+ "files": [+ "src/**/*.ts",+ "!src/**/*.test.ts",+ "!src/**/__tests__/**",+ "README.md",+ "LICENSE",+ "CHANGELOG.md"+ ],+ "scripts": {+ "typecheck": "tsc --noEmit",+ "build": "tsc --noEmit",+ "test": "KILN_SPIKE_LIVE=0 bun test",+ "test:live": "KILN_SPIKE_LIVE=1 bun test",+ "lint": "biome check ."+ },+ "dependencies": {+ "@gltf-transform/core": "^4.4.0",+ "@gltf-transform/functions": "^4.4.0",+ "@openrouter/ai-sdk-provider": "^2.9.1",+ "@types/three": "^0.184.1",+ "acorn": "^8.17.0",+ "acorn-walk": "^8.3.5",+ "manifold-3d": "^3.5.1",+ "sharp": "^0.34.5",+ "three": "0.184.0",+ "three-subdivide": "^1.1.5",+ "xatlasjs": "^0.2.0",+ "zod": "^4.4.3"+ },+ "peerDependencies": {+ "@ai-sdk/provider": "^3.0.0",+ "@strands-agents/sdk": "^1.4.0"+ },+ "peerDependenciesMeta": {+ "@ai-sdk/provider": {+ "optional": true+ },+ "@strands-agents/sdk": {+ "optional": true+ }+ },+ "devDependencies": {+ "@ai-sdk/provider": "^3.0.10",+ "@anthropic-ai/sdk": "^0.104.1",+ "@aws-sdk/client-bedrock-runtime": "^3.1075.0",+ "@google/genai": "^2.8.0",+ "@strands-agents/sdk": "^1.4.0",+ "@types/bun": "^1.3.14",+ "ai": "^6.0.202",+ "openai": "^6.42.0",+ "typescript": "^6.0.3"+ }+}diff --git a/src/__tests__/companions.test.ts b/src/__tests__/companions.test.tsdeleted file mode 100644index 28d58dea..00000000--- a/src/__tests__/companions.test.ts+++ /dev/null@@ -1,222 +0,0 @@-/**- * Kiln companion entries (W2.1)- *- * Render-only + mocked-SDK tests for the `editKilnCode`, `compactCode`,- * `refactorCode`, and `inspectGeneratedAnimation` entry points. Keeps us- * honest that the ports from `packages/server/src/services/claude.ts` into- * `@pixel-forge/core/kiln` behave the same, and that the new joint-warning- * inspector catches common LLM animation mistakes.- *- * All SDK calls are mocked — no network, no ANTHROPIC_API_KEY, no cost.- */--import { describe, expect, test, mock, beforeEach } from 'bun:test';--// These companions test the SINGLE-SHOT machinery (mocked claude-agent-sdk).-// The codegen default is now the Strands agent loop — pin this file's runs to-// the mocked path before the module under test is imported.-process.env['KILN_CODEGEN'] = 'single-shot';--// Mocks must be declared before importing the module under test.-let queryImpl = async function* (_args: unknown): AsyncGenerator<unknown> {- yield { type: 'result', subtype: 'success', result: '', session_id: 'test' };-};--mock.module('@anthropic-ai/claude-agent-sdk', () => ({- query: (args: unknown) => queryImpl(args),-}));--// Fresh import helper so each test gets a clean module registry slot —-// prevents cross-test mock bleed when bun runs several tests in a row.-let counter = 0;-let kiln: typeof import('../index');-async function freshImport() {- counter += 1;- return (await import(`../index?test=${counter}`)) as typeof import('../index');-}--describe('kiln.editCode', () => {- beforeEach(async () => {- queryImpl = async function* () {- yield {- type: 'result',- subtype: 'success',- structured_output: {- code: 'const meta = { name: "Edited" }; function build() { return {}; }',- },- session_id: 'edit-session',- };- };- kiln = await freshImport();- });-- test('returns edited code with session id', async () => {- const result = await kiln.editKilnCode('const meta = {}; function build() { return {}; }', 'make it red');- expect(result.success).toBe(true);- expect(result.code).toContain('Edited');- expect(result.sessionId).toBe('edit-session');- });-});--describe('kiln.compactCode', () => {- test('extracts code from markdown fence', async () => {- queryImpl = async function* () {- yield {- type: 'assistant',- message: { content: [{ type: 'text', text: '```js\nconst x=1;\n```' }] },- };- };- kiln = await freshImport();- const result = await kiln.compactCode('verbose code');- expect(result.success).toBe(true);- expect(result.code).toBe('const x=1;');- });-- test('returns raw text when no fence', async () => {- queryImpl = async function* () {- yield {- type: 'assistant',- message: { content: [{ type: 'text', text: 'bare text' }] },- };- };- kiln = await freshImport();- const result = await kiln.compactCode('verbose code');- expect(result.success).toBe(true);- expect(result.code).toBe('bare text');- });-- test('accepts timeoutMs override', async () => {- let observedOptions: { abortController?: AbortController } | undefined;- queryImpl = async function* (args: unknown) {- observedOptions = (args as { options?: { abortController?: AbortController } }).options;- yield { type: 'assistant', message: { content: [{ type: 'text', text: 'ok' }] } };- };- kiln = await freshImport();- await kiln.compactCode('code', { timeoutMs: 1000 });- expect(observedOptions?.abortController).toBeInstanceOf(AbortController);- });-});--describe('kiln.refactorCode', () => {- test('returns structured output with session id', async () => {- queryImpl = async function* () {- yield {- type: 'result',- subtype: 'success',- structured_output: { code: 'new geo', effectCode: 'new eff' },- session_id: 'refactor-session',- };- };- kiln = await freshImport();- const result = await kiln.refactorCode({- instruction: 'reshape',- geometryCode: 'old geo',- effectCode: 'old eff',- target: 'both',- });- expect(result.success).toBe(true);- expect(result.code).toBe('new geo');- expect(result.effectCode).toBe('new eff');- expect(result.sessionId).toBe('refactor-session');- });-- test('surfaces thrown errors from query', async () => {- // eslint-disable-next-line require-yield -- the throw is the whole point of this fake- queryImpl = async function* () {- throw new Error('SDK boom');- };- kiln = await freshImport();- const result = await kiln.refactorCode({- instruction: 'fail me',- geometryCode: 'x',- target: 'geometry',- });- expect(result.success).toBe(false);- expect(result.error).toBe('SDK boom');- });-});--describe('kiln.inspectGeneratedAnimation', () => {- test('flags tracks targeting unknown nodes', async () => {- kiln = await freshImport();-- // Execute a minimal code string so we can get a real Three scene + clip- // pair to pass into the inspector.- const code = `-const meta = { name: 'InspectTest' };-function build() {- const root = createRoot('InspectTest');- createPivot('Body', [0, 1, 0], root);- return root;-}-function animate() {- // Note: "Joint_Missing" does NOT exist in the scene — this should warn.- return [createClip('wiggle', 1, [- rotationTrack('Joint_Missing', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [30, 0, 0] }]),- ])];-}-`;- const { root, clips } = await kiln.executeKilnCode(code);- const warnings = kiln.inspectGeneratedAnimation(root, clips);- expect(warnings.length).toBeGreaterThan(0);- expect(warnings.some((w) => w.includes('Joint_Missing'))).toBe(true);- });-- test('is silent when all tracks resolve', async () => {- kiln = await freshImport();- const code = `-const meta = { name: 'Good' };-function build() {- const root = createRoot('Good');- createPivot('Body', [0, 1, 0], root);- return root;-}-function animate() {- return [createClip('breathe', 1, [- rotationTrack('Joint_Body', [{ time: 0, rotation: [0, 0, 0] }, { time: 1, rotation: [10, 0, 0] }]),- ])];-}-`;- const { root, clips } = await kiln.executeKilnCode(code);- const warnings = kiln.inspectGeneratedAnimation(root, clips);- expect(warnings).toEqual([]);- });-- test('returns [] when no clips present', async () => {- kiln = await freshImport();- const code = `-const meta = { name: 'Static' };-function build() {- const root = createRoot('Static');- return root;-}-`;- const { root, clips } = await kiln.executeKilnCode(code);- expect(clips).toEqual([]);- expect(kiln.inspectGeneratedAnimation(root, clips)).toEqual([]);- });-});--describe('kiln.generateKilnCode', () => {- test('passes timeoutMs through to query', async () => {- let observedOptions: { abortController?: AbortController; model?: string } | undefined;- queryImpl = async function* (args: unknown) {- observedOptions = (args as { options?: { abortController?: AbortController; model?: string } }).options;- yield {- type: 'result',- subtype: 'success',- structured_output: {- code: 'const meta = {}; function build() { return {}; }',- },- session_id: 's',- };- };- kiln = await freshImport();- await kiln.generateKilnCode(- { prompt: 'x', mode: 'glb', category: 'prop' },- { timeoutMs: 5000, model: 'claude-opus-4-7' }- );- expect(observedOptions?.model).toBe('claude-opus-4-7');- expect(observedOptions?.abortController).toBeInstanceOf(AbortController);- });-});diff --git a/src/__tests__/deps-smoke.test.ts b/src/__tests__/deps-smoke.test.tsdeleted file mode 100644index debc30ac..00000000--- a/src/__tests__/deps-smoke.test.ts+++ /dev/null@@ -1,32 +0,0 @@-/**- * Wave 1C smoke test: verify the new WASM/module deps load cleanly in Node.- * If any of these fail to import, the downstream CSG/UV/subdivide primitives- * (Waves 2A / 2B / 3A) won't work.- */--import { describe, it, expect } from 'bun:test';--describe('Wave 1C: new dependency smoke tests', () => {- it('manifold-3d loads and initializes', async () => {- const module = (await import('manifold-3d')) as unknown as {- default: () => Promise<Record<string, unknown>>;- };- const init = module.default;- expect(typeof init).toBe('function');-- const Manifold = (await init()) as Record<string, unknown>;- expect(Manifold).toBeDefined();- expect(typeof Manifold['Manifold']).toBe('function');- });-- it('three-subdivide loads', async () => {- const mod = (await import('three-subdivide')) as Record<string, unknown>;- expect(mod).toBeDefined();- expect(typeof mod['LoopSubdivision']).toBe('function');- });-- it('xatlas-three loads', async () => {- const mod = (await import('xatlas-three')) as Record<string, unknown>;- expect(mod).toBeDefined();- });-});diff --git a/src/__tests__/prompt-api.test.ts b/src/__tests__/prompt-api.test.tsindex 311c6a62..d01db837 100644--- a/src/__tests__/prompt-api.test.ts+++ b/src/__tests__/prompt-api.test.ts@@ -12,7 +12,7 @@*/import { describe, expect, test } from 'bun:test';-import { readFileSync } from 'node:fs';+import { existsSync, readFileSync } from 'node:fs';import { resolve, dirname } from 'node:path';import { fileURLToPath } from 'node:url';@@ -159,7 +159,9 @@ describe('unified api surface (examples folded in)', () => {// (3) Skill drift gate// =============================================================================-describe('kiln-glb skill files match the catalog render', () => {+// The kiln-glb skill is a downstream artifact (lives outside the engine repo); this+// gate stays dormant here and fires wherever the skill is vendored at the expected depth.+describe.skipIf(!existsSync(SKILL_DIR))('kiln-glb skill files match the catalog render', () => {test('references/primitives.md is up to date (bun run kiln:gen-skill)', () => {const onDisk = readFileSync(resolve(SKILL_DIR, 'references/primitives.md'), 'utf-8');expect(onDisk.replace(/\r\n/g, '\n')).toBe(renderPrimitivesMarkdown(listPrimitives()));diff --git a/src/__tests__/refactor-validation.test.ts b/src/__tests__/refactor-validation.test.tsdeleted file mode 100644index 5735e6ef..00000000--- a/src/__tests__/refactor-validation.test.ts+++ /dev/null@@ -1,101 +0,0 @@-/**- * kiln.refactor + hardened validation wiring (W3b.4)- *- * Verifies that refactorCode runs the W3b.3 validator over its output and- * re-prompts the SDK once when the first attempt fails validation. Mocks- * the agent SDK so no network / API key needed.- */--import { describe, expect, test, mock } from 'bun:test';--// Track every call so we can verify the re-prompt happened.-let calls = 0;-const responses: string[] = [];--mock.module('@anthropic-ai/claude-agent-sdk', () => ({- query: () =>- (async function* () {- const idx = calls;- calls += 1;- const code = responses[idx] ?? responses[responses.length - 1] ?? '';- yield {- type: 'result',- subtype: 'success',- structured_output: { code },- session_id: `session-${idx}`,- };- })(),-}));--let counter = 0;-async function freshImport(): Promise<typeof import('../index')> {- counter += 1;- return (await import(`../index?refactor-validation=${counter}`)) as typeof import('../index');-}--describe('kiln.refactor — hardened validation', () => {- test('returns immediately when refactored code passes validation', async () => {- calls = 0;- responses.length = 0;- responses.push(`-const meta = { name: 'OK' };-function build() { return createRoot('OK'); }-`);-- const kiln = await freshImport();- const result = await kiln.refactor({- instruction: 'tweak',- geometryCode: 'old',- target: 'geometry',- });-- expect(result.success).toBe(true);- expect(result.code).toContain('OK');- expect(calls).toBe(1);- });-- test('re-prompts once when first attempt fails validation', async () => {- calls = 0;- responses.length = 0;- // First attempt: missing build() — invalid.- responses.push(`const meta = { name: 'X' };`);- // Retry: valid.- responses.push(`-const meta = { name: 'X' };-function build() { return createRoot('X'); }-`);-- const kiln = await freshImport();- const result = await kiln.refactor({- instruction: 'tweak',- geometryCode: 'old',- target: 'geometry',- });-- expect(result.success).toBe(true);- expect(calls).toBe(2);- expect(result.code).toContain('build');- });-- test('skips validation for effect-only refactors', async () => {- calls = 0;- responses.length = 0;- // Effect refactor returns whatever; not subject to geometry validator.- responses.push('// some TSL effect code');-- const kiln = await freshImport();- const result = await kiln.refactor({- instruction: 'tweak shader',- effectCode: 'old shader',- target: 'effect',- });-- expect(result.success).toBe(true);- expect(calls).toBe(1);- });-- test('alias `refactor` resolves to refactorCode', async () => {- const kiln = await freshImport();- expect(kiln.refactor).toBe(kiln.refactorCode);- });-});diff --git a/src/__tests__/spike.test.ts b/src/__tests__/spike.test.tsdeleted file mode 100644index be834970..00000000--- a/src/__tests__/spike.test.ts+++ /dev/null@@ -1,234 +0,0 @@-/**- * Kiln Headless Spike (W1.1)- *- * Gate test for the core refactor cycle. Validates that the headless- * Kiln pipeline in @pixel-forge/core can regenerate existing war-assets- * GLBs with roughly equivalent structure.- *- * Two bars:- * 1. renderGLB(<known-good-code>) produces a valid GLB Buffer and- * validate(<known-good-code>) is clean. (no LLM required)- * 2. For 3 reference GLBs, generate(prompt) produces output whose- * triangle count and named-part count are within tolerance.- * (LLM required - ~$0.10-0.30 per run at current Opus rates)- *- * Tolerances are deliberately loose because LLM output varies run-to-- * run. ±5% tri-count (from the W1.1 plan) was optimistic; ±20% is the- * realistic bar for a single-shot generation. Named-parts length is- * compared with a ±2 slack.- *- * Set ANTHROPIC_API_KEY (or let the Claude Code OAuth token do it) to- * run the live path. Set KILN_SPIKE_LIVE=0 to force skip.- *- * Run: cd packages/core && bun test- */--import { describe, expect, test } from 'bun:test';-import { existsSync, readFileSync } from 'node:fs';-import { NodeIO } from '@gltf-transform/core';--import { generate, renderGLB, validate } from '../index';-import { FIXTURES, KNOWN_GOOD_CODE, type GlbFixture } from './fixtures';--const LIVE_DISABLED = process.env['KILN_SPIKE_LIVE'] === '0';-const HAS_AUTH = Boolean(- process.env['ANTHROPIC_API_KEY'] ||- process.env['CLAUDE_CODE_OAUTH_TOKEN']-);-const LIVE = !LIVE_DISABLED && HAS_AUTH;--// The claude-agent-sdk spawns a nested Claude Code process. When this test-// runs inside an active Claude Code session (e.g. from a subagent), that-// nested launch is refused. Strip the session markers so the SDK can spawn-// its own child process cleanly. No-op outside Claude Code.-if (LIVE) {- delete process.env['CLAUDECODE'];- delete process.env['CLAUDE_CODE_ENTRYPOINT'];-}--const io = new NodeIO();--interface GlbSummary {- triangleCount: number;- namedParts: string[];- animationTracks: string[];- byteLength: number;-}--async function summarizeGlb(bytes: Uint8Array): Promise<GlbSummary> {- const doc = await io.readBinary(bytes);- const root = doc.getRoot();-- let triangleCount = 0;- for (const mesh of root.listMeshes()) {- for (const prim of mesh.listPrimitives()) {- const indices = prim.getIndices();- if (indices) {- triangleCount += indices.getCount() / 3;- } else {- const pos = prim.getAttribute('POSITION');- if (pos) triangleCount += pos.getCount() / 3;- }- }- }-- const namedParts: string[] = [];- for (const node of root.listNodes()) {- const name = node.getName();- if (name) namedParts.push(name);- }-- const animationTracks: string[] = [];- for (const anim of root.listAnimations()) {- for (const channel of anim.listChannels()) {- const targetNode = channel.getTargetNode();- const path = channel.getTargetPath();- if (targetNode && path) {- animationTracks.push(`${targetNode.getName() ?? '?'}.${path}`);- }- }- }-- return {- triangleCount: Math.floor(triangleCount),- namedParts,- animationTracks,- byteLength: bytes.byteLength,- };-}--// =============================================================================-// Tier 1 - Render-only (no LLM required)-// =============================================================================--describe('kiln headless render (no LLM)', () => {- test('validate() passes known-good code', () => {- const result = validate(KNOWN_GOOD_CODE);- expect(result.valid).toBe(true);- expect(result.errors).toEqual([]);- });-- test('validate() rejects code with imports', () => {- const bad = `import * as THREE from 'three';\n` + KNOWN_GOOD_CODE;- const result = validate(bad);- expect(result.valid).toBe(false);- expect(result.errors.join(' ')).toMatch(/import/i);- });-- test('validate() rejects wrong keyframe format', () => {- const bad = `-const meta = { name: 'X' };-function build() {- const r = createRoot('X');- createPivot('A', [0,0,0], r);- return r;-}-function animate() {- return [createClip('c', 1, [rotationTrack('Joint_A', [{ time: 0, value: [0,0,0] }])])];-}-`;- const result = validate(bad);- expect(result.valid).toBe(false);- expect(result.errors.join(' ')).toMatch(/value:/);- });-- test('renderGLB() produces a valid GLB from known-good code', async () => {- const render = await renderGLB(KNOWN_GOOD_CODE);-- // Basic sanity.- expect(render.glb).toBeInstanceOf(Buffer);- expect(render.glb.byteLength).toBeGreaterThan(1000);- expect(render.tris).toBeGreaterThan(0);- expect(render.meta.name).toBe('TestChest');-- // Re-read via NodeIO to confirm it's a readable GLB.- const summary = await summarizeGlb(render.glb);- expect(summary.triangleCount).toBeGreaterThan(0);- expect(summary.namedParts.length).toBeGreaterThan(0);- expect(summary.animationTracks.length).toBe(1); // the Open animation- expect(summary.animationTracks[0]).toMatch(/Joint_Lid\.rotation/);- });-});--// =============================================================================-// Tier 2 - Live generation against reference GLBs (LLM required)-// =============================================================================--describe('kiln headless generate against reference GLBs', () => {- const filter = process.env['KILN_SPIKE_ONLY'];- const fixtures = filter- ? FIXTURES.filter((f) => f.label === filter || f.slug === filter)- : FIXTURES;-- for (const fixture of fixtures) {- // Each fixture becomes its own test. We check fixture presence upfront- // and skip cleanly if it's missing (war-assets is gitignored).- runFixtureTest(fixture);- }-});--function runFixtureTest(fixture: GlbFixture): void {- const label = `${fixture.label} - ${fixture.slug}`;-- if (!LIVE) {- test.skip(`${label} (live path disabled: set ANTHROPIC_API_KEY or unset KILN_SPIKE_LIVE=0)`, () => {});- return;- }-- if (!existsSync(fixture.glbPath)) {- test.skip(`${label} (reference GLB missing at ${fixture.glbPath})`, () => {});- return;- }-- // 300s per fixture: LLM call + parse + render budget.- test(- label,- async () => {- const referenceBytes = readFileSync(fixture.glbPath);- const reference = await summarizeGlb(referenceBytes);-- const result = await generate(fixture.prompt, {- mode: 'glb',- category: fixture.category,- style: fixture.style,- includeAnimation: fixture.includeAnimation,- });-- expect(result.glb).toBeInstanceOf(Buffer);- expect(result.glb.byteLength).toBeGreaterThan(1000);-- const generated = await summarizeGlb(result.glb);-- const triRatio = generated.triangleCount / reference.triangleCount;- const nodeDelta = Math.abs(generated.namedParts.length - reference.namedParts.length);-- // Diagnostic output first - fires whether the assertions pass or- // fail so spike-report.md can reference the numbers either way.- console.log(`\n[${label}] prompt source: ${fixture.promptSource}`);- console.log(` reference: ${reference.triangleCount} tris, ${reference.namedParts.length} named nodes, ${reference.animationTracks.length} animation tracks`);- console.log(` generated: ${generated.triangleCount} tris, ${generated.namedParts.length} named nodes, ${generated.animationTracks.length} animation tracks`);- console.log(` ratio: ${triRatio.toFixed(3)}x tris, Δ${nodeDelta} nodes`);- if (result.warnings.length > 0) {- console.log(` warnings: ${result.warnings.join(' | ')}`);- }-- // Tri-count: ±20% tolerance. LLM output varies enough that exact- // match is unrealistic. We care about the order of magnitude -- // a 500-tri asset coming out as 5000 or 50 is the failure case.- expect(triRatio).toBeGreaterThan(0.5);- expect(triRatio).toBeLessThan(1.5);-- // Named-parts length: ±8 slack. The "±2" in the original plan held- // for trivial/medium assets but the guard tower has ~30+ named- // nodes and the LLM can legitimately merge, e.g., "4 legs" into 1- // parent + 4 meshes vs. 4 separate pivots. We require the same- // order of magnitude.- expect(nodeDelta).toBeLessThanOrEqual(8);-- // Animation tracks: for fixtures with includeAnimation=false we- // expect 0. For animated fixtures, we just match track count.- expect(generated.animationTracks.length).toBe(reference.animationTracks.length);- },- 780_000 // 13 min for LLM + render (generate.ts aborts query at 12 min)- );-}diff --git a/src/__tests__/top-level-generate.test.ts b/src/__tests__/top-level-generate.test.tsdeleted file mode 100644index eb387333..00000000--- a/src/__tests__/top-level-generate.test.ts+++ /dev/null@@ -1,179 +0,0 @@-/**- * Top-level kiln.generate() coverage (W7.3)- *- * The promise-y end-to-end entry point in `kiln/index.ts` was uncovered:- * its zero-arg-spread happy path, its option pass-through to the- * underlying generator, and its hard-failure throw. Mocks the SDK so- * we can drive both branches without an LLM round-trip.- */--import { describe, expect, test, mock, beforeEach, afterAll } from 'bun:test';--// Per-importer mock pattern, matching companions.test.ts. Each test gets-// a fresh import of `../index` so the module-scoped mock state stays clean.-let queryImpl = async function* (_args: unknown): AsyncGenerator<unknown> {- yield { type: 'result', subtype: 'success', result: '', session_id: 'test' };-};--mock.module('@anthropic-ai/claude-agent-sdk', () => ({- query: (args: unknown) => queryImpl(args),-}));--let counter = 0;-let kiln: typeof import('../index');-async function freshImport(): Promise<typeof import('../index')> {- counter += 1;- return (await import(`../index?top-level=${counter}`)) as typeof import('../index');-}--const VALID_CODE = `-const meta = { name: 'TopLevel', category: 'prop' };-function build() {- const root = createRoot('TopLevel');- createPart('Body', boxGeo(1, 1, 1), gameMaterial(0xff0000), { parent: root });- return root;-}-`;--// These tests cover the SINGLE-SHOT fallback path (the Claude Agent SDK query),-// which kiln.generate() now reaches only via codegen='single-shot' /-// KILN_CODEGEN=single-shot. The default 'agent' path is covered by the agent-// engine tests (agent/generate.test.ts) + the live e2e; pin single-shot here so-// the SDK mock is the one exercised.-describe('kiln.generate() top-level pipeline (single-shot fallback)', () => {- const savedCodegen = process.env['KILN_CODEGEN'];- beforeEach(async () => {- process.env['KILN_CODEGEN'] = 'single-shot';- queryImpl = async function* () {- yield {- type: 'result',- subtype: 'success',- structured_output: { code: VALID_CODE },- session_id: 'top-session',- };- };- kiln = await freshImport();- });- afterAll(() => {- if (savedCodegen === undefined) delete process.env['KILN_CODEGEN'];- else process.env['KILN_CODEGEN'] = savedCodegen;- });-- test('returns code + glb + meta + warnings for a valid response', async () => {- const out = await kiln.generate('a small red box');-- expect(out.code).toContain('TopLevel');- expect(out.glb).toBeInstanceOf(Buffer);- expect(out.glb.byteLength).toBeGreaterThan(1000);- expect(out.meta.name).toBe('TopLevel');- expect(out.meta.category).toBe('prop');- expect(typeof out.meta.tris).toBe('number');- expect(Array.isArray(out.warnings)).toBe(true);- });-- test('passes category, style, includeAnimation, model, timeoutMs through to the SDK', async () => {- let observedOptions:- | { abortController?: AbortController; model?: string; systemPrompt?: string }- | undefined;- let observedPrompt: string | undefined;- queryImpl = async function* (args: unknown) {- const a = args as {- prompt: string;- options?: { abortController?: AbortController; model?: string; systemPrompt?: string };- };- observedPrompt = a.prompt;- observedOptions = a.options;- yield {- type: 'result',- subtype: 'success',- structured_output: { code: VALID_CODE },- session_id: 's',- };- };- kiln = await freshImport();-- await kiln.generate('a low-poly chest', {- category: 'prop',- style: 'low-poly',- includeAnimation: false,- model: 'claude-opus-4-7',- timeoutMs: 5000,- });-- expect(observedOptions?.model).toBe('claude-opus-4-7');- expect(observedOptions?.abortController).toBeInstanceOf(AbortController);- // Style template lands in the prompt; "Do NOT include an animate()" too.- expect(observedPrompt).toContain('Low-Poly');- expect(observedPrompt).toContain('Do NOT include an animate()');- });-- test('default category is prop and animation is requested by default', async () => {- let observedPrompt: string | undefined;- queryImpl = async function* (args: unknown) {- observedPrompt = (args as { prompt: string }).prompt;- yield {- type: 'result',- subtype: 'success',- structured_output: { code: VALID_CODE },- session_id: 's',- };- };- kiln = await freshImport();-- await kiln.generate('a thing');- expect(observedPrompt).toContain('Create a prop');- expect(observedPrompt).toContain('Animation Requirements');- });-- test('throws when SDK reports a failure', async () => {- queryImpl = async function* () {- yield {- type: 'result',- subtype: 'error_max_turns',- errors: ['ran out of turns'],- };- };- kiln = await freshImport();-- await expect(kiln.generate('x')).rejects.toThrow(/Kiln code generation failed/);- });-- test('throws when SDK reports auth failure', async () => {- queryImpl = async function* () {- yield { type: 'auth_status', error: 'invalid token' };- };- kiln = await freshImport();-- await expect(kiln.generate('x')).rejects.toThrow(/Auth failed/);- });-- test('throws when SDK loop yields nothing', async () => {- // Drives the "no result received from query" branch. Yielding once- // with an unrelated message type also reaches it (the for-await- // loop completes without ever seeing a `result`/`auth_status` event).- queryImpl = async function* () {- yield { type: 'system', subtype: 'init' };- };- kiln = await freshImport();-- await expect(kiln.generate('x')).rejects.toThrow(/No result received/);- });-- test('strips CLAUDECODE markers from the parent env before invoking the SDK', async () => {- process.env['CLAUDECODE'] = '1';- process.env['CLAUDE_CODE_ENTRYPOINT'] = 'cli';- queryImpl = async function* () {- // After strip, both env vars should be undefined inside the query.- expect(process.env['CLAUDECODE']).toBeUndefined();- expect(process.env['CLAUDE_CODE_ENTRYPOINT']).toBeUndefined();- yield {- type: 'result',- subtype: 'success',- structured_output: { code: VALID_CODE },- };- };- kiln = await freshImport();-- await kiln.generate('x');- });-});diff --git a/src/fbx-ingest/__tests__/ingest.test.ts b/src/fbx-ingest/__tests__/ingest.test.tsdeleted file mode 100644index b3ddb545..00000000--- a/src/fbx-ingest/__tests__/ingest.test.ts+++ /dev/null@@ -1,38 +0,0 @@-/**- * FBX ingest — live Chromium test, gated on KILN_FBX_LIVE=1.- *- * Survival-kit zip sits at the TIJ project root; unzip it ahead of running- * this test:- * mkdir -p tmp/survival-kit- * unzip C:/Users/Mattm/X/games-3d/terror-in-the-jungle/survival-kit.zip -d tmp/survival-kit- * KILN_FBX_LIVE=1 KILN_FBX_FIXTURE=tmp/survival-kit/Models/FBX/barrel.fbx bun test ingest- */--import { describe, expect, test } from 'bun:test';-import { existsSync, readFileSync } from 'node:fs';--import { ingestFbx } from '../ingest';--const LIVE = process.env.KILN_FBX_LIVE === '1';-const FIXTURE_ENV = process.env.KILN_FBX_FIXTURE;--describe.if(LIVE && !!FIXTURE_ENV)('ingestFbx (live)', () => {- test('converts an FBX file to a non-empty GLB', async () => {- const fixture = FIXTURE_ENV!;- if (!existsSync(fixture)) {- throw new Error(`KILN_FBX_FIXTURE does not exist: ${fixture}`);- }- const fbx = readFileSync(fixture);- const result = await ingestFbx(fbx, { scale: 1.0, mergeMaterials: true });- // GLB magic 'glTF' = 0x46546C67 little-endian.- expect(result.glb.readUInt32LE(0)).toBe(0x46546c67);- expect(result.meta.bytes).toBeGreaterThan(1000);- expect(result.meta.sourceBytes).toBe(fbx.byteLength);- }, 60_000);-});--describe.if(!(LIVE && FIXTURE_ENV))('ingestFbx (skipped)', () => {- test('set KILN_FBX_LIVE=1 + KILN_FBX_FIXTURE=/path/to/file.fbx to run', () => {- expect(LIVE && FIXTURE_ENV).toBeFalsy();- });-});diff --git a/src/fbx-ingest/index.ts b/src/fbx-ingest/index.tsdeleted file mode 100644index 6690852a..00000000--- a/src/fbx-ingest/index.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * kiln/fbx-ingest — FBX -> GLB conversion via three.js FBXLoader + GLTFExporter.- *- * import { kiln } from '@pixel-forge/core';- * const { glb, meta } = await kiln.ingestFbx(fbxBuffer, { scale: 0.01 });- *- * For batch ingest of many FBX files, reuse a session:- * const session = await kiln.openFbxIngestSession();- * for (const path of files) await session.ingest(path);- * await session.close();- */--export { ingestFbx, openFbxIngestSession } from './ingest';-export type {- IngestFbxOptions,- IngestFbxResult,- IngestFbxSession,-} from './ingest';diff --git a/src/fbx-ingest/ingest.ts b/src/fbx-ingest/ingest.tsdeleted file mode 100644index 133353d6..00000000--- a/src/fbx-ingest/ingest.ts+++ /dev/null@@ -1,205 +0,0 @@-/**- * FBX -> GLB ingest.- *- * Host: Playwright Chromium (same pattern as kiln/imposter). FBXLoader and- * GLTFExporter both live in three/examples/jsm; they assume a browser- * context for Blob/URL/atob shims. Running them in-browser is simpler and- * more robust than backporting Node shims.- *- * Flow per input FBX:- * 1. Read bytes, base64-encode into a data: URL.- * 2. page.evaluate -> FBXLoader.parse(ArrayBuffer) -> THREE.Group.- * 3. Optional: scale the root to meters (FBX commonly exports in cm).- * 4. GLTFExporter.parse(group, { binary: true }) -> ArrayBuffer -> base64.- * 5. Decode to Buffer in Node, optionally run @gltf-transform dedup/prune.- */--import { readFileSync } from 'node:fs';-import { basename } from 'node:path';-import { Buffer } from 'node:buffer';--import { NodeIO } from '@gltf-transform/core';-import { dedup, prune } from '@gltf-transform/functions';-import { chromium, type Browser, type BrowserContext, type Page } from 'playwright';--export interface IngestFbxOptions {- /**- * Multiply the imported scene's root scale by this factor before export.- * FBX files commonly use centimeters — set 0.01 to normalize to meters.- * Default 1.0 (no rescale).- */- scale?: number;- /** Run @gltf-transform dedup + prune after serialization. Default true. */- mergeMaterials?: boolean;- /** Optional name stored in the exported glTF scene. Default = file basename. */- sceneName?: string;-}--export interface IngestFbxResult {- glb: Buffer;- meta: {- sceneName: string;- triangles: number;- bytes: number;- sourceBytes: number;- };-}--export interface IngestFbxSession {- ingest(fbx: Buffer | string, opts?: IngestFbxOptions): Promise<IngestFbxResult>;- close(): Promise<void>;-}--export async function openFbxIngestSession(): Promise<IngestFbxSession> {- const browser: Browser = await chromium.launch();- const ctx: BrowserContext = await browser.newContext();- const page: Page = await ctx.newPage();- await page.setContent(buildHarnessHtml());- await page.waitForFunction(- () => (globalThis as unknown as { __fbxReady?: boolean }).__fbxReady === true,- { timeout: 30_000 },- );-- return {- ingest: (fbx, opts) => ingestOnPage(page, fbx, opts ?? {}),- close: async () => {- await ctx.close();- await browser.close();- },- };-}--export async function ingestFbx(- fbx: Buffer | string,- opts: IngestFbxOptions = {},-): Promise<IngestFbxResult> {- const session = await openFbxIngestSession();- try {- return await session.ingest(fbx, opts);- } finally {- await session.close();- }-}--async function ingestOnPage(- page: Page,- fbx: Buffer | string,- opts: IngestFbxOptions,-): Promise<IngestFbxResult> {- const buf = typeof fbx === 'string' ? readFileSync(fbx) : fbx;- const sourcePath = typeof fbx === 'string' ? fbx : undefined;- const scale = opts.scale ?? 1.0;- const sceneName = opts.sceneName ?? (sourcePath ? basename(sourcePath, '.fbx') : 'Scene');-- const dataUrl = `data:application/octet-stream;base64,${buf.toString('base64')}`;- const out = (await page.evaluate(- async ([url, s, name]) => {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const w = globalThis as any;- return w.__fbxIngest(url, s, name);- },- [dataUrl, scale, sceneName] as const,- )) as { glbBase64: string; triangles: number };-- let glb = Buffer.from(out.glbBase64, 'base64');- if (opts.mergeMaterials !== false) {- // Run dedup + prune through gltf-transform for a tighter output.- const io = new NodeIO();- const doc = await io.readBinary(glb);- await doc.transform(prune(), dedup());- glb = Buffer.from(await io.writeBinary(doc));- }-- return {- glb,- meta: {- sceneName,- triangles: out.triangles,- bytes: glb.byteLength,- sourceBytes: buf.byteLength,- },- };-}--function buildHarnessHtml(): string {- return `<!DOCTYPE html>-<html><head>-<meta charset="utf-8">-<script type="importmap">-{- "imports": {- "three": "https://unpkg.com/[email protected]/build/three.module.js",- "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"- }-}-</script>-</head>-<body>-<script type="module">-import * as THREE from 'three';-import { FBXLoader } from 'three/addons/loaders/FBXLoader.js';-import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';--function countTris(root) {- let tris = 0;- root.traverse((o) => {- if (!o.isMesh || !o.geometry) return;- const g = o.geometry;- if (g.index) tris += g.index.count / 3;- else if (g.attributes.position) tris += g.attributes.position.count / 3;- });- return Math.round(tris);-}--window.__fbxIngest = async (dataUrl, scale, sceneName) => {- const resp = await fetch(dataUrl);- const arrayBuf = await resp.arrayBuffer();- const loader = new FBXLoader();- const group = loader.parse(arrayBuf, '');- if (scale !== 1) group.scale.multiplyScalar(scale);- group.name = sceneName;- const tris = countTris(group);-- // Strip texture map references — our ingest path doesn't load external- // texture files (FBXLoader was given an empty base path), so keeping the- // map slots populated with broken proxy textures triggers GLTFExporter's- // "No valid image data" error. We preserve each material's name and- // baseColor tint instead so a downstream retex pass can restore textures.- group.traverse((obj) => {- if (!obj.isMesh || !obj.material) return;- const mats = Array.isArray(obj.material) ? obj.material : [obj.material];- for (const m of mats) {- for (const key of ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap', 'bumpMap', 'specularMap']) {- if (m[key]) m[key] = null;- }- if (typeof m.needsUpdate !== 'undefined') m.needsUpdate = true;- }- });-- const exporter = new GLTFExporter();- const glb = await new Promise((resolve, reject) => {- exporter.parse(- group,- (result) => {- if (result instanceof ArrayBuffer) resolve(result);- else reject(new Error('GLTFExporter returned non-binary output'));- },- (err) => reject(err),- { binary: true, onlyVisible: true, trs: false },- );- });-- // ArrayBuffer -> base64 for postMessage.- const bytes = new Uint8Array(glb);- let bin = '';- const CHUNK = 0x8000;- for (let i = 0; i < bytes.length; i += CHUNK) {- bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK));- }- return { glbBase64: btoa(bin), triangles: tris };-};--window.__fbxReady = true;-</script>-</body></html>`;-}diff --git a/src/generate.ts b/src/generate.tsdeleted file mode 100644index 827c59cf..00000000--- a/src/generate.ts+++ /dev/null@@ -1,663 +0,0 @@-/**- * Claude-backed Kiln code generator- *- * Headless wrapper over the Claude Agent SDK. Drives prompt -> code- * generation (via structured JSON output) and the companion refactor flows:- * - generateKilnCode — primary generate path with validate+retry- * - editKilnCode — generate with an `existingCode` edit target- * - compactCode — code-golf pass via Haiku- * - refactorCode — structured edit with geometry + effect targeting- *- * Replaces the duplicate implementation that previously lived in- * packages/server/src/services/claude.ts; the server now delegates to- * these entry points.- */--import { query } from '@anthropic-ai/claude-agent-sdk';--import {- generateKilnCodeCandidate,- generateTextWithRoute,- isExperimentalKilnModel,- resolveKilnModelRoute,-} from '../llm';-import {- buildUserPrompt,- getSystemPrompt,- type KilnGenerateRequest,- type RenderMode,-} from './prompt';-import { validate } from './validation';--// =============================================================================-// Types-// =============================================================================--export interface KilnGenerateResult {- success: boolean;- code?: string;- effectCode?: string;- usage?: {- inputTokens: number;- outputTokens: number;- };- sessionId?: string;- error?: string;-}--export interface RefactorRequest {- instruction: string;- geometryCode?: string;- effectCode?: string;- target: 'geometry' | 'effect' | 'both';-}--/** Per-call tunables for the Opus generate path. */-export interface KilnGenerateCallOptions {- /** Abort milliseconds (default 720_000 = 12 min). */- timeoutMs?: number;- /** Override the model (default `claude-opus-4-7`). */- model?: string;-}--const KILN_OUTPUT_SCHEMA = {- type: 'object',- properties: {- code: {- type: 'string',- description:- 'JavaScript code with const meta, function build(), and optionally function animate()',- },- effectCode: {- type: 'string',- description: 'TSL shader code (for tsl/both modes only)',- },- },- required: ['code'],-};--// =============================================================================-// Defaults-// =============================================================================--// Claude Opus can take 2-5 minutes on coordinate-heavy prompts (guard-// towers, vehicles) and has occasionally stretched past 8 min in testing.-// Default 12 min gives the compound-prompt path breathing room.-const DEFAULT_QUERY_TIMEOUT_MS = 720_000;--/** The pinned Opus generation model. Bump in one place. */-// History:-// - 2026-04-23 (early): temporarily downgraded to 'claude-sonnet-4-6' because-// claude-agent-sdk 0.2.50 sent `thinking.type=enabled` which Opus 4.7-// rejects ("use thinking.type=adaptive + effort").-// - 2026-04-23 (late): SDK bumped to ^0.2.118 which accepts the new thinking-// API. Restored to 'claude-opus-4-7'. If a future SDK release regresses,-// set `KILN_MODEL=claude-sonnet-4-6` in the environment to bypass without-// touching code.-const DEFAULT_OPUS_MODEL =- process.env['KILN_MODEL'] ??- process.env['PIXEL_FORGE_MODEL'] ??- 'claude-opus-4-7';--/** The pinned Haiku compaction model. */-const DEFAULT_HAIKU_MODEL = 'claude-haiku-4-5-20251001';--type QueryMessage = {- type?: string;- subtype?: string;- session_id?: string;- structured_output?: { code: string; effectCode?: string };- result?: string;- errors?: unknown;- error?: string;-};--/**- * The `@anthropic-ai/claude-agent-sdk` spawns a nested Claude Code process- * and refuses to run when `CLAUDECODE` or `CLAUDE_CODE_ENTRYPOINT` are set- * in the parent env — which is exactly the case when anything in this repo- * is invoked from a Claude Code session (tests, subagents, manual dev).- *- * We strip them unconditionally before every SDK query so the kiln.*- * entry points "just work" regardless of how they're called. If a future- * consumer needs the markers preserved, they can set them again in their- * own child process.- */-function stripClaudeCodeNestingMarkers(): void {- delete process.env['CLAUDECODE'];- delete process.env['CLAUDE_CODE_ENTRYPOINT'];-}--/**- * Resolve the codegen mechanism: `KILN_CODEGEN` env > 'agent' default. Shared- * by `kiln.generate()` (index.ts) and `generateKilnCode` (this file) so both- * forks flip together.- */-export function resolveCodegenMode(explicit?: 'agent' | 'single-shot'): 'agent' | 'single-shot' {- if (explicit) return explicit;- const env = process.env['KILN_CODEGEN']?.trim().toLowerCase();- if (env === 'single-shot' || env === 'singleshot' || env === 'single') return 'single-shot';- return 'agent';-}---// =============================================================================-// Public API-// =============================================================================--/**- * Generate Kiln code (LLM only, no rendering). Validates GLB output and- * retries once with feedback if validation fails.- */-export async function generateKilnCode(- request: KilnGenerateRequest,- opts: KilnGenerateCallOptions = {}-): Promise<KilnGenerateResult> {- stripClaudeCodeNestingMarkers();-- try {- // DEFAULT: the Strands agent tool loop (code-only — callers render- // separately, exactly as with the single-shot emitter). This retires the- // last fork: the editor server route + editKilnCode now ride the same- // engine as the CLI/MCP/batch/studio. Falls through to single-shot for- // tsl/both modes, reference-image requests, KILN_CODEGEN=single-shot, or- // a model id the agent path can't translate.- if (resolveCodegenMode() === 'agent' && request.mode === 'glb' && !request.referenceImageUrl) {- // Lazy imports keep @strands-agents/sdk out of the non-agent module- // graph (browser/editor bundle safety) — same pattern as kiln.generate.- const { harnessIdToAgentModelId } = await import('./agent/providers');- const agentModel = opts.model ? harnessIdToAgentModelId(opts.model) : undefined;- if (!opts.model || agentModel) {- const { generateKilnCodeAgent } = await import('./agent/generate');- const result = await generateKilnCodeAgent({- prompt: request.prompt,- category: request.category,- ...(request.style ? { style: request.style } : {}),- includeAnimation: request.includeAnimation ?? false,- ...(request.existingCode ? { existingCode: request.existingCode } : {}),- ...(request.originalPrompt ? { originalPrompt: request.originalPrompt } : {}),- ...(agentModel ? { model: agentModel } : {}),- });- if (!result.success) return { success: false, error: result.error };- if (result.code) {- const validation = validate(result.code);- if (!validation.valid) {- return retryWithFeedback(request, result.code, validation.errors, opts);- }- }- return { success: true, code: result.code, usage: result.usage };- }- // opts.model had no agent translation — single-shot owns that id.- }-- if (shouldUseModelHarness(opts.model)) {- const result = await runHarnessGenerate(request, opts);- if (!result.success) return result;- if (result.code && request.mode !== 'tsl') {- const validation = validate(result.code);- if (!validation.valid) {- return retryWithFeedback(request, result.code, validation.errors, opts);- }- }- return result;- }-- const userPrompt = buildUserPrompt(request);- const systemPrompt = getSystemPrompt(request.mode);-- const result = await runStructuredQuery(userPrompt, systemPrompt, request.mode, opts);-- if (!result.success) return result;-- // Validate GLB code- if (result.code && request.mode !== 'tsl') {- const validation = validate(result.code);- if (!validation.valid) {- return retryWithFeedback(request, result.code, validation.errors, opts);- }- }-- return result;- } catch (error) {- const message = error instanceof Error ? error.message : 'Unknown error';- return { success: false, error: message };- }-}--/**- * Edit existing Kiln code with an instruction. Delegates to- * `generateKilnCode` with the existing code wired in as context.- */-export async function editKilnCode(- currentCode: string,- editRequest: string,- mode: RenderMode = 'glb',- opts: KilnGenerateCallOptions = {}-): Promise<KilnGenerateResult> {- return generateKilnCode(- {- prompt: editRequest,- mode,- category: 'prop',- existingCode: currentCode,- },- opts- );-}--/**- * Compact a bloated Kiln code string via Haiku.- * Code golf: minimize characters while producing identical visual output.- */-export async function compactCode(- code: string,- opts: KilnGenerateCallOptions = {}-): Promise<KilnGenerateResult> {- stripClaudeCodeNestingMarkers();-- const abortController = new AbortController();- const timeoutMs = opts.timeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS;- const timeout = setTimeout(() => abortController.abort(), timeoutMs);-- try {- const q = query({- prompt: `Code golf this Three.js code - minimize characters while producing IDENTICAL visual output.--- Shorten variable names-- Remove whitespace and comments-- Inline simple expressions-- Reuse identical materials/geometries-- Keep EXACT same visual result--\`\`\`typescript-${code}-\`\`\`--Output minified code only.`,- options: {- abortController,- model: opts.model ?? DEFAULT_HAIKU_MODEL,- maxTurns: 1,- permissionMode: 'bypassPermissions',- allowDangerouslySkipPermissions: true,- },- });-- let result = '';- for await (const message of q) {- if (message.type === 'assistant' && message.message?.content) {- for (const block of message.message.content) {- if (block.type === 'text') {- result += block.text;- }- }- }- }-- // Extract code from markdown fences if present- const codeMatch = result.match(/```(?:typescript|ts|javascript|js)?\n?([\s\S]*?)\n?```/);- if (codeMatch?.[1]) {- result = codeMatch[1];- }-- return { success: true, code: result.trim() };- } catch (error) {- const message = error instanceof Error ? error.message : 'Unknown error';- return { success: false, error: message };- } finally {- clearTimeout(timeout);- }-}--/**- * Refactor existing code (geometry, effect, or both) against an instruction.- * Preserves asset character; structured output keeps the client's downstream- * rendering path stable.- *- * For geometry refactors, runs the (W3b.3) hardened validator over the- * refactored code and re-prompts once if validation fails. Effect-only- * refactors are returned as-is — the geometry validator doesn't apply to- * TSL shader code.- */-export async function refactorCode(- request: RefactorRequest,- opts: KilnGenerateCallOptions = {}-): Promise<KilnGenerateResult> {- stripClaudeCodeNestingMarkers();-- const buildRefactorPrompt = (extraInstruction?: string): string => {- const codeContext: string[] = [];- if (request.geometryCode) {- codeContext.push(- `## Current Geometry Code\n\`\`\`typescript\n${request.geometryCode}\n\`\`\``- );- }- if (request.effectCode) {- codeContext.push(- `## Current Effect Code\n\`\`\`typescript\n${request.effectCode}\n\`\`\``- );- }-- const outputInstructions =- request.target === 'both'- ? 'Update BOTH geometry and effect code'- : request.target === 'geometry'- ? 'Update only the geometry code'- : 'Update only the effect code';-- return `${codeContext.join('\n\n')}--## Refactor Instructions-${request.instruction}-${extraInstruction ? `\n${extraInstruction}\n` : ''}-## Task-${outputInstructions}`;- };-- const systemPrompt = `You are refactoring existing 3D asset code.-Preserve the asset's character and style while applying the requested changes.-Keep working code - only modify what's necessary for the refactor.`;-- const initial = await runRefactorQuery(buildRefactorPrompt(), systemPrompt, opts);- if (!initial.success) return initial;-- // Skip validation when no geometry was generated (effect-only refactor).- if (!initial.code || request.target === 'effect') return initial;-- const v = validate(initial.code);- if (v.valid) return initial;-- // Re-prompt once with the structured errors as feedback. Mirrors the- // retryWithFeedback pattern used by generateKilnCode.- const retryInstruction = `Previous attempt had validation errors:-${v.issues- .map((i) => `- [${i.code}] ${i.message}${i.fixHint ? ` (${i.fixHint})` : ''}`)- .join('\n')}--Fix these issues before producing the refactored code.`;-- const retried = await runRefactorQuery(- buildRefactorPrompt(retryInstruction),- systemPrompt,- opts- );- return retried;-}--/**- * Maps a single SDK message to a terminal KilnGenerateResult, or returns- * null if the message is not terminal and the caller should keep iterating.- *- * Shared between runRefactorQuery and runStructuredQuery to dedupe the- * three branches (success / error result / auth failure).- */-function handleQueryMessage(- message: QueryMessage,- fallbackErrorLabel: string-): KilnGenerateResult | null {- if (message['type'] === 'result' && message['subtype'] === 'success') {- const sessionId = message['session_id'];- if (message['structured_output']) {- const output = message['structured_output'] as { code: string; effectCode?: string };- return {- success: true,- code: output.code,- effectCode: output.effectCode,- sessionId,- };- }- return parseResultText(message['result'] ?? '', sessionId);- }- if (message['type'] === 'result' && message['subtype']?.startsWith('error')) {- const errs = message['errors'];- return {- success: false,- error: Array.isArray(errs) ? errs.join('; ') : fallbackErrorLabel,- };- }- if (message['type'] === 'auth_status' && message['error']) {- return {- success: false,- error: `Auth failed: ${message['error']}. Run "claude auth login".`,- };- }- return null;-}--async function runRefactorQuery(- prompt: string,- systemPrompt: string,- opts: KilnGenerateCallOptions-): Promise<KilnGenerateResult> {- if (shouldUseModelHarness(opts.model)) {- return runHarnessTextQuery(prompt, systemPrompt, opts);- }-- const abortController = new AbortController();- const timeoutMs = opts.timeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS;- const timeout = setTimeout(() => abortController.abort(), timeoutMs);-- try {- const q = query({- prompt,- options: {- abortController,- model: opts.model ?? DEFAULT_OPUS_MODEL,- systemPrompt,- maxTurns: 1,- outputFormat: {- type: 'json_schema',- schema: KILN_OUTPUT_SCHEMA,- },- permissionMode: 'bypassPermissions',- allowDangerouslySkipPermissions: true,- },- });-- for await (const message of q) {- const terminal = handleQueryMessage(message as QueryMessage, 'Refactor failed');- if (terminal) return terminal;- }-- return { success: false, error: 'No result received from refactor query' };- } catch (error) {- const message = error instanceof Error ? error.message : 'Unknown error';- return { success: false, error: message };- } finally {- clearTimeout(timeout);- }-}--// =============================================================================-// Internal-// =============================================================================--async function runStructuredQuery(- userPrompt: string,- systemPrompt: string,- _mode: RenderMode,- opts: KilnGenerateCallOptions-): Promise<KilnGenerateResult> {- const abortController = new AbortController();- const timeoutMs = opts.timeoutMs ?? DEFAULT_QUERY_TIMEOUT_MS;- const timeout = setTimeout(() => abortController.abort(), timeoutMs);-- try {- const q = query({- prompt: userPrompt,- options: {- abortController,- model: opts.model ?? DEFAULT_OPUS_MODEL,- systemPrompt,- maxTurns: 3,- outputFormat: {- type: 'json_schema',- schema: KILN_OUTPUT_SCHEMA,- },- permissionMode: 'bypassPermissions',- allowDangerouslySkipPermissions: true,- },- });-- for await (const message of q) {- const terminal = handleQueryMessage(message as QueryMessage, 'Generation failed');- if (terminal) return terminal;- }-- return { success: false, error: 'No result received from query' };- } finally {- clearTimeout(timeout);- }-}--async function runHarnessTextQuery(- prompt: string,- systemPrompt: string,- opts: KilnGenerateCallOptions,-): Promise<KilnGenerateResult> {- try {- const route = resolveKilnModelRoute({- model:- opts.model ??- process.env['KILN_MODEL'] ??- process.env['PIXEL_FORGE_MODEL'],- });- const out = await generateTextWithRoute({- route,- system: systemPrompt,- prompt,- maxOutputTokens: 16_000,- });- const parsed = parseResultText(out.text);- return {- ...parsed,- usage: toKilnUsage(out.usage),- };- } catch (error) {- const message = error instanceof Error ? error.message : 'Unknown error';- return { success: false, error: message };- }-}--async function retryWithFeedback(- request: KilnGenerateRequest,- failedCode: string,- errors: string[],- opts: KilnGenerateCallOptions-): Promise<KilnGenerateResult> {- if (shouldUseModelHarness(opts.model)) {- try {- const candidate = await generateKilnCodeCandidate(request, {- model:- opts.model ??- process.env['KILN_MODEL'] ??- process.env['PIXEL_FORGE_MODEL'],- priorCode: failedCode,- priorWarnings: errors,- });- return {- success: true,- code: candidate.code,- usage: toKilnUsage(candidate.usage),- };- } catch (error) {- const message = error instanceof Error ? error.message : 'Unknown error';- return { success: false, error: `Retry failed: ${message}` };- }- }-- const retryPrompt = `Previous attempt had validation errors:-${errors.map((e) => `- ${e}`).join('\n')}--Failed code:-\`\`\`javascript-${failedCode}-\`\`\`--Fix these issues and regenerate. Remember: NO imports, NO exports, use rotation:/position: not value: in keyframes.`;-- const systemPrompt = getSystemPrompt(request.mode);-- try {- return await runStructuredQuery(retryPrompt, systemPrompt, request.mode, opts);- } catch (error) {- const message = error instanceof Error ? error.message : 'Unknown error';- return { success: false, error: `Retry failed: ${message}` };- }-}--function parseResultText(result: string, sessionId?: string): KilnGenerateResult {- if (!result) return { success: false, error: 'Empty result text' };-- // Try JSON first.- try {- const parsed = JSON.parse(result);- if (parsed.code) {- return {- success: true,- code: parsed.code,- effectCode: parsed.effectCode,- sessionId,- };- }- } catch {- // Not JSON - fall through to code fence extraction.- }-- const geoMatch = result.match(- /```(?:geometry|typescript|javascript|js)?\n?([\s\S]*?function build[\s\S]*?)```/- );- if (geoMatch?.[1]) {- const effectMatch = result.match(- /```(?:effect|typescript)\n?(import[\s\S]*?export \{ material \}[\s\S]*?)```/- );- return {- success: true,- code: geoMatch[1].trim(),- effectCode: effectMatch?.[1]?.trim(),- sessionId,- };- }-- return { success: true, code: result.trim(), sessionId };-}--function shouldUseModelHarness(model: string | undefined): boolean {- return isExperimentalKilnModel(- model ?? process.env['KILN_MODEL'] ?? process.env['PIXEL_FORGE_MODEL'],- );-}--async function runHarnessGenerate(- request: KilnGenerateRequest,- opts: KilnGenerateCallOptions,-): Promise<KilnGenerateResult> {- try {- const candidate = await generateKilnCodeCandidate(request, {- model:- opts.model ??- process.env['KILN_MODEL'] ??- process.env['PIXEL_FORGE_MODEL'],- });- return {- success: true,- code: candidate.code,- usage: toKilnUsage(candidate.usage),- };- } catch (error) {- const message = error instanceof Error ? error.message : 'Unknown error';- return { success: false, error: message };- }-}--function toKilnUsage(- usage: { inputTokens?: number; outputTokens?: number } | undefined,-): KilnGenerateResult['usage'] | undefined {- if (usage?.inputTokens === undefined && usage?.outputTokens === undefined) {- return undefined;- }- return {- inputTokens: usage?.inputTokens ?? 0,- outputTokens: usage?.outputTokens ?? 0,- };-}diff --git a/src/imposter/__tests__/animated-bake.test.ts b/src/imposter/__tests__/animated-bake.test.tsdeleted file mode 100644index af39ee51..00000000--- a/src/imposter/__tests__/animated-bake.test.ts+++ /dev/null@@ -1,32 +0,0 @@-/**- * Animated bake math tests. Live Playwright bake is covered by the review script.- */--import { describe, expect, test } from 'bun:test';--import { enumerateOctahedralGrid } from '../animated-bake';--describe('enumerateOctahedralGrid', () => {- test('returns one unit direction per view tile', () => {- const tiles = enumerateOctahedralGrid(6, 6);- expect(tiles).toHaveLength(36);- for (const tile of tiles) {- expect(Math.hypot(...tile.dir)).toBeCloseTo(1, 6);- }- });-- test('uses row-major tile order', () => {- const tiles = enumerateOctahedralGrid(2, 2);- expect(tiles.map((tile) => [tile.i, tile.j])).toEqual([- [0, 0],- [1, 0],- [0, 1],- [1, 1],- ]);- });-- test('rejects invalid dimensions', () => {- expect(() => enumerateOctahedralGrid(0, 6)).toThrow();- expect(() => enumerateOctahedralGrid(6.5, 6)).toThrow();- });-});diff --git a/src/imposter/__tests__/animated-schema.test.ts b/src/imposter/__tests__/animated-schema.test.tsdeleted file mode 100644index 048daeff..00000000--- a/src/imposter/__tests__/animated-schema.test.ts+++ /dev/null@@ -1,225 +0,0 @@-/**- * Animated imposter sidecar schema tests.- */--import { describe, expect, test } from 'bun:test';--import {- ANIMATED_IMPOSTER_KIND,- ANIMATED_IMPOSTER_SCHEMA_VERSION,- AnimatedImposterMetaSchema,- type AnimatedImposterMeta,-} from '../animated-schema';--const VALID: AnimatedImposterMeta = {- version: ANIMATED_IMPOSTER_SCHEMA_VERSION,- kind: ANIMATED_IMPOSTER_KIND,- source: {- path: 'characters/nva.glb',- bytes: 4_200_000,- tris: 12_000,- skinned: true,- animationClips: ['CharacterArmature|Idle', 'CharacterArmature|Walk'],- },- bbox: {- min: [-0.5, 0, -0.4],- max: [0.5, 1.8, 0.4],- worldSize: 1.8,- yOffset: 0.9,- },- projection: 'orthographic',- view: {- layout: 'octahedral',- directionEncoding: 'octahedral',- grid: { x: 6, y: 6, count: 36 },- tileSize: 96,- framesPerClip: 8,- },- clips: [- {- target: 'idle',- resolved: 'Idle',- rawName: 'CharacterArmature|Idle',- matchedBy: 'exact',- frameCount: 8,- durationSec: 1,- },- {- target: 'walking',- resolved: 'Walk',- rawName: 'CharacterArmature|Walk',- matchedBy: 'alias',- frameCount: 8,- durationSec: 1,- },- ],- textures: {- layout: 'array',- color: {- uri: 'nva-albedo.ktx2',- format: 'r8-palette-index',- width: 576,- height: 576,- layers: 16,- bytes: 5_308_416,- colorSpace: 'srgb',- },- palette: {- uri: 'nva-palette.png',- width: 128,- rows: 1,- bytes: 512,- },- },- runtime: {- renderer: 'webgl2',- primitive: 'instanced-quad',- material: 'ShaderMaterial',- textureMode: 'data-array-texture',- attributes: ['frameOffset', 'clip', 'variant', 'yaw', 'paletteRow'],- },- storage: {- colorBytes: 5_308_416,- paletteBytes: 512,- totalRawBytes: 5_308_928,- envelopeBytes: 31_457_280,- fitsEnvelope: true,- },- validation: {- warnings: [- {- code: 'ANIMATED_IMPOSTER_CLIP_FALLBACK',- severity: 'warning',- message: 'shoot used idle fallback in this debug bake',- },- ],- },-};--describe('AnimatedImposterMetaSchema', () => {- test('accepts the animated octahedral sidecar contract', () => {- expect(AnimatedImposterMetaSchema.parse(VALID)).toEqual(VALID);- });-- test('round-trips through JSON', () => {- const decoded = AnimatedImposterMetaSchema.parse(JSON.parse(JSON.stringify(VALID)));- expect(decoded).toEqual(VALID);- });-- test('accepts source attachments for baked weapons', () => {- const withAttachment = {- ...VALID,- source: {- ...VALID.source,- attachments: [- {- id: 'ak47',- kind: 'weapon',- sourcePath: 'tmp/weapon-rig-lab/weapons/ak47.glb',- bytes: 67_588,- hash: '1fab1876b236f1cf2c5759cb7e669c5badf7fc4195fd6640c35f46c515c43ce8',- },- ],- },- };- expect(AnimatedImposterMetaSchema.parse(withAttachment).source.attachments?.[0]?.id).toBe('ak47');- });-- test('rejects the static imposter kind', () => {- const bad = { ...VALID, kind: 'imposter' };- expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();- });-- test('rejects mismatched grid counts', () => {- const bad = {- ...VALID,- view: {- ...VALID.view,- grid: { ...VALID.view.grid, count: 35 },- },- };- expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();- });-- test('rejects color dimensions that do not match grid and tile size', () => {- const bad = {- ...VALID,- textures: {- ...VALID.textures,- color: { ...VALID.textures.color, width: 512 },- },- };- expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();- });-- test('rejects layer counts that do not match clip frames', () => {- const bad = {- ...VALID,- textures: {- ...VALID.textures,- color: { ...VALID.textures.color, layers: 15 },- },- };- expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();- });-- test('requires the WebGL runtime attributes needed by the first slice', () => {- const bad = {- ...VALID,- runtime: {- ...VALID.runtime,- attributes: ['frameOffset', 'clip', 'variant', 'yaw'],- },- };- expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();- });-- test('keeps texture array and packed atlas runtime modes explicit', () => {- const bad = {- ...VALID,- runtime: {- ...VALID.runtime,- textureMode: 'packed-2d-atlas',- },- };- expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();- });-- test('accepts packed 2D atlas fallback dimensions', () => {- const packed = {- ...VALID,- textures: {- ...VALID.textures,- layout: 'atlas',- color: {- ...VALID.textures.color,- uri: 'nva-albedo-packed.png',- width: 576 * 4,- height: 576 * 4,- framesX: 4,- framesY: 4,- },- },- runtime: {- ...VALID.runtime,- textureMode: 'packed-2d-atlas',- },- };- expect(() => AnimatedImposterMetaSchema.parse(packed)).not.toThrow();- });-- test('packed 2D atlas fallback requires frame grid metadata', () => {- const bad = {- ...VALID,- textures: {- ...VALID.textures,- layout: 'atlas',- },- runtime: {- ...VALID.runtime,- textureMode: 'packed-2d-atlas',- },- };- expect(() => AnimatedImposterMetaSchema.parse(bad)).toThrow();- });-});diff --git a/src/imposter/__tests__/animated-validate.test.ts b/src/imposter/__tests__/animated-validate.test.tsdeleted file mode 100644index 93b0a23f..00000000--- a/src/imposter/__tests__/animated-validate.test.ts+++ /dev/null@@ -1,201 +0,0 @@-/**- * Animated imposter pre-bake validator tests.- */--import { describe, expect, test } from 'bun:test';--import {- estimateAnimatedImposterStorage,- validateAnimatedImposterPreBake,-} from '../animated-validate';-import type { AnimatedImposterPreBakeInput } from '../animated-schema';--const VALID = {- source: {- path: 'characters/nva.glb',- bytes: 4_200_000,- tris: 12_000,- skinned: true,- clipNames: [- 'CharacterArmature|Idle',- 'CharacterArmature|Walk',- 'CharacterArmature|Run',- 'CharacterArmature|Slash',- ],- },- clipTargets: ['idle', 'walking'],- viewGrid: { x: 6, y: 6 },- tileSize: 96,- framesPerClip: 8,- textureFormat: 'r8-palette-index',- textureLayout: 'array',- includeNormal: false,- includeDepth: false,- paletteWidth: 128,- paletteRows: 1,- envelopeBytes: 30 * 1024 * 1024,- clipFallbacks: [],-} satisfies AnimatedImposterPreBakeInput;--describe('estimateAnimatedImposterStorage', () => {- test('estimates one array layer per animation frame', () => {- const storage = estimateAnimatedImposterStorage(VALID);- expect(storage.atlasWidth).toBe(576);- expect(storage.atlasHeight).toBe(576);- expect(storage.layers).toBe(16);- expect(storage.bytesPerColorPixel).toBe(1);- expect(storage.colorBytes).toBe(576 * 576 * 16);- expect(storage.paletteBytes).toBe(512);- expect(storage.totalRawBytes).toBe(storage.colorBytes + storage.paletteBytes);- expect(storage.fitsEnvelope).toBe(true);- });-- test('accounts for rgba debug output and aux layers', () => {- const storage = estimateAnimatedImposterStorage({- ...VALID,- textureFormat: 'rgba8',- includeNormal: true,- includeDepth: true,- });- const pixels = 576 * 576 * 16;- expect(storage.colorBytes).toBe(pixels * 4);- expect(storage.normalBytes).toBe(pixels * 4);- expect(storage.depthBytes).toBe(pixels * 4);- expect(storage.paletteBytes).toBe(0);- });-});--describe('validateAnimatedImposterPreBake', () => {- test('accepts the first-slice contract without warnings', () => {- const report = validateAnimatedImposterPreBake(VALID);- expect(report.ok).toBe(true);- expect(report.blockers).toEqual([]);- expect(report.warnings).toEqual([]);- expect(report.clipResolution.clips.idle?.resolved).toBe('Idle');- expect(report.clipResolution.clips.walking?.resolved).toBe('Walk');- });-- test('accepts 7x7 as the centered-front review grid', () => {- const report = validateAnimatedImposterPreBake({- ...VALID,- viewGrid: { x: 7, y: 7 },- });- expect(report.ok).toBe(true);- expect(report.warnings.map((issue) => issue.code)).not.toContain('ANIMATED_IMPOSTER_VIEW_GRID_UNPROVEN');- });-- test('blocks non-skinned sources', () => {- const report = validateAnimatedImposterPreBake({- ...VALID,- source: { ...VALID.source, skinned: false },- });- expect(report.ok).toBe(false);- expect(report.blockers.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_SOURCE_NOT_SKINNED');- });-- test('surfaces missing clip coverage without hiding the rest of the contract', () => {- const report = validateAnimatedImposterPreBake({- ...VALID,- clipTargets: ['idle', 'death'],- });- expect(report.ok).toBe(true);- expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_CLIP_MISSING');- expect(report.clipResolution.clips.death?.resolved).toBeNull();- });-- test('reports explicit fallback clips', () => {- const report = validateAnimatedImposterPreBake({- ...VALID,- source: {- ...VALID.source,- clipNames: ['CharacterArmature|Idle', 'CharacterArmature|Run'],- },- clipTargets: ['idle', 'walking', 'running'],- clipFallbacks: [{ target: 'walking', donor: 'running' }],- });- expect(report.ok).toBe(true);- expect(report.clipResolution.clips.walking?.resolved).toBe('Run');- expect(report.clipResolution.clips.walking?.matchedBy).toBe('fallback');- expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_CLIP_FALLBACK');- });-- test('allows a logical target to use an explicit raw source clip fallback', () => {- const report = validateAnimatedImposterPreBake({- ...VALID,- source: {- ...VALID.source,- clipNames: ['Armature|Walk_Fight_Forward|baselayer'],- },- clipTargets: ['shoot'],- clipFallbacks: [{ target: 'shoot', rawName: 'Armature|Walk_Fight_Forward|baselayer' }],- });- expect(report.ok).toBe(true);- expect(report.clipResolution.clips.shoot?.rawName).toBe('Armature|Walk_Fight_Forward|baselayer');- expect(report.clipResolution.clips.shoot?.matchedBy).toBe('fallback');- expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_CLIP_FALLBACK');- });-- test('blocks if no requested clips resolve', () => {- const report = validateAnimatedImposterPreBake({- ...VALID,- source: { ...VALID.source, clipNames: ['Jump'] },- clipTargets: ['idle', 'walking'],- });- expect(report.ok).toBe(false);- expect(report.blockers.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_NO_RESOLVED_CLIPS');- });-- test('warns when the view grid or frame count leaves the initial validation lane', () => {- const report = validateAnimatedImposterPreBake({- ...VALID,- viewGrid: { x: 4, y: 4 },- tileSize: 128,- framesPerClip: 24,- });- expect(report.ok).toBe(true);- expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_VIEW_GRID_UNPROVEN');- expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_TILE_SIZE_UNPROVEN');- expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_FRAME_COUNT_UNPROVEN');- });-- test('blocks invalid octahedral grids and tile sizes', () => {- const report = validateAnimatedImposterPreBake({- ...VALID,- viewGrid: { x: 6, y: 8 },- tileSize: 95,- });- expect(report.ok).toBe(false);- expect(report.blockers.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_VIEW_GRID_NOT_SQUARE');- expect(report.blockers.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_TILE_SIZE_OUT_OF_RANGE');- });-- test('reports source manifest drift', () => {- const report = validateAnimatedImposterPreBake({- ...VALID,- source: {- ...VALID.source,- manifest: {- expectedBytes: 1,- actualBytes: 2,- expectedHash: 'old',- actualHash: 'new',- },- },- });- expect(report.ok).toBe(true);- expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_SOURCE_MANIFEST_BYTES_DRIFT');- expect(report.warnings.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_SOURCE_MANIFEST_HASH_DRIFT');- });-- test('blocks storage estimates that exceed the per-character envelope', () => {- const report = validateAnimatedImposterPreBake({- ...VALID,- clipTargets: ['idle', 'walking', 'running', 'shoot'],- viewGrid: { x: 8, y: 8 },- framesPerClip: 16,- });- expect(report.ok).toBe(false);- expect(report.storage.fitsEnvelope).toBe(false);- expect(report.blockers.map((issue) => issue.code)).toContain('ANIMATED_IMPOSTER_STORAGE_ENVELOPE_EXCEEDED');- });-});diff --git a/src/imposter/__tests__/atlas-profiles.test.ts b/src/imposter/__tests__/atlas-profiles.test.tsdeleted file mode 100644index 8aafaad8..00000000--- a/src/imposter/__tests__/atlas-profiles.test.ts+++ /dev/null@@ -1,115 +0,0 @@-import { describe, expect, test } from 'bun:test';--import {- ATLAS_PROFILES,- ATLAS_PROFILE_NAMES,- isAtlasProfileName,- validateAgainstAtlasProfile,-} from '../atlas-profiles';--describe('atlas-profiles catalog', () => {- test('exports four named profiles', () => {- const names: string[] = [...ATLAS_PROFILE_NAMES];- expect(names.sort()).toEqual(- ['canopy-balanced', 'canopy-hero', 'ground-compact', 'mid-balanced'],- );- });-- test('ground-compact does not require normal layer', () => {- expect(ATLAS_PROFILES['ground-compact'].normalRequired).toBe(false);- });-- test('canopy-* and mid-balanced require normal layer', () => {- expect(ATLAS_PROFILES['mid-balanced'].normalRequired).toBe(true);- expect(ATLAS_PROFILES['canopy-balanced'].normalRequired).toBe(true);- expect(ATLAS_PROFILES['canopy-hero'].normalRequired).toBe(true);- });-- test('hero allows the largest tiles', () => {- expect(ATLAS_PROFILES['canopy-hero'].maxTileSize).toBe(1024);- expect(ATLAS_PROFILES['ground-compact'].maxTileSize).toBe(256);- });-});--describe('isAtlasProfileName', () => {- test('accepts the four named profiles', () => {- expect(isAtlasProfileName('ground-compact')).toBe(true);- expect(isAtlasProfileName('mid-balanced')).toBe(true);- expect(isAtlasProfileName('canopy-balanced')).toBe(true);- expect(isAtlasProfileName('canopy-hero')).toBe(true);- });-- test('rejects non-string and unknown values', () => {- expect(isAtlasProfileName('made-up-profile')).toBe(false);- expect(isAtlasProfileName(undefined)).toBe(false);- expect(isAtlasProfileName(42)).toBe(false);- expect(isAtlasProfileName(null)).toBe(false);- });-});--describe('validateAgainstAtlasProfile', () => {- test('clean ground-compact meta passes', () => {- const result = validateAgainstAtlasProfile(- { tileSize: 256, angles: 8 },- 'ground-compact',- );- expect(result.ok).toBe(true);- expect(result.violations).toEqual([]);- expect(result.profile).toBe('ground-compact');- });-- test('flags tileSize over the profile max', () => {- const result = validateAgainstAtlasProfile(- { tileSize: 1024, angles: 8 },- 'ground-compact',- );- expect(result.ok).toBe(false);- expect(result.violations.some((v) => v.field === 'tileSize')).toBe(true);- });-- test('flags angles over the profile max', () => {- const result = validateAgainstAtlasProfile(- { tileSize: 256, angles: 32 },- 'ground-compact',- );- expect(result.ok).toBe(false);- expect(result.violations.some((v) => v.field === 'angles')).toBe(true);- });-- test('flags missing normal aux layer when required', () => {- const result = validateAgainstAtlasProfile(- { tileSize: 512, angles: 16, auxLayers: [], normalSpace: 'capture-view' },- 'mid-balanced',- );- expect(result.ok).toBe(false);- expect(result.violations.some((v) => v.field === 'normal-aux-layer')).toBe(true);- });-- test('flags wrong normalSpace when normal layer is required', () => {- const result = validateAgainstAtlasProfile(- { tileSize: 512, angles: 16, auxLayers: ['normal'], normalSpace: 'world' },- 'canopy-balanced',- );- expect(result.ok).toBe(false);- expect(result.violations.some((v) => v.field === 'normal-space')).toBe(true);- });-- test('passes valid canopy-hero meta with normal layer + capture-view space', () => {- const result = validateAgainstAtlasProfile(- {- tileSize: 1024,- angles: 32,- auxLayers: ['normal'],- normalSpace: 'capture-view',- },- 'canopy-hero',- );- expect(result.ok).toBe(true);- expect(result.limits.maxTileSize).toBe(1024);- });-- test('skips numeric checks if fields are absent (read-only validator)', () => {- const result = validateAgainstAtlasProfile({}, 'ground-compact');- expect(result.ok).toBe(true);- });-});diff --git a/src/imposter/__tests__/bake.test.ts b/src/imposter/__tests__/bake.test.tsdeleted file mode 100644index e18d1f56..00000000--- a/src/imposter/__tests__/bake.test.ts+++ /dev/null@@ -1,114 +0,0 @@-/**- * Live bake test — gated on KILN_IMPOSTER_LIVE=1.- *- * Real Chromium launch + GLB load + tile render. Slow (~15-30s). Skipped by- * default so the core test suite stays fast. Exercises the full pipeline- * against a known-good vegetation GLB from the Poly Pizza tier-A set.- *- * To run:- * KILN_IMPOSTER_LIVE=1 cd packages/core && bun test imposter/bake.test.ts- */--import { describe, expect, test } from 'bun:test';-import { existsSync, readFileSync } from 'node:fs';-import { join, resolve } from 'node:path';-import { fileURLToPath } from 'node:url';-import sharp from 'sharp';--import { bakeImposter, bleedTransparentRgb } from '../bake';-import { ImposterMetaSchema } from '../schema';--const LIVE = process.env.KILN_IMPOSTER_LIVE === '1';--// Vegetation-research fixture. Pick any bamboo variant; they're all small.-const here = resolve(fileURLToPath(import.meta.url), '..');-const FIXTURE_CANDIDATES = [- // Primary: vegetation-research mount on the dev workstation.- 'C:/Users/Mattm/X/vegetation-research/assets/tier-a-psx/polypizza/bamboo-google-1/model.glb',- // Fallback: any tiny GLB bundled in war-assets/ for CI.- join(here, '../../../../../../war-assets/validation/gear.glb'),-];--function findFixture(): string | null {- for (const p of FIXTURE_CANDIDATES) {- if (existsSync(p)) return p;- }- return null;-}--describe.if(LIVE)('bakeImposter (live)', () => {- test('bakes a 16-angle hemi atlas with non-zero content', async () => {- const fixture = findFixture();- if (!fixture) {- throw new Error(- `no imposter fixture found. Tried:\n ${FIXTURE_CANDIDATES.join('\n ')}`,- );- }- const glb = readFileSync(fixture);-- const result = await bakeImposter(glb, {- angles: 16,- axis: 'hemi-y',- tileSize: 256,- auxLayers: ['normal', 'depth'],- bgColor: 'transparent',- colorLayer: 'baseColor',- edgeBleedPx: 2,- sourcePath: fixture,- });-- // Meta shape is valid.- const meta = ImposterMetaSchema.parse(result.meta);- expect(meta.angles).toBe(16);- expect(meta.tilesX).toBe(4);- expect(meta.tilesY).toBe(4);- expect(meta.atlasWidth).toBe(1024);- expect(meta.atlasHeight).toBe(1024);- expect(meta.source.tris).toBeGreaterThan(0);- expect(meta.worldSize).toBeGreaterThan(0);- expect(meta.colorLayer).toBe('baseColor');- expect(meta.auxLayers).toContain('normal');- expect(meta.normalSpace).toBe('capture-view');- expect(meta.edgeBleedPx).toBe(2);-- // Albedo atlas is a valid PNG buffer.- expect(result.atlas.byteLength).toBeGreaterThan(1000);- expect(result.atlas.subarray(0, 4).toString('hex')).toBe('89504e47'); // PNG magic-- // Aux normal atlas present.- expect(result.aux.normal).toBeTruthy();- expect(result.aux.normal!.byteLength).toBeGreaterThan(1000);-- // Aux depth atlas present.- expect(result.aux.depth).toBeTruthy();- expect(result.aux.depth!.byteLength).toBeGreaterThan(1000);- }, 60_000);-});--describe('bleedTransparentRgb', () => {- test('extends RGB into transparent pixels without changing alpha', async () => {- const input = Buffer.from([- 0, 0, 0, 0, 80, 140, 30, 255,- 0, 0, 0, 0, 0, 0, 0, 0,- ]);- const png = await sharp(input, { raw: { width: 2, height: 2, channels: 4 } }).png().toBuffer();- const out = await bleedTransparentRgb(png, 1);- const { data } = await sharp(out).ensureAlpha().raw().toBuffer({ resolveWithObject: true });-- expect(data[0]).toBe(80);- expect(data[1]).toBe(140);- expect(data[2]).toBe(30);- expect(data[3]).toBe(0);- expect(data[4]).toBe(80);- expect(data[5]).toBe(140);- expect(data[6]).toBe(30);- expect(data[7]).toBe(255);- });-});--// When LIVE is off, still run at least one placeholder so bun reports the file.-describe.if(!LIVE)('bakeImposter (skipped)', () => {- test('set KILN_IMPOSTER_LIVE=1 to run', () => {- expect(LIVE).toBe(false);- });-});diff --git a/src/imposter/__tests__/clip-resolver.test.ts b/src/imposter/__tests__/clip-resolver.test.tsdeleted file mode 100644index fe9e9e8c..00000000--- a/src/imposter/__tests__/clip-resolver.test.ts+++ /dev/null@@ -1,150 +0,0 @@-/**- * Clip resolver tests — uses realistic clip lists pulled from the Quaternius- * soldier set so behavior is validated against real-world naming, not toys.- */--import { describe, expect, test } from 'bun:test';--import {- applyClipFallbacks,- normalizeClipName,- resolveClips,-} from '../clip-resolver';--// Real clip lists from CHARACTERS_MANIFEST.json (Poly Pizza / Quaternius set).-const HERO_CLIPS = [- 'CharacterArmature|Attacking_Idle',- 'CharacterArmature|Dagger_Attack',- 'CharacterArmature|Death',- 'CharacterArmature|Idle',- 'CharacterArmature|PickUp',- 'CharacterArmature|Punch',- 'CharacterArmature|RecieveHit',- 'CharacterArmature|Roll',- 'CharacterArmature|Run',- 'CharacterArmature|Walk',-];--const NVA_MATT_CLIPS = [- 'CharacterArmature|Death',- 'CharacterArmature|Idle',- 'CharacterArmature|Idle_Gun',- 'CharacterArmature|Punch',- 'CharacterArmature|Run',- 'CharacterArmature|Run_Gun',- 'CharacterArmature|Run_Slash',- 'CharacterArmature|Slash',- 'CharacterArmature|Stab',- 'CharacterArmature|Walk',- 'CharacterArmature|Walk_Gun',-];--const US_SOLDIER_CLIPS = [- 'CharacterArmature|Death',- 'CharacterArmature|Idle',- 'CharacterArmature|Idle_Shoot',- 'CharacterArmature|Run',- 'CharacterArmature|Run_Gun',-];--describe('normalizeClipName', () => {- test('strips single armature prefix', () => {- expect(normalizeClipName('CharacterArmature|Walk')).toBe('Walk');- });- test('strips repeated prefixes', () => {- expect(normalizeClipName('CharacterArmature|CharacterArmature|Idle')).toBe('Idle');- });- test('preserves un-prefixed names', () => {- expect(normalizeClipName('Run')).toBe('Run');- });-});--describe('resolveClips — hero (Quaternius Character_Animated)', () => {- test('resolves idle + walking + running from exact + alias matches', () => {- const r = resolveClips(HERO_CLIPS, ['idle', 'walking', 'running']);- expect(r.clips.idle?.resolved).toBe('Idle');- expect(r.clips.idle?.matchedBy).toBe('exact');- expect(r.clips.walking?.resolved).toBe('Walk');- expect(r.clips.running?.resolved).toBe('Run');- expect(r.missing).toHaveLength(0);- });-- test('shoot falls through to Punch (melee fallback in alias list)', () => {- const r = resolveClips(HERO_CLIPS, ['shoot']);- expect(r.clips.shoot?.resolved).toBe('Punch');- expect(r.clips.shoot?.matchedBy).toBe('alias');- expect(r.missing).toHaveLength(0);- });-- test('returns raw clip name (with armature prefix) for AnimationMixer', () => {- const r = resolveClips(HERO_CLIPS, ['idle']);- expect(r.clips.idle?.rawName).toBe('CharacterArmature|Idle');- });-- test('unmapped clips are surfaced for debugging', () => {- const r = resolveClips(HERO_CLIPS, ['idle', 'walking']);- expect(r.unmapped).toContain('CharacterArmature|Death');- expect(r.unmapped).toContain('CharacterArmature|Roll');- });-});--describe('resolveClips — NVA (Matt)', () => {- test('idle + walking match directly', () => {- const r = resolveClips(NVA_MATT_CLIPS, ['idle', 'walking']);- expect(r.clips.idle?.resolved).toBe('Idle');- expect(r.clips.walking?.resolved).toBe('Walk');- });-- test('shoot falls through to Slash (no Gun_Shoot / Shoot clip)', () => {- const r = resolveClips(NVA_MATT_CLIPS, ['shoot']);- expect(r.clips.shoot?.resolved).toBe('Slash');- expect(r.clips.shoot?.matchedBy).toBe('alias');- });-});--describe('resolveClips — US Soldier (PpLF4rt4ah)', () => {- test('walking falls through to Run when Walk is absent', () => {- // US Soldier has no Walk clip; the alias list for 'walking' includes only- // Walk / Walk_Gun / Walking. Expect missing (no Run substitution yet).- const r = resolveClips(US_SOLDIER_CLIPS, ['walking']);- expect(r.clips.walking?.resolved).toBeNull();- expect(r.missing).toContain('walking');- });-- test('Idle_Shoot resolves shoot via alias', () => {- const r = resolveClips(US_SOLDIER_CLIPS, ['shoot']);- expect(r.clips.shoot?.resolved).toBe('Idle_Shoot');- });-});--describe('applyClipFallbacks', () => {- test('promotes running -> walking when walking is missing', () => {- const initial = resolveClips(US_SOLDIER_CLIPS, ['idle', 'walking', 'running']);- expect(initial.missing).toContain('walking');-- const after = applyClipFallbacks(initial, { walking: 'running' });- expect(after.clips.walking?.resolved).toBe('Run');- expect(after.clips.walking?.matchedBy).toBe('fallback');- expect(after.clips.walking?.fallbackFor).toBe('running');- expect(after.missing).not.toContain('walking');- });-- test('no-op when donor target is also missing', () => {- const initial = resolveClips(['Idle'], ['idle', 'walking']);- const after = applyClipFallbacks(initial, { walking: 'running' });- // running was never resolved -> walking stays null.- expect(after.clips.walking?.resolved).toBeNull();- expect(after.missing).toContain('walking');- });-- test('does not overwrite an already-resolved target', () => {- const initial = resolveClips(HERO_CLIPS, ['idle', 'walking', 'running']);- const after = applyClipFallbacks(initial, { walking: 'running' });- // Target "walking" does not exact-match clip "Walk" (different words);- // it resolves via the "Walk" alias. The fallback must not overwrite an- // already-populated slot regardless of whether it was exact or alias.- expect(after.clips.walking?.resolved).toBe('Walk');- expect(after.clips.walking?.matchedBy).toBe('alias');- expect(after.clips.walking?.fallbackFor).toBeUndefined();- });-});diff --git a/src/imposter/__tests__/npc-character-pack.test.ts b/src/imposter/__tests__/npc-character-pack.test.tsdeleted file mode 100644index 6ba0c6d7..00000000--- a/src/imposter/__tests__/npc-character-pack.test.ts+++ /dev/null@@ -1,229 +0,0 @@-import { describe, expect, test } from 'bun:test';--import {- NpcCharacterPackManifestSchema,- validateNpcCharacterPack,-} from '../npc-character-pack';--function makeManifest(): unknown {- const clips = [- ['idle', ['idle']],- ['patrol_walk', ['patrolling']],- ['traverse_run', ['seeking_cover']],- ['walk_fight_forward', ['engaging', 'advancing']],- ['death_fall_back', ['dead']],- ] as const;-- return {- id: 'test-pack',- createdFrom: { base: 'test' },- policy: {- promoteToWarAssets: false,- recoil: 'Runtime procedural.',- excludedClips: [{ id: 'walk_forward_while_shooting', reason: 'Rejected in review.' }],- },- socketContract: {- characterForward: '+Z',- weaponForward: '+X',- rightHandBone: 'RightHand',- leftHandBone: 'LeftHand',- runtimeNotes: ['Attach weapon at runtime.'],- },- factions: {- nva: { label: 'NVA regular', headgear: 'pith-cap', primaryWeapon: 'ak47' },- },- clips: clips.map(([id, states]) => ({- id,- label: id,- tijStates: states,- status: 'candidate',- note: 'Test clip.',- })),- outputs: clips.map(([id, states]) => ({- faction: 'nva',- clip: id,- label: `nva ${id}`,- path: `tmp/${id}.glb`,- bytes: 1000,- tijStates: states,- status: 'candidate',- primaryWeapon: 'ak47',- })),- };-}--function makePackagedManifest(): unknown {- const source = makeManifest() as {- id: string;- socketContract: unknown;- factions: unknown;- clips: Array<{- id: string;- label: string;- tijStates: string[];- status: string;- note: string;- }>;- outputs: Array<{- faction: string;- clip: string;- label: string;- path: string;- bytes: number;- tijStates: string[];- status: string;- primaryWeapon: string;- }>;- };-- return {- schemaVersion: 1,- id: source.id,- sourceManifest: '../../source/manifest.json',- generatedAt: '2026-04-28T00:00:00.000Z',- promoteToWarAssets: false,- note: 'Review-only package.',- settings: {- viewGrid: { x: 7, y: 7, count: 49 },- tileSize: 96,- framesPerClip: 8,- textureLayout: 'atlas',- textureFormat: 'rgba8-debug',- },- socketContract: source.socketContract,- factions: source.factions,- clips: source.clips,- weapons: {},- combinedGlbs: {- nva: {- uri: 'glb-combined/nva.glb',- bytes: 2000,- hash: 'abc',- animations: source.clips.map((clip) => clip.id),- },- },- entries: source.outputs.map((output) => ({- faction: output.faction,- factionLabel: 'NVA regular',- clip: output.clip,- clipLabel: output.label,- status: output.status,- tijStates: output.tijStates,- primaryWeapon: output.primaryWeapon,- glb: {- uri: output.path,- bytes: output.bytes,- hash: 'abc',- },- impostor: {- dir: `impostors/${output.faction}/${output.clip}`,- sidecar: `impostors/${output.faction}/${output.clip}/animated-imposter.json`,- atlas: `impostors/${output.faction}/${output.clip}/animated-albedo-packed.png`,- frameStrip: `impostors/${output.faction}/${output.clip}/animated-frame-strip.png`,- atlasHash: 'abc',- sidecarValid: true,- storage: {- colorBytes: 100,- totalRawBytes: 100,- envelopeBytes: 1000,- fitsEnvelope: true,- },- warnings: [],- },- })),- totals: {- entries: source.outputs.length,- glbBytes: source.outputs.reduce((sum, output) => sum + output.bytes, 0),- atlasPngBytes: 1000,- rawImpostorBytes: 500,- warnings: 0,- },- };-}--describe('NpcCharacterPackManifestSchema', () => {- test('accepts the minimum TIJ character pack contract', () => {- expect(() => NpcCharacterPackManifestSchema.parse(makeManifest())).not.toThrow();- });-- test('accepts the packaged review bundle contract', () => {- expect(() => NpcCharacterPackManifestSchema.parse(makePackagedManifest())).not.toThrow();- });-});--describe('validateNpcCharacterPack', () => {- test('accepts a complete manifest without filesystem checks', async () => {- const report = await validateNpcCharacterPack(makeManifest(), { checkFiles: false });- expect(report.ok).toBe(true);- expect(report.blockers).toEqual([]);- expect(report.metrics.factions.nva?.outputs).toBe(5);- expect(report.metrics.factions.nva?.clips).toBe(5);- });-- test('accepts a packaged review manifest without filesystem checks', async () => {- const report = await validateNpcCharacterPack(makePackagedManifest(), { checkFiles: false });- expect(report.ok).toBe(true);- expect(report.blockers).toEqual([]);- expect(report.metrics.factions.nva?.outputs).toBe(5);- });-- test('blocks missing GLB files when file checks are enabled', async () => {- const report = await validateNpcCharacterPack(makeManifest(), {- checkFiles: true,- inspectGlbs: false,- rootDir: process.cwd(),- });- expect(report.ok).toBe(false);- expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_OUTPUT_MISSING');- });-- test('blocks outputs for unknown factions', async () => {- const manifest = makeManifest() as { outputs: Array<{ faction: string }> };- manifest.outputs[0]!.faction = 'unknown';- const report = await validateNpcCharacterPack(manifest, { checkFiles: false });- expect(report.ok).toBe(false);- expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_UNKNOWN_FACTION');- });-- test('blocks missing hand socket names', async () => {- const manifest = makeManifest() as { socketContract: { rightHandBone: string; leftHandBone: string } };- manifest.socketContract.rightHandBone = '';- manifest.socketContract.leftHandBone = ' ';- const report = await validateNpcCharacterPack(manifest, { checkFiles: false });- expect(report.ok).toBe(false);- expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_RIGHT_HAND_BONE_MISSING');- expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_LEFT_HAND_BONE_MISSING');- });-- test('reports invalid TIJ state mappings through the schema gate', async () => {- const manifest = makeManifest() as { clips: Array<{ tijStates: string[] }> };- manifest.clips[0]!.tijStates = ['dance'];- const report = await validateNpcCharacterPack(manifest, { checkFiles: false });- expect(report.ok).toBe(false);- expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_SCHEMA_INVALID');- });-- test('blocks rejected clips from production outputs', async () => {- const manifest = makeManifest() as {- clips: Array<{ id: string; label: string; tijStates: string[]; status: string; note: string }>;- outputs: Array<{ clip: string; label: string; path: string; tijStates: string[] }>;- };- manifest.clips.push({- id: 'walk_forward_while_shooting',- label: 'Rejected walk shoot',- tijStates: ['engaging'],- status: 'rejected',- note: 'Rejected in review.',- });- manifest.outputs.push({- ...manifest.outputs[0]!,- clip: 'walk_forward_while_shooting',- label: 'Rejected output',- path: 'tmp/rejected.glb',- tijStates: ['engaging'],- });- const report = await validateNpcCharacterPack(manifest, { checkFiles: false });- expect(report.ok).toBe(false);- expect(report.blockers.map((issue) => issue.code)).toContain('NPC_CHARACTER_PACK_EXCLUDED_CLIP_OUTPUT');- });-});diff --git a/src/imposter/__tests__/projection.test.ts b/src/imposter/__tests__/projection.test.tsdeleted file mode 100644index 9fbcf008..00000000--- a/src/imposter/__tests__/projection.test.ts+++ /dev/null@@ -1,155 +0,0 @@-/**- * Projection math tests — pure, no WebGL, no Chromium.- */--import { describe, expect, test } from 'bun:test';--import {- dirFromAzEl,- enumerateOctahedralTiles,- enumerateTiles,- octaDecode,- octaEncode,- resolveLayout,-} from '../projection';--function unit(v: [number, number, number]): boolean {- const len = Math.hypot(v[0], v[1], v[2]);- return Math.abs(len - 1) < 1e-6;-}--describe('resolveLayout', () => {- test('8 / hemi-y -> 4×2 with 4 azimuths and 2 elevations', () => {- const layout = resolveLayout(8, 'hemi-y');- expect(layout.tilesX).toBe(4);- expect(layout.tilesY).toBe(2);- expect(layout.azimuths).toHaveLength(4);- expect(layout.elevations).toHaveLength(2);- // Top row is HIGHER elevation than bottom row.- expect(layout.elevations[0]!).toBeGreaterThan(layout.elevations[1]!);- });-- test('16 / y -> 8×2 full sphere (one above, one below horizon)', () => {- const layout = resolveLayout(16, 'y');- expect(layout.tilesX).toBe(8);- expect(layout.tilesY).toBe(2);- expect(layout.elevations[0]!).toBeGreaterThan(0);- expect(layout.elevations[1]!).toBeLessThan(0);- });-- test('16 / hemi-y -> 4×4 hemi', () => {- const layout = resolveLayout(16, 'hemi-y');- expect(layout.tilesX).toBe(4);- expect(layout.tilesY).toBe(4);- // All elevations strictly above the horizon.- for (const e of layout.elevations) expect(e).toBeGreaterThan(0);- });-- test('32 / hemi-y -> 8×4', () => {- const layout = resolveLayout(32, 'hemi-y');- expect(layout.tilesX).toBe(8);- expect(layout.tilesY).toBe(4);- });-- test('rejects 8 / y', () => {- expect(() => resolveLayout(8, 'y')).toThrow(/hemi-y/);- });-- test('rejects 32 / y', () => {- expect(() => resolveLayout(32, 'y')).toThrow(/hemi-y/);- });-});--describe('dirFromAzEl', () => {- test('azimuth 0, elevation 0 = +X (asset forward)', () => {- const d = dirFromAzEl(0, 0);- expect(d[0]).toBeCloseTo(1, 6);- expect(d[1]).toBeCloseTo(0, 6);- expect(d[2]).toBeCloseTo(0, 6);- });-- test('azimuth pi/2, elevation 0 = +Z (asset right)', () => {- const d = dirFromAzEl(Math.PI / 2, 0);- expect(d[0]).toBeCloseTo(0, 6);- expect(d[1]).toBeCloseTo(0, 6);- expect(d[2]).toBeCloseTo(1, 6);- });-- test('elevation pi/2 = +Y (zenith)', () => {- const d = dirFromAzEl(0, Math.PI / 2);- expect(d[1]).toBeCloseTo(1, 6);- });-- test('arbitrary (az, el) returns a unit vector', () => {- for (const az of [0.3, 1.2, 2.5, -1.7]) {- for (const el of [0.1, 0.7, -0.4]) {- expect(unit(dirFromAzEl(az, el))).toBe(true);- }- }- });-});--describe('enumerateTiles', () => {- test('16 / hemi-y yields exactly 16 unique unit directions', () => {- const layout = resolveLayout(16, 'hemi-y');- const tiles = enumerateTiles(layout);- expect(tiles).toHaveLength(16);- for (const t of tiles) expect(unit(t.dir)).toBe(true);-- // Each tile's (i,j) is unique.- const keys = new Set(tiles.map((t) => `${t.i},${t.j}`));- expect(keys.size).toBe(16);- });-- test('row-major order: first tile is (0,0) — top-left, highest elevation', () => {- const layout = resolveLayout(16, 'hemi-y');- const tiles = enumerateTiles(layout);- expect(tiles[0]!.i).toBe(0);- expect(tiles[0]!.j).toBe(0);- // Top row == highest elevation.- expect(tiles[0]!.el).toBe(Math.max(...layout.elevations));- });-- test('tile count matches angle count for every supported combo', () => {- expect(enumerateTiles(resolveLayout(8, 'hemi-y'))).toHaveLength(8);- expect(enumerateTiles(resolveLayout(16, 'y'))).toHaveLength(16);- expect(enumerateTiles(resolveLayout(16, 'hemi-y'))).toHaveLength(16);- expect(enumerateTiles(resolveLayout(32, 'hemi-y'))).toHaveLength(32);- });-});--describe('octahedral projection', () => {- test('enumerateOctahedralTiles returns row-major unit directions', () => {- const tiles = enumerateOctahedralTiles({ x: 4, y: 4 });- expect(tiles).toHaveLength(16);- expect(tiles.map((tile) => [tile.i, tile.j]).slice(0, 5)).toEqual([- [0, 0],- [1, 0],- [2, 0],- [3, 0],- [0, 1],- ]);- for (const tile of tiles) expect(unit(tile.dir)).toBe(true);- });-- test('octaEncode and octaDecode round-trip canonical directions', () => {- for (const dir of [- [1, 0, 0],- [0, 1, 0],- [0, -1, 0],- [0, 0, 1],- [0, 0, -1],- ] as Array<[number, number, number]>) {- const encoded = octaEncode(dir);- const decoded = octaDecode(encoded[0], encoded[1]);- expect(decoded[0]).toBeCloseTo(dir[0], 6);- expect(decoded[1]).toBeCloseTo(dir[1], 6);- expect(decoded[2]).toBeCloseTo(dir[2], 6);- }- });-- test('rejects invalid octahedral grid dimensions', () => {- expect(() => enumerateOctahedralTiles({ x: 0, y: 4 })).toThrow();- expect(() => enumerateOctahedralTiles({ x: 4.5, y: 4 })).toThrow();- });-});diff --git a/src/imposter/__tests__/schema.test.ts b/src/imposter/__tests__/schema.test.tsdeleted file mode 100644index 7efd553b..00000000--- a/src/imposter/__tests__/schema.test.ts+++ /dev/null@@ -1,147 +0,0 @@-/**- * ImposterMeta zod schema round-trip tests.- */--import { describe, expect, test } from 'bun:test';--import {- IMPOSTER_LEGACY_SCHEMA_VERSION,- IMPOSTER_SCHEMA_VERSION,- ImposterMetaSchema,- type ImposterMeta,-} from '../schema';--const VALID: ImposterMeta = {- version: IMPOSTER_LEGACY_SCHEMA_VERSION,- angles: 16,- tilesX: 4,- tilesY: 4,- tileSize: 512,- atlasWidth: 2048,- atlasHeight: 2048,- worldSize: 6.25,- yOffset: 3.1,- projection: 'orthographic',- axis: 'hemi-y',- hemi: true,- layout: 'latlon',- azimuths: [0, Math.PI / 2, Math.PI, (3 * Math.PI) / 2],- elevations: [1.3, 0.87, 0.44, 0.087],- bbox: { min: [-0.5, 0, -0.5], max: [0.5, 6.2, 0.5] },- source: { path: 'foo.glb', bytes: 12345, tris: 987 },- auxLayers: ['albedo', 'depth'],- bgColor: 'transparent',- colorLayer: 'beauty',- normalSpace: 'capture-view',- edgeBleedPx: 0,- textureColorSpace: 'srgb',-};--describe('ImposterMetaSchema', () => {- test('accepts a valid payload', () => {- expect(() => ImposterMetaSchema.parse(VALID)).not.toThrow();- });-- test('round-trips via JSON', () => {- const json = JSON.stringify(VALID);- const decoded = ImposterMetaSchema.parse(JSON.parse(json));- expect(decoded).toEqual(VALID);- });-- test('rejects unsupported angles', () => {- const bad = { ...VALID, angles: 24 as unknown as 16 };- expect(() => ImposterMetaSchema.parse(bad)).toThrow();- });-- test('rejects non-orthographic projection', () => {- const bad = { ...VALID, projection: 'perspective' as unknown as 'orthographic' };- expect(() => ImposterMetaSchema.parse(bad)).toThrow();- });-- test('rejects mismatched version', () => {- const bad = { ...VALID, version: 99 as unknown as typeof IMPOSTER_SCHEMA_VERSION };- expect(() => ImposterMetaSchema.parse(bad)).toThrow();- });-- test('source.path is optional', () => {- const noPath = { ...VALID, source: { bytes: 0, tris: 0 } };- expect(() => ImposterMetaSchema.parse(noPath)).not.toThrow();- });-- test('defaults legacy sidecars to the beauty contract', () => {- const legacy = { ...VALID };- delete (legacy as Partial<ImposterMeta>).colorLayer;- delete (legacy as Partial<ImposterMeta>).normalSpace;- delete (legacy as Partial<ImposterMeta>).edgeBleedPx;- delete (legacy as Partial<ImposterMeta>).textureColorSpace;-- const decoded = ImposterMetaSchema.parse(legacy);- expect(decoded.colorLayer).toBe('beauty');- expect(decoded.normalSpace).toBe('capture-view');- expect(decoded.edgeBleedPx).toBe(0);- expect(decoded.textureColorSpace).toBe('srgb');- });-- test('requires normal output for baseColor production bakes', () => {- const bad = { ...VALID, colorLayer: 'baseColor' as const, auxLayers: ['albedo'] };- expect(() => ImposterMetaSchema.parse(bad)).toThrow();- const ok = { ...bad, auxLayers: ['albedo', 'normal'] };- expect(() => ImposterMetaSchema.parse(ok)).not.toThrow();- });-- test('accepts v2 latlon sidecars for forward-compatible static bakes', () => {- const decoded = ImposterMetaSchema.parse({ ...VALID, version: IMPOSTER_SCHEMA_VERSION });- expect(decoded.version).toBe(IMPOSTER_SCHEMA_VERSION);- expect(decoded.layout).toBe('latlon');- });-- test('accepts a valid v2 octahedral sidecar', () => {- const octa = {- ...VALID,- version: IMPOSTER_SCHEMA_VERSION,- angles: 4,- tilesX: 2,- tilesY: 2,- atlasWidth: 1024,- atlasHeight: 1024,- axis: 'octahedral',- hemi: false,- layout: 'octahedral',- directionEncoding: 'octahedral',- directions: [- [1, 0, 0],- [0, 1, 0],- [0, 0, 1],- [-1, 0, 0],- ],- };- delete (octa as Record<string, unknown>).azimuths;- delete (octa as Record<string, unknown>).elevations;-- const decoded = ImposterMetaSchema.parse(octa);- expect(decoded.version).toBe(2);- expect(decoded.layout).toBe('octahedral');- if (decoded.layout !== 'octahedral') throw new Error('expected octahedral payload');- expect(decoded.directions).toHaveLength(4);- });-- test('rejects octahedral sidecars with non-unit directions', () => {- const bad = {- ...VALID,- version: IMPOSTER_SCHEMA_VERSION,- angles: 1,- tilesX: 1,- tilesY: 1,- atlasWidth: 512,- atlasHeight: 512,- axis: 'octahedral',- hemi: false,- layout: 'octahedral',- directionEncoding: 'octahedral',- directions: [[2, 0, 0]],- };- delete (bad as Record<string, unknown>).azimuths;- delete (bad as Record<string, unknown>).elevations;- expect(() => ImposterMetaSchema.parse(bad)).toThrow();- });-});diff --git a/src/imposter/__tests__/validate.test.ts b/src/imposter/__tests__/validate.test.tsdeleted file mode 100644index b9523cb2..00000000--- a/src/imposter/__tests__/validate.test.ts+++ /dev/null@@ -1,128 +0,0 @@-import { mkdtempSync, writeFileSync } from 'node:fs';-import { tmpdir } from 'node:os';-import { join } from 'node:path';--import { describe, expect, test } from 'bun:test';-import sharp from 'sharp';--import { validateImposterSidecar } from '../validate';--const BASE_META = {- tileSize: 128,- worldSize: 1,- yOffset: 0.5,- projection: 'orthographic',- bbox: { min: [0, 0, 0], max: [1, 1, 0] },- source: { path: 'one-triangle.glb', bytes: 988, tris: 1 },- auxLayers: ['albedo', 'normal', 'depth'],- bgColor: 'transparent',- colorLayer: 'baseColor',- normalSpace: 'capture-view',- edgeBleedPx: 2,- textureColorSpace: 'srgb',-} as const;--function makeDir(): string {- return mkdtempSync(join(tmpdir(), 'pf-imposter-validate-'));-}--async function writePng(path: string, width: number, height: number): Promise<void> {- const png = await sharp({- create: {- width,- height,- channels: 4,- background: { r: 80, g: 120, b: 40, alpha: 1 },- },- }).png().toBuffer();- writeFileSync(path, png);-}--async function writeSidecarSet(dir: string, name: string, meta: unknown): Promise<string> {- const sidecar = join(dir, `${name}.json`);- writeFileSync(sidecar, JSON.stringify(meta, null, 2), 'utf-8');- const m = meta as { atlasWidth: number; atlasHeight: number };- await writePng(join(dir, `${name}.png`), m.atlasWidth, m.atlasHeight);- await writePng(join(dir, `${name}.normal.png`), m.atlasWidth, m.atlasHeight);- await writePng(join(dir, `${name}.depth.png`), m.atlasWidth, m.atlasHeight);- return sidecar;-}--describe('validateImposterSidecar', () => {- test('accepts a v1 latlon sidecar and sibling PNGs', async () => {- const dir = makeDir();- const meta = {- version: 1,- angles: 16,- tilesX: 4,- tilesY: 4,- atlasWidth: 512,- atlasHeight: 512,- axis: 'hemi-y',- hemi: true,- layout: 'latlon',- azimuths: [0, Math.PI / 2, Math.PI, (3 * Math.PI) / 2],- elevations: [1.4, 1.0, 0.5, 0.1],- ...BASE_META,- };- const sidecar = await writeSidecarSet(dir, 'latlon', meta);-- const result = await validateImposterSidecar(sidecar);- expect(result.ok).toBe(true);- expect(result.meta?.version).toBe(1);- expect(result.meta?.layout).toBe('latlon');- });-- test('accepts a v2 octahedral sidecar with unit directions', async () => {- const dir = makeDir();- const meta = {- version: 2,- angles: 4,- tilesX: 2,- tilesY: 2,- atlasWidth: 256,- atlasHeight: 256,- axis: 'octahedral',- hemi: false,- layout: 'octahedral',- directionEncoding: 'octahedral',- directions: [- [1, 0, 0],- [0, 1, 0],- [0, 0, 1],- [-1, 0, 0],- ],- ...BASE_META,- };- const sidecar = await writeSidecarSet(dir, 'octa', meta);-- const result = await validateImposterSidecar(sidecar);- expect(result.ok).toBe(true);- expect(result.meta?.version).toBe(2);- expect(result.meta?.layout).toBe('octahedral');- });-- test('flags sibling PNG dimension mismatches', async () => {- const dir = makeDir();- const meta = {- version: 1,- angles: 8,- tilesX: 4,- tilesY: 2,- atlasWidth: 512,- atlasHeight: 256,- axis: 'hemi-y',- hemi: true,- layout: 'latlon',- azimuths: [0, Math.PI / 2, Math.PI, (3 * Math.PI) / 2],- elevations: [1.0, 0.2],- ...BASE_META,- };- const sidecar = await writeSidecarSet(dir, 'bad-png', meta);- await writePng(join(dir, 'bad-png.normal.png'), 128, 128);-- const result = await validateImposterSidecar(sidecar);- expect(result.ok).toBe(false);- expect(result.issues.some((issue) => issue.message.includes('PNG dimensions'))).toBe(true);- });-});diff --git a/src/imposter/animated-bake.ts b/src/imposter/animated-bake.tsdeleted file mode 100644index 3354a7b3..00000000--- a/src/imposter/animated-bake.ts+++ /dev/null@@ -1,767 +0,0 @@-/**- * Animated octahedral imposter baker.- *- * W2 emits a packed RGBA8 debug atlas for review. Production R8 palette and- * KTX2/DataArrayTexture packaging stay behind the review gate.- */--import { Buffer } from 'node:buffer';-import { createHash } from 'node:crypto';-import { readFileSync } from 'node:fs';-import sharp from 'sharp';-import { chromium, type Page } from 'playwright';--import {- ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES,- ANIMATED_IMPOSTER_KIND,- ANIMATED_IMPOSTER_SCHEMA_VERSION,- AnimatedImposterMetaSchema,- type AnimatedClipTarget,- type AnimatedImposterMeta,- type AnimatedImposterPreBakeInput,- type AnimatedImposterTextureLayout,-} from './animated-schema';-import {- validateAnimatedImposterPreBake,- type AnimatedImposterPreBakeReport,-} from './animated-validate';-import type { ResolvedClip } from './clip-resolver';-import { enumerateOctahedralTiles } from './projection';--export interface AnimatedTileCamera {- i: number;- j: number;- u: number;- v: number;- dir: [number, number, number];-}--export interface BakeAnimatedImposterOptions {- clipTargets?: AnimatedClipTarget[];- clipFallbacks?: AnimatedImposterPreBakeInput['clipFallbacks'];- attachments?: AnimatedImposterAttachment[];- viewGrid?: { x: number; y: number };- tileSize?: number;- framesPerClip?: number;- textureLayout?: AnimatedImposterTextureLayout;- sourcePath?: string;- colorUri?: string;- envelopeBytes?: number;-}--export interface AnimatedImposterAttachment {- id: string;- kind: 'weapon';- glb: Buffer | string;- sourcePath?: string;- lengthMeters: number;- gripNames?: string[];- supportNames?: string[];- muzzleNames?: string[];- stockNames?: string[];- sourceForward?: [number, number, number];- pitchTrimDeg?: number;- forwardHold?: number;- gripOffset?: number;- socketMode?: 'shouldered-forward';-}--export interface BakeAnimatedImposterResult {- atlas: Buffer;- frameAtlases: Buffer[];- meta: AnimatedImposterMeta;- preBake: AnimatedImposterPreBakeReport;- frameAtlas: {- width: number;- height: number;- framesX: number;- framesY: number;- };-}--export interface AnimatedImposterSession {- bake(glb: Buffer | string, opts?: BakeAnimatedImposterOptions): Promise<BakeAnimatedImposterResult>;- close(): Promise<void>;-}--interface LoadedAnimatedGlbInfo {- bbox: { min: [number, number, number]; max: [number, number, number] };- tris: number;- skinned: boolean;- clipNames: string[];- clipDurations: Record<string, number>;-}--interface BrowserAttachmentInput extends Omit<AnimatedImposterAttachment, 'glb'> {- dataUrl: string;- bytes: number;- hash: string;-}--export function enumerateOctahedralGrid(x: number, y: number): AnimatedTileCamera[] {- return enumerateOctahedralTiles({ x, y });-}--export async function openAnimatedImposterSession(): Promise<AnimatedImposterSession> {- const browser = await chromium.launch();- const ctx = await browser.newContext({ viewport: { width: 1024, height: 1024 }, deviceScaleFactor: 1 });- const page = await ctx.newPage();- await page.setContent(buildAnimatedHarnessHtml());- await page.waitForFunction(- () => (globalThis as unknown as { __animatedImposterReady?: boolean }).__animatedImposterReady === true,- { timeout: 30_000 },- );-- return {- bake: (glb, opts) => bakeAnimatedOnPage(page, glb, opts ?? {}),- close: async () => {- await ctx.close();- await browser.close();- },- };-}--export async function bakeAnimatedImposter(- glb: Buffer | string,- opts: BakeAnimatedImposterOptions = {},-): Promise<BakeAnimatedImposterResult> {- const session = await openAnimatedImposterSession();- try {- return await session.bake(glb, opts);- } finally {- await session.close();- }-}--async function bakeAnimatedOnPage(- page: Page,- glb: Buffer | string,- opts: BakeAnimatedImposterOptions,-): Promise<BakeAnimatedImposterResult> {- const buf = typeof glb === 'string' ? readFileSync(glb) : glb;- const sourcePath = opts.sourcePath ?? (typeof glb === 'string' ? glb : undefined);- const clipTargets = opts.clipTargets ?? ['walking'];- const viewGrid = opts.viewGrid ?? { x: 6, y: 6 };- const tileSize = opts.tileSize ?? 96;- const framesPerClip = opts.framesPerClip ?? 8;- const textureLayout = opts.textureLayout ?? 'atlas';- const colorUri = opts.colorUri ?? 'animated-albedo-packed.png';- const envelopeBytes = opts.envelopeBytes ?? ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES;- const attachments = loadBrowserAttachments(opts.attachments ?? []);-- if (textureLayout !== 'atlas') {- throw new Error('W2 animated imposter bake currently writes packed 2D atlas output only');- }-- const loadInfo = (await page.evaluate(- async ([dataUrl, tileSz, browserAttachments]) => {- const w = globalThis as unknown as {- __animatedImposterLoadGlb: (- dataUrl: string,- tileSize: number,- attachments: BrowserAttachmentInput[],- ) => Promise<LoadedAnimatedGlbInfo>;- };- return w.__animatedImposterLoadGlb(dataUrl, tileSz, browserAttachments);- },- [`data:model/gltf-binary;base64,${buf.toString('base64')}`, tileSize, attachments] as const,- )) as LoadedAnimatedGlbInfo;-- const preBake = validateAnimatedImposterPreBake({- source: {- ...(sourcePath ? { path: sourcePath } : {}),- bytes: buf.byteLength,- tris: loadInfo.tris,- skinned: loadInfo.skinned,- clipNames: loadInfo.clipNames,- },- clipTargets,- clipFallbacks: opts.clipFallbacks ?? [],- viewGrid,- tileSize,- framesPerClip,- textureFormat: 'rgba8',- textureLayout,- includeNormal: false,- includeDepth: false,- envelopeBytes,- });-- if (!preBake.ok) {- throw new Error(`animated imposter pre-bake failed: ${preBake.blockers.map((i) => i.message).join('; ')}`);- }-- const tiles = enumerateOctahedralGrid(viewGrid.x, viewGrid.y);- const frameAtlases: Buffer[] = [];- const clips = clipTargets- .map((target) => preBake.clipResolution.clips[target])- .filter(isRenderableClip);-- for (const clip of clips) {- const durationSec = durationForClip(loadInfo.clipDurations, clip.rawName!, clip.resolved!);- for (let frame = 0; frame < framesPerClip; frame++) {- const timeSec = durationSec * (frame / framesPerClip);- const tilePngs: Buffer[] = [];- for (const tile of tiles) {- const dataUrl = (await page.evaluate(- (args) => {- const w = globalThis as unknown as {- __animatedImposterRenderTile: (args: {- dir: [number, number, number];- clipRawName: string;- timeSec: number;- tileSize: number;- }) => string;- };- return w.__animatedImposterRenderTile(args);- },- {- dir: tile.dir,- clipRawName: clip.rawName!,- timeSec,- tileSize,- },- )) as string;- tilePngs.push(Buffer.from(dataUrl.split(',')[1]!, 'base64'));- }- frameAtlases.push(await composeAtlas(tilePngs, tileSize, viewGrid.x, viewGrid.y));- }- }-- const layerWidth = viewGrid.x * tileSize;- const layerHeight = viewGrid.y * tileSize;- const { framesX, framesY } = chooseFrameGrid(frameAtlases.length);- const atlas = await composeAtlas(frameAtlases, layerWidth, framesX, framesY, layerHeight);- const min = loadInfo.bbox.min;- const max = loadInfo.bbox.max;- const worldSize = Math.max(max[0] - min[0], max[1] - min[1], max[2] - min[2]);- const yOffset = (min[1] + max[1]) * 0.5;-- const meta: AnimatedImposterMeta = {- version: ANIMATED_IMPOSTER_SCHEMA_VERSION,- kind: ANIMATED_IMPOSTER_KIND,- source: {- ...(sourcePath ? { path: sourcePath } : {}),- bytes: buf.byteLength,- tris: loadInfo.tris,- skinned: loadInfo.skinned,- hash: createHash('sha256').update(buf).digest('hex'),- animationClips: loadInfo.clipNames,- ...(attachments.length- ? {- attachments: attachments.map((attachment) => ({- id: attachment.id,- kind: attachment.kind,- ...(attachment.sourcePath ? { sourcePath: attachment.sourcePath } : {}),- bytes: attachment.bytes,- hash: attachment.hash,- })),- }- : {}),- },- bbox: { min, max, worldSize, yOffset },- projection: 'orthographic',- view: {- layout: 'octahedral',- directionEncoding: 'octahedral',- grid: { x: viewGrid.x, y: viewGrid.y, count: viewGrid.x * viewGrid.y },- tileSize,- framesPerClip,- },- clips: clips.map((clip) => ({- target: clip.target,- resolved: clip.resolved,- rawName: clip.rawName,- matchedBy: clip.matchedBy,- ...(clip.fallbackFor ? { fallbackFor: clip.fallbackFor } : {}),- ...(clip.fallbackRawName ? { fallbackRawName: clip.fallbackRawName } : {}),- frameCount: framesPerClip,- durationSec: durationForClip(loadInfo.clipDurations, clip.rawName!, clip.resolved!),- })),- textures: {- layout: textureLayout,- color: {- uri: colorUri,- format: 'rgba8',- width: layerWidth * framesX,- height: layerHeight * framesY,- layers: frameAtlases.length,- framesX,- framesY,- bytes: atlas.byteLength,- colorSpace: 'srgb',- },- },- runtime: {- renderer: 'webgl2',- primitive: 'instanced-quad',- material: 'ShaderMaterial',- textureMode: 'packed-2d-atlas',- attributes: ['frameOffset', 'clip', 'variant', 'yaw', 'paletteRow'],- },- storage: {- colorBytes: preBake.storage.colorBytes,- totalRawBytes: preBake.storage.totalRawBytes,- envelopeBytes: preBake.storage.envelopeBytes,- fitsEnvelope: preBake.storage.fitsEnvelope,- },- validation: {- warnings: preBake.warnings,- },- };-- return {- atlas,- frameAtlases,- meta: AnimatedImposterMetaSchema.parse(meta),- preBake,- frameAtlas: { width: layerWidth, height: layerHeight, framesX, framesY },- };-}--function loadBrowserAttachments(attachments: AnimatedImposterAttachment[]): BrowserAttachmentInput[] {- return attachments.map((attachment) => {- const buf = typeof attachment.glb === 'string' ? readFileSync(attachment.glb) : attachment.glb;- const { glb: _glb, ...rest } = attachment;- return {- ...rest,- dataUrl: `data:model/gltf-binary;base64,${buf.toString('base64')}`,- bytes: buf.byteLength,- hash: createHash('sha256').update(buf).digest('hex'),- };- });-}--async function composeAtlas(- tilePngs: Buffer[],- tileWidth: number,- tilesX: number,- tilesY: number,- tileHeight = tileWidth,-): Promise<Buffer> {- const composites: sharp.OverlayOptions[] = [];- for (let idx = 0; idx < tilePngs.length; idx++) {- const i = idx % tilesX;- const j = Math.floor(idx / tilesX);- composites.push({ input: tilePngs[idx]!, left: i * tileWidth, top: j * tileHeight });- }-- return sharp({- create: { width: tilesX * tileWidth, height: tilesY * tileHeight, channels: 4, background: { r: 0, g: 0, b: 0, alpha: 0 } },- })- .composite(composites)- .png()- .toBuffer();-}--function durationForClip(durations: Record<string, number>, rawName: string, resolved: string): number {- return durations[rawName] ?? durations[resolved] ?? durations[resolved.toLowerCase()] ?? 1;-}--function isRenderableClip(clip: ResolvedClip | undefined): clip is ResolvedClip & { rawName: string; resolved: string } {- return Boolean(clip?.rawName && clip.resolved);-}--function chooseFrameGrid(layerCount: number): { framesX: number; framesY: number } {- let best = { framesX: layerCount, framesY: 1, waste: 0, aspectPenalty: Number.POSITIVE_INFINITY };- for (let y = 1; y <= layerCount; y++) {- const x = Math.ceil(layerCount / y);- const waste = x * y - layerCount;- const aspectPenalty = Math.abs(x / y - 2);- if (waste < best.waste || (waste === best.waste && aspectPenalty < best.aspectPenalty)) {- best = { framesX: x, framesY: y, waste, aspectPenalty };- }- }- return { framesX: best.framesX, framesY: best.framesY };-}--function buildAnimatedHarnessHtml(): string {- return `<!DOCTYPE html>-<html><head>-<meta charset="utf-8">-<style>html,body{margin:0;padding:0;background:#000}#app{width:1024px;height:1024px}</style>-<script type="importmap">-{- "imports": {- "three": "https://unpkg.com/[email protected]/build/three.module.js",- "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"- }-}-</script>-</head>-<body>-<div id="app"></div>-<script type="module">-import * as THREE from 'three';-import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';--const app = document.getElementById('app');-const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });-renderer.setPixelRatio(1);-renderer.setSize(1024, 1024);-renderer.outputColorSpace = THREE.SRGBColorSpace;-app.appendChild(renderer.domElement);--const scene = new THREE.Scene();-scene.add(new THREE.AmbientLight(0xffffff, 0.55));-const key = new THREE.DirectionalLight(0xffffff, 1.1);-key.position.set(1.5, 2, 1);-scene.add(key);-const fill = new THREE.DirectionalLight(0xffffff, 0.35);-fill.position.set(-1, 0.5, -1);-scene.add(fill);--let actorGroup = null;-let root = null;-let mixer = null;-let clips = [];-let boundsRadius = 1;-let boundsCenter = new THREE.Vector3();-let originalMaterials = new Map();-let bones = {};-let rootMotionBase = null;-let weaponPivot = new THREE.Group();-let currentWeapon = null;-let currentWeaponMeta = null;--function normalizeClipName(raw) {- let s = raw;- while (s.includes('|')) s = s.slice(s.indexOf('|') + 1);- return s;-}--function findClip(rawName) {- return clips.find((c) => c.name === rawName)- || clips.find((c) => normalizeClipName(c.name) === normalizeClipName(rawName));-}--window.__animatedImposterLoadGlb = async (dataUrl, tileSize, attachments = []) => {- if (actorGroup) scene.remove(actorGroup);- originalMaterials.clear();- bones = {};- rootMotionBase = null;- currentWeapon = null;- currentWeaponMeta = null;- weaponPivot = new THREE.Group();- if (renderer.domElement.width !== tileSize) renderer.setSize(tileSize, tileSize);- const loader = new GLTFLoader();- return new Promise((resolve, reject) => {- loader.load(dataUrl, async (gltf) => {- root = gltf.scene;- clips = gltf.animations || [];- mixer = new THREE.AnimationMixer(root);- actorGroup = new THREE.Group();- actorGroup.add(root);- actorGroup.add(weaponPivot);- scene.add(actorGroup);- collectBones(root);- const firstClip = clips[0];- if (firstClip) {- const action = mixer.clipAction(firstClip);- action.reset();- action.setLoop(THREE.LoopRepeat, Infinity);- action.play();- mixer.setTime(0);- root.updateMatrixWorld(true);- }- rootMotionBase = bones.Hips ? bones.Hips.position.clone() : null;-- if (attachments.length > 0) {- currentWeaponMeta = attachments[0];- try {- const weaponGltf = await loadGltf(loader, currentWeaponMeta.dataUrl);- currentWeapon = weaponGltf.scene;- normalizeWeapon(currentWeapon, currentWeaponMeta);- weaponPivot.add(currentWeapon);- updateWeaponSocket();- } catch (error) {- console.warn('Animated imposter weapon attachment failed', error);- }- }-- actorGroup.updateMatrixWorld(true);- const box = new THREE.Box3().setFromObject(actorGroup);- boundsCenter = box.getCenter(new THREE.Vector3());- const size = box.getSize(new THREE.Vector3());- boundsRadius = Math.sqrt(size.x * size.x + size.y * size.y + size.z * size.z) * 0.5 || 1;- let tris = 0;- let skinned = false;- actorGroup.traverse((obj) => {- if (obj.isSkinnedMesh) skinned = true;- if (obj.isMesh && obj.material) {- originalMaterials.set(obj, obj.material);- const mats = Array.isArray(obj.material) ? obj.material : [obj.material];- for (const m of mats) {- m.side = THREE.FrontSide;- m.needsUpdate = true;- }- if (obj.geometry && obj.geometry.index) tris += obj.geometry.index.count / 3;- else if (obj.geometry && obj.geometry.attributes.position) tris += obj.geometry.attributes.position.count / 3;- }- });- const clipDurations = {};- for (const clip of clips) {- clipDurations[clip.name] = clip.duration || 1;- clipDurations[normalizeClipName(clip.name)] = clip.duration || 1;- clipDurations[normalizeClipName(clip.name).toLowerCase()] = clip.duration || 1;- }- resolve({- bbox: { min: [box.min.x, box.min.y, box.min.z], max: [box.max.x, box.max.y, box.max.z] },- tris: Math.round(tris),- skinned,- clipNames: clips.map((c) => c.name),- clipDurations,- });- }, undefined, (err) => reject(err));- });-};--window.__animatedImposterRenderTile = ({ dir, clipRawName, timeSec, tileSize }) => {- if (!root || !mixer) throw new Error('no animated GLB loaded');- if (renderer.domElement.width !== tileSize) renderer.setSize(tileSize, tileSize);-- const clip = findClip(clipRawName);- if (!clip) throw new Error('clip not found: ' + clipRawName);- mixer.stopAllAction();- const action = mixer.clipAction(clip);- action.reset();- action.setLoop(THREE.LoopRepeat, Infinity);- action.play();- mixer.setTime((timeSec || 0) % (clip.duration || 1));- lockRootMotion();- root.updateMatrixWorld(true);- updateWeaponSocket();- actorGroup?.updateMatrixWorld(true);-- actorGroup.traverse((o) => {- if (o.isMesh && originalMaterials.has(o)) o.material = originalMaterials.get(o);- });-- const half = boundsRadius * 1.05;- const far = Math.max(200, boundsRadius * 8);- const camera = new THREE.OrthographicCamera(-half, half, half, -half, 0.01, far);- const d = new THREE.Vector3(dir[0], dir[1], dir[2]).normalize();- camera.position.copy(boundsCenter).addScaledVector(d, boundsRadius * 4);- camera.up.set(0, 1, 0);- if (Math.abs(d.dot(camera.up)) > 0.97) camera.up.set(0, 0, 1);- camera.lookAt(boundsCenter);-- scene.background = null;- renderer.setClearColor(0x000000, 0);- renderer.render(scene, camera);- return renderer.domElement.toDataURL('image/png');-};--function loadGltf(loader, dataUrl) {- return new Promise((resolve, reject) => {- loader.load(dataUrl, resolve, undefined, reject);- });-}--function collectBones(rootObject) {- bones = {};- rootObject.traverse((node) => {- if (node.isBone) bones[node.name] = node;- });-}--function findNamed(rootObject, names = []) {- for (const name of names) {- let found = null;- rootObject.traverse((node) => {- if (!found && node.name === name) found = node;- });- if (found) return found;- }- return null;-}--function centerOfObject(rootObject, object) {- if (!object) return null;- rootObject.updateMatrixWorld(true);- const box = new THREE.Box3().setFromObject(object);- if (box.isEmpty()) return null;- const center = box.getCenter(new THREE.Vector3());- return rootObject.worldToLocal(center.clone());-}--function normalizeWeapon(weaponRoot, weapon) {- weaponRoot.updateMatrixWorld(true);- const box = new THREE.Box3().setFromObject(weaponRoot);- const size = box.getSize(new THREE.Vector3());- const long = Math.max(size.x, size.y, size.z) || 1;- const scale = weapon.lengthMeters / long;- weaponRoot.scale.setScalar(scale);- const gripObject = findNamed(weaponRoot, weapon.gripNames || []);- const supportObject = findNamed(weaponRoot, weapon.supportNames || []);- const muzzleObject = findNamed(weaponRoot, weapon.muzzleNames || []);- const stockObject = findNamed(weaponRoot, weapon.stockNames || []);- const grip = centerOfObject(weaponRoot, gripObject) || new THREE.Vector3(0, 0, 0);- const support = centerOfObject(weaponRoot, supportObject);- const muzzle = centerOfObject(weaponRoot, muzzleObject);- const stock = centerOfObject(weaponRoot, stockObject);- const muzzleDirection = weapon.sourceForward- ? new THREE.Vector3(...weapon.sourceForward)- : muzzle- ? muzzle.clone().sub(grip)- : new THREE.Vector3(1, 0, 0);- const alignment = muzzleDirection.lengthSq() > 0.0001- ? new THREE.Quaternion().setFromUnitVectors(muzzleDirection.normalize(), new THREE.Vector3(1, 0, 0))- : new THREE.Quaternion();- weaponRoot.quaternion.copy(alignment);- const transformLocal = (point) => point.clone().multiplyScalar(scale).applyQuaternion(weaponRoot.quaternion);- const transformedGrip = transformLocal(grip);- weaponRoot.position.copy(transformedGrip.multiplyScalar(-1));- weaponRoot.userData.stockOffset = stock- ? transformLocal(stock).sub(transformLocal(grip))- : new THREE.Vector3(-0.28, 0.04, 0);- weaponRoot.userData.supportOffset = support- ? transformLocal(support).sub(transformLocal(grip))- : new THREE.Vector3(0.28, 0.02, 0);- weaponRoot.updateMatrixWorld(true);-}--function worldPosition(name) {- const bone = bones[name];- if (!bone) return null;- return bone.getWorldPosition(new THREE.Vector3());-}--function rootForward() {- const q = root.getWorldQuaternion(new THREE.Quaternion());- return new THREE.Vector3(0, 0, 1).applyQuaternion(q).normalize();-}--function bodyForward() {- const hips = bones.Hips || bones.Spine || root;- const q = hips.getWorldQuaternion(new THREE.Quaternion());- return new THREE.Vector3(0, 0, 1).applyQuaternion(q).normalize();-}--function lockRootMotion() {- if (!rootMotionBase || !bones.Hips) return;- bones.Hips.position.x = rootMotionBase.x;- bones.Hips.position.z = rootMotionBase.z;-}--const boneUp = new THREE.Vector3(0, 1, 0);--function setBoneDirectionWorld(bone, directionWorld) {- if (!bone?.parent) return;- const direction = directionWorld.clone().normalize();- if (direction.lengthSq() < 0.0001) return;- const parentInv = bone.parent.getWorldQuaternion(new THREE.Quaternion()).invert();- const targetLocal = direction.applyQuaternion(parentInv).normalize();- bone.quaternion.setFromUnitVectors(boneUp, targetLocal);- bone.updateMatrixWorld(true);-}--function solveArmToTarget(side, target, axes) {- const upper = bones[side + 'Arm'];- const fore = bones[side + 'ForeArm'];- const hand = bones[side + 'Hand'];- if (!upper || !fore || !hand || !target) return;-- root.updateMatrixWorld(true);- const shoulder = upper.getWorldPosition(new THREE.Vector3());- const elbowNow = fore.getWorldPosition(new THREE.Vector3());- const handNow = hand.getWorldPosition(new THREE.Vector3());- const upperLength = Math.max(0.001, shoulder.distanceTo(elbowNow));- const foreLength = Math.max(0.001, elbowNow.distanceTo(handNow));- const reach = Math.max(0.08, upperLength + foreLength - 0.025);- const targetVector = target.clone().sub(shoulder);- const distance = targetVector.length();- if (distance < 0.001) return;-- const direction = targetVector.clone().normalize();- const clampedTarget = distance > reach- ? shoulder.clone().add(direction.clone().multiplyScalar(reach))- : target.clone();- const clampedDistance = Math.min(distance, reach);- const sideSign = side === 'Right' ? 1 : -1;- const pole = shoulder.clone()- .add(axes.cleanUp.clone().multiplyScalar(-0.24))- .add(axes.actorRight.clone().multiplyScalar(0.22 * sideSign))- .add(axes.forward.clone().multiplyScalar(0.04));- let planeNormal = direction.clone().cross(pole.clone().sub(shoulder)).normalize();- if (planeNormal.lengthSq() < 0.0001) planeNormal = axes.actorRight.clone().multiplyScalar(sideSign);- const bendDirection = planeNormal.clone().cross(direction).normalize();- const along = (upperLength * upperLength - foreLength * foreLength + clampedDistance * clampedDistance) / (2 * clampedDistance);- const height = Math.sqrt(Math.max(0, upperLength * upperLength - along * along));- const elbow = shoulder.clone()- .add(direction.clone().multiplyScalar(along))- .add(bendDirection.multiplyScalar(height));-- setBoneDirectionWorld(upper, elbow.clone().sub(shoulder));- root.updateMatrixWorld(true);- const elbowWorld = fore.getWorldPosition(new THREE.Vector3());- setBoneDirectionWorld(fore, clampedTarget.clone().sub(elbowWorld));- root.updateMatrixWorld(true);-}--function updateWeaponSocket() {- if (!currentWeapon || !currentWeaponMeta) return;- const right = worldPosition('RightHand');- const leftShoulder = worldPosition('LeftArm') || worldPosition('LeftShoulder');- const rightShoulder = worldPosition('RightArm') || worldPosition('RightShoulder');- if (!right) return;-- const up = new THREE.Vector3(0, 1, 0);- const travelForward = rootForward();- travelForward.y = 0;- if (travelForward.lengthSq() < 0.0001) travelForward.set(0, 0, 1);- travelForward.normalize();- const torsoForward = bodyForward();- torsoForward.y = 0;- if (torsoForward.lengthSq() < 0.0001) torsoForward.set(0, 0, 1);- torsoForward.normalize();- const forward = currentWeaponMeta.socketMode === 'shouldered-forward' ? travelForward : torsoForward;- let actorRight = new THREE.Vector3().crossVectors(forward, up).normalize();- if (leftShoulder && rightShoulder) {- const shoulderSpan = rightShoulder.clone().sub(leftShoulder);- shoulderSpan.y = 0;- if (shoulderSpan.lengthSq() > 0.0001) {- shoulderSpan.normalize();- if (shoulderSpan.dot(actorRight) < 0) shoulderSpan.multiplyScalar(-1);- actorRight = shoulderSpan;- }- }- const cleanUp = new THREE.Vector3().crossVectors(actorRight, forward).normalize();- const matrix = new THREE.Matrix4().makeBasis(forward, cleanUp, actorRight);- weaponPivot.quaternion.setFromRotationMatrix(matrix);- if (currentWeaponMeta.pitchTrimDeg) {- weaponPivot.rotateZ(THREE.MathUtils.degToRad(currentWeaponMeta.pitchTrimDeg));- }-- const shoulder = rightShoulder || right;- const shoulderCenter = leftShoulder && rightShoulder- ? leftShoulder.clone().lerp(rightShoulder, 0.5)- : shoulder.clone().sub(actorRight.clone().multiplyScalar(0.12));- const shoulderPocket = shoulder.clone()- .lerp(shoulderCenter, 0.42)- .add(cleanUp.clone().multiplyScalar(-0.035));- const stockOffset = currentWeapon.userData.stockOffset instanceof THREE.Vector3- ? currentWeapon.userData.stockOffset.clone()- : new THREE.Vector3(-0.28, 0.04, 0);- const stockWorldOffset = stockOffset.applyQuaternion(weaponPivot.quaternion);- const offset = currentWeaponMeta.gripOffset || 0;- const stockAnchoredGrip = shoulderPocket.clone()- .add(forward.clone().multiplyScalar((currentWeaponMeta.forwardHold ?? 0.06) + offset))- .sub(stockWorldOffset);- weaponPivot.position.copy(stockAnchoredGrip).add(actorRight.clone().multiplyScalar(0.006));-- const supportOffset = currentWeapon.userData.supportOffset instanceof THREE.Vector3- ? currentWeapon.userData.supportOffset.clone()- : new THREE.Vector3(0.28, 0.02, 0);- const supportTarget = weaponPivot.position.clone().add(supportOffset.applyQuaternion(weaponPivot.quaternion));- const gripTarget = weaponPivot.position.clone();- const axes = { forward, cleanUp, actorRight };- solveArmToTarget('Right', gripTarget, axes);- solveArmToTarget('Left', supportTarget, axes);- root.updateMatrixWorld(true);-}--window.__animatedImposterReady = true;-</script>-</body></html>`;-}diff --git a/src/imposter/animated-schema.ts b/src/imposter/animated-schema.tsdeleted file mode 100644index f8a4117d..00000000--- a/src/imposter/animated-schema.ts+++ /dev/null@@ -1,346 +0,0 @@-/**- * Animated octahedral imposter sidecar and pre-bake contract.- *- * Version 2 is intentionally separate from the static imposter v1 schema:- * one array layer is one animation frame containing the full octahedral view grid.- */--import { z } from 'zod';--export const ANIMATED_IMPOSTER_SCHEMA_VERSION = 2 as const;-export const ANIMATED_IMPOSTER_KIND = 'animated-octahedral-imposter' as const;-export const ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES = 30 * 1024 * 1024;--export const AnimatedClipTargetSchema = z.enum(['idle', 'walking', 'running', 'shoot', 'death']);-export const AnimatedImposterTextureFormatSchema = z.enum(['r8-palette-index', 'rgba8']);-export const AnimatedImposterTextureLayoutSchema = z.enum(['array', 'atlas']);-export const AnimatedImposterTextureModeSchema = z.enum(['data-array-texture', 'packed-2d-atlas']);-export const AnimatedImposterRuntimeAttributeSchema = z.enum([- 'frameOffset',- 'clip',- 'variant',- 'yaw',- 'paletteRow',- 'lodAlpha',-]);--export const AnimatedImposterWarningSchema = z- .object({- code: z.string().min(1),- severity: z.enum(['info', 'warning', 'error']),- message: z.string().min(1),- fixHint: z.string().min(1).optional(),- })- .strict();--const Vec3Schema = z.tuple([z.number(), z.number(), z.number()]);--const AnimatedAttachmentMetaSchema = z- .object({- id: z.string().min(1),- kind: z.enum(['weapon']),- sourcePath: z.string().optional(),- bytes: z.number().int().nonnegative(),- hash: z.string().optional(),- })- .strict();--const AnimatedClipMetaSchema = z- .object({- target: AnimatedClipTargetSchema,- resolved: z.string().nullable(),- rawName: z.string().nullable(),- matchedBy: z.enum(['exact', 'alias', 'fallback', 'missing']),- fallbackFor: AnimatedClipTargetSchema.optional(),- fallbackRawName: z.string().optional(),- frameCount: z.number().int().nonnegative(),- durationSec: z.number().positive().optional(),- })- .strict();--const AnimatedTextureLayerSchema = z- .object({- uri: z.string().min(1),- format: AnimatedImposterTextureFormatSchema,- width: z.number().int().positive(),- height: z.number().int().positive(),- layers: z.number().int().positive(),- framesX: z.number().int().positive().optional(),- framesY: z.number().int().positive().optional(),- bytes: z.number().int().nonnegative(),- colorSpace: z.enum(['srgb', 'linear']),- })- .strict();--export const AnimatedImposterMetaSchema = z- .object({- version: z.literal(ANIMATED_IMPOSTER_SCHEMA_VERSION),- kind: z.literal(ANIMATED_IMPOSTER_KIND),- source: z- .object({- path: z.string().optional(),- bytes: z.number().int().nonnegative(),- tris: z.number().int().nonnegative(),- skinned: z.boolean(),- hash: z.string().optional(),- animationClips: z.array(z.string()),- attachments: z.array(AnimatedAttachmentMetaSchema).optional(),- })- .strict(),- bbox: z- .object({- min: Vec3Schema,- max: Vec3Schema,- worldSize: z.number().positive(),- yOffset: z.number(),- })- .strict(),- projection: z.literal('orthographic'),- view: z- .object({- layout: z.literal('octahedral'),- directionEncoding: z.literal('octahedral'),- grid: z- .object({- x: z.number().int().positive(),- y: z.number().int().positive(),- count: z.number().int().positive(),- })- .strict(),- tileSize: z.number().int().positive(),- framesPerClip: z.number().int().positive(),- })- .strict(),- clips: z.array(AnimatedClipMetaSchema).min(1),- textures: z- .object({- layout: AnimatedImposterTextureLayoutSchema,- color: AnimatedTextureLayerSchema,- palette: z- .object({- uri: z.string().min(1),- width: z.number().int().positive(),- rows: z.number().int().positive(),- bytes: z.number().int().nonnegative(),- })- .strict()- .optional(),- normal: AnimatedTextureLayerSchema.optional(),- depth: AnimatedTextureLayerSchema.optional(),- })- .strict(),- runtime: z- .object({- renderer: z.literal('webgl2'),- primitive: z.literal('instanced-quad'),- material: z.literal('ShaderMaterial'),- textureMode: AnimatedImposterTextureModeSchema,- attributes: z.array(AnimatedImposterRuntimeAttributeSchema).min(1),- })- .strict(),- storage: z- .object({- colorBytes: z.number().int().nonnegative(),- normalBytes: z.number().int().nonnegative().optional(),- depthBytes: z.number().int().nonnegative().optional(),- paletteBytes: z.number().int().nonnegative().optional(),- totalRawBytes: z.number().int().nonnegative(),- envelopeBytes: z.number().int().positive(),- fitsEnvelope: z.boolean(),- })- .strict(),- validation: z- .object({- warnings: z.array(AnimatedImposterWarningSchema),- })- .strict(),- })- .strict()- .superRefine((meta, ctx) => {- const grid = meta.view.grid;- if (grid.count !== grid.x * grid.y) {- ctx.addIssue({- code: 'custom',- path: ['view', 'grid', 'count'],- message: 'grid.count must equal grid.x * grid.y',- });- }-- const expectedLayerWidth = grid.x * meta.view.tileSize;- const expectedLayerHeight = grid.y * meta.view.tileSize;-- const expectedLayers = meta.clips.reduce((sum, clip) => sum + clip.frameCount, 0);- if (meta.textures.color.layers !== expectedLayers) {- ctx.addIssue({- code: 'custom',- path: ['textures', 'color', 'layers'],- message: 'color texture layers must equal the sum of clip frame counts',- });- }-- if (meta.textures.layout === 'array') {- if (meta.textures.color.width !== expectedLayerWidth) {- ctx.addIssue({- code: 'custom',- path: ['textures', 'color', 'width'],- message: 'array color texture width must equal grid.x * tileSize',- });- }- if (meta.textures.color.height !== expectedLayerHeight) {- ctx.addIssue({- code: 'custom',- path: ['textures', 'color', 'height'],- message: 'array color texture height must equal grid.y * tileSize',- });- }- if (meta.textures.color.framesX !== undefined || meta.textures.color.framesY !== undefined) {- ctx.addIssue({- code: 'custom',- path: ['textures', 'color'],- message: 'array color textures must not set framesX or framesY',- });- }- } else {- const framesX = meta.textures.color.framesX;- const framesY = meta.textures.color.framesY;- if (framesX === undefined || framesY === undefined) {- ctx.addIssue({- code: 'custom',- path: ['textures', 'color'],- message: 'packed atlas color texture requires framesX and framesY',- });- } else {- if (meta.textures.color.width !== expectedLayerWidth * framesX) {- ctx.addIssue({- code: 'custom',- path: ['textures', 'color', 'width'],- message: 'packed atlas color texture width must equal frameAtlasWidth * framesX',- });- }- if (meta.textures.color.height !== expectedLayerHeight * framesY) {- ctx.addIssue({- code: 'custom',- path: ['textures', 'color', 'height'],- message: 'packed atlas color texture height must equal frameAtlasHeight * framesY',- });- }- if (framesX * framesY < expectedLayers) {- ctx.addIssue({- code: 'custom',- path: ['textures', 'color'],- message: 'packed atlas frame grid must have capacity for every layer',- });- }- }- }-- const requiredAttributes = ['frameOffset', 'clip', 'variant', 'yaw', 'paletteRow'] as const;- for (const attr of requiredAttributes) {- if (!meta.runtime.attributes.includes(attr)) {- ctx.addIssue({- code: 'custom',- path: ['runtime', 'attributes'],- message: `runtime.attributes must include ${attr}`,- });- }- }-- if (meta.runtime.textureMode === 'data-array-texture' && meta.textures.layout !== 'array') {- ctx.addIssue({- code: 'custom',- path: ['runtime', 'textureMode'],- message: 'data-array-texture runtime mode requires textures.layout=array',- });- }- if (meta.runtime.textureMode === 'packed-2d-atlas' && meta.textures.layout !== 'atlas') {- ctx.addIssue({- code: 'custom',- path: ['runtime', 'textureMode'],- message: 'packed-2d-atlas runtime mode requires textures.layout=atlas',- });- }-- const expectedTotal =- meta.storage.colorBytes +- (meta.storage.normalBytes ?? 0) +- (meta.storage.depthBytes ?? 0) +- (meta.storage.paletteBytes ?? 0);- if (meta.storage.totalRawBytes !== expectedTotal) {- ctx.addIssue({- code: 'custom',- path: ['storage', 'totalRawBytes'],- message: 'storage.totalRawBytes must equal the sum of texture and palette bytes',- });- }- if (meta.storage.fitsEnvelope !== meta.storage.totalRawBytes <= meta.storage.envelopeBytes) {- ctx.addIssue({- code: 'custom',- path: ['storage', 'fitsEnvelope'],- message: 'storage.fitsEnvelope must match totalRawBytes <= envelopeBytes',- });- }- });--export const AnimatedImposterPreBakeInputSchema = z- .object({- source: z- .object({- path: z.string().optional(),- bytes: z.number().int().nonnegative(),- tris: z.number().int().nonnegative(),- skinned: z.boolean(),- clipNames: z.array(z.string()),- manifest: z- .object({- path: z.string().optional(),- expectedBytes: z.number().int().nonnegative().optional(),- actualBytes: z.number().int().nonnegative().optional(),- expectedHash: z.string().optional(),- actualHash: z.string().optional(),- })- .strict()- .optional(),- })- .strict(),- clipTargets: z.array(AnimatedClipTargetSchema).min(1),- clipFallbacks: z- .array(- z- .object({- target: AnimatedClipTargetSchema,- donor: AnimatedClipTargetSchema.optional(),- rawName: z.string().min(1).optional(),- })- .strict()- .refine((value) => Boolean(value.donor) !== Boolean(value.rawName), {- message: 'clip fallback must set exactly one of donor or rawName',- }),- )- .default([]),- viewGrid: z- .object({- x: z.number().int().positive(),- y: z.number().int().positive(),- })- .strict(),- tileSize: z.number().int().positive(),- framesPerClip: z.number().int().positive(),- textureFormat: AnimatedImposterTextureFormatSchema.default('r8-palette-index'),- textureLayout: AnimatedImposterTextureLayoutSchema.default('array'),- includeNormal: z.boolean().default(false),- includeDepth: z.boolean().default(false),- paletteWidth: z.number().int().positive().default(128),- paletteRows: z.number().int().positive().default(1),- envelopeBytes: z.number().int().positive().default(ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES),- })- .strict();--export type AnimatedClipTarget = z.infer<typeof AnimatedClipTargetSchema>;-export type AnimatedImposterTextureFormat = z.infer<typeof AnimatedImposterTextureFormatSchema>;-export type AnimatedImposterTextureLayout = z.infer<typeof AnimatedImposterTextureLayoutSchema>;-export type AnimatedImposterTextureMode = z.infer<typeof AnimatedImposterTextureModeSchema>;-export type AnimatedImposterRuntimeAttribute = z.infer<typeof AnimatedImposterRuntimeAttributeSchema>;-export type AnimatedImposterWarning = z.infer<typeof AnimatedImposterWarningSchema>;-export type AnimatedImposterMeta = z.infer<typeof AnimatedImposterMetaSchema>;-export type AnimatedImposterPreBakeInput = z.input<typeof AnimatedImposterPreBakeInputSchema>;-export type AnimatedImposterPreBakeConfig = z.output<typeof AnimatedImposterPreBakeInputSchema>;diff --git a/src/imposter/animated-validate.ts b/src/imposter/animated-validate.tsdeleted file mode 100644index b27970e6..00000000--- a/src/imposter/animated-validate.ts+++ /dev/null@@ -1,308 +0,0 @@-/**- * Pure pre-bake validation for animated octahedral impostors.- *- * This stage does not load GLBs or write artifacts. Callers pass discovered- * source facts, and the validator makes the first bake contract explicit.- */--import {- ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES,- AnimatedImposterPreBakeInputSchema,- type AnimatedClipTarget,- type AnimatedImposterPreBakeConfig,- type AnimatedImposterPreBakeInput,- type AnimatedImposterTextureFormat,- type AnimatedImposterWarning,-} from './animated-schema';-import {- applyClipFallbacks,- applyRawClipFallbacks,- resolveClips,- type ClipResolutionReport,- type ClipTarget,-} from './clip-resolver';--export interface AnimatedImposterStorageEstimate {- atlasWidth: number;- atlasHeight: number;- layers: number;- bytesPerColorPixel: number;- colorBytes: number;- normalBytes: number;- depthBytes: number;- paletteBytes: number;- totalRawBytes: number;- envelopeBytes: number;- fitsEnvelope: boolean;-}--export interface AnimatedImposterPreBakeReport {- ok: boolean;- blockers: AnimatedImposterWarning[];- warnings: AnimatedImposterWarning[];- clipResolution: ClipResolutionReport;- storage: AnimatedImposterStorageEstimate;- normalized: AnimatedImposterPreBakeConfig;-}--export function estimateAnimatedImposterStorage(- input: Pick<- AnimatedImposterPreBakeConfig,- | 'viewGrid'- | 'tileSize'- | 'framesPerClip'- | 'clipTargets'- | 'textureFormat'- | 'includeNormal'- | 'includeDepth'- | 'paletteWidth'- | 'paletteRows'- | 'envelopeBytes'- >,-): AnimatedImposterStorageEstimate {- const atlasWidth = input.viewGrid.x * input.tileSize;- const atlasHeight = input.viewGrid.y * input.tileSize;- const layers = input.framesPerClip * input.clipTargets.length;- const pixels = atlasWidth * atlasHeight * layers;- const bytesPerColorPixel = bytesPerPixel(input.textureFormat);- const colorBytes = pixels * bytesPerColorPixel;- const normalBytes = input.includeNormal ? pixels * 4 : 0;- const depthBytes = input.includeDepth ? pixels * 4 : 0;- const paletteBytes = input.textureFormat === 'r8-palette-index'- ? input.paletteWidth * input.paletteRows * 4- : 0;- const totalRawBytes = colorBytes + normalBytes + depthBytes + paletteBytes;- const envelopeBytes = input.envelopeBytes ?? ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES;-- return {- atlasWidth,- atlasHeight,- layers,- bytesPerColorPixel,- colorBytes,- normalBytes,- depthBytes,- paletteBytes,- totalRawBytes,- envelopeBytes,- fitsEnvelope: totalRawBytes <= envelopeBytes,- };-}--export function validateAnimatedImposterPreBake(- raw: AnimatedImposterPreBakeInput,-): AnimatedImposterPreBakeReport {- const input = AnimatedImposterPreBakeInputSchema.parse(raw);- const blockers: AnimatedImposterWarning[] = [];- const warnings: AnimatedImposterWarning[] = [];-- const add = (issue: AnimatedImposterWarning) => {- if (issue.severity === 'error') blockers.push(issue);- else warnings.push(issue);- };-- if (input.source.bytes <= 0) {- add({- code: 'ANIMATED_IMPOSTER_SOURCE_EMPTY',- severity: 'error',- message: 'Source GLB has no bytes.',- fixHint: 'Pass a non-empty GLB buffer or file path before baking.',- });- }-- if (input.source.tris <= 0) {- add({- code: 'ANIMATED_IMPOSTER_SOURCE_NO_TRIS',- severity: 'error',- message: 'Source GLB has no triangles.',- fixHint: 'Inspect the source GLB and select a mesh-backed character asset.',- });- }-- if (!input.source.skinned) {- add({- code: 'ANIMATED_IMPOSTER_SOURCE_NOT_SKINNED',- severity: 'error',- message: 'Animated octahedral impostors need a skinned source character.',- fixHint: 'Use a skinned GLB or pivot to the static imposter path for rigid props.',- });- }-- if (input.source.clipNames.length === 0) {- add({- code: 'ANIMATED_IMPOSTER_SOURCE_NO_CLIPS',- severity: 'error',- message: 'Source GLB has no animation clips.',- fixHint: 'Choose an animated character GLB before starting the bake.',- });- }-- let clipResolution = resolveClips(input.source.clipNames, toClipTargets(input.clipTargets));- if (input.clipFallbacks.length > 0) {- clipResolution = applyClipFallbacks(clipResolution, fallbackMap(input.clipFallbacks));- clipResolution = applyRawClipFallbacks(clipResolution, input.source.clipNames, rawFallbacks(input.clipFallbacks));- }-- for (const target of input.clipTargets) {- const clip = clipResolution.clips[target];- if (!clip || !clip.resolved) {- add({- code: 'ANIMATED_IMPOSTER_CLIP_MISSING',- severity: 'warning',- message: `No source clip resolved for ${target}.`,- fixHint: 'Add a clip fallback or remove the target from this bake slice.',- });- } else if (clip.matchedBy === 'fallback') {- const donor = clip.fallbackRawName ?? clip.fallbackFor;- add({- code: 'ANIMATED_IMPOSTER_CLIP_FALLBACK',- severity: 'warning',- message: `${target} will use ${donor} as a fallback clip.`,- fixHint: 'Treat the output as visually provisional until a dedicated clip exists.',- });- }- }-- const resolvedCount = input.clipTargets.filter((target) => clipResolution.clips[target]?.resolved).length;- if (resolvedCount === 0) {- add({- code: 'ANIMATED_IMPOSTER_NO_RESOLVED_CLIPS',- severity: 'error',- message: 'None of the requested clip targets resolved to source animation clips.',- fixHint: 'Check the clip list from the GLB and update aliases or fallback rules.',- });- }-- if (input.viewGrid.x !== input.viewGrid.y) {- add({- code: 'ANIMATED_IMPOSTER_VIEW_GRID_NOT_SQUARE',- severity: 'error',- message: 'The first octahedral view grid must be square.',- fixHint: 'Use 6x6, 7x7, or 8x8 for the first implementation slice.',- });- }-- if (input.viewGrid.x < 4 || input.viewGrid.x > 16 || input.viewGrid.y < 4 || input.viewGrid.y > 16) {- add({- code: 'ANIMATED_IMPOSTER_VIEW_GRID_OUT_OF_RANGE',- severity: 'error',- message: 'View grid dimensions must stay between 4 and 16.',- fixHint: 'Use 6x6 for the storage-safe spike, 7x7 for centered head-on reads, or 8x8 for the quality spike.',- });- } else if (![6, 7, 8].includes(input.viewGrid.x)) {- add({- code: 'ANIMATED_IMPOSTER_VIEW_GRID_UNPROVEN',- severity: 'warning',- message: 'Only 6x6, 7x7, and 8x8 view grids are part of the initial validation plan.',- fixHint: 'Prefer 6x6, 7x7, or 8x8 until yaw-sweep validation proves another grid.',- });- }-- if (input.tileSize < 32 || input.tileSize > 512 || input.tileSize % 8 !== 0) {- add({- code: 'ANIMATED_IMPOSTER_TILE_SIZE_OUT_OF_RANGE',- severity: 'error',- message: 'Tile size must be 32-512 pixels and divisible by 8.',- fixHint: 'Use 96 for the first slice unless a validation gallery proves otherwise.',- });- } else if (input.tileSize !== 96) {- add({- code: 'ANIMATED_IMPOSTER_TILE_SIZE_UNPROVEN',- severity: 'warning',- message: 'The first implementation slice is budgeted around 96px tiles.',- fixHint: 'Use 96px until storage and yaw-sweep validation produce a better target.',- });- }-- if (input.framesPerClip < 1 || input.framesPerClip > 64) {- add({- code: 'ANIMATED_IMPOSTER_FRAME_COUNT_OUT_OF_RANGE',- severity: 'error',- message: 'Frames per clip must be between 1 and 64.',- fixHint: 'Use 8-16 frames per clip for the first slice.',- });- } else if (input.framesPerClip < 8 || input.framesPerClip > 16) {- add({- code: 'ANIMATED_IMPOSTER_FRAME_COUNT_UNPROVEN',- severity: 'warning',- message: 'The first implementation slice expects 8-16 frames per clip.',- fixHint: 'Keep early bakes inside 8-16 frames before tuning cadence.',- });- }-- const manifest = input.source.manifest;- if (- manifest?.expectedBytes !== undefined &&- manifest.actualBytes !== undefined &&- manifest.expectedBytes !== manifest.actualBytes- ) {- add({- code: 'ANIMATED_IMPOSTER_SOURCE_MANIFEST_BYTES_DRIFT',- severity: 'warning',- message: 'Source manifest byte count does not match the discovered GLB bytes.',- fixHint: 'Refresh the source manifest before trusting cache or resumability decisions.',- });- }-- if (- manifest?.expectedHash !== undefined &&- manifest.actualHash !== undefined &&- manifest.expectedHash !== manifest.actualHash- ) {- add({- code: 'ANIMATED_IMPOSTER_SOURCE_MANIFEST_HASH_DRIFT',- severity: 'warning',- message: 'Source manifest hash does not match the discovered GLB hash.',- fixHint: 'Refresh the source manifest or select the exact GLB revision intended for bake.',- });- }-- const storage = estimateAnimatedImposterStorage(input);- if (!storage.fitsEnvelope) {- add({- code: 'ANIMATED_IMPOSTER_STORAGE_ENVELOPE_EXCEEDED',- severity: 'error',- message: `Raw animated imposter storage estimate is ${storage.totalRawBytes} bytes, above the ${storage.envelopeBytes} byte envelope.`,- fixHint: 'Reduce view grid, tile size, frames per clip, clip count, or aux layers before baking.',- });- }-- return {- ok: blockers.length === 0,- blockers,- warnings,- clipResolution,- storage,- normalized: input,- };-}--function bytesPerPixel(format: AnimatedImposterTextureFormat): number {- return format === 'r8-palette-index' ? 1 : 4;-}--function toClipTargets(targets: AnimatedClipTarget[]): ClipTarget[] {- return targets.map((target) => target as ClipTarget);-}--function fallbackMap(- fallbacks: AnimatedImposterPreBakeConfig['clipFallbacks'],-): Partial<Record<ClipTarget, ClipTarget>> {- const out: Partial<Record<ClipTarget, ClipTarget>> = {};- for (const fallback of fallbacks) {- if (fallback.donor) {- out[fallback.target as ClipTarget] = fallback.donor as ClipTarget;- }- }- return out;-}--function rawFallbacks(- fallbacks: AnimatedImposterPreBakeConfig['clipFallbacks'],-): Array<{ target: ClipTarget; rawName: string }> {- const out: Array<{ target: ClipTarget; rawName: string }> = [];- for (const fallback of fallbacks) {- if (fallback.rawName) out.push({ target: fallback.target as ClipTarget, rawName: fallback.rawName });- }- return out;-}diff --git a/src/imposter/atlas-profiles.ts b/src/imposter/atlas-profiles.tsdeleted file mode 100644index 766ba611..00000000--- a/src/imposter/atlas-profiles.ts+++ /dev/null@@ -1,107 +0,0 @@-/**- * Atlas profile rules for static (lat-lon / hemi-y) imposter bakes.- *- * Profiles define the maximum tile size, angle count, and whether a normal- * aux layer is required for a given imposter "tier" (ground cover vs canopy- * etc). Originally lived inline in scripts/validate-tij-vegetation-package.ts;- * lifted to core in W6 so non-TIJ consumers can reuse the same contract.- *- * Species-to-profile mapping stays in the consumer (e.g. TIJ vegetation- * pipeline) — profiles describe the *bake contract*, not the catalog.- */--export const ATLAS_PROFILES = {- 'ground-compact': { maxTileSize: 256, maxAngles: 8, normalRequired: false },- 'mid-balanced': { maxTileSize: 512, maxAngles: 16, normalRequired: true },- 'canopy-balanced': { maxTileSize: 512, maxAngles: 32, normalRequired: true },- 'canopy-hero': { maxTileSize: 1024, maxAngles: 32, normalRequired: true },-} as const;--export type AtlasProfileName = keyof typeof ATLAS_PROFILES;-export type AtlasProfileLimits = (typeof ATLAS_PROFILES)[AtlasProfileName];--export const ATLAS_PROFILE_NAMES = Object.keys(ATLAS_PROFILES) as AtlasProfileName[];--export function isAtlasProfileName(value: unknown): value is AtlasProfileName {- return typeof value === 'string' && value in ATLAS_PROFILES;-}--/**- * Subset of static-imposter sidecar fields the profile cares about.- * Accepts unknown so callers can pass JSON-parsed metadata directly.- */-export interface AtlasProfileMetaInput {- tileSize?: unknown;- angles?: unknown;- auxLayers?: unknown;- normalSpace?: unknown;-}--export type AtlasProfileViolationField =- | 'tileSize'- | 'angles'- | 'normal-aux-layer'- | 'normal-space';--export interface AtlasProfileViolation {- field: AtlasProfileViolationField;- message: string;-}--export interface AtlasProfileValidationResult {- ok: boolean;- profile: AtlasProfileName;- limits: AtlasProfileLimits;- violations: AtlasProfileViolation[];-}--/**- * Validates an imposter sidecar (or atlas metadata) against the named profile.- * Returns { ok, violations[] } so callers can render their own error format.- *- * Read-only. Does not throw — invalid profile names produce a violation list- * with `ok: false`. Pass a real `AtlasProfileName` (typed) and you'll get a- * clean limits echo on success.- */-export function validateAgainstAtlasProfile(- meta: AtlasProfileMetaInput,- profile: AtlasProfileName,-): AtlasProfileValidationResult {- const limits = ATLAS_PROFILES[profile];- const violations: AtlasProfileViolation[] = [];-- if (typeof meta.tileSize === 'number' && meta.tileSize > limits.maxTileSize) {- violations.push({- field: 'tileSize',- message: `tileSize=${meta.tileSize} exceeds profile ${profile} max ${limits.maxTileSize}`,- });- }- if (typeof meta.angles === 'number' && meta.angles > limits.maxAngles) {- violations.push({- field: 'angles',- message: `angles=${meta.angles} exceeds profile ${profile} max ${limits.maxAngles}`,- });- }- if (limits.normalRequired) {- const aux = Array.isArray(meta.auxLayers) ? (meta.auxLayers as unknown[]) : [];- if (!aux.includes('normal')) {- violations.push({- field: 'normal-aux-layer',- message: `profile ${profile} requires the 'normal' aux layer`,- });- }- if (meta.normalSpace !== 'capture-view') {- violations.push({- field: 'normal-space',- message: `profile ${profile} requires normalSpace='capture-view' (got ${String(meta.normalSpace)})`,- });- }- }-- return {- ok: violations.length === 0,- profile,- limits,- violations,- };-}diff --git a/src/imposter/bake.ts b/src/imposter/bake.tsdeleted file mode 100644index ce6f8a7a..00000000--- a/src/imposter/bake.ts+++ /dev/null@@ -1,620 +0,0 @@-/**- * Imposter baker — renders a GLB from N camera angles into a packed atlas.- *- * Backend: Playwright + Chromium.- * Reason: the kiln render substrate (render.ts) is pure scene-graph math with- * no WebGL, so actual pixel output requires a real browser context. The public- * pixelforge CLI runs this path through Node, which is Playwright's supported- * JavaScript runtime across Windows, macOS, and Linux.- *- * Strategy:- * 1. Launch one Chromium page per session (ImposterSession).- * 2. Inject a tiny three.js 0.184 harness that loads GLBs from data URLs.- * 3. For each tile, set an orthographic camera to (az, el), render, capture- * PNG tile via canvas.toDataURL.- * 4. Composite tiles into a single atlas via sharp.- * 5. Optionally bake auxiliary layers (depth, normal) with shared geometry- * and a swapped material — each emits its own atlas PNG.- *- * The session is reusable — one Chromium launch can bake dozens of GLBs.- */--import { Buffer } from 'node:buffer';-import { existsSync, readFileSync } from 'node:fs';-import { createRequire } from 'node:module';-import { dirname, extname, resolve, sep } from 'node:path';-import sharp from 'sharp';-import { chromium, type Page } from 'playwright';--import type {- ImposterAngleCount,- ImposterAuxLayer,- ImposterBgColor,- ImposterColorLayer,- ImposterLayout,- ImposterMeta,- LatLonImposterAxis,-} from './schema';-import { IMPOSTER_LEGACY_SCHEMA_VERSION, IMPOSTER_SCHEMA_VERSION, ImposterMetaSchema } from './schema';-import { enumerateOctahedralTiles, enumerateTiles, resolveLayout } from './projection';--const HARNESS_ORIGIN = 'https://pixel-forge-kiln.local';-const nodeRequire = createRequire(import.meta.url);--export interface BakeImposterOptions {- angles?: ImposterAngleCount;- axis?: LatLonImposterAxis | 'octahedral';- /** Tile layout. Defaults to lat/lon unless axis is the octahedral compatibility alias. */- layout?: ImposterLayout;- /** Octahedral grid dimensions. Defaults to 8x8 when layout='octahedral'. */- grid?: { x: number; y: number };- /** Pixel size of a single tile (square). Atlas size = tileSize * tilesX × tilesY. */- tileSize?: 128 | 256 | 512 | 1024;- /** Which layers to produce. 'albedo' is always included. */- auxLayers?: ImposterAuxLayer[];- /** Background color for the albedo bake. 'transparent' uses RGBA alpha. */- bgColor?: ImposterBgColor;- /** 'beauty' preserves legacy lit bakes; 'baseColor' emits unlit color for runtime lighting. */- colorLayer?: ImposterColorLayer;- /** RGB bleed radius into transparent pixels before atlas packing. Defaults to 2 for baseColor bakes. */- edgeBleedPx?: number;- /** Included in meta.source.path for provenance. */- sourcePath?: string;- /** Pin deterministic browser and PNG settings where Chromium permits it. */- deterministic?: boolean;-}--export interface BakeImposterResult {- /** Packed albedo atlas (PNG). */- atlas: Buffer;- /** Auxiliary atlases keyed by layer name. */- aux: Partial<Record<ImposterAuxLayer, Buffer>>;- /** Sidecar metadata — write alongside the atlas. */- meta: ImposterMeta;-}--export interface ImposterSession {- bake(glb: Buffer | string, opts: BakeImposterOptions): Promise<BakeImposterResult>;- close(): Promise<void>;-}--export interface OpenImposterSessionOptions {- deterministic?: boolean;-}--/** Spin up a reusable Playwright session. Call close() when you're done batching. */-export async function openImposterSession(opts: OpenImposterSessionOptions = {}): Promise<ImposterSession> {- assertSupportedBrowserBakeRuntime();- const browser = await chromium.launch({- ...(opts.deterministic- ? {- args: [- '--disable-gpu',- '--use-angle=swiftshader-webgl',- '--use-gl=angle',- ],- }- : {}),- });- const ctx = await browser.newContext({ viewport: { width: 1024, height: 1024 }, deviceScaleFactor: 1 });- const page = await ctx.newPage();- await installHarnessRoutes(page);- await page.setContent(buildHarnessHtml({ deterministic: Boolean(opts.deterministic) }));- await page.waitForFunction(- () => (globalThis as unknown as { __imposterReady?: boolean }).__imposterReady === true,- { timeout: 30_000 },- );-- return {- bake: (glb, opts) => bakeOnPage(page, glb, opts),- close: async () => {- await ctx.close();- await browser.close();- },- };-}--function assertSupportedBrowserBakeRuntime(): void {- const isBun = Boolean((globalThis as { Bun?: unknown }).Bun);- if (isBun && process.platform === 'win32') {- throw new Error(- 'Playwright-backed imposter baking is not supported through Bun on Windows. Build and run the public Node CLI instead: bun run --filter @pixel-forge/cli build && node packages/cli/dist/index.js kiln bake-imposter ...',- );- }-}--/** Convenience: one-shot bake. Internally opens + closes a session. */-export async function bakeImposter(- glb: Buffer | string,- opts: BakeImposterOptions,-): Promise<BakeImposterResult> {- const session = await openImposterSession({ deterministic: opts.deterministic });- try {- return await session.bake(glb, opts);- } finally {- await session.close();- }-}--// ============================================================================-// Internals-// ============================================================================--async function bakeOnPage(- page: Page,- glb: Buffer | string,- opts: BakeImposterOptions,-): Promise<BakeImposterResult> {- const requestedLayout: ImposterLayout = opts.layout ?? (opts.axis === 'octahedral' ? 'octahedral' : 'latlon');- const tileSize = opts.tileSize ?? 512;- const auxLayers = uniqueAuxLayers(opts.auxLayers ?? []);- const bgColor: ImposterBgColor = opts.bgColor ?? 'transparent';- const colorLayer: ImposterColorLayer = opts.colorLayer ?? 'beauty';- const edgeBleedPx = opts.edgeBleedPx ?? (colorLayer === 'baseColor' && bgColor === 'transparent' ? 2 : 0);-- if (!Number.isInteger(edgeBleedPx) || edgeBleedPx < 0) {- throw new Error(`edgeBleedPx must be a non-negative integer (got ${edgeBleedPx})`);- }- if (colorLayer === 'baseColor' && !auxLayers.includes('normal')) {- throw new Error("baseColor imposter bakes require auxLayers to include 'normal'");- }-- const buf = typeof glb === 'string' ? readFileSync(glb) : glb;- const sourcePath = opts.sourcePath ?? (typeof glb === 'string' ? glb : undefined);-- const resolved = resolveBakeLayout(opts, requestedLayout);- const tiles = resolved.layout === 'octahedral'- ? enumerateOctahedralTiles(resolved.grid)- : enumerateTiles(resolved.latLon);-- // Load the GLB into the harness and pull back bbox + tri count.- const loadInfo = (await page.evaluate(- async ([dataUrl, tileSz]) => {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const w = globalThis as any;- return w.__imposterLoadGlb(dataUrl, tileSz);- },- [`data:model/gltf-binary;base64,${buf.toString('base64')}`, tileSize] as const,- )) as { bbox: { min: [number, number, number]; max: [number, number, number] }; tris: number };-- // Render each layer.- const layers: ImposterAuxLayer[] = ['albedo', ...auxLayers];- const atlases: Partial<Record<ImposterAuxLayer, Buffer>> = {};- for (const layer of layers) {- const tilePngs: Buffer[] = [];- for (const tile of tiles) {- const dataUrl = (await page.evaluate(- (args) => {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const w = globalThis as any;- return w.__imposterRenderTile(args);- },- {- dir: tile.dir,- layer,- bgColor,- colorLayer,- tileSize,- },- )) as string;- const png = Buffer.from(dataUrl.split(',')[1]!, 'base64');- tilePngs.push(png);- }- atlases[layer] = await composeAtlas(tilePngs, tileSize, resolved.tilesX, resolved.tilesY, bgColor, edgeBleedPx);- }-- const albedo = atlases.albedo!;- // Separate aux from albedo in the result surface.- const aux: Partial<Record<ImposterAuxLayer, Buffer>> = {};- for (const layer of auxLayers) {- if (atlases[layer]) aux[layer] = atlases[layer];- }-- // Build the ImposterMeta sidecar.- const min = loadInfo.bbox.min;- const max = loadInfo.bbox.max;- const sizeX = max[0] - min[0];- const sizeY = max[1] - min[1];- const sizeZ = max[2] - min[2];- const worldSize = Math.max(sizeX, sizeY, sizeZ);- const yOffset = (min[1] + max[1]) * 0.5;-- const common = {- angles: resolved.angles,- tilesX: resolved.tilesX,- tilesY: resolved.tilesY,- tileSize,- atlasWidth: resolved.tilesX * tileSize,- atlasHeight: resolved.tilesY * tileSize,- worldSize,- yOffset,- projection: 'orthographic',- bbox: { min, max },- source: {- ...(sourcePath ? { path: sourcePath } : {}),- bytes: buf.byteLength,- tris: loadInfo.tris,- },- auxLayers: layers,- bgColor,- colorLayer,- normalSpace: 'capture-view',- edgeBleedPx,- textureColorSpace: 'srgb',- } as const;-- const metaPayload = resolved.layout === 'octahedral'- ? {- version: IMPOSTER_SCHEMA_VERSION,- ...common,- axis: 'octahedral',- hemi: false,- layout: 'octahedral',- directionEncoding: 'octahedral',- directions: tiles.map((tile) => tile.dir),- }- : {- version: IMPOSTER_LEGACY_SCHEMA_VERSION,- ...common,- axis: resolved.latLon.axis,- hemi: resolved.latLon.axis === 'hemi-y',- layout: 'latlon',- azimuths: resolved.latLon.azimuths,- elevations: resolved.latLon.elevations,- };- ImposterMetaSchema.parse(metaPayload);- const meta = metaPayload as ImposterMeta;-- return { atlas: albedo, aux, meta };-}--type ResolvedBakeLayout =- | {- layout: 'latlon';- angles: ImposterAngleCount;- tilesX: number;- tilesY: number;- latLon: ReturnType<typeof resolveLayout>;- }- | {- layout: 'octahedral';- angles: number;- tilesX: number;- tilesY: number;- grid: { x: number; y: number };- };--function resolveBakeLayout(- opts: BakeImposterOptions,- layout: ImposterLayout,-): ResolvedBakeLayout {- if (layout === 'octahedral') {- const grid = opts.grid ?? { x: 8, y: 8 };- if (!Number.isInteger(grid.x) || !Number.isInteger(grid.y) || grid.x <= 0 || grid.y <= 0) {- throw new Error(`octahedral grid must be positive integers (got ${grid.x}x${grid.y})`);- }- return {- layout,- angles: grid.x * grid.y,- tilesX: grid.x,- tilesY: grid.y,- grid,- };- }-- if (opts.axis === 'octahedral') {- throw new Error("axis='octahedral' requires layout='octahedral'");- }- const angles = opts.angles ?? 16;- const axis: LatLonImposterAxis = opts.axis ?? (angles === 16 ? 'y' : 'hemi-y');- const latLon = resolveLayout(angles, axis);- return {- layout,- angles,- tilesX: latLon.tilesX,- tilesY: latLon.tilesY,- latLon,- };-}--async function composeAtlas(- tilePngs: Buffer[],- tileSize: number,- tilesX: number,- tilesY: number,- bgColor: ImposterBgColor,- edgeBleedPx: number,-): Promise<Buffer> {- const width = tilesX * tileSize;- const height = tilesY * tileSize;- const bg =- bgColor === 'transparent'- ? { r: 0, g: 0, b: 0, alpha: 0 }- : { r: 255, g: 0, b: 255, alpha: 1 };-- const composites: sharp.OverlayOptions[] = [];- for (let idx = 0; idx < tilePngs.length; idx++) {- const i = idx % tilesX;- const j = Math.floor(idx / tilesX);- const input = bgColor === 'transparent' && edgeBleedPx > 0- ? await bleedTransparentRgb(tilePngs[idx]!, edgeBleedPx)- : tilePngs[idx]!;- composites.push({ input, left: i * tileSize, top: j * tileSize });- }-- const atlas = await sharp({- create: { width, height, channels: 4, background: bg },- })- .composite(composites)- .png({ compressionLevel: 9, adaptiveFiltering: false })- .toBuffer();-- return bgColor === 'transparent' && edgeBleedPx > 0- ? bleedTransparentRgb(atlas, edgeBleedPx)- : atlas;-}--function uniqueAuxLayers(layers: ImposterAuxLayer[]): ImposterAuxLayer[] {- const out: ImposterAuxLayer[] = [];- for (const layer of layers) {- if (layer === 'albedo') continue;- if (!out.includes(layer)) out.push(layer);- }- return out;-}--async function installHarnessRoutes(page: Page): Promise<void> {- const threeRoot = dirname(dirname(nodeRequire.resolve('three')));- await page.route(`${HARNESS_ORIGIN}/three/**`, async (route) => {- const url = new URL(route.request().url());- const rel = decodeURIComponent(url.pathname.replace(/^\/three\//, ''));- const filePath = resolve(threeRoot, rel);- const rootWithSep = threeRoot.endsWith(sep) ? threeRoot : `${threeRoot}${sep}`;- if (filePath !== threeRoot && !filePath.startsWith(rootWithSep)) {- await route.abort();- return;- }- if (!existsSync(filePath)) {- await route.abort();- return;- }- await route.fulfill({- status: 200,- contentType: contentTypeFor(filePath),- body: readFileSync(filePath),- });- });-}--function contentTypeFor(filePath: string): string {- switch (extname(filePath).toLowerCase()) {- case '.js':- return 'application/javascript';- case '.wasm':- return 'application/wasm';- case '.json':- return 'application/json';- default:- return 'application/octet-stream';- }-}--export async function bleedTransparentRgb(png: Buffer, radius: number): Promise<Buffer> {- if (radius <= 0) return png;- const { data, info } = await sharp(png).ensureAlpha().raw().toBuffer({ resolveWithObject: true });- const width = info.width;- const height = info.height;- let src = Buffer.from(data);- let dst = Buffer.from(data);-- for (let pass = 0; pass < radius; pass++) {- let changed = false;- src.copy(dst);- for (let y = 0; y < height; y++) {- for (let x = 0; x < width; x++) {- const idx = (y * width + x) * 4;- if (src[idx + 3] !== 0) continue;-- let r = 0;- let g = 0;- let b = 0;- let n = 0;- for (let oy = -1; oy <= 1; oy++) {- const ny = y + oy;- if (ny < 0 || ny >= height) continue;- for (let ox = -1; ox <= 1; ox++) {- if (ox === 0 && oy === 0) continue;- const nx = x + ox;- if (nx < 0 || nx >= width) continue;- const ni = (ny * width + nx) * 4;- if (src[ni + 3] === 0) continue;- r += src[ni]!;- g += src[ni + 1]!;- b += src[ni + 2]!;- n++;- }- }- if (n > 0) {- dst[idx] = Math.round(r / n);- dst[idx + 1] = Math.round(g / n);- dst[idx + 2] = Math.round(b / n);- changed = true;- }- }- }- if (!changed) break;- const tmp = src;- src = dst;- dst = tmp;- }-- return sharp(src, { raw: { width, height, channels: 4 } })- .png({ compressionLevel: 9, adaptiveFiltering: false })- .toBuffer();-}--// ============================================================================-// In-browser harness - local three.js modules, with loader + render helpers.-// ============================================================================--function buildHarnessHtml(opts: { deterministic: boolean }): string {- const antialias = opts.deterministic ? 'false' : 'true';- return `<!DOCTYPE html>-<html><head>-<meta charset="utf-8">-<style>html,body{margin:0;padding:0;background:#ff00ff}#app{width:1024px;height:1024px}</style>-<script type="importmap">-{- "imports": {- "three": "${HARNESS_ORIGIN}/three/build/three.module.js",- "three/addons/": "${HARNESS_ORIGIN}/three/examples/jsm/"- }-}-</script>-</head>-<body>-<div id="app"></div>-<script type="module">-import * as THREE from 'three';-import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';-import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';--const W = () => renderer.domElement.width;-const app = document.getElementById('app');-const renderer = new THREE.WebGLRenderer({ antialias: ${antialias}, alpha: true, preserveDrawingBuffer: true });-renderer.setPixelRatio(1);-renderer.setSize(1024, 1024);-renderer.outputColorSpace = THREE.SRGBColorSpace;-app.appendChild(renderer.domElement);--const scene = new THREE.Scene();-const ambient = new THREE.AmbientLight(0xffffff, 0.45);-scene.add(ambient);-const key = new THREE.DirectionalLight(0xffffff, 1.0);-key.position.set(1.5, 2, 1);-scene.add(key);-const fill = new THREE.DirectionalLight(0xffffff, 0.35);-fill.position.set(-1, 0.5, -1);-scene.add(fill);--let root = null;-let boundsRadius = 1;-let boundsCenter = new THREE.Vector3();-let originalMaterials = new Map();-let baseColorMaterials = new Map();--window.__imposterLoadGlb = async (dataUrl, tileSize) => {- if (root) scene.remove(root);- originalMaterials.clear();- baseColorMaterials.clear();- if (renderer.domElement.width !== tileSize) {- renderer.setSize(tileSize, tileSize);- }- const loader = new GLTFLoader();- const dracoLoader = new DRACOLoader();- dracoLoader.setDecoderPath('${HARNESS_ORIGIN}/three/examples/jsm/libs/draco/');- loader.setDRACOLoader(dracoLoader);- return new Promise((resolve, reject) => {- loader.load(dataUrl, (gltf) => {- root = gltf.scene;- scene.add(root);- const box = new THREE.Box3().setFromObject(root);- boundsCenter = box.getCenter(new THREE.Vector3());- const size = box.getSize(new THREE.Vector3());- const diag = Math.sqrt(size.x * size.x + size.y * size.y + size.z * size.z);- boundsRadius = diag * 0.5 || 1;- let tris = 0;- root.traverse((obj) => {- if (obj.isMesh && obj.material) {- originalMaterials.set(obj, obj.material);- const mats = Array.isArray(obj.material) ? obj.material : [obj.material];- const baseMats = mats.map((material) => createBaseColorMaterial(material, obj.geometry));- baseColorMaterials.set(obj, Array.isArray(obj.material) ? baseMats : baseMats[0]);- for (const m of mats) {- m.side = THREE.FrontSide;- m.needsUpdate = true;- }- if (obj.geometry && obj.geometry.index) tris += obj.geometry.index.count / 3;- else if (obj.geometry && obj.geometry.attributes.position) tris += obj.geometry.attributes.position.count / 3;- }- });- resolve({- bbox: { min: [box.min.x, box.min.y, box.min.z], max: [box.max.x, box.max.y, box.max.z] },- tris: Math.round(tris),- });- }, undefined, (err) => reject(err));- });-};--function createBaseColorMaterial(source, geometry) {- const mat = new THREE.MeshBasicMaterial({- color: source.color ? source.color.clone() : new THREE.Color(0xffffff),- map: source.map ?? null,- alphaMap: source.alphaMap ?? null,- vertexColors: Boolean(source.vertexColors || geometry?.attributes?.color),- opacity: source.opacity ?? 1,- transparent: Boolean(source.transparent || (source.opacity ?? 1) < 1 || source.alphaMap),- alphaTest: source.alphaTest ?? 0,- side: THREE.FrontSide,- });- mat.name = source.name ? source.name + '__baseColor' : 'baseColor';- return mat;-}--window.__imposterRenderTile = ({ dir, layer, bgColor, colorLayer, tileSize }) => {- if (!root) throw new Error('no GLB loaded');- if (renderer.domElement.width !== tileSize) renderer.setSize(tileSize, tileSize);-- // Swap materials for the active layer.- if (layer === 'normal') {- const normMat = new THREE.MeshNormalMaterial({ side: THREE.FrontSide });- root.traverse((o) => { if (o.isMesh) o.material = normMat; });- } else if (layer === 'depth') {- const depthMat = new THREE.MeshDepthMaterial({- side: THREE.FrontSide,- depthPacking: THREE.RGBADepthPacking,- });- root.traverse((o) => { if (o.isMesh) o.material = depthMat; });- } else {- // albedo: legacy beauty restores original materials, production baseColor- // swaps to unlit MeshBasicMaterial so runtime lighting owns the shade.- root.traverse((o) => {- if (!o.isMesh) return;- if (colorLayer === 'baseColor' && baseColorMaterials.has(o)) {- o.material = baseColorMaterials.get(o);- } else if (originalMaterials.has(o)) {- o.material = originalMaterials.get(o);- }- });- }-- // Orthographic camera sized to the bounding sphere.- const half = boundsRadius * 1.02;- const far = Math.max(200, boundsRadius * 8);- const camera = new THREE.OrthographicCamera(-half, half, half, -half, 0.01, far);- const d = new THREE.Vector3(dir[0], dir[1], dir[2]).normalize();- camera.position.copy(boundsCenter).addScaledVector(d, boundsRadius * 4);- camera.up.set(0, 1, 0);- if (Math.abs(d.dot(camera.up)) > 0.97) camera.up.set(0, 0, 1);- camera.lookAt(boundsCenter);-- // Background.- if (layer === 'albedo' && bgColor === 'transparent') {- scene.background = null;- renderer.setClearColor(0x000000, 0);- } else if (layer === 'albedo' && bgColor === 'magenta') {- scene.background = new THREE.Color(0xff00ff);- renderer.setClearColor(0xff00ff, 1);- } else {- scene.background = null;- renderer.setClearColor(0x000000, 0);- }-- renderer.render(scene, camera);- return renderer.domElement.toDataURL('image/png');-};--window.__imposterReady = true;-</script>-</body></html>`;-}diff --git a/src/imposter/clip-resolver.ts b/src/imposter/clip-resolver.tsdeleted file mode 100644index 12fcc2e6..00000000--- a/src/imposter/clip-resolver.ts+++ /dev/null@@ -1,259 +0,0 @@-/**- * Animation-clip resolver for animated imposters.- *- * Real character GLBs use inconsistent clip names — a soldier might call- * its stand-still pose "Idle", "Attacking_Idle", "Idle_Gun", "Idle_Neutral",- * and a Blender export typically prefixes them with "CharacterArmature|".- * The baker needs a deterministic way to pick ONE clip per logical target.- *- * Resolution rules (per target):- * 1. Exact case-insensitive match on the normalized (no armature prefix) name.- * 2. First alias in the target's priority list that matches any clip.- * 3. null — clip is missing; caller decides whether to skip or fall back.- *- * This module is pure — no Three.js import, no file I/O. Consumers pass in- * a flat list of clip names (from gltf.animations) and get back a map of- * target -> resolved clip name.- */--/** Logical clip targets the animated imposter baker cares about. */-export type ClipTarget = 'idle' | 'walking' | 'running' | 'shoot' | 'death';--/** Priority-ordered candidate names for each target. First match wins. */-export const CLIP_ALIASES: Record<ClipTarget, string[]> = {- idle: [- 'Idle',- 'Idle_Gun',- 'Idle_Neutral',- 'Attacking_Idle',- 'Idle_Shoot',- 'Idle_Hold',- ],- walking: [- 'Walk',- 'Walk_Gun',- 'Walking',- 'Walk_Forward',- ],- running: [- 'Run',- 'Run_Gun',- 'Running',- ],- shoot: [- // Prefer dedicated shoot clips, then stationary gun-ready, then melee.- 'Gun_Shoot',- 'Shoot',- 'Idle_Gun_Shoot',- 'Run_Shoot',- 'Idle_Shoot',- 'Attack',- 'Slash',- 'Stab',- 'Punch',- 'Punch_Right',- 'Idle_Gun_Pointing',- ],- death: [- 'Death',- 'Die',- 'HitRecieve', // Quaternius misspells "Receive"- 'HitReact',- ],-};--export interface ResolvedClip {- target: ClipTarget;- /** Actual clip name in the GLB (post armature-prefix strip). Null = missing. */- resolved: string | null;- /** The raw clip name with any armature prefix kept, for AnimationMixer.clipAction lookup. */- rawName: string | null;- /** Which alias matched. "exact" = exact case-insensitive target name. */- matchedBy: 'exact' | 'alias' | 'fallback' | 'missing';- /** If the matcher fell through to a best-guess, note what target was missing and what was used. */- fallbackFor?: ClipTarget;- /** If the fallback was a specific source clip, keep the requested raw name for traceability. */- fallbackRawName?: string;-}--export interface ClipResolutionReport {- /** Map from logical target -> resolved clip (or null). */- clips: Partial<Record<ClipTarget, ResolvedClip>>;- /** Targets that had no match at all, after aliases were exhausted. */- missing: ClipTarget[];- /** Clip names present in the GLB that we did NOT map. Useful for debugging. */- unmapped: string[];-}--/**- * Normalize a clip name by stripping common exporter prefixes.- * "CharacterArmature|Walk" -> "Walk"- * "CharacterArmature|CharacterArmature|Idle" -> "Idle"- */-export function normalizeClipName(raw: string): string {- let s = raw;- // Strip repeated "Name|" prefixes until none left.- while (s.includes('|')) s = s.slice(s.indexOf('|') + 1);- return s;-}--/**- * Resolve the requested targets against a GLB's clip list.- *- * @param clipNames - flat list of clip names from gltf.animations (raw, including any "Armature|" prefixes).- * @param targets - which logical clips the caller wants.- */-export function resolveClips(clipNames: string[], targets: ClipTarget[]): ClipResolutionReport {- const report: ClipResolutionReport = {- clips: {},- missing: [],- unmapped: [],- };-- // Build a lookup { normalized-lower: raw-name } for case-insensitive match.- // Last-write-wins on duplicates — Quaternius exports often have the same- // clip twice (with and without armature prefix). Either form works for- // AnimationMixer.clipAction once you have the raw.- const byNorm = new Map<string, string>();- for (const raw of clipNames) {- const norm = normalizeClipName(raw).toLowerCase();- if (!byNorm.has(norm)) byNorm.set(norm, raw);- }-- const consumed = new Set<string>();-- for (const target of targets) {- const aliases = CLIP_ALIASES[target];- let resolved: ResolvedClip | null = null;-- // 1. Exact target name (e.g. target='idle' matches clip 'Idle').- const exactHit = byNorm.get(target.toLowerCase());- if (exactHit) {- resolved = {- target,- resolved: normalizeClipName(exactHit),- rawName: exactHit,- matchedBy: 'exact',- };- }-- // 2. Alias hits (preserves priority order).- if (!resolved) {- for (const alias of aliases) {- const hit = byNorm.get(alias.toLowerCase());- if (hit) {- resolved = {- target,- resolved: normalizeClipName(hit),- rawName: hit,- matchedBy: 'alias',- };- break;- }- }- }-- if (resolved) {- report.clips[target] = resolved;- consumed.add(resolved.resolved!.toLowerCase());- } else {- report.missing.push(target);- report.clips[target] = {- target,- resolved: null,- rawName: null,- matchedBy: 'missing',- };- }- }-- for (const [norm, raw] of byNorm) {- if (!consumed.has(norm)) report.unmapped.push(raw);- }-- return report;-}--/**- * Apply a fallback strategy to a resolution report — promotes a different- * target's clip into a missing slot. Common pattern: 'shoot' fell through- * but 'idle' was found -> use idle as a stationary-pose stand-in for the- * shoot target.- *- * Returns a NEW report with the fallbacks applied. Original report is- * not mutated.- */-export function applyClipFallbacks(- report: ClipResolutionReport,- fallbacks: Partial<Record<ClipTarget, ClipTarget>>,-): ClipResolutionReport {- const next: ClipResolutionReport = {- clips: { ...report.clips },- missing: [...report.missing],- unmapped: [...report.unmapped],- };- for (const [targetStr, donorTarget] of Object.entries(fallbacks) as [ClipTarget, ClipTarget][]) {- const target = targetStr;- const current = next.clips[target];- if (current && current.resolved) continue;- const donor = next.clips[donorTarget];- if (!donor || !donor.resolved) continue;- next.clips[target] = {- target,- resolved: donor.resolved,- rawName: donor.rawName,- matchedBy: 'fallback',- fallbackFor: donorTarget,- };- const mIdx = next.missing.indexOf(target);- if (mIdx >= 0) next.missing.splice(mIdx, 1);- }- return next;-}--export function applyRawClipFallbacks(- report: ClipResolutionReport,- clipNames: string[],- fallbacks: Array<{ target: ClipTarget; rawName: string }>,-): ClipResolutionReport {- const next: ClipResolutionReport = {- clips: { ...report.clips },- missing: [...report.missing],- unmapped: [...report.unmapped],- };- const byRaw = new Map<string, string>();- const byNorm = new Map<string, string>();- for (const raw of clipNames) {- byRaw.set(raw.toLowerCase(), raw);- byNorm.set(normalizeClipName(raw).toLowerCase(), raw);- }-- for (const fallback of fallbacks) {- const current = next.clips[fallback.target];- if (current?.resolved) continue;-- const hit =- byRaw.get(fallback.rawName.toLowerCase()) ??- byNorm.get(normalizeClipName(fallback.rawName).toLowerCase());- if (!hit) continue;-- const normalized = normalizeClipName(hit);- next.clips[fallback.target] = {- target: fallback.target,- resolved: normalized,- rawName: hit,- matchedBy: 'fallback',- fallbackRawName: fallback.rawName,- };-- const missingIdx = next.missing.indexOf(fallback.target);- if (missingIdx >= 0) next.missing.splice(missingIdx, 1);-- const unmappedIdx = next.unmapped.findIndex(- (raw) => raw === hit || normalizeClipName(raw).toLowerCase() === normalized.toLowerCase(),- );- if (unmappedIdx >= 0) next.unmapped.splice(unmappedIdx, 1);- }-- return next;-}diff --git a/src/imposter/index.ts b/src/imposter/index.tsdeleted file mode 100644index cf7a50a0..00000000--- a/src/imposter/index.ts+++ /dev/null@@ -1,143 +0,0 @@-/**- * kiln/imposter — octahedral / lat-lon imposter atlas baker.- *- * Public surface consumed via the `kiln` namespace:- *- * import { kiln } from '@pixel-forge/core';- * const { atlas, aux, meta } = await kiln.bakeImposter(glbBuffer, {- * angles: 16, axis: 'hemi-y', tileSize: 512, auxLayers: ['depth'],- * });- */--export { bakeImposter, openImposterSession } from './bake';-export type {- BakeImposterOptions,- BakeImposterResult,- ImposterSession,- OpenImposterSessionOptions,-} from './bake';--export {- ATLAS_PROFILES,- ATLAS_PROFILE_NAMES,- isAtlasProfileName,- validateAgainstAtlasProfile,-} from './atlas-profiles';--export { validateImposterSidecar } from './validate';-export type {- ImposterValidationIssue,- ImposterValidationResult,- ValidateImposterOptions,-} from './validate';-export type {- AtlasProfileLimits,- AtlasProfileMetaInput,- AtlasProfileName,- AtlasProfileValidationResult,- AtlasProfileViolation,- AtlasProfileViolationField,-} from './atlas-profiles';--export {- IMPOSTER_LEGACY_SCHEMA_VERSION,- IMPOSTER_SCHEMA_VERSION,- ImposterMetaSchema,-} from './schema';-export {- ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES,- ANIMATED_IMPOSTER_KIND,- ANIMATED_IMPOSTER_SCHEMA_VERSION,- AnimatedClipTargetSchema,- AnimatedImposterMetaSchema,- AnimatedImposterPreBakeInputSchema,- AnimatedImposterRuntimeAttributeSchema,- AnimatedImposterTextureFormatSchema,- AnimatedImposterTextureLayoutSchema,- AnimatedImposterTextureModeSchema,- AnimatedImposterWarningSchema,-} from './animated-schema';-export type {- ImposterMeta,- ImposterAngleCount,- ImposterAxis,- LatLonImposterAxis,- ImposterLayout,- ImposterAuxLayer,- ImposterBgColor,- ImposterColorLayer,- ImposterNormalSpace,- ImposterTextureColorSpace,-} from './schema';-export type {- AnimatedClipTarget,- AnimatedImposterMeta,- AnimatedImposterPreBakeConfig,- AnimatedImposterPreBakeInput,- AnimatedImposterRuntimeAttribute,- AnimatedImposterTextureFormat,- AnimatedImposterTextureLayout,- AnimatedImposterTextureMode,- AnimatedImposterWarning,-} from './animated-schema';--export {- dirFromAzEl,- enumerateOctahedralTiles,- enumerateTiles,- octaDecode,- octaEncode,- resolveLayout,-} from './projection';-export type {- OctahedralGrid,- OctahedralTileCamera,- TileCamera,- TileLayout,-} from './projection';--export {- resolveClips,- applyClipFallbacks,- normalizeClipName,- CLIP_ALIASES,-} from './clip-resolver';-export type {- ClipTarget,- ResolvedClip,- ClipResolutionReport,-} from './clip-resolver';--export {- estimateAnimatedImposterStorage,- validateAnimatedImposterPreBake,-} from './animated-validate';-export type {- AnimatedImposterPreBakeReport,- AnimatedImposterStorageEstimate,-} from './animated-validate';--export {- bakeAnimatedImposter,- enumerateOctahedralGrid,- openAnimatedImposterSession,-} from './animated-bake';-export type {- AnimatedImposterSession,- AnimatedTileCamera,- BakeAnimatedImposterOptions,- BakeAnimatedImposterResult,-} from './animated-bake';--export {- NpcCharacterPackManifestSchema,- validateNpcCharacterPack,-} from './npc-character-pack';-export type {- NpcCharacterPackFactionMetrics,- NpcCharacterPackIssue,- NpcCharacterPackManifest,- NpcCharacterPackOutputMetrics,- NpcCharacterPackValidationReport,- ValidateNpcCharacterPackOptions,-} from './npc-character-pack';diff --git a/src/imposter/npc-character-pack.ts b/src/imposter/npc-character-pack.tsdeleted file mode 100644index 3a682257..00000000--- a/src/imposter/npc-character-pack.ts+++ /dev/null@@ -1,721 +0,0 @@-import { existsSync, statSync } from 'node:fs';-import { isAbsolute, resolve } from 'node:path';--import { NodeIO, type Mesh } from '@gltf-transform/core';-import { z } from 'zod';--const NpcCharacterPackClipStatusSchema = z.enum(['reference', 'review', 'candidate', 'approved', 'rejected']);-const NpcCharacterPackTijStateSchema = z.enum([- 'idle',- 'patrolling',- 'alert',- 'engaging',- 'suppressing',- 'advancing',- 'retreating',- 'seeking_cover',- 'defending',- 'dead',- 'boarding',- 'in_vehicle',- 'dismounting',-]);--const NpcCharacterPackIssueSchema = z- .object({- code: z.string().min(1),- severity: z.enum(['info', 'warning', 'error']),- message: z.string().min(1),- path: z.string().optional(),- fixHint: z.string().optional(),- })- .strict();--const NpcCharacterPackOutputSchema = z- .object({- faction: z.string().min(1),- clip: z.string().min(1),- label: z.string().min(1),- path: z.string().min(1),- bytes: z.number().int().nonnegative(),- tijStates: z.array(NpcCharacterPackTijStateSchema).min(1),- status: NpcCharacterPackClipStatusSchema,- primaryWeapon: z.string().min(1),- })- .strict();--const NpcCharacterPackSourceManifestSchema = z- .object({- id: z.string().min(1),- createdFrom: z.record(z.string(), z.unknown()).default({}),- policy: z- .object({- promoteToWarAssets: z.boolean(),- recoil: z.string().min(1),- excludedClips: z- .array(- z- .object({- id: z.string().min(1),- reason: z.string().min(1),- })- .strict(),- )- .default([]),- })- .strict(),- socketContract: z- .object({- characterForward: z.string().min(1),- weaponForward: z.string().min(1),- rightHandBone: z.string(),- leftHandBone: z.string(),- runtimeNotes: z.array(z.string()).default([]),- })- .strict(),- factions: z.record(- z.string().min(1),- z- .object({- label: z.string().min(1),- headgear: z.string().min(1),- primaryWeapon: z.string().min(1),- })- .strict(),- ),- clips: z- .array(- z- .object({- id: z.string().min(1),- label: z.string().min(1),- tijStates: z.array(NpcCharacterPackTijStateSchema).min(1),- status: NpcCharacterPackClipStatusSchema,- note: z.string().min(1),- })- .strict(),- )- .min(1),- outputs: z.array(NpcCharacterPackOutputSchema).min(1),- })- .strict();--const NpcCharacterPackPackagedEntrySchema = z- .object({- faction: z.string().min(1),- factionLabel: z.string().min(1),- clip: z.string().min(1),- clipLabel: z.string().min(1),- status: NpcCharacterPackClipStatusSchema,- tijStates: z.array(NpcCharacterPackTijStateSchema).min(1),- primaryWeapon: z.string().min(1),- glb: z- .object({- uri: z.string().min(1),- bytes: z.number().int().nonnegative(),- hash: z.string().min(1).optional(),- })- .strict(),- impostor: z- .object({- dir: z.string().min(1),- sidecar: z.string().min(1),- atlas: z.string().min(1),- frameStrip: z.string().min(1),- atlasHash: z.string().min(1).optional(),- sidecarValid: z.boolean(),- alphaCoverage: z.unknown().optional(),- storage: z- .object({- colorBytes: z.number().int().nonnegative(),- normalBytes: z.number().int().nonnegative().optional(),- depthBytes: z.number().int().nonnegative().optional(),- paletteBytes: z.number().int().nonnegative().optional(),- totalRawBytes: z.number().int().nonnegative(),- envelopeBytes: z.number().int().positive(),- fitsEnvelope: z.boolean(),- })- .strict(),- warnings: z.array(NpcCharacterPackIssueSchema),- })- .strict(),- })- .strict();--const NpcCharacterPackPackagedManifestSchema = z- .object({- schemaVersion: z.literal(1),- id: z.string().min(1),- sourceManifest: z.string().min(1),- generatedAt: z.string().min(1),- promoteToWarAssets: z.boolean(),- note: z.string().min(1),- settings: z- .object({- viewGrid: z- .object({- x: z.number().int().positive(),- y: z.number().int().positive(),- count: z.number().int().positive(),- })- .strict(),- tileSize: z.number().int().positive(),- framesPerClip: z.number().int().positive(),- textureLayout: z.string().min(1),- textureFormat: z.string().min(1),- })- .strict(),- socketContract: z- .object({- characterForward: z.string().min(1),- weaponForward: z.string().min(1),- rightHandBone: z.string(),- leftHandBone: z.string(),- runtimeNotes: z.array(z.string()).default([]),- })- .strict(),- factions: z.record(- z.string().min(1),- z- .object({- label: z.string().min(1),- headgear: z.string().min(1),- primaryWeapon: z.string().min(1),- })- .strict(),- ),- clips: z- .array(- z- .object({- id: z.string().min(1),- label: z.string().min(1),- tijStates: z.array(NpcCharacterPackTijStateSchema).min(1),- status: NpcCharacterPackClipStatusSchema,- note: z.string().min(1),- })- .strict(),- )- .min(1),- weapons: z.record(z.string(), z.unknown()).default({}),- combinedGlbs: z- .record(- z.string().min(1),- z- .object({- uri: z.string().min(1),- bytes: z.number().int().nonnegative(),- hash: z.string().min(1).optional(),- animations: z.array(z.string()),- })- .strict(),- )- .default({}),- entries: z.array(NpcCharacterPackPackagedEntrySchema).min(1),- totals: z- .object({- entries: z.number().int().nonnegative(),- glbBytes: z.number().int().nonnegative(),- atlasPngBytes: z.number().int().nonnegative(),- rawImpostorBytes: z.number().int().nonnegative(),- warnings: z.number().int().nonnegative(),- })- .strict(),- })- .strict();--export const NpcCharacterPackManifestSchema = z.union([- NpcCharacterPackSourceManifestSchema,- NpcCharacterPackPackagedManifestSchema,-]);--export type NpcCharacterPackManifest = z.infer<typeof NpcCharacterPackManifestSchema>;-export type NpcCharacterPackIssue = z.infer<typeof NpcCharacterPackIssueSchema>;-type NpcCharacterPackSourceManifest = z.infer<typeof NpcCharacterPackSourceManifestSchema>;-type NpcCharacterPackPackagedManifest = z.infer<typeof NpcCharacterPackPackagedManifestSchema>;--export interface NpcCharacterPackOutputMetrics {- faction: string;- clip: string;- path: string;- exists: boolean;- expectedBytes: number;- actualBytes?: number;- triangles?: number;- joints?: number;- animations?: number;- hasRightHandBone?: boolean;- hasLeftHandBone?: boolean;-}--export interface NpcCharacterPackFactionMetrics {- outputs: number;- clips: number;- maxBytes: number;- maxTris: number;- minJoints: number;-}--export interface NpcCharacterPackValidationReport {- ok: boolean;- manifest: NpcCharacterPackManifest | null;- blockers: NpcCharacterPackIssue[];- warnings: NpcCharacterPackIssue[];- metrics: {- factions: Record<string, NpcCharacterPackFactionMetrics>;- outputs: NpcCharacterPackOutputMetrics[];- };-}--export interface ValidateNpcCharacterPackOptions {- rootDir?: string;- checkFiles?: boolean;- inspectGlbs?: boolean;- productionClipIds?: string[];-}--const DEFAULT_PRODUCTION_CLIP_IDS = [- 'idle',- 'patrol_walk',- 'traverse_run',- 'walk_fight_forward',- 'death_fall_back',-];--export async function validateNpcCharacterPack(- raw: unknown,- opts: ValidateNpcCharacterPackOptions = {},-): Promise<NpcCharacterPackValidationReport> {- const blockers: NpcCharacterPackIssue[] = [];- const warnings: NpcCharacterPackIssue[] = [];- const add = (issue: NpcCharacterPackIssue) => {- if (issue.severity === 'error') blockers.push(issue);- else warnings.push(issue);- };-- const parsed = NpcCharacterPackManifestSchema.safeParse(raw);- if (!parsed.success) {- return {- ok: false,- manifest: null,- blockers: [- {- code: 'NPC_CHARACTER_PACK_SCHEMA_INVALID',- severity: 'error',- message: parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`).join('; '),- fixHint: 'Fix the character pack manifest shape before using it as a bake source.',- },- ],- warnings: [],- metrics: { factions: {}, outputs: [] },- };- }-- const rawManifest = parsed.data;- const packagedManifest = isPackagedManifest(rawManifest) ? rawManifest : null;- const manifest = normalizeManifest(rawManifest);- const checkFiles = opts.checkFiles ?? false;- const inspectGlbs = opts.inspectGlbs ?? checkFiles;- const rootDir = opts.rootDir ?? process.cwd();- const productionClipIds = opts.productionClipIds ?? DEFAULT_PRODUCTION_CLIP_IDS;- const excludedClipIds = new Set(manifest.policy.excludedClips.map((clip) => clip.id));- const factionIds = new Set(Object.keys(manifest.factions));- const clipIds = new Set(manifest.clips.map((clip) => clip.id));- const outputKeys = new Set<string>();- const outputsByFaction = new Map<string, Set<string>>();- const metrics: NpcCharacterPackValidationReport['metrics'] = {- factions: Object.fromEntries(- Object.keys(manifest.factions).map((faction) => [- faction,- { outputs: 0, clips: 0, maxBytes: 0, maxTris: 0, minJoints: Number.POSITIVE_INFINITY },- ]),- ),- outputs: [],- };-- if (packagedManifest) {- validatePackagedManifest(packagedManifest, rootDir, checkFiles, add);- }-- if (!manifest.socketContract.rightHandBone.trim()) {- add({- code: 'NPC_CHARACTER_PACK_RIGHT_HAND_BONE_MISSING',- severity: 'error',- message: 'socketContract.rightHandBone is required.',- path: 'socketContract.rightHandBone',- fixHint: 'Set the right hand bone used for weapon attachment.',- });- }-- if (!manifest.socketContract.leftHandBone.trim()) {- add({- code: 'NPC_CHARACTER_PACK_LEFT_HAND_BONE_MISSING',- severity: 'error',- message: 'socketContract.leftHandBone is required.',- path: 'socketContract.leftHandBone',- fixHint: 'Set the left hand bone used for weapon support.',- });- }-- for (const clip of manifest.clips) {- if (excludedClipIds.has(clip.id)) {- add({- code: 'NPC_CHARACTER_PACK_EXCLUDED_CLIP_DECLARED',- severity: 'warning',- message: `Excluded clip ${clip.id} is still declared in clips.`,- path: `clips.${clip.id}`,- fixHint: 'Keep rejected actions out of the production clip list.',- });- }- }-- for (const output of manifest.outputs) {- const outputKey = `${output.faction}/${output.clip}`;- const metric: NpcCharacterPackOutputMetrics = {- faction: output.faction,- clip: output.clip,- path: output.path,- exists: false,- expectedBytes: output.bytes,- };- metrics.outputs.push(metric);-- if (outputKeys.has(outputKey)) {- add({- code: 'NPC_CHARACTER_PACK_DUPLICATE_OUTPUT',- severity: 'error',- message: `Duplicate output for ${outputKey}.`,- path: `outputs.${outputKey}`,- fixHint: 'Keep one GLB per faction and clip id.',- });- }- outputKeys.add(outputKey);-- if (!factionIds.has(output.faction)) {- add({- code: 'NPC_CHARACTER_PACK_UNKNOWN_FACTION',- severity: 'error',- message: `Output references unknown faction ${output.faction}.`,- path: `outputs.${outputKey}.faction`,- fixHint: 'Add the faction to the manifest or remove the output.',- });- }-- if (!clipIds.has(output.clip)) {- add({- code: 'NPC_CHARACTER_PACK_UNKNOWN_CLIP',- severity: 'error',- message: `Output references unknown clip ${output.clip}.`,- path: `outputs.${outputKey}.clip`,- fixHint: 'Add the clip metadata to the manifest or remove the output.',- });- }-- if (excludedClipIds.has(output.clip)) {- add({- code: 'NPC_CHARACTER_PACK_EXCLUDED_CLIP_OUTPUT',- severity: 'error',- message: `Excluded clip ${output.clip} has an output for ${output.faction}.`,- path: `outputs.${outputKey}`,- fixHint: 'Do not bake or validate rejected production clips.',- });- }-- const faction = manifest.factions[output.faction];- if (faction && output.primaryWeapon !== faction.primaryWeapon) {- add({- code: 'NPC_CHARACTER_PACK_WEAPON_MISMATCH',- severity: 'warning',- message: `${outputKey} uses ${output.primaryWeapon}, but faction default is ${faction.primaryWeapon}.`,- path: `outputs.${outputKey}.primaryWeapon`,- fixHint: 'Use the faction primary weapon unless this output is an intentional variant.',- });- }-- const factionClips = outputsByFaction.get(output.faction) ?? new Set<string>();- factionClips.add(output.clip);- outputsByFaction.set(output.faction, factionClips);-- if (metrics.factions[output.faction]) {- const factionMetric = metrics.factions[output.faction]!;- factionMetric.outputs += 1;- factionMetric.clips = factionClips.size;- factionMetric.maxBytes = Math.max(factionMetric.maxBytes, output.bytes);- }-- if (checkFiles || inspectGlbs) {- await inspectOutputGlb(output, metric, rootDir, inspectGlbs, manifest, add);- if (metrics.factions[output.faction]) {- const factionMetric = metrics.factions[output.faction]!;- factionMetric.maxTris = Math.max(factionMetric.maxTris, metric.triangles ?? 0);- factionMetric.minJoints = Math.min(factionMetric.minJoints, metric.joints ?? factionMetric.minJoints);- }- }- }-- for (const factionId of factionIds) {- const factionClips = outputsByFaction.get(factionId) ?? new Set<string>();- if (factionClips.size === 0) {- add({- code: 'NPC_CHARACTER_PACK_FACTION_NO_OUTPUTS',- severity: 'error',- message: `Faction ${factionId} has no GLB outputs.`,- path: `factions.${factionId}`,- fixHint: 'Generate or remove the faction before baking animated impostors.',- });- }-- for (const clipId of productionClipIds) {- if (!factionClips.has(clipId)) {- add({- code: 'NPC_CHARACTER_PACK_PRODUCTION_CLIP_MISSING',- severity: 'error',- message: `Faction ${factionId} is missing production clip ${clipId}.`,- path: `outputs.${factionId}.${clipId}`,- fixHint: 'Build the same approved production clip set for every faction.',- });- }- }- }-- for (const factionMetric of Object.values(metrics.factions)) {- if (factionMetric.minJoints === Number.POSITIVE_INFINITY) factionMetric.minJoints = 0;- }-- return {- ok: blockers.length === 0,- manifest,- blockers,- warnings,- metrics,- };-}--function isPackagedManifest(- manifest: NpcCharacterPackManifest,-): manifest is NpcCharacterPackPackagedManifest {- return 'entries' in manifest;-}--function normalizeManifest(manifest: NpcCharacterPackManifest): NpcCharacterPackSourceManifest {- if (!isPackagedManifest(manifest)) return manifest;-- return {- id: manifest.id,- createdFrom: {- sourceManifest: manifest.sourceManifest,- schemaVersion: manifest.schemaVersion,- generatedAt: manifest.generatedAt,- },- policy: {- promoteToWarAssets: manifest.promoteToWarAssets,- recoil: 'Runtime procedural.',- excludedClips: manifest.clips- .filter((clip) => clip.status === 'rejected')- .map((clip) => ({ id: clip.id, reason: clip.note })),- },- socketContract: manifest.socketContract,- factions: manifest.factions,- clips: manifest.clips,- outputs: manifest.entries.map((entry) => ({- faction: entry.faction,- clip: entry.clip,- label: entry.clipLabel,- path: entry.glb.uri,- bytes: entry.glb.bytes,- tijStates: entry.tijStates,- status: entry.status,- primaryWeapon: entry.primaryWeapon,- })),- };-}--function validatePackagedManifest(- manifest: NpcCharacterPackPackagedManifest,- rootDir: string,- checkFiles: boolean,- add: (issue: NpcCharacterPackIssue) => void,-): void {- if (manifest.promoteToWarAssets) {- add({- code: 'NPC_CHARACTER_PACK_REVIEW_ONLY_VIOLATION',- severity: 'error',- message: 'Packaged NPC manifests must remain review-only.',- path: 'promoteToWarAssets',- fixHint: 'Set promoteToWarAssets=false and keep generated output under tmp/ until runtime import is approved.',- });- }-- if (manifest.totals.entries !== manifest.entries.length) {- add({- code: 'NPC_CHARACTER_PACK_TOTALS_DRIFT',- severity: 'error',- message: `totals.entries is ${manifest.totals.entries}, but entries contains ${manifest.entries.length}.`,- path: 'totals.entries',- fixHint: 'Regenerate the package manifest after rebuilding entries.',- });- }-- for (const [faction, combined] of Object.entries(manifest.combinedGlbs)) {- if (!manifest.factions[faction]) {- add({- code: 'NPC_CHARACTER_PACK_UNKNOWN_COMBINED_FACTION',- severity: 'error',- message: `combinedGlbs contains unknown faction ${faction}.`,- path: `combinedGlbs.${faction}`,- fixHint: 'Remove the combined GLB or add the faction metadata.',- });- }- if (checkFiles) {- requirePackagedFile(add, `combinedGlbs.${faction}.uri`, combined.uri, rootDir);- }- }-- for (const entry of manifest.entries) {- const key = `${entry.faction}/${entry.clip}`;- if (!entry.impostor.sidecarValid) {- add({- code: 'NPC_CHARACTER_PACK_IMPOSTER_SIDECAR_INVALID',- severity: 'error',- message: `${key} animated imposter sidecar failed schema validation during packaging.`,- path: `entries.${key}.impostor.sidecar`,- fixHint: 'Fix the animated imposter sidecar before using this entry as a bake/runtime source.',- });- }- if (!entry.impostor.storage.fitsEnvelope) {- add({- code: 'NPC_CHARACTER_PACK_IMPOSTER_STORAGE_OVER_BUDGET',- severity: 'error',- message: `${key} animated imposter exceeds the configured storage envelope.`,- path: `entries.${key}.impostor.storage`,- fixHint: 'Reduce view grid, frame count, tile size, or texture format before runtime import.',- });- }-- if (!checkFiles) continue;- requirePackagedFile(add, `entries.${key}.glb.uri`, entry.glb.uri, rootDir);- requirePackagedFile(add, `entries.${key}.impostor.sidecar`, entry.impostor.sidecar, rootDir);- requirePackagedFile(add, `entries.${key}.impostor.atlas`, entry.impostor.atlas, rootDir);- requirePackagedFile(add, `entries.${key}.impostor.frameStrip`, entry.impostor.frameStrip, rootDir);- }-}--function requirePackagedFile(- add: (issue: NpcCharacterPackIssue) => void,- path: string,- filePath: string,- rootDir: string,-): void {- const absPath = isAbsolute(filePath) ? filePath : resolve(rootDir, filePath);- if (!existsSync(absPath)) {- add({- code: 'NPC_CHARACTER_PACK_FILE_MISSING',- severity: 'error',- message: `Packaged file is missing: ${filePath}.`,- path,- fixHint: 'Rebuild the package or fix the manifest path.',- });- }-}--async function inspectOutputGlb(- output: z.infer<typeof NpcCharacterPackOutputSchema>,- metric: NpcCharacterPackOutputMetrics,- rootDir: string,- inspectGlbs: boolean,- manifest: NpcCharacterPackManifest,- add: (issue: NpcCharacterPackIssue) => void,-): Promise<void> {- const absPath = isAbsolute(output.path) ? output.path : resolve(rootDir, output.path);- if (!existsSync(absPath)) {- add({- code: 'NPC_CHARACTER_PACK_OUTPUT_MISSING',- severity: 'error',- message: `Output GLB is missing: ${output.path}.`,- path: `outputs.${output.faction}.${output.clip}.path`,- fixHint: 'Rebuild the pack or fix the manifest path before baking.',- });- return;- }-- metric.exists = true;- metric.actualBytes = statSync(absPath).size;- if (metric.actualBytes !== output.bytes) {- add({- code: 'NPC_CHARACTER_PACK_OUTPUT_BYTES_DRIFT',- severity: 'warning',- message: `${output.path} is ${metric.actualBytes} bytes, manifest expected ${output.bytes}.`,- path: `outputs.${output.faction}.${output.clip}.bytes`,- fixHint: 'Refresh the manifest after rebuilding GLBs.',- });- }-- if (!inspectGlbs) return;-- try {- const doc = await new NodeIO().read(absPath);- const root = doc.getRoot();- metric.triangles = countTriangles(root.listMeshes());- metric.animations = root.listAnimations().length;- const jointNames = new Set(root.listSkins().flatMap((skin) => skin.listJoints().map((joint) => joint.getName())));- const nodeNames = new Set(root.listNodes().map((node) => node.getName()));- metric.joints = jointNames.size;- metric.hasRightHandBone = jointNames.has(manifest.socketContract.rightHandBone) || nodeNames.has(manifest.socketContract.rightHandBone);- metric.hasLeftHandBone = jointNames.has(manifest.socketContract.leftHandBone) || nodeNames.has(manifest.socketContract.leftHandBone);-- if (metric.triangles <= 0) {- add({- code: 'NPC_CHARACTER_PACK_OUTPUT_NO_TRIS',- severity: 'error',- message: `${output.path} has no renderable triangles.`,- path: `outputs.${output.faction}.${output.clip}.path`,- fixHint: 'Use a mesh-backed GLB output.',- });- }- if (metric.joints <= 0) {- add({- code: 'NPC_CHARACTER_PACK_OUTPUT_NO_SKIN',- severity: 'error',- message: `${output.path} has no skin joints.`,- path: `outputs.${output.faction}.${output.clip}.path`,- fixHint: 'Use a skinned character GLB for animated impostor baking.',- });- }- if (output.status !== 'reference' && (metric.animations ?? 0) <= 0) {- add({- code: 'NPC_CHARACTER_PACK_OUTPUT_NO_ANIMATION',- severity: 'error',- message: `${output.path} has no animation clips.`,- path: `outputs.${output.faction}.${output.clip}.path`,- fixHint: 'Select an animated clip GLB or mark this output as reference-only.',- });- }- if (!metric.hasRightHandBone || !metric.hasLeftHandBone) {- add({- code: 'NPC_CHARACTER_PACK_HAND_BONES_NOT_FOUND',- severity: 'error',- message: `${output.path} does not expose both configured hand bones.`,- path: `outputs.${output.faction}.${output.clip}.path`,- fixHint: 'Set socketContract hand bone names to the exported skeleton names.',- });- }- } catch (err) {- add({- code: 'NPC_CHARACTER_PACK_OUTPUT_INSPECT_FAILED',- severity: 'error',- message: `${output.path} could not be inspected: ${(err as Error).message}`,- path: `outputs.${output.faction}.${output.clip}.path`,- fixHint: 'Verify the path points to a valid GLB file.',- });- }-}--function countTriangles(meshes: Mesh[]): number {- let tris = 0;- for (const mesh of meshes) {- for (const primitive of mesh.listPrimitives()) {- tris += Math.floor((primitive.getIndices()?.getCount() ?? primitive.getAttribute('POSITION')?.getCount() ?? 0) / 3);- }- }- return tris;-}diff --git a/src/imposter/projection.ts b/src/imposter/projection.tsdeleted file mode 100644index 5c81b4a2..00000000--- a/src/imposter/projection.ts+++ /dev/null@@ -1,204 +0,0 @@-/**- * Imposter camera-direction math.- *- * Lat/lon layout (azimuth × elevation). For the angle counts supported:- *- * angles=8 hemi-y 4 az × 2 el → 4×2 tile grid- * angles=16 y 8 az × 2 el → 8×2 tile grid (full sphere: 2 elevations = +45° and -45°)- * angles=16 hemi-y 4 az × 4 el → 4×4 tile grid- * angles=32 hemi-y 8 az × 4 el → 8×4 tile grid- *- * Tiles are stored row-major, left-to-right / top-to-bottom. The TOP row is the- * HIGHEST elevation; this is the convention baked into the atlas and recorded- * in meta.elevations (top to bottom = high to low). Both arrays go in the- * order the shader expects when indexing by (tileX, tileY).- *- * Kiln world frame: +X forward (asset nose / canopy front), +Y up, +Z right.- * Azimuth 0 looks at the asset from +X. Azimuth increases toward +Z (right-side- * profile at azimuth π/2). All camera up-vectors stay (0,1,0).- */--export type ImposterAngleCount = 8 | 16 | 32;-export type ImposterAxis = 'y' | 'hemi-y';--export interface TileCamera {- /** Tile column (0 = leftmost). */- i: number;- /** Tile row (0 = topmost = highest elevation). */- j: number;- /** Azimuth in radians. */- az: number;- /** Elevation in radians. 0 = horizon, positive = above. */- el: number;- /** Unit direction FROM target center TOWARD camera. */- dir: [number, number, number];-}--export interface TileLayout {- tilesX: number;- tilesY: number;- azimuths: number[]; // length === tilesX- elevations: number[]; // length === tilesY (top row first)- axis: ImposterAxis;-}--export interface OctahedralGrid {- x: number;- y: number;-}--export interface OctahedralTileCamera {- /** Tile column (0 = leftmost). */- i: number;- /** Tile row (0 = topmost). */- j: number;- /** Octahedral encoded U coordinate at tile center, -1..1. */- u: number;- /** Octahedral encoded V coordinate at tile center, -1..1. */- v: number;- /** Unit direction FROM target center TOWARD camera. */- dir: [number, number, number];-}--/**- * Resolve grid dimensions + angle sequences for a given (angles, axis) combo.- * Throws on unsupported combinations.- */-export function resolveLayout(angles: ImposterAngleCount, axis: ImposterAxis): TileLayout {- if (angles === 8) {- if (axis !== 'hemi-y') {- throw new Error(`8-angle imposter requires axis='hemi-y' (got '${axis}')`);- }- return {- tilesX: 4,- tilesY: 2,- axis,- azimuths: evenAzimuths(4),- // Two elevations above the horizon: steep + shallow. Top row = high.- elevations: [degToRad(55), degToRad(15)],- };- }-- if (angles === 16) {- if (axis === 'y') {- return {- tilesX: 8,- tilesY: 2,- axis,- azimuths: evenAzimuths(8),- // One above horizon, one below — full-sphere with minimal rows.- elevations: [degToRad(30), degToRad(-30)],- };- }- // hemi-y: 4 × 4. Elevations pushed higher at the top so aircraft/helicopter- // cameras looking down still land on a populated tile. Top row is nearly- // straight-down (85°); bottom row near-horizon (5°).- return {- tilesX: 4,- tilesY: 4,- axis,- azimuths: evenAzimuths(4),- elevations: [degToRad(85), degToRad(60), degToRad(30), degToRad(5)],- };- }-- if (angles === 32) {- if (axis !== 'hemi-y') {- throw new Error(`32-angle imposter requires axis='hemi-y' (got '${axis}')`);- }- // 8 azimuths × 4 elevations. Elevation 85° gives near-zenith coverage for- // aerial cameras; the full column spread means smoother transitions as a- // helicopter banks.- return {- tilesX: 8,- tilesY: 4,- axis,- azimuths: evenAzimuths(8),- elevations: [degToRad(85), degToRad(60), degToRad(30), degToRad(5)],- };- }-- throw new Error(`Unsupported angle count: ${angles}`);-}--/** Enumerate every tile for a layout, left-to-right top-to-bottom. */-export function enumerateTiles(layout: TileLayout): TileCamera[] {- const out: TileCamera[] = [];- for (let j = 0; j < layout.tilesY; j++) {- for (let i = 0; i < layout.tilesX; i++) {- const az = layout.azimuths[i]!;- const el = layout.elevations[j]!;- out.push({ i, j, az, el, dir: dirFromAzEl(az, el) });- }- }- return out;-}--/** Unit direction FROM target TOWARD camera, from (azimuth, elevation). */-export function dirFromAzEl(az: number, el: number): [number, number, number] {- const ce = Math.cos(el);- const x = Math.cos(az) * ce;- const z = Math.sin(az) * ce;- const y = Math.sin(el);- return [x, y, z];-}--/** Enumerate an octahedral atlas grid, left-to-right top-to-bottom. */-export function enumerateOctahedralTiles(grid: OctahedralGrid): OctahedralTileCamera[] {- if (!Number.isInteger(grid.x) || !Number.isInteger(grid.y) || grid.x <= 0 || grid.y <= 0) {- throw new Error('octahedral grid dimensions must be positive integers');- }- const out: OctahedralTileCamera[] = [];- for (let j = 0; j < grid.y; j++) {- for (let i = 0; i < grid.x; i++) {- const u = ((i + 0.5) / grid.x) * 2 - 1;- const v = 1 - ((j + 0.5) / grid.y) * 2;- out.push({ i, j, u, v, dir: octaDecode(u, v) });- }- }- return out;-}--/**- * Decode 2D octahedral coordinates into a Kiln world-frame direction.- * The Y component is world-up, matching the animated imposter baker.- */-export function octaDecode(u: number, v: number): [number, number, number] {- let x = u;- const y = 1 - Math.abs(u) - Math.abs(v);- let z = v;- if (y < 0) {- const ox = x;- x = (1 - Math.abs(z)) * Math.sign(ox || 1);- z = (1 - Math.abs(ox)) * Math.sign(z || 1);- }- const len = Math.hypot(x, y, z) || 1;- return [x / len, y / len, z / len];-}--/** Encode a Kiln world-frame direction into octahedral coordinates. */-export function octaEncode(dir: [number, number, number]): [number, number] {- const len = Math.hypot(dir[0], dir[1], dir[2]) || 1;- let x = dir[0] / len;- const y = dir[1] / len;- let z = dir[2] / len;- const denom = Math.abs(x) + Math.abs(y) + Math.abs(z) || 1;- x /= denom;- z /= denom;- if (y < 0) {- const ox = x;- x = (1 - Math.abs(z)) * Math.sign(ox || 1);- z = (1 - Math.abs(ox)) * Math.sign(z || 1);- }- return [x, z];-}--function evenAzimuths(count: number): number[] {- const out: number[] = [];- for (let i = 0; i < count; i++) out.push((i / count) * Math.PI * 2);- return out;-}--function degToRad(deg: number): number {- return (deg / 180) * Math.PI;-}diff --git a/src/imposter/schema.ts b/src/imposter/schema.tsdeleted file mode 100644index c1cfafde..00000000--- a/src/imposter/schema.ts+++ /dev/null@@ -1,183 +0,0 @@-/**- * ImposterMeta schema — sidecar written next to every baked imposter atlas.- *- * A consumer shader (TIJ's billboard system, or any three.js plane material)- * uses this to:- * - size the billboard quad to match the source bbox (worldSize, yOffset)- * - map a view-direction to a tile via layout + azimuths + elevations- * - sample auxiliary atlases (depth for parallax popping, normal for light)- *- * Static lat/lon sidecars shipped as version 1. Version 2 adds static- * octahedral layouts while keeping v1 lat/lon readers valid.- */--import { z } from 'zod';--export const IMPOSTER_LEGACY_SCHEMA_VERSION = 1 as const;-export const IMPOSTER_SCHEMA_VERSION = 2 as const;--export type ImposterAngleCount = 8 | 16 | 32;-export type LatLonImposterAxis = 'y' | 'hemi-y';-export type ImposterAxis = LatLonImposterAxis | 'octahedral';-export type ImposterLayout = 'latlon' | 'octahedral';-export type ImposterAuxLayer = 'albedo' | 'normal' | 'depth';-export type ImposterBgColor = 'magenta' | 'transparent';-export type ImposterColorLayer = 'baseColor' | 'beauty';-export type ImposterNormalSpace = 'capture-view';-export type ImposterTextureColorSpace = 'srgb';--const finiteNumber = z.number().finite();-const directionTuple = z.tuple([finiteNumber, finiteNumber, finiteNumber]);-const bboxSchema = z.object({- min: z.tuple([finiteNumber, finiteNumber, finiteNumber]),- max: z.tuple([finiteNumber, finiteNumber, finiteNumber]),-});-const sourceSchema = z.object({- path: z.string().optional(),- bytes: z.number().int().nonnegative(),- tris: z.number().int().nonnegative(),-});--const commonMetaSchema = z.object({- /** Total viewpoints baked into the atlas. */- angles: z.number().int().positive(),- /** Atlas grid dimensions — tiles across / down. */- tilesX: z.number().int().positive(),- tilesY: z.number().int().positive(),- /** Pixel size of a single tile (square). */- tileSize: z.number().int().positive(),- /** Total atlas width/height in pixels (tilesX*tileSize, tilesY*tileSize). */- atlasWidth: z.number().int().positive(),- atlasHeight: z.number().int().positive(),-- /** Bounding-sphere diameter of the source mesh, world units. Scale the billboard quad to this. */- worldSize: z.number().positive(),- /** Offset from the GLB origin to the bbox center along Y, world units. */- yOffset: finiteNumber,-- /** Orthographic — imposters need constant silhouette. */- projection: z.literal('orthographic'),-- /** Axis convention. 'y' = full sphere, 'hemi-y' = upper hemi, 'octahedral' = octa map. */- axis: z.enum(['y', 'hemi-y', 'octahedral']),- /** Redundant helper for shaders - true if axis === 'hemi-y'. False for octahedral. */- hemi: z.boolean(),-- /** Tile layout strategy. */- layout: z.enum(['latlon', 'octahedral']),-- /** Axis-aligned bbox of the source mesh, world units. */- bbox: bboxSchema,-- /** Source mesh stats for provenance. */- source: sourceSchema,-- /** Auxiliary layers packed alongside albedo (as separate PNGs). */- auxLayers: z.array(z.enum(['albedo', 'normal', 'depth'])),-- /** Background color used for the bake. 'transparent' uses RGBA alpha. */- bgColor: z.enum(['magenta', 'transparent']),-- /** Color layer contract. Legacy sidecars default to lit beauty output. */- colorLayer: z.enum(['baseColor', 'beauty']).default('beauty'),- /** Normal layer coordinate contract. Current baker emits capture/view-space normal RGB. */- normalSpace: z.literal('capture-view').default('capture-view'),- /** RGB bleed radius applied into transparent pixels before atlas packing. */- edgeBleedPx: z.number().int().nonnegative().default(0),- /** Color atlas storage space. PNG color layers are authored as sRGB. */- textureColorSpace: z.literal('srgb').default('srgb'),-});--const latLonMetaSchema = commonMetaSchema.extend({- version: z.union([z.literal(IMPOSTER_LEGACY_SCHEMA_VERSION), z.literal(IMPOSTER_SCHEMA_VERSION)]),- angles: z.union([z.literal(8), z.literal(16), z.literal(32)]),- axis: z.enum(['y', 'hemi-y']),- layout: z.literal('latlon'),- /**- * For layout='latlon': azimuth angles (radians) per column. Length === tilesX.- * Azimuth 0 = +X (the asset's forward). Increases toward +Z (right).- */- azimuths: z.array(z.number()),- /**- * For layout='latlon': elevation angles (radians) per row. Length === tilesY.- * 0 = horizon. +π/2 = zenith. Rows go top-to-bottom = high-to-low elevation.- */- elevations: z.array(z.number()),-});--const octahedralMetaSchema = commonMetaSchema.extend({- version: z.literal(IMPOSTER_SCHEMA_VERSION),- axis: z.literal('octahedral'),- hemi: z.literal(false),- layout: z.literal('octahedral'),- directionEncoding: z.literal('octahedral'),- /** Per-tile unit direction vectors, row-major, from target center toward camera. */- directions: z.array(directionTuple),-});--function refineCommon(meta: z.infer<typeof commonMetaSchema>, ctx: z.RefinementCtx): void {- if (meta.colorLayer === 'baseColor' && !meta.auxLayers.includes('normal')) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ['auxLayers'],- message: "baseColor production imposters must include a 'normal' aux layer",- });- }- if (meta.atlasWidth !== meta.tilesX * meta.tileSize) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ['atlasWidth'],- message: 'atlasWidth must equal tilesX * tileSize',- });- }- if (meta.atlasHeight !== meta.tilesY * meta.tileSize) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ['atlasHeight'],- message: 'atlasHeight must equal tilesY * tileSize',- });- }-}--export const ImposterMetaSchema = z.union([- latLonMetaSchema.superRefine((meta, ctx) => {- refineCommon(meta, ctx);- if (meta.azimuths.length !== meta.tilesX) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ['azimuths'],- message: 'azimuths length must match tilesX',- });- }- if (meta.elevations.length !== meta.tilesY) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ['elevations'],- message: 'elevations length must match tilesY',- });- }- }),- octahedralMetaSchema.superRefine((meta, ctx) => {- refineCommon(meta, ctx);- if (meta.directions.length !== meta.tilesX * meta.tilesY) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ['directions'],- message: 'directions length must match tilesX * tilesY',- });- }- for (let idx = 0; idx < meta.directions.length; idx++) {- const dir = meta.directions[idx]!;- const len = Math.hypot(dir[0], dir[1], dir[2]);- if (Math.abs(len - 1) > 1e-4) {- ctx.addIssue({- code: z.ZodIssueCode.custom,- path: ['directions', idx],- message: 'direction must be a unit vector',- });- }- }- }),-]);--export type ImposterMeta = z.infer<typeof ImposterMetaSchema>;diff --git a/src/imposter/validate.ts b/src/imposter/validate.tsdeleted file mode 100644index 7fb7908c..00000000--- a/src/imposter/validate.ts+++ /dev/null@@ -1,154 +0,0 @@-import { existsSync, readFileSync } from 'node:fs';-import { extname, resolve } from 'node:path';-import sharp from 'sharp';--import {- isAtlasProfileName,- validateAgainstAtlasProfile,- type AtlasProfileName,- type AtlasProfileValidationResult,- type AtlasProfileViolation,-} from './atlas-profiles';-import { ImposterMetaSchema, type ImposterAuxLayer, type ImposterMeta } from './schema';--export interface ImposterValidationIssue {- field: string;- message: string;-}--export interface ValidateImposterOptions {- profile?: AtlasProfileName;- checkFiles?: boolean;-}--export interface ImposterValidationResult {- ok: boolean;- sidecarPath: string;- meta: ImposterMeta | null;- issues: ImposterValidationIssue[];- profile?: AtlasProfileValidationResult;-}--export async function validateImposterSidecar(- sidecarPathInput: string,- opts: ValidateImposterOptions = {},-): Promise<ImposterValidationResult> {- const sidecarPath = resolve(sidecarPathInput);- const issues: ImposterValidationIssue[] = [];-- let raw: unknown;- try {- raw = JSON.parse(readFileSync(sidecarPath, 'utf-8'));- } catch (err) {- return {- ok: false,- sidecarPath,- meta: null,- issues: [{ field: 'sidecar', message: err instanceof Error ? err.message : String(err) }],- };- }-- const parsed = ImposterMetaSchema.safeParse(raw);- if (!parsed.success) {- return {- ok: false,- sidecarPath,- meta: null,- issues: parsed.error.issues.map((issue) => ({- field: issue.path.join('.') || 'sidecar',- message: issue.message,- })),- };- }-- const meta = parsed.data;- validateBbox(meta, issues);- if (meta.angles !== meta.tilesX * meta.tilesY) {- issues.push({- field: 'angles',- message: 'angles must match tilesX * tilesY',- });- }-- let profile: AtlasProfileValidationResult | undefined;- if (opts.profile) {- if (!isAtlasProfileName(opts.profile)) {- issues.push({ field: 'profile', message: `unknown atlas profile: ${opts.profile}` });- } else {- profile = validateAgainstAtlasProfile(meta, opts.profile);- for (const violation of profile.violations) {- issues.push(profileViolationToIssue(violation));- }- }- }-- if (opts.checkFiles !== false) {- await validatePngFiles(sidecarPath, meta, issues);- }-- return {- ok: issues.length === 0,- sidecarPath,- meta,- issues,- ...(profile ? { profile } : {}),- };-}--function validateBbox(meta: ImposterMeta, issues: ImposterValidationIssue[]): void {- const { min, max } = meta.bbox;- for (let axis = 0; axis < 3; axis++) {- const lo = min[axis]!;- const hi = max[axis]!;- if (!(hi >= lo)) {- issues.push({- field: `bbox.${axis}`,- message: 'bbox max must be greater than or equal to min',- });- }- }-}--async function validatePngFiles(- sidecarPath: string,- meta: ImposterMeta,- issues: ImposterValidationIssue[],-): Promise<void> {- const base = sidecarPath.replace(new RegExp(`${escapeRegExp(extname(sidecarPath))}$`), '');- const expected = { width: meta.atlasWidth, height: meta.atlasHeight };- await validatePng(`${base}.png`, 'albedo', expected, issues);- for (const layer of meta.auxLayers) {- if (layer === 'albedo') continue;- await validatePng(`${base}.${layer}.png`, layer, expected, issues);- }-}--async function validatePng(- filePath: string,- layer: ImposterAuxLayer,- expected: { width: number; height: number },- issues: ImposterValidationIssue[],-): Promise<void> {- if (!existsSync(filePath)) {- issues.push({ field: `auxLayers.${layer}`, message: `missing PNG: ${filePath}` });- return;- }- const meta = await sharp(filePath).metadata();- if (meta.width !== expected.width || meta.height !== expected.height) {- issues.push({- field: `auxLayers.${layer}`,- message: `PNG dimensions ${meta.width}x${meta.height} do not match sidecar ${expected.width}x${expected.height}`,- });- }-}--function profileViolationToIssue(violation: AtlasProfileViolation): ImposterValidationIssue {- return {- field: `profile.${violation.field}`,- message: violation.message,- };-}--function escapeRegExp(value: string): string {- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-}diff --git a/src/index.ts b/src/index.tsdeleted file mode 100644index 98bcf5d6..00000000--- a/src/index.ts+++ /dev/null@@ -1,424 +0,0 @@-/**- * @pixel-forge/core - Kiln public API- *- * Headless Kiln pipeline: prompt -> Claude -> code -> GLB Buffer.- *- * This is the W1.1 spike surface. W2 will migrate the server and client to- * consume these entry points (replacing the duplicate copies currently- * living in packages/{client,shared,server}).- */--import type { KilnCodeMeta } from './render';-import { renderGLB } from './render';-import { generateKilnCode, resolveCodegenMode } from './generate';--export { renderGLB, renderSceneToGLB, inspectGeneratedAnimation, gradeGlbBytes } from './render';-export {- generateKilnCode,- editKilnCode,- compactCode,- refactorCode,- // Companion aliases on the namespace for agent ergonomics:- editKilnCode as editCode,- compactCode as compact,- refactorCode as refactor,-} from './generate';-export type {- RefactorRequest,- KilnGenerateResult,- KilnGenerateCallOptions,-} from './generate';-export { validate, validateKilnCode } from './validation';-export { collectGlbMetrics, gradeInstanceability } from './metrics';-export type {- InstanceabilityMetrics,- InstanceabilityGrade,- InstanceabilityReport,-} from './metrics';-export { inspect } from './inspect';-export type {- InspectResult,- InspectNamedPart,- InspectAnimationTrack,- InspectBoundingBox,- Vec3Tuple,-} from './inspect';-export { listPrimitives } from './list-primitives';-export type { PrimitiveSpec } from './list-primitives';-export {- renderApiSection,- renderPrimitivesMarkdown,- renderSkillQuickReference,-} from './prompt-api';-export {- buildUserPrompt,- getSystemPrompt,- STYLE_TEMPLATES,- KILN_SYSTEM_PROMPT,- KILN_TSL_SYSTEM_PROMPT,- KILN_BOTH_SYSTEM_PROMPT,- type KilnGenerateRequest,- type RenderMode,- type AssetCategory,- type AssetStyle,- type AssetBudget,-} from './prompt';-export type {- KilnCodeMeta,- RenderResult,- RenderSceneResult,- RenderSceneOptions,- ExecutedKilnCode,-} from './render';-export { executeKilnCode } from './render';-export {- buildSandboxGlobals,- countTriangles,- countMaterials,- getJointNames,- validateAsset,- // Primitive re-exports so the editor can `import { createRoot, boxGeo, ... } from '@pixel-forge/core/kiln'`- createRoot,- createPivot,- createPart,- capsuleGeo,- capsuleXGeo,- capsuleZGeo,- cylinderGeo,- cylinderXGeo,- cylinderZGeo,- cylinderOnAxis,- boxGeo,- sphereGeo,- coneGeo,- coneXGeo,- coneZGeo,- taperConeGeo,- torusGeo,- planeGeo,- wingGeo,- createWingPair,- beamBetween,- createLadder,- snapTo,- room,- wallWithOpening,- createRoofPlanes,- createStairs,- foliageCardGeo,- crossedQuadsGeo,- octaGridPlane,- gameMaterial,- basicMaterial,- glassMaterial,- lambertMaterial,- rotationTrack,- positionTrack,- scaleTrack,- createClip,- idleBreathing,- bobbingAnimation,- spinAnimation,- cloneGeometry,- cloneMaterial,- createInstance,-} from './primitives';-export type { TrackInterpolation } from './primitives';-export { boolUnion, boolDiff, boolIntersect, hull } from './solids';-export {- arrayLinear,- arrayRadial,- mirror,- subdivide,- mergeVertices,- curveToMesh,- pipeAlongPath,- lathe,- revolveGeo,- bezierCurve,-} from './ops';-export { autoUnwrap } from './uv';-export type { AutoUnwrapOptions } from './uv';-export { boxUnwrap, cylinderUnwrap, planeUnwrap } from './uv-shapes';-export { gearGeo, bladeGeo } from './gears';-export type { GearOptions, BladeOptions } from './gears';-export { loadTexture, pbrMaterial } from './textures';-export type { PbrMaterialOptions, TextureSource, EncodedTextureData } from './textures';--// ------------------------------------------------------------------------------// Shared tool registry (kiln/tools) — Kiln Bench capability surface-// ------------------------------------------------------------------------------export { kilnToolRegistry } from './tools/registry';-export type { KilnToolDef, KilnRenderMetrics } from './tools/registry';--// ------------------------------------------------------------------------------// LOD chain generator (kiln/lod)-// ------------------------------------------------------------------------------// Note: `countTriangles` is intentionally NOT re-exported from the kiln-// namespace — primitives.ts already exports a THREE.Object3D variant under-// the same name. Reach into `./lod/generate` if you need the Document variant.-export { generateLODChain } from './lod';-export type {- GenerateLODChainOptions,- GenerateLODChainResult,- LODLevel,-} from './lod';--// ------------------------------------------------------------------------------// Sprite atlas packer (kiln/sprite-atlas)-// ------------------------------------------------------------------------------export { packSpriteAtlas } from './sprite-atlas';-export type {- PackSpriteAtlasInput,- PackSpriteAtlasOptions,- PackSpriteAtlasResult,- SpriteFrame,- SpriteFrameTable,-} from './sprite-atlas';-export {- SPRITE_ATLAS_SCHEMA_VERSION,- SpriteFrameSchema,- SpriteFrameTableSchema,-} from './sprite-atlas';--// ------------------------------------------------------------------------------// FBX ingest (kiln/fbx-ingest)-// ------------------------------------------------------------------------------export { ingestFbx, openFbxIngestSession } from './fbx-ingest';-export type { IngestFbxOptions, IngestFbxResult, IngestFbxSession } from './fbx-ingest';--// ------------------------------------------------------------------------------// Character retex (kiln/retex)-// ------------------------------------------------------------------------------export { retexCharacter, FACTION_PRESETS } from './retex';-export type { RetexCharacterOptions, RetexCharacterResult, FactionPreset } from './retex';--// ------------------------------------------------------------------------------// Photogrammetry cleanup (kiln/photogrammetry)-// ------------------------------------------------------------------------------export { cleanupPhotogrammetry } from './photogrammetry';-export type {- CleanupPhotogrammetryOptions,- CleanupPhotogrammetryResult,-} from './photogrammetry';--// ------------------------------------------------------------------------------// Imposter baker (kiln/imposter)-// ------------------------------------------------------------------------------export { bakeImposter, openImposterSession } from './imposter';-export type {- BakeImposterOptions,- BakeImposterResult,- ImposterSession,- OpenImposterSessionOptions,- ImposterValidationIssue,- ImposterValidationResult,- ImposterMeta,- ImposterAngleCount,- ImposterAxis,- LatLonImposterAxis,- ImposterLayout,- ImposterAuxLayer,- ImposterBgColor,- ImposterColorLayer,- ImposterNormalSpace,- ImposterTextureColorSpace,- AnimatedClipTarget,- AnimatedImposterMeta,- AnimatedImposterPreBakeConfig,- AnimatedImposterPreBakeInput,- AnimatedImposterPreBakeReport,- AnimatedImposterRuntimeAttribute,- AnimatedImposterStorageEstimate,- AnimatedImposterTextureFormat,- AnimatedImposterTextureLayout,- AnimatedImposterTextureMode,- AnimatedImposterWarning,- AnimatedImposterSession,- AnimatedTileCamera,- BakeAnimatedImposterOptions,- BakeAnimatedImposterResult,- AtlasProfileLimits,- AtlasProfileMetaInput,- AtlasProfileName,- AtlasProfileValidationResult,- AtlasProfileViolation,- AtlasProfileViolationField,- NpcCharacterPackFactionMetrics,- NpcCharacterPackIssue,- NpcCharacterPackManifest,- NpcCharacterPackOutputMetrics,- NpcCharacterPackValidationReport,- ValidateImposterOptions,- ValidateNpcCharacterPackOptions,-} from './imposter';-export {- ANIMATED_IMPOSTER_DEFAULT_ENVELOPE_BYTES,- ANIMATED_IMPOSTER_KIND,- ANIMATED_IMPOSTER_SCHEMA_VERSION,- AnimatedClipTargetSchema,- AnimatedImposterMetaSchema,- AnimatedImposterPreBakeInputSchema,- AnimatedImposterRuntimeAttributeSchema,- AnimatedImposterTextureFormatSchema,- AnimatedImposterTextureLayoutSchema,- AnimatedImposterTextureModeSchema,- AnimatedImposterWarningSchema,- ATLAS_PROFILES,- ATLAS_PROFILE_NAMES,- ImposterMetaSchema,- IMPOSTER_LEGACY_SCHEMA_VERSION,- IMPOSTER_SCHEMA_VERSION,- dirFromAzEl,- enumerateOctahedralTiles,- enumerateTiles,- estimateAnimatedImposterStorage,- isAtlasProfileName,- octaDecode,- octaEncode,- resolveLayout,- validateAgainstAtlasProfile,- validateAnimatedImposterPreBake,- validateImposterSidecar,- bakeAnimatedImposter,- enumerateOctahedralGrid,- openAnimatedImposterSession,- NpcCharacterPackManifestSchema,- validateNpcCharacterPack,-} from './imposter';--// =============================================================================-// Top-level `generate()` - the full pipeline: prompt -> code -> GLB-// =============================================================================--export interface KilnGenerateOptions {- /** Spike supports glb only. Ignored if set otherwise. */- mode?: 'glb';- category?: 'character' | 'prop' | 'vfx' | 'environment' | 'architecture';- style?: 'low-poly' | 'stylized' | 'voxel' | 'detailed' | 'realistic';- referenceImageUrl?: string;- /**- * Whether to ask the LLM to emit an animate() function. Defaults to true to- * match the server's behavior.- */- includeAnimation?: boolean;- /**- * Abort milliseconds for the underlying single-shot SDK query. Defaults to- * 720_000 (12 min). Ignored by the default 'agent' path (the tool loop manages- * its own timeouts).- */- timeoutMs?: number;- /**- * Override the code model. In the default 'agent' path this is a Strands model- * id (e.g. 'google:gemini-3.5-flash', 'anthropic:claude-opus-4-8'); in the- * 'single-shot' fallback it is the Claude/harness model id.- */- model?: string;- /**- * Codegen mechanism. 'agent' (default) drives the Strands tool loop- * (list -> validate -> render -> submit, Gemini 3.5 Flash default, self-- * correcting on render metrics); 'single-shot' uses the legacy emit-and-render- * path. Falls back to the `KILN_CODEGEN` env var, then 'agent'.- */- codegen?: 'agent' | 'single-shot';- /**- * Also rasterize the final asset into the six-view grid PNG (`output.views`)- * for sidecars / review UIs. Best-effort; agent codegen path only.- */- captureViews?: boolean;- /** Style anchor: a complete Kiln program rendered as "## Reference Asset"- * (fresh generation only). ~5-15k input tokens/run; mostly prompt-cached. */- exemplarCode?: string;-}--export interface KilnGenerateOutput {- /** The JS code the LLM produced. */- code: string;- /** Rendered GLB, ready to write to disk. */- glb: Buffer;- /** Extracted from the code's `const meta = {...}` block, plus `tris`. */- meta: KilnCodeMeta;- /** Non-fatal issues (e.g. animation target missing). */- warnings: string[];- /** Resolved Strands provider (agent path only) - for honest provenance. */- provider?: string;- /** Resolved concrete model id (agent path only) - for honest provenance. */- model?: string;- /** Tools the agent called, in order (agent path only). */- toolCalls?: string[];- /** Number of agent-loop iterations (agent path only). */- steps?: number;- /** Six-view grid PNG (only when `captureViews` was set; agent path only). */- views?: Buffer;-}---/**- * End-to-end Kiln generation: prompt -> code -> rendered GLB.- *- * Default path is the Strands agent tool loop (Gemini 3.5 Flash); set- * `codegen: 'single-shot'` or `KILN_CODEGEN=single-shot` for the legacy- * emit-and-render fallback. Throws on any hard failure (LLM error, invalid code,- * render failure); non-fatal issues surface via `warnings`.- */-export async function generate(- prompt: string,- opts: KilnGenerateOptions = {}-): Promise<KilnGenerateOutput> {- const category = opts.category ?? 'prop';-- // Default: the Strands agent tool loop. Imported lazily so @strands-agents/sdk- // never enters the non-agent core module graph (browser/editor bundle safety).- if (resolveCodegenMode(opts.codegen) === 'agent') {- const { generateKilnAsset } = await import('./agent/generate');- const r = await generateKilnAsset({- prompt,- category,- includeAnimation: opts.includeAnimation ?? true,- ...(opts.style ? { style: opts.style } : {}),- ...(opts.model ? { model: opts.model } : {}),- ...(opts.captureViews ? { captureViews: true } : {}),- ...(opts.exemplarCode ? { exemplarCode: opts.exemplarCode } : {}),- });- return {- code: r.code,- glb: r.glb,- meta: r.meta,- warnings: r.warnings,- provider: r.provider,- model: r.model,- toolCalls: r.toolCalls,- steps: r.steps,- ...(r.views ? { views: r.views } : {}),- };- }-- // Fallback (KILN_CODEGEN=single-shot): legacy emit-and-render.- const genResult = await generateKilnCode(- {- prompt,- mode: 'glb',- category,- style: opts.style,- includeAnimation: opts.includeAnimation ?? true,- referenceImageUrl: opts.referenceImageUrl,- },- {- timeoutMs: opts.timeoutMs,- model: opts.model,- }- );-- if (!genResult.success || !genResult.code) {- throw new Error(`Kiln code generation failed: ${genResult.error ?? 'unknown error'}`);- }-- const render = await renderGLB(genResult.code);-- return {- code: genResult.code,- glb: render.glb,- meta: render.meta,- warnings: render.warnings,- };-}diff --git a/src/lod/__tests__/generate.test.ts b/src/lod/__tests__/generate.test.tsdeleted file mode 100644index c866b87f..00000000--- a/src/lod/__tests__/generate.test.ts+++ /dev/null@@ -1,66 +0,0 @@-/**- * LOD chain generator tests — uses a trivial procedural mesh so the suite- * stays fast and offline.- */--import { describe, expect, test } from 'bun:test';-import * as THREE from 'three';--import { renderSceneToGLB } from '../../render';-import { generateLODChain } from '../generate';--// Build a small GLB fixture with ~1000 triangles — enough for meshopt to bite.-async function makeFixture(segments = 32): Promise<Buffer> {- const root = new THREE.Group();- root.name = 'Fixture';- const geom = new THREE.SphereGeometry(1, segments, segments);- const mat = new THREE.MeshStandardMaterial({ color: 0x00aa66 });- const mesh = new THREE.Mesh(geom, mat);- mesh.name = 'Sphere';- root.add(mesh);-- const { bytes } = await renderSceneToGLB(root, {});- return Buffer.from(bytes);-}--describe('generateLODChain', () => {- test('default ratios produce 4 levels with descending tri counts', async () => {- const fixture = await makeFixture(32);- const result = await generateLODChain(fixture);-- expect(result.lods).toHaveLength(4);- expect(result.source.triangles).toBeGreaterThan(1000);-- // LOD0 preserves the source exactly (ratio = 1.0).- expect(result.lods[0]!.ratio).toBe(1.0);- expect(result.lods[0]!.triangles).toBe(result.source.triangles);-- // Each subsequent LOD has strictly fewer triangles.- for (let i = 1; i < result.lods.length; i++) {- expect(result.lods[i]!.triangles).toBeLessThan(result.lods[i - 1]!.triangles);- }-- // All level GLBs are valid binary (glTF magic = 0x46546C67 "glTF").- for (const lod of result.lods) {- expect(lod.glb.readUInt32LE(0)).toBe(0x46546c67);- expect(lod.bytes).toBe(lod.glb.byteLength);- }- }, 60_000);-- test('custom ratios honored', async () => {- const fixture = await makeFixture(24);- const result = await generateLODChain(fixture, { ratios: [1.0, 0.2] });- expect(result.lods).toHaveLength(2);- expect(result.lods[0]!.ratio).toBe(1.0);- expect(result.lods[1]!.ratio).toBe(0.2);- // 20% target should leave far fewer than the source tris.- expect(result.lods[1]!.triangles).toBeLessThan(result.source.triangles * 0.6);- }, 60_000);-- test('ratio = 1.0 is a pass-through (no simplification)', async () => {- const fixture = await makeFixture(16);- const result = await generateLODChain(fixture, { ratios: [1.0] });- expect(result.lods).toHaveLength(1);- expect(result.lods[0]!.triangles).toBe(result.source.triangles);- }, 30_000);-});diff --git a/src/lod/generate.ts b/src/lod/generate.tsdeleted file mode 100644index 02fa9a66..00000000--- a/src/lod/generate.ts+++ /dev/null@@ -1,125 +0,0 @@-/**- * LOD chain generator — meshoptimizer-backed decimation.- *- * Produces N simplified copies of a source GLB at descending tri ratios.- * Each level is returned as its own Buffer so the caller can write them as- * `lod0.glb`, `lod1.glb`, ... per the TIJ pipeline's directory contract.- *- * Pipeline per level:- * 1. Re-read source GLB (fresh Document — transforms are destructive).- * 2. weld() — collapse duplicate verts so simplify has something to collapse.- * 3. simplify() with the requested ratio + error threshold.- * 4. prune() — remove unused accessors/textures the simplifier orphaned.- * 5. dedup() — merge identical materials, textures, accessors.- *- * Skinned (rigged) meshes: simplify preserves JOINTS_0 / WEIGHTS_0 vertex- * attributes, so bone animation continues to work. Animations are unchanged- * because the skeleton node graph is untouched. Quality at ratios ≤ 0.1 on- * characters can degrade silhouette — the gallery is the final arbiter.- */--import { readFileSync } from 'node:fs';-import { Buffer } from 'node:buffer';--import { NodeIO, type Document } from '@gltf-transform/core';-import { simplify, weld, prune, dedup } from '@gltf-transform/functions';-import { MeshoptSimplifier } from 'meshoptimizer';--export interface GenerateLODChainOptions {- /** Target ratios of vertices to keep, one per LOD level. Default [1.0, 0.5, 0.25, 0.1]. */- ratios?: number[];- /** Max permitted error as a fraction of mesh radius. Default 0.01. */- errorThreshold?: number;- /** Lock topological borders — use for tiled terrain. Default false. */- lockBorder?: boolean;-}--export interface LODLevel {- /** Index in the chain (0 = highest detail, N-1 = lowest). */- level: number;- /** Target ratio passed to meshopt. */- ratio: number;- /** Serialized GLB bytes for this level. */- glb: Buffer;- /** Total triangle count in this level (post-decimation). */- triangles: number;- /** Byte length of the GLB. */- bytes: number;-}--export interface GenerateLODChainResult {- lods: LODLevel[];- source: {- triangles: number;- bytes: number;- };-}--export async function generateLODChain(- input: Buffer | string,- opts: GenerateLODChainOptions = {},-): Promise<GenerateLODChainResult> {- const ratios = opts.ratios ?? [1.0, 0.5, 0.25, 0.1];- const errorThreshold = opts.errorThreshold ?? 0.01;- const lockBorder = opts.lockBorder ?? false;-- // meshoptimizer ships WASM — gate on ready before first use.- await MeshoptSimplifier.ready;-- const io = new NodeIO();- const srcBuf = typeof input === 'string' ? readFileSync(input) : input;- const srcDoc = await io.readBinary(srcBuf);- const srcTris = countTriangles(srcDoc);-- const lods: LODLevel[] = [];- for (let level = 0; level < ratios.length; level++) {- const ratio = ratios[level]!;- // Fresh Document per level — @gltf-transform transforms mutate in place.- const doc = await io.readBinary(srcBuf);-- if (ratio < 1.0) {- await doc.transform(- weld(),- simplify({- simplifier: MeshoptSimplifier,- ratio,- error: errorThreshold,- lockBorder,- }),- prune(),- dedup(),- );- }-- const bytes = await io.writeBinary(doc);- const glb = Buffer.from(bytes);- lods.push({- level,- ratio,- glb,- triangles: countTriangles(doc),- bytes: glb.byteLength,- });- }-- return {- lods,- source: { triangles: srcTris, bytes: srcBuf.byteLength },- };-}--export function countTriangles(doc: Document): number {- let tris = 0;- for (const mesh of doc.getRoot().listMeshes()) {- for (const prim of mesh.listPrimitives()) {- const index = prim.getIndices();- if (index) {- tris += index.getCount() / 3;- } else {- const pos = prim.getAttribute('POSITION');- if (pos) tris += pos.getCount() / 3;- }- }- }- return Math.round(tris);-}diff --git a/src/lod/index.ts b/src/lod/index.tsdeleted file mode 100644index 9b305bb2..00000000--- a/src/lod/index.ts+++ /dev/null@@ -1,16 +0,0 @@-/**- * kiln/lod — meshopt-backed LOD chain generator.- *- * import { kiln } from '@pixel-forge/core';- * const { lods, source } = await kiln.generateLODChain(glb, {- * ratios: [1.0, 0.5, 0.25, 0.1],- * });- * for (const lod of lods) writeFileSync(`lod${lod.level}.glb`, lod.glb);- */--export { generateLODChain, countTriangles } from './generate';-export type {- GenerateLODChainOptions,- GenerateLODChainResult,- LODLevel,-} from './generate';diff --git a/src/photogrammetry/__tests__/cleanup.test.ts b/src/photogrammetry/__tests__/cleanup.test.tsdeleted file mode 100644index 74338939..00000000--- a/src/photogrammetry/__tests__/cleanup.test.ts+++ /dev/null@@ -1,48 +0,0 @@-/**- * Photogrammetry cleanup — verifies the simplify + texture-compress pipeline- * on a high-poly procedural fixture (a 64-segment sphere ~= 8k tris).- */--import { describe, expect, test } from 'bun:test';-import { Buffer } from 'node:buffer';-import * as THREE from 'three';--import { renderSceneToGLB } from '../../render';-import { cleanupPhotogrammetry } from '../cleanup';--async function makeHighPolyFixture(segments = 64): Promise<Buffer> {- const root = new THREE.Group();- root.name = 'ScanFixture';- const geom = new THREE.SphereGeometry(1, segments, segments);- const mat = new THREE.MeshStandardMaterial({ color: 0x88aa88 });- const mesh = new THREE.Mesh(geom, mat);- root.add(mesh);- const { bytes } = await renderSceneToGLB(root, {});- return Buffer.from(bytes);-}--describe('cleanupPhotogrammetry', () => {- test('decimates to near the target triangle budget', async () => {- const fixture = await makeHighPolyFixture(64);- const result = await cleanupPhotogrammetry(fixture, {- targetTriangles: 2000,- textureSize: 512,- errorThreshold: 0.05,- });- expect(result.meta.sourceTriangles).toBeGreaterThan(5000);- expect(result.meta.targetTriangles).toBeLessThan(result.meta.sourceTriangles);- // GLB magic.- expect(result.glb.readUInt32LE(0)).toBe(0x46546c67);- }, 60_000);-- test('no-op when source is already below target', async () => {- const fixture = await makeHighPolyFixture(8); // ~100 tris- const result = await cleanupPhotogrammetry(fixture, {- targetTriangles: 10_000,- textureSize: 256,- });- expect(result.meta.ratio).toBe(1);- // No decimation requested — tri count stays the same.- expect(result.meta.targetTriangles).toBe(result.meta.sourceTriangles);- }, 30_000);-});diff --git a/src/photogrammetry/cleanup.ts b/src/photogrammetry/cleanup.tsdeleted file mode 100644index 9c42c8a7..00000000--- a/src/photogrammetry/cleanup.ts+++ /dev/null@@ -1,103 +0,0 @@-/**- * Photogrammetry cleanup — preset composition for raw scans.- *- * Poly Haven tier-C plants come in at 50k–300k triangles with 2K–4K PBR- * texture stacks. That's fine for offline imposter bakes but unusable as- * runtime geometry. This module collapses them to a bake-ready state:- *- * 1. weld — merge coincident verts.- * 2. simplify — meshopt decimation to a target triangle budget.- * 3. textureCompress — resize diffuse/normal/roughness to <=1K, encode PNG.- * 4. dedup + prune — drop anything orphaned by the above.- *- * Gated per proposal §P6 — only run when tier-C quality beats the Poly Pizza- * shortlist in the validation gallery. For Poly Pizza sources, skip this- * module entirely; they're already sub-5k-tri PSX-style meshes.- */--import { Buffer } from 'node:buffer';-import { readFileSync } from 'node:fs';--import { NodeIO } from '@gltf-transform/core';-import { dedup, prune, simplify, textureCompress, weld } from '@gltf-transform/functions';-import { MeshoptSimplifier } from 'meshoptimizer';-import sharp from 'sharp';--import { countTriangles } from '../lod/generate';--export interface CleanupPhotogrammetryOptions {- /** Target post-decimation triangle count. Default 10000. */- targetTriangles?: number;- /** Max texture dimension (w = h). Default 1024. */- textureSize?: number;- /**- * Max permitted error as a fraction of mesh radius. Higher tolerates more- * distortion — photogrammetry is noisy so 0.02 is a safe default.- */- errorThreshold?: number;-}--export interface CleanupPhotogrammetryResult {- glb: Buffer;- meta: {- sourceTriangles: number;- targetTriangles: number;- ratio: number;- textureSize: number;- sourceBytes: number;- bytes: number;- };-}--export async function cleanupPhotogrammetry(- input: Buffer | string,- opts: CleanupPhotogrammetryOptions = {},-): Promise<CleanupPhotogrammetryResult> {- const targetTris = opts.targetTriangles ?? 10_000;- const textureSize = opts.textureSize ?? 1024;- const errorThreshold = opts.errorThreshold ?? 0.02;-- await MeshoptSimplifier.ready;-- const io = new NodeIO();- const srcBuf = typeof input === 'string' ? readFileSync(input) : input;- const doc = await io.readBinary(srcBuf);- const srcTris = countTriangles(doc);-- // Compute the ratio to hit targetTris. If source is already smaller, skip- // decimation (ratio = 1.0 is a no-op).- const ratio = srcTris > 0 ? Math.min(1, targetTris / srcTris) : 1;-- await doc.transform(- weld(),- simplify({- simplifier: MeshoptSimplifier,- ratio,- error: errorThreshold,- lockBorder: false,- }),- textureCompress({- encoder: sharp,- targetFormat: 'png',- resize: [textureSize, textureSize],- }),- dedup(),- prune(),- );-- const outBytes = await io.writeBinary(doc);- const glb = Buffer.from(outBytes);- const finalTris = countTriangles(doc);-- return {- glb,- meta: {- sourceTriangles: srcTris,- targetTriangles: finalTris,- ratio,- textureSize,- sourceBytes: srcBuf.byteLength,- bytes: glb.byteLength,- },- };-}diff --git a/src/photogrammetry/index.ts b/src/photogrammetry/index.tsdeleted file mode 100644index 758f3bc6..00000000--- a/src/photogrammetry/index.ts+++ /dev/null@@ -1,15 +0,0 @@-/**- * kiln/photogrammetry — cleanup pass for raw photogrammetry GLBs.- *- * import { kiln } from '@pixel-forge/core';- * const { glb, meta } = await kiln.cleanupPhotogrammetry(scanGlb, {- * targetTriangles: 8000,- * textureSize: 1024,- * });- */--export { cleanupPhotogrammetry } from './cleanup';-export type {- CleanupPhotogrammetryOptions,- CleanupPhotogrammetryResult,-} from './cleanup';diff --git a/src/retex/__tests__/retex.test.ts b/src/retex/__tests__/retex.test.tsdeleted file mode 100644index 2a52da35..00000000--- a/src/retex/__tests__/retex.test.ts+++ /dev/null@@ -1,97 +0,0 @@-/**- * Retex tests — builds a procedural GLB with one textured material, swaps the- * diffuse, and verifies the output GLB carries the new bytes.- */--import { describe, expect, test } from 'bun:test';-import { Buffer } from 'node:buffer';-import sharp from 'sharp';-import * as THREE from 'three';--import { NodeIO } from '@gltf-transform/core';--import { renderSceneToGLB } from '../../render';-import { retexCharacter } from '../retex';--async function solid(w: number, h: number, rgb: [number, number, number]): Promise<Buffer> {- return sharp({- create: { width: w, height: h, channels: 4, background: { r: rgb[0], g: rgb[1], b: rgb[2], alpha: 1 } },- })- .png()- .toBuffer();-}--async function makeFixture(): Promise<Buffer> {- const root = new THREE.Group();- root.name = 'TexturedCube';- const geom = new THREE.BoxGeometry(1, 1, 1);- const mat = new THREE.MeshStandardMaterial({ color: 0xffffff });- mat.name = 'CharacterAtlas';- // DataTexture works headlessly — no HTMLImageElement needed.- const data = new Uint8Array(4 * 4 * 4);- for (let i = 0; i < data.length; i += 4) {- data[i] = 200;- data[i + 1] = 180;- data[i + 2] = 100;- data[i + 3] = 255;- }- const dataTex = new THREE.DataTexture(data, 4, 4, THREE.RGBAFormat);- dataTex.needsUpdate = true;- mat.map = dataTex;- const mesh = new THREE.Mesh(geom, mat);- root.add(mesh);-- const { bytes } = await renderSceneToGLB(root, {});- return Buffer.from(bytes);-}--describe('retexCharacter', () => {- test('swaps the first material\'s base-color texture', async () => {- const fixture = await makeFixture();- const newDiffuse = await solid(32, 32, [50, 150, 50]); // OG-107-ish- const result = await retexCharacter(fixture, {- diffuse: newDiffuse,- presetName: 'OG-107-jungle',- });- expect(result.glb.readUInt32LE(0)).toBe(0x46546c67);- expect(result.meta.materialIndex).toBe(0);- expect(result.meta.presetName).toBe('OG-107-jungle');- expect(result.meta.sourceBytes).toBe(fixture.byteLength);-- // Verify the new texture is in the output GLB by re-reading it.- const io = new NodeIO();- const doc = await io.readBinary(result.glb);- const textures = doc.getRoot().listTextures();- expect(textures.length).toBeGreaterThanOrEqual(1);- const diffuseImg = textures[0]!.getImage();- expect(diffuseImg).toBeTruthy();- // The embedded texture size should match the new diffuse, not the original 4x4.- expect(diffuseImg!.length).toBe(newDiffuse.length);- });-- test('selects material by name', async () => {- const fixture = await makeFixture();- const newDiffuse = await solid(16, 16, [10, 10, 10]);- const result = await retexCharacter(fixture, {- diffuse: newDiffuse,- materialName: 'CharacterAtlas',- });- expect(result.meta.materialName).toBe('CharacterAtlas');- });-- test('throws on unknown material name', async () => {- const fixture = await makeFixture();- const newDiffuse = await solid(16, 16, [10, 10, 10]);- await expect(- retexCharacter(fixture, { diffuse: newDiffuse, materialName: 'NoSuchMaterial' }),- ).rejects.toThrow(/no material named/);- });-- test('throws on out-of-bounds materialIndex', async () => {- const fixture = await makeFixture();- const newDiffuse = await solid(16, 16, [10, 10, 10]);- await expect(- retexCharacter(fixture, { diffuse: newDiffuse, materialIndex: 99 }),- ).rejects.toThrow(/out of bounds/);- });-});diff --git a/src/retex/index.ts b/src/retex/index.tsdeleted file mode 100644index 2e4d2cdd..00000000--- a/src/retex/index.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * kiln/retex — character diffuse-texture swap (faction retex).- *- * import { kiln } from '@pixel-forge/core';- * const { glb, meta } = await kiln.retexCharacter(sourceGlbBuffer, {- * diffuse: og107PngBuffer,- * presetName: 'OG-107-jungle',- * });- */--export { retexCharacter, FACTION_PRESETS } from './retex';-export type { RetexCharacterOptions, RetexCharacterResult, FactionPreset } from './retex';diff --git a/src/retex/retex.ts b/src/retex/retex.tsdeleted file mode 100644index f623d124..00000000--- a/src/retex/retex.ts+++ /dev/null@@ -1,131 +0,0 @@-/**- * Character retex — swap a GLB material's base-color texture.- *- * First-pass implementation focuses on the 99% case: Quaternius-style- * characters bake their whole outfit into one diffuse atlas on a single- * material. Swap that texture and the character gets a new uniform without- * touching UVs or vertex data. Region-aware LUT retex (separate skin vs- * uniform zones) is a future enhancement — deferred per proposal §P5 scope.- *- * For batch faction retex (OG-107, ERDL, tiger-stripe, khaki, black-pajama),- * the caller generates five preset diffuse PNGs once per base character (via- * the sprite pipeline or hand-authored) and feeds them through this function- * as `diffuse` buffers.- */--import { Buffer } from 'node:buffer';-import { readFileSync } from 'node:fs';--import { NodeIO, type Material } from '@gltf-transform/core';--export interface RetexCharacterOptions {- /** New base-color PNG bytes (or path to a PNG on disk). */- diffuse: Buffer | string;- /** Target material by its glTF name. First match wins. */- materialName?: string;- /**- * Target material by 0-based index in doc.listMaterials(). Ignored if- * materialName is set.- */- materialIndex?: number;- /**- * Label stored in the output meta for provenance (e.g. 'OG-107-jungle').- * Does not affect the GLB itself.- */- presetName?: string;-}--export interface RetexCharacterResult {- glb: Buffer;- meta: {- materialName: string;- materialIndex: number;- bytes: number;- sourceBytes: number;- presetName?: string;- };-}--export async function retexCharacter(- input: Buffer | string,- opts: RetexCharacterOptions,-): Promise<RetexCharacterResult> {- const srcBuf = typeof input === 'string' ? readFileSync(input) : input;- const diffuseBytes =- typeof opts.diffuse === 'string' ? readFileSync(opts.diffuse) : opts.diffuse;-- const io = new NodeIO();- const doc = await io.readBinary(srcBuf);- const materials = doc.getRoot().listMaterials();- if (!materials.length) {- throw new Error('retexCharacter: GLB has no materials to retex');- }-- const { material, index } = selectMaterial(materials, opts);-- // Reuse the existing base-color texture if present; otherwise create one.- let texture = material.getBaseColorTexture();- if (!texture) {- texture = doc.createTexture(`${material.getName() || 'mat'}_baseColor`);- material.setBaseColorTexture(texture);- }- texture.setImage(new Uint8Array(diffuseBytes));- texture.setMimeType('image/png');-- const outBytes = await io.writeBinary(doc);- const glb = Buffer.from(outBytes);-- return {- glb,- meta: {- materialName: material.getName(),- materialIndex: index,- bytes: glb.byteLength,- sourceBytes: srcBuf.byteLength,- ...(opts.presetName ? { presetName: opts.presetName } : {}),- },- };-}--function selectMaterial(- materials: Material[],- opts: RetexCharacterOptions,-): { material: Material; index: number } {- if (opts.materialName) {- const idx = materials.findIndex((m) => m.getName() === opts.materialName);- if (idx < 0) {- throw new Error(- `retexCharacter: no material named "${opts.materialName}" (available: ${materials- .map((m) => m.getName() || '(unnamed)')- .join(', ')})`,- );- }- return { material: materials[idx]!, index: idx };- }- if (typeof opts.materialIndex === 'number') {- const idx = opts.materialIndex;- if (idx < 0 || idx >= materials.length) {- throw new Error(- `retexCharacter: materialIndex ${idx} out of bounds (have ${materials.length})`,- );- }- return { material: materials[idx]!, index: idx };- }- // Default: first material (Quaternius pattern — one atlas per character).- return { material: materials[0]!, index: 0 };-}--/**- * Known faction preset names. These are labels for provenance — this module- * does NOT ship the baked diffuse PNGs; the caller provides them. Presets- * are expected to be generated by the sprite pipeline once per base model- * and cached alongside the source GLB.- */-export const FACTION_PRESETS = [- 'OG-107-jungle',- 'ERDL-leaf',- 'tiger-stripe',- 'khaki-plain',- 'black-pajama',-] as const;-export type FactionPreset = (typeof FACTION_PRESETS)[number];diff --git a/src/sprite-atlas/__tests__/pack.test.ts b/src/sprite-atlas/__tests__/pack.test.tsdeleted file mode 100644index bb1be84f..00000000--- a/src/sprite-atlas/__tests__/pack.test.ts+++ /dev/null@@ -1,123 +0,0 @@-/**- * Sprite atlas packer tests — generates RGBA fixtures via sharp, then verifies- * frame placement, overlap, and POT sizing.- */--import { describe, expect, test } from 'bun:test';-import { Buffer } from 'node:buffer';-import sharp from 'sharp';--import { packSpriteAtlas } from '../pack';-import { SpriteFrameTableSchema } from '../schema';--async function solid(w: number, h: number, rgb: [number, number, number]): Promise<Buffer> {- return sharp({- create: {- width: w,- height: h,- channels: 4,- background: { r: rgb[0], g: rgb[1], b: rgb[2], alpha: 1 },- },- })- .png()- .toBuffer();-}--describe('packSpriteAtlas', () => {- test('packs 10 equal-size sprites with no overlap', async () => {- const sprites = await Promise.all(- Array.from({ length: 10 }, async (_unused, i) => ({- name: `sprite-${i}`,- data: await solid(32, 32, [i * 20, 80, 200]),- })),- );- const result = await packSpriteAtlas(sprites, { padding: 2, pot: true });-- expect(result.frames.frames).toHaveLength(10);- expect(() => SpriteFrameTableSchema.parse(result.frames)).not.toThrow();-- // Atlas is a valid PNG.- expect(result.atlas.subarray(0, 4).toString('hex')).toBe('89504e47');-- // No two frames overlap.- const fs = result.frames.frames;- for (let i = 0; i < fs.length; i++) {- for (let j = i + 1; j < fs.length; j++) {- const a = fs[i]!;- const b = fs[j]!;- const overlap = !(a.x + a.w <= b.x || b.x + b.w <= a.x || a.y + a.h <= b.y || b.y + b.h <= a.y);- expect(overlap).toBe(false);- }- }-- // All frames fit inside the atlas.- for (const f of fs) {- expect(f.x + f.w).toBeLessThanOrEqual(result.frames.atlasWidth);- expect(f.y + f.h).toBeLessThanOrEqual(result.frames.atlasHeight);- }-- // Atlas is power-of-two.- expect(isPot(result.frames.atlasWidth)).toBe(true);- expect(isPot(result.frames.atlasHeight)).toBe(true);- });-- test('preserves input order in the frame table', async () => {- const sprites = [- { name: 'tall', data: await solid(16, 64, [255, 0, 0]) },- { name: 'wide', data: await solid(128, 16, [0, 255, 0]) },- { name: 'small', data: await solid(8, 8, [0, 0, 255]) },- ];- const result = await packSpriteAtlas(sprites);- expect(result.frames.frames.map((f) => f.name)).toEqual(['tall', 'wide', 'small']);- });-- test('respects maxSize — throws when nothing fits', async () => {- await expect(- packSpriteAtlas([{ name: 'giant', data: await solid(512, 512, [0, 0, 0]) }], {- maxSize: 1024,- padding: 0,- pot: false,- }),- ).resolves.toBeTruthy();- await expect(- packSpriteAtlas(- [- { name: 'a', data: await solid(900, 900, [0, 0, 0]) },- { name: 'b', data: await solid(900, 900, [0, 0, 0]) },- ],- { maxSize: 1024, padding: 0, pot: false },- ),- ).rejects.toThrow(/ran out of atlas room/);- });-- test('rejects a sprite larger than maxSize', async () => {- await expect(- packSpriteAtlas([{ name: 'huge', data: await solid(600, 600, [0, 0, 0]) }], {- maxSize: 1024,- padding: 0,- pot: false,- }),- ).resolves.toBeTruthy();- await expect(- packSpriteAtlas([{ name: 'huge', data: await solid(1200, 1200, [0, 0, 0]) }], {- maxSize: 1024,- }),- ).rejects.toThrow(/larger than maxSize/);- });-- test('padding increases spacing between frames', async () => {- const sprites = [- { name: 'a', data: await solid(32, 32, [255, 0, 0]) },- { name: 'b', data: await solid(32, 32, [0, 255, 0]) },- ];- const noPad = await packSpriteAtlas(sprites, { padding: 0, pot: false });- const padded = await packSpriteAtlas(sprites, { padding: 8, pot: false });- const gapNo = noPad.frames.frames[1]!.x - (noPad.frames.frames[0]!.x + noPad.frames.frames[0]!.w);- const gapPad = padded.frames.frames[1]!.x - (padded.frames.frames[0]!.x + padded.frames.frames[0]!.w);- expect(gapPad).toBeGreaterThan(gapNo);- });-});--function isPot(n: number): boolean {- return n > 0 && (n & (n - 1)) === 0;-}diff --git a/src/sprite-atlas/index.ts b/src/sprite-atlas/index.tsdeleted file mode 100644index 77cd567a..00000000--- a/src/sprite-atlas/index.ts+++ /dev/null@@ -1,23 +0,0 @@-/**- * kiln/sprite-atlas — shelf-packed sprite atlases with JSON frame tables.- *- * import { kiln } from '@pixel-forge/core';- * const { atlas, frames } = await kiln.packSpriteAtlas(- * [{ name: 'fern-01', data: pngBuf }, ...],- * { maxSize: 2048, padding: 2, pot: true }- * );- */--export { packSpriteAtlas } from './pack';-export type {- PackSpriteAtlasInput,- PackSpriteAtlasOptions,- PackSpriteAtlasResult,-} from './pack';--export {- SPRITE_ATLAS_SCHEMA_VERSION,- SpriteFrameSchema,- SpriteFrameTableSchema,-} from './schema';-export type { SpriteFrame, SpriteFrameTable } from './schema';diff --git a/src/sprite-atlas/pack.ts b/src/sprite-atlas/pack.tsdeleted file mode 100644index ac09db0d..00000000--- a/src/sprite-atlas/pack.ts+++ /dev/null@@ -1,169 +0,0 @@-/**- * Sprite atlas packer — shelf algorithm.- *- * Sorts sprites by descending height, places them in horizontal shelves- * (rows). Not the densest packing possible (MaxRects would be ~10% tighter),- * but simple, deterministic, and fast. For <500 sprites at typical game-asset- * sizes this leaves plenty of atlas headroom.- *- * Output is a single RGBA PNG plus a JSON frame table.- */--import { Buffer } from 'node:buffer';-import sharp from 'sharp';--import {- SPRITE_ATLAS_SCHEMA_VERSION,- type SpriteFrame,- type SpriteFrameTable,-} from './schema';--export interface PackSpriteAtlasInput {- /** Species / asset name — preserved into the frame table. */- name: string;- /** PNG or other sharp-readable bytes. */- data: Buffer;-}--export interface PackSpriteAtlasOptions {- /** Maximum atlas edge in pixels. Default 2048. */- maxSize?: 1024 | 2048 | 4096;- /** Transparent pixels between packed sprites. Default 2. */- padding?: number;- /** Force the final atlas to power-of-two dimensions. Default true. */- pot?: boolean;-}--export interface PackSpriteAtlasResult {- atlas: Buffer;- frames: SpriteFrameTable;-}--interface Prepared {- name: string;- buf: Buffer;- w: number;- h: number;- sourceWidth: number;- sourceHeight: number;-}--interface Placed extends Prepared {- x: number;- y: number;-}--export async function packSpriteAtlas(- sprites: PackSpriteAtlasInput[],- opts: PackSpriteAtlasOptions = {},-): Promise<PackSpriteAtlasResult> {- if (!sprites.length) {- throw new Error('packSpriteAtlas: at least one sprite is required');- }- const maxSize = opts.maxSize ?? 2048;- const padding = opts.padding ?? 2;- const pot = opts.pot ?? true;-- // Normalize input PNGs through sharp so downstream composite treats them uniformly.- const prepared: Prepared[] = await Promise.all(- sprites.map(async (s): Promise<Prepared> => {- const { data, info } = await sharp(s.data).ensureAlpha().toBuffer({ resolveWithObject: true });- return {- name: s.name,- buf: data,- w: info.width,- h: info.height,- sourceWidth: info.width,- sourceHeight: info.height,- };- }),- );-- // Sort by height descending — standard shelf heuristic.- const sorted = prepared.slice().sort((a, b) => b.h - a.h);-- // Shelf-pack.- const placed: Placed[] = [];- let shelfX = 0;- let shelfY = 0;- let shelfH = 0;- let atlasW = 0;- for (const s of sorted) {- const w = s.w + padding * 2;- const h = s.h + padding * 2;- if (w > maxSize || h > maxSize) {- throw new Error(- `packSpriteAtlas: sprite "${s.name}" (${s.w}×${s.h}) larger than maxSize ${maxSize}`,- );- }- if (shelfX + w > maxSize) {- shelfY += shelfH;- shelfX = 0;- shelfH = 0;- }- if (shelfY + h > maxSize) {- throw new Error(- `packSpriteAtlas: ran out of atlas room at sprite "${s.name}". ` +- `Increase maxSize (currently ${maxSize}) or split the input.`,- );- }- placed.push({ ...s, x: shelfX + padding, y: shelfY + padding });- shelfX += w;- shelfH = Math.max(shelfH, h);- atlasW = Math.max(atlasW, shelfX);- }- const atlasH = shelfY + shelfH;-- const finalW = pot ? nextPot(atlasW) : atlasW;- const finalH = pot ? nextPot(atlasH) : atlasH;-- const composites: sharp.OverlayOptions[] = placed.map((p) => ({- input: p.buf,- left: p.x,- top: p.y,- }));- const atlas = await sharp({- create: {- width: finalW,- height: finalH,- channels: 4,- background: { r: 0, g: 0, b: 0, alpha: 0 },- },- })- .composite(composites)- .png()- .toBuffer();-- // Build the frame table in the INPUT order (not the packed order).- const byName = new Map(placed.map((p) => [p.name, p]));- const frames: SpriteFrame[] = sprites.map((s) => {- const p = byName.get(s.name);- if (!p) throw new Error(`packSpriteAtlas: missing placement for "${s.name}"`);- return {- name: s.name,- x: p.x,- y: p.y,- w: p.w,- h: p.h,- sourceWidth: p.sourceWidth,- sourceHeight: p.sourceHeight,- };- });-- return {- atlas,- frames: {- version: SPRITE_ATLAS_SCHEMA_VERSION,- atlasWidth: finalW,- atlasHeight: finalH,- padding,- frames,- },- };-}--function nextPot(n: number): number {- let p = 1;- while (p < n) p *= 2;- return p;-}diff --git a/src/sprite-atlas/schema.ts b/src/sprite-atlas/schema.tsdeleted file mode 100644index 1223a27c..00000000--- a/src/sprite-atlas/schema.ts+++ /dev/null@@ -1,37 +0,0 @@-/**- * SpriteFrameTable — sidecar emitted alongside a packed sprite atlas.- *- * TIJ's GPUBillboardSystem reads either (frame) to render a single species- * or the full table to pick tiles by species name at runtime.- */--import { z } from 'zod';--export const SPRITE_ATLAS_SCHEMA_VERSION = 1 as const;--export const SpriteFrameSchema = z.object({- /** Species / asset name, matches the input entry. */- name: z.string(),- /** Top-left x in atlas pixels. */- x: z.number().int().nonnegative(),- /** Top-left y in atlas pixels. */- y: z.number().int().nonnegative(),- /** Width in atlas pixels (post-trim if trimming was enabled). */- w: z.number().int().positive(),- /** Height in atlas pixels. */- h: z.number().int().positive(),- /** Original (un-trimmed) width, useful for restoring layout on the consumer. */- sourceWidth: z.number().int().positive(),- /** Original un-trimmed height. */- sourceHeight: z.number().int().positive(),-});-export type SpriteFrame = z.infer<typeof SpriteFrameSchema>;--export const SpriteFrameTableSchema = z.object({- version: z.literal(SPRITE_ATLAS_SCHEMA_VERSION),- atlasWidth: z.number().int().positive(),- atlasHeight: z.number().int().positive(),- padding: z.number().int().nonnegative(),- frames: z.array(SpriteFrameSchema),-});-export type SpriteFrameTable = z.infer<typeof SpriteFrameTableSchema>;diff --git a/tsconfig.json b/tsconfig.jsonnew file mode 100644index 00000000..81601258--- /dev/null+++ b/tsconfig.json@@ -0,0 +1,26 @@+{+ "compilerOptions": {+ "lib": ["ESNext"],+ "types": ["bun"],+ "target": "ESNext",+ "module": "Preserve",+ "moduleDetection": "force",+ "allowJs": true,++ "moduleResolution": "bundler",+ "allowImportingTsExtensions": true,+ "verbatimModuleSyntax": true,+ "noEmit": true,++ "strict": true,+ "skipLibCheck": true,+ "noFallthroughCasesInSwitch": true,+ "noUncheckedIndexedAccess": true,+ "noImplicitOverride": true,++ "noUnusedLocals": false,+ "noUnusedParameters": false,+ "noPropertyAccessFromIndexSignature": false+ },+ "include": ["src/**/*.ts", "src/**/*.d.ts"]+}