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
Add editable and runtime asset export profiles (#116)
Matthew Kissinger764d0e320fa3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ce34b15d..b59b9f3e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,14 @@ GitHub. The package is not published on the npm registry.[qualification report](docs/evaluation/community-exporter.md). The candidate is not yetqualified to replace the default for all supported workflows.+## Unreleased: Saved-asset export profiles++- Keep byte-preserving `editable` exports as the default. Opt-in `runtime` exports+ move Kiln's duplicated scene review clips to a versioned, hash-linked sidecar,+ preserving standalone native glTF playback and the canonical saved revision.+ Available through the CLI, MCP and `@kiln/engine/asset-export` library entry.+ [Usage, provenance contract and limits](docs/export-profiles.md).+## 0.7.1: Preserve CLI outputs on failed writes- GLB, preview PNG, and generated source replacements are written to unique siblingdiff --git a/README.md b/README.mdindex f918d9c7..b2b01ef8 100644--- a/README.md+++ b/README.md@@ -170,6 +170,14 @@ Run `node kiln.mjs view` to browse **This project** and **Your library**, inspecand download GLBs or editable ZIP bundles. Both use the same portable collection format andthe same viewer. See [saved assets and the viewer](docs/collections.md).+For application delivery, export with `--profile runtime --out asset.glb` to move+Kiln's animation review metadata into a hash-linked JSON sidecar. Native glTF animation+still plays without that sidecar. The default `editable` profile preserves saved files+exactly; keep its ZIP for source and build records. The delivery profile is independent+of the established/experimental converter selected during generation.+[Which options to use, why they exist, and examples](docs/export-profiles.md#which-option-should-i-use)+are also included in the authoring and QA skills installed into new asset workspaces.+## Use Kiln in a chat clientCreate and refine assets in ChatGPT through a private MCP connection, then ask todiff --git a/dist/build.json b/dist/build.jsonindex 3ca38764..5d7a0676 100644--- a/dist/build.json+++ b/dist/build.json@@ -1,11 +1,11 @@{"schemaVersion": 1,"entries": {- "mcp": {- "identity": "sha256:413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8",+ "worker": {+ "identity": "sha256:880a8a0108f54e052c288c468745267d552fa98cb201cc03e82cd06180485480","engineVersion": "0.7.1","toolchain": "[email protected]",- "sourceHash": "767ffb8182f45dc2315a23673908397a2d492d40fe2d0ccf53151926e750e93b",+ "sourceHash": "473f464e372a97ef0cd14bd66c982c6a6b67c78589d5322d1c9f830a029fe91b","dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc","dependencies": {"@gltf-transform/core": "4.5.0",@@ -27,14 +27,14 @@"zod": "^4.6.4"},"target": "node",- "file": "mcp-server.mjs",- "bundleHash": "sha256:9a32a2dcd15e237ad0ad10aeb0c389d436a569cda70d5793cf243ab63cc86b34"+ "file": "evaluator-worker.mjs",+ "bundleHash": "sha256:791ac0f53486e31487bf731a24be45e74048436cec203d3d25c9df8343de374f"},- "cli": {- "identity": "sha256:413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8",+ "agent-run": {+ "identity": "sha256:880a8a0108f54e052c288c468745267d552fa98cb201cc03e82cd06180485480","engineVersion": "0.7.1","toolchain": "[email protected]",- "sourceHash": "767ffb8182f45dc2315a23673908397a2d492d40fe2d0ccf53151926e750e93b",+ "sourceHash": "473f464e372a97ef0cd14bd66c982c6a6b67c78589d5322d1c9f830a029fe91b","dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc","dependencies": {"@gltf-transform/core": "4.5.0",@@ -56,14 +56,14 @@"zod": "^4.6.4"},"target": "node",- "file": "cli.mjs",- "bundleHash": "sha256:9e7e7fc81233f4bb34584eabfa5a82a82f5c0f636965ec0f3b78872df5c539ed"+ "file": "agent-run.mjs",+ "bundleHash": "sha256:4bbdfa2c89ce3f25cfb829be3aba0ff6ce5bf9c33a77a33355754af421935fad"},- "worker": {- "identity": "sha256:413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8",+ "agent-providers": {+ "identity": "sha256:880a8a0108f54e052c288c468745267d552fa98cb201cc03e82cd06180485480","engineVersion": "0.7.1","toolchain": "[email protected]",- "sourceHash": "767ffb8182f45dc2315a23673908397a2d492d40fe2d0ccf53151926e750e93b",+ "sourceHash": "473f464e372a97ef0cd14bd66c982c6a6b67c78589d5322d1c9f830a029fe91b","dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc","dependencies": {"@gltf-transform/core": "4.5.0",@@ -85,14 +85,14 @@"zod": "^4.6.4"},"target": "node",- "file": "evaluator-worker.mjs",- "bundleHash": "sha256:791ac0f53486e31487bf731a24be45e74048436cec203d3d25c9df8343de374f"+ "file": "agent-providers.mjs",+ "bundleHash": "sha256:fb2295599724eaa739ef31919eccae0ff6adece4c36b6886863eb7eeacb35650"},- "agent-run": {- "identity": "sha256:413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8",+ "mcp": {+ "identity": "sha256:880a8a0108f54e052c288c468745267d552fa98cb201cc03e82cd06180485480","engineVersion": "0.7.1","toolchain": "[email protected]",- "sourceHash": "767ffb8182f45dc2315a23673908397a2d492d40fe2d0ccf53151926e750e93b",+ "sourceHash": "473f464e372a97ef0cd14bd66c982c6a6b67c78589d5322d1c9f830a029fe91b","dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc","dependencies": {"@gltf-transform/core": "4.5.0",@@ -114,14 +114,14 @@"zod": "^4.6.4"},"target": "node",- "file": "agent-run.mjs",- "bundleHash": "sha256:4bbdfa2c89ce3f25cfb829be3aba0ff6ce5bf9c33a77a33355754af421935fad"+ "file": "mcp-server.mjs",+ "bundleHash": "sha256:30e17cb877559a28338cbfa5c0044bfa4a7520e0060f3f975705ec177799a992"},- "agent-providers": {- "identity": "sha256:413501ff069d991b8be09cdbabc57c8ca2333179bc67288e2c33eca586959ef8",+ "cli": {+ "identity": "sha256:880a8a0108f54e052c288c468745267d552fa98cb201cc03e82cd06180485480","engineVersion": "0.7.1","toolchain": "[email protected]",- "sourceHash": "767ffb8182f45dc2315a23673908397a2d492d40fe2d0ccf53151926e750e93b",+ "sourceHash": "473f464e372a97ef0cd14bd66c982c6a6b67c78589d5322d1c9f830a029fe91b","dependencyHash": "363701eaf4938fc8f46405e6e92d0b36e218439c548b2427da0468edcc78a3dc","dependencies": {"@gltf-transform/core": "4.5.0",@@ -143,8 +143,8 @@"zod": "^4.6.4"},"target": "node",- "file": "agent-providers.mjs",- "bundleHash": "sha256:fb2295599724eaa739ef31919eccae0ff6adece4c36b6886863eb7eeacb35650"+ "file": "cli.mjs",+ "bundleHash": "sha256:e052c3176f9524546dc5fa6ad23578fa92fd56201a91c7860b792194484235d6"}}}diff --git a/dist/cli.mjs b/dist/cli.mjsindex fe35e00a..fdd25848 100644--- a/dist/cli.mjs+++ b/dist/cli.mjs@@ -30,6 +30,7 @@ import { randomUUID } from "node:crypto";import {chmod,lstat,+ link,mkdir,open,realpath,@@ -38,7 +39,7 @@ import {unlink,writeFile} from "node:fs/promises";-import { dirname, join } from "node:path";+import { dirname, join, resolve } from "node:path";async function prepareDestination(path) {await mkdir(dirname(path), { recursive: true });return path;@@ -73,6 +74,46 @@ async function writeDestinationAtomic(path, data) {await unlink(temporary).catch(() => {});}}+async function writeNewDestinationsAtomic(outputs) {+ const paths = outputs.map(({ path }) => {+ const absolute = resolve(path);+ return process.platform === "win32" ? absolute.toLowerCase() : absolute;+ });+ if (new Set(paths).size !== paths.length)+ throw new Error("Export destinations must be distinct");+ const staged = [];+ try {+ for (const { path, data } of outputs) {+ await prepareDestination(path);+ const temporary = join(dirname(path), `.kiln-write-${randomUUID()}.tmp`);+ const file = await open(temporary, "wx");+ staged.push({ path, temporary, published: false });+ try {+ await writeFile(file, data);+ } finally {+ await file.close();+ }+ }+ for (const output of staged) {+ await link(output.temporary, output.path);+ output.published = true;+ }+ } catch (error) {+ for (const output of staged.filter((item) => item.published).reverse()) {+ try {+ const [destination, temporary] = await Promise.all([+ lstat(output.path),+ lstat(output.temporary)+ ]);+ if (destination.dev === temporary.dev && destination.ino === temporary.ino)+ await unlink(output.path);+ } catch {}+ }+ throw error;+ } finally {+ await Promise.all(staged.map(({ temporary }) => unlink(temporary).catch(() => {})));+ }+}var init_cli_output = () => {};// src/evaluator/authoring-diagnostic.ts@@ -25822,9 +25863,9 @@ var init_program_store = __esm(() => {});// src/program-store-node.ts-import { link, lstat as lstat2, mkdir as mkdir2, readFile, readdir, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";+import { link as link2, lstat as lstat2, mkdir as mkdir2, readFile, readdir, stat as stat2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";import { randomUUID as randomUUID2 } from "node:crypto";-import { join as join3, resolve as resolve2 } from "node:path";+import { join as join3, resolve as resolve3 } from "node:path";class FileProgramStore {directory;@@ -25907,7 +25948,7 @@ class FileProgramStore {await writeFile2(temporary, ref, { encoding: "utf8", flag: "wx", mode: 384 });try {try {- await link(temporary, join3(directory, `${handle}.ref`));+ await link2(temporary, join3(directory, `${handle}.ref`));return handle;} catch (error) {if (error.code !== "EEXIST")@@ -25929,7 +25970,7 @@ class FileProgramStore {await writeFile2(temporary, code, { encoding: "utf8", flag: "wx", mode: 384 });try {try {- await link(temporary, target);+ await link2(temporary, target);} catch (error) {if (error.code !== "EEXIST")throw error;@@ -25942,7 +25983,7 @@ class FileProgramStore {}}function localProgramStore() {- return new FileProgramStore(resolve2(process.env["KILN_PROGRAM_STORE"] ?? ".kiln/programs"));+ return new FileProgramStore(resolve3(process.env["KILN_PROGRAM_STORE"] ?? ".kiln/programs"));}var init_program_store_node = __esm(() => {init_program_store();@@ -26124,14 +26165,14 @@ import {utimes,writeFile as writeFile3} from "node:fs/promises";-import { join as join4, resolve as resolve3 } from "node:path";+import { join as join4, resolve as resolve4 } from "node:path";class FileBuildCache {maxBytes;directory;constructor(directory, maxBytes = 128 * 1024 * 1024) {this.maxBytes = maxBytes;- this.directory = resolve3(directory);+ this.directory = resolve4(directory);if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || maxBytes > 1024 * 1024 * 1024)throw new Error("File build cache size must be 0..1 GiB.");}@@ -26352,7 +26393,7 @@ var digest3 = (bytes) => createHash8("sha256").update(bytes).digest("hex"), compvar init_runtime_identity = () => {};// src/local-runtime.ts-import { dirname as dirname3, join as join6, resolve as resolve4 } from "node:path";+import { dirname as dirname3, join as join6, resolve as resolve5 } from "node:path";import { fileURLToPath as fileURLToPath4 } from "node:url";function integer2(env, name, fallback, min, max) {const value = env[name] === undefined ? fallback : Number(env[name]);@@ -26424,7 +26465,7 @@ function createLocalToolContext(base = {}, env = process.env) {return {...base,geometryPolicy,- programStore: base.programStore ?? new FileProgramStore(resolve4(env.KILN_PROGRAM_STORE ?? ".kiln/programs")),+ programStore: base.programStore ?? new FileProgramStore(resolve5(env.KILN_PROGRAM_STORE ?? ".kiln/programs")),evaluatorPort,assetBuildOptions: {optimize,@@ -26476,7 +26517,7 @@ async function createPackagedLocalToolContext(base = {}, env = process.env, inst}const cacheBytes = integer2(env, "KILN_BUILD_CACHE_MB", 128, 0, 1024) * 1024 * 1024;const store = context.programStore;- const directory = resolve4(env.KILN_BUILD_CACHE_DIR ?? join6(store instanceof FileProgramStore ? dirname3(store.directory) : ".kiln", "cache", "builds"));+ const directory = resolve5(env.KILN_BUILD_CACHE_DIR ?? join6(store instanceof FileProgramStore ? dirname3(store.directory) : ".kiln", "cache", "builds"));context.buildCache = new FileBuildCache(directory, cacheBytes);context.evaluatorCacheIdentity = `${identity.identity}:${JSON.stringify({execution: context.localExecution,@@ -27503,11 +27544,107 @@ var init_measurement = __esm(() => {init_camera();});+// src/asset-export.ts+async function sha2562(bytes) {+ const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));+ return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;+}+function validateMetadataFileName(name) {+ if (name.length > 200 || !/^[a-z0-9][a-z0-9._-]*\.kiln-metadata\.json$/i.test(name) || /^(con|prn|aux|nul|com[0-9]|lpt[0-9])\./i.test(name))+ throw new Error("Runtime metadata filename must be a portable sibling *.kiln-metadata.json filename");+}+async function exportAssetGlb(record, options = {}) {+ const profile = options.profile ?? "editable";+ if (profile !== "editable" && profile !== "runtime")+ throw new Error("Unknown export profile");+ validateRecordShape(record);+ const bytes = record.files["asset.glb"];+ if (profile === "editable")+ return { profile, glb: bytes };+ const name = options.metadataFileName ?? "runtime.kiln-metadata.json";+ validateMetadataFileName(name);+ for (const [file, data] of Object.entries(record.files)) {+ if (await sha2562(data) !== record.manifest.files[file].sha256)+ throw new Error(`Asset integrity mismatch: ${file}`);+ }+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ let end = 12;+ while (end < bytes.length) {+ if (end + 8 > bytes.length)+ throw new Error("Invalid GLB chunk header");+ const length = view.getUint32(end, true);+ if (length % 4 || end + 8 + length > bytes.length)+ throw new Error("Invalid GLB chunk length");+ end += 8 + length;+ }+ const jsonEnd = 20 + view.getUint32(12, true);+ const json = JSON.parse(decoder.decode(bytes.subarray(20, jsonEnd)));+ if (!object(json) || !object(json.asset) || json.asset.version !== "2.0")+ throw new Error("Invalid glTF asset");+ const asset = json.asset;+ if (owns(asset, "extras") && !object(asset.extras))+ throw new Error("Cannot add provenance to non-object asset extras");+ const extras = asset.extras ?? {};+ if (owns(extras, "kilnProvenanceV1"))+ throw new Error("Asset extras already contain kilnProvenanceV1; export from the canonical revision");+ const scenes = [];+ if (json.scenes !== undefined && !Array.isArray(json.scenes))+ throw new Error("Invalid glTF scenes");+ for (const [index, scene] of (json.scenes ?? []).entries()) {+ if (!object(scene) || !object(scene.extras) || !owns(scene.extras, "kilnReviewClipsV1"))+ continue;+ const review = scene.extras.kilnReviewClipsV1;+ if (!object(review) || review.version !== 1 || !Array.isArray(review.clips))+ throw new Error("Unsupported scenes[].extras.kilnReviewClipsV1");+ scenes.push({ index, kilnReviewClipsV1: review });+ delete scene.extras.kilnReviewClipsV1;+ }+ const metadata = {+ version: "kiln.runtime-metadata.v1",+ source: {+ assetId: record.manifest.assetId,+ revisionId: record.manifest.revisionId,+ glbSha256: record.manifest.files["asset.glb"].sha256,+ ...record.manifest.files["source.kiln.js"] ? { sourceSha256: record.manifest.files["source.kiln.js"].sha256 } : {}+ },+ scenes+ };+ const metadataBytes = encoder.encode(JSON.stringify(metadata));+ asset.extras = {+ ...extras,+ kilnProvenanceV1: {+ version: "kiln.provenance.v1",+ profile: "runtime",+ metadata: { uri: name, sha256: await sha2562(metadataBytes) }+ }+ };+ const jsonBytes = encoder.encode(JSON.stringify(json));+ const length = Math.ceil(jsonBytes.length / 4) * 4;+ const result = new Uint8Array(20 + length + bytes.length - jsonEnd);+ if (result.length > ASSET_LIMIT || metadataBytes.length > ASSET_LIMIT)+ throw new Error("Runtime export exceeds 64 MiB");+ result.set(bytes.subarray(0, 20));+ const header = new DataView(result.buffer);+ header.setUint32(8, result.length, true);+ header.setUint32(12, length, true);+ result.fill(32, 20, 20 + length);+ result.set(jsonBytes, 20);+ result.set(bytes.subarray(jsonEnd), 20 + length);+ return { profile, glb: result, metadata: { name, bytes: metadataBytes } };+}+var encoder, decoder, object = (value) => value !== null && typeof value === "object" && !Array.isArray(value), owns = (value, key) => Object.hasOwn(value, key);+var init_asset_export = __esm(() => {+ init_assets();+ encoder = new TextEncoder;+ decoder = new TextDecoder;+});+// src/assets-resources.tsvar exports_assets_resources = {};__export(exports_assets_resources, {assetLinks: () => assetLinks,- readAssetResource: () => readAssetResource+ readAssetResource: () => readAssetResource,+ runtimeAssetLinks: () => runtimeAssetLinks});function assetLinks(collection, manifest) {const manifestBytes = new TextEncoder().encode(JSON.stringify(manifest, null, 2)).byteLength;@@ -27526,8 +27663,24 @@ function assetLinks(collection, manifest) {function assetMime(name) {return name.endsWith(".glb") ? "model/gltf-binary" : name.endsWith(".png") ? "image/png" : name.endsWith(".zip") ? "application/zip" : name.endsWith(".json") ? "application/json" : "text/javascript";}+async function runtimeAssetLinks(collection, record) {+ const output = await exportAssetGlb(record, { profile: "runtime" });+ if (output.profile !== "runtime")+ throw new Error("Expected runtime export");+ return [+ { name: "runtime.glb", bytes: output.glb },+ { name: output.metadata.name, bytes: output.metadata.bytes }+ ].map(({ name, bytes }) => ({+ type: "resource_link",+ name,+ uri: `kiln://assets/${collection}/${record.manifest.assetId}/${record.manifest.revisionId}/${name}`,+ mimeType: assetMime(name),+ size: bytes.length,+ annotations: { audience: ["user"], priority: name.endsWith(".glb") ? 0.9 : 0.3 }+ }));+}async function readAssetResource(library, uri) {- const match = /^kiln:\/\/assets\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/(asset\.glb|source\.kiln\.js|preview\.png|manifest\.json|editable\.zip)$/.exec(uri);+ const match = /^kiln:\/\/assets\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/(asset\.glb|runtime\.glb|runtime\.kiln-metadata\.json|source\.kiln\.js|preview\.png|manifest\.json|editable\.zip)$/.exec(uri);if (!match)throw new Error("Unknown asset resource");const collection = match[1];@@ -27535,6 +27688,16 @@ async function readAssetResource(library, uri) {const revision = match[3];const name = match[4];const record = await library.read(collection, asset, revision);+ if (name === "runtime.glb" || name === "runtime.kiln-metadata.json") {+ const output = await exportAssetGlb(record, { profile: "runtime" });+ if (output.profile !== "runtime")+ throw new Error("Expected runtime export");+ return {+ bytes: name === "runtime.glb" ? output.glb : output.metadata.bytes,+ mimeType: assetMime(name),+ name+ };+ }const bytes = name === "editable.zip" ? encodeAssetBundle([record]) : name === "manifest.json" ? new TextEncoder().encode(JSON.stringify(record.manifest, null, 2)) : record.files[name];if (!bytes)throw new Error("Asset file unavailable");@@ -27543,6 +27706,7 @@ async function readAssetResource(library, uri) {var audiences, priorities;var init_assets_resources = __esm(() => {init_assets();+ init_asset_export();audiences = {"asset.glb": ["user"],"preview.png": ["user"],@@ -28618,6 +28782,9 @@ function createKilnAssetDefs(context) {limit: z4.number().int().min(1).max(50).default(20)});const exportInput = z4.object(assetSelector);+ const profileExportInput = exportInput.extend({+ profile: z4.enum(["editable", "runtime"]).default("editable").describe("editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.")+ });const importInput = z4.object({...assetSelector,sourceCollection: assetSelector.collection@@ -28764,10 +28931,24 @@ function createKilnAssetDefs(context) {},{name: "kiln_export",- description: "Get exact GLB, source, preview, and manifest descriptors for one saved revision. Their resource URIs remain readable through resources/read, and configured hosts may also return download URLs including a portable editable ZIP. No binary bytes are placed in tool text.",- inputSchema: exportInput,+ description: "Export one saved revision. Default editable returns exact GLB, source, preview, and manifest descriptors; configured hosts may include portable editable ZIP download URLs. Opt-in runtime returns a standalone GLB plus a versioned metadata sidecar, moving only Kiln review clips out of GLB extras while preserving native animation and application metadata. Resource URIs remain readable through resources/read. Canonical revisions never change; no binary bytes are placed in tool text.",+ inputSchema: profileExportInput,run: async (raw) => {- const input = exportInput.parse(raw);+ const input = profileExportInput.parse(raw);+ if (input.profile === "runtime") {+ const record = await library().read(input.collection, input.assetId, input.revisionId);+ return {+ ok: true,+ profile: input.profile,+ collection: input.collection,+ asset: {+ assetId: input.assetId,+ revisionId: input.revisionId,+ name: record.manifest.name+ },+ resources: await (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).runtimeAssetLinks(input.collection, record)+ };+ }return links(input.collection, (await library().read(input.collection, input.assetId, input.revisionId)).manifest);}},@@ -29239,7 +29420,7 @@ import { createHash as createHash10, randomUUID as randomUUID4 } from "node:crypimport { readFileSync as readFileSync2 } from "node:fs";import { lstat as lstat3, mkdir as mkdir4, readFile as readFile4, readdir as readdir4, realpath as realpath3, rename as rename3, rm, writeFile as writeFile4 } from "node:fs/promises";import { homedir, platform } from "node:os";-import { dirname as dirname4, join as join8, relative as relative2, resolve as resolve5, sep } from "node:path";+import { dirname as dirname4, join as join8, relative as relative2, resolve as resolve6, sep } from "node:path";async function verifyAssetRecord(record) {for (const [name, info] of Object.entries(record.manifest.files)) {const bytes = record.files[name];@@ -29254,7 +29435,7 @@ class FileAssetLibrary {constructor(roots) {if (!Object.keys(roots).length)throw new Error("Configure at least one collection");- this.roots = Object.fromEntries(Object.entries(roots).map(([id, path]) => [assetIdSchema.parse(id), resolve5(path)]));+ this.roots = Object.fromEntries(Object.entries(roots).map(([id, path]) => [assetIdSchema.parse(id), resolve6(path)]));}collections() {return Object.keys(this.roots).map((id) => ({@@ -29408,7 +29589,7 @@ class FileAssetLibrary {}}function collectionConfigPath(env = process.env) {- const workspace = env.KILN_PROGRAM_STORE ? dirname4(dirname4(resolve5(env.KILN_PROGRAM_STORE))) : process.cwd();+ const workspace = env.KILN_PROGRAM_STORE ? dirname4(dirname4(resolve6(env.KILN_PROGRAM_STORE))) : process.cwd();return join8(workspace, ".kiln", "collections.json");}function defaultUserLibraryRoot(env = process.env, home = homedir(), operatingSystem = platform()) {@@ -29574,7 +29755,7 @@ __export(exports_asset_cli, {assetMain: () => assetMain});import { readFile as readFile6, writeFile as writeFile5, stat as stat5, mkdir as mkdir5, rename as rename4 } from "node:fs/promises";-import { basename, resolve as resolve6, dirname as dirname6 } from "node:path";+import { basename, resolve as resolve7, dirname as dirname6 } from "node:path";import { randomUUID as randomUUID5 } from "node:crypto";async function assetMain(argv) {const command = argv[0];@@ -29592,6 +29773,7 @@ async function assetMain(argv) {"tag","out","format",+ "profile","port","render"]);@@ -29633,9 +29815,9 @@ async function assetMain(argv) {throw new Error("collections add requires name and directory");assetIdSchema.parse(name);const roots = Object.fromEntries(library.collections().map((c) => [c.id, library.directory(c.id)]));- if (roots[name] && roots[name] !== resolve6(directory))+ if (roots[name] && roots[name] !== resolve7(directory))throw new Error("Collection name already points to another directory");- roots[name] = resolve6(directory);+ roots[name] = resolve7(directory);const path = collectionConfigPath();await mkdir5(dirname6(path), { recursive: true });const temporary = `${path}.${randomUUID5()}.tmp`;@@ -29687,14 +29869,36 @@ async function assetMain(argv) {} else {if (!flags.out)throw new Error("export requires --out");- const format = flags.format ?? "bundle";+ const profile = flags.profile ?? "editable";+ if (profile !== "editable" && profile !== "runtime")+ throw new Error("Unknown export profile");+ const format = flags.format ?? (profile === "runtime" ? "glb" : "bundle");if (!["bundle", "glb", "source"].includes(format))throw new Error("Unknown export format");+ if (profile === "runtime") {+ if (format !== "glb")+ throw new Error("Runtime profile requires GLB format; use editable for source or bundle");+ const destination = resolve7(flags.out);+ if (!destination.toLowerCase().endsWith(".glb"))+ throw new Error("Runtime output must end in .glb");+ const metadataFileName = `${basename(destination).slice(0, -4)}.kiln-metadata.json`;+ const output = await exportAssetGlb(record, { profile, metadataFileName });+ if (output.profile !== "runtime")+ throw new Error("Expected runtime export");+ const metadataPath = resolve7(dirname6(destination), output.metadata.name);+ await writeNewDestinationsAtomic([+ { path: metadataPath, data: output.metadata.bytes },+ { path: destination, data: output.glb }+ ]);+ console.log(`Saved ${destination}+Saved ${metadataPath}`);+ return 0;+ }const bytes = format === "bundle" ? encodeAssetBundle([record]) : record.files[format === "glb" ? "asset.glb" : "source.kiln.js"];if (!bytes)throw new Error("Source unavailable");- await writeFile5(await prepareDestination(resolve6(flags.out)), bytes, { flag: "wx" });- console.log(`Saved ${resolve6(flags.out)}`);+ await writeFile5(await prepareDestination(resolve7(flags.out)), bytes, { flag: "wx" });+ console.log(`Saved ${resolve7(flags.out)}`);}} else if (command === "import") {const file = positional[0];@@ -29710,7 +29914,7 @@ async function assetMain(argv) {if (file) {if ((await stat5(file)).isDirectory()) {await Promise.resolve().then(() => init_assets_node());- target = new FileAssetLibrary({ project: resolve6(file) });+ target = new FileAssetLibrary({ project: resolve7(file) });} elsestandalone = { name: basename(file), bytes: await fileBytes(file) };}@@ -29739,6 +29943,7 @@ ASSETS & VIEWERkiln assets [--collection project] list saved revisions (JSON)kiln asset <id> <revision> [--collection project] [--restore]kiln export <id> <revision> --out asset.zip [--format bundle|glb|source]+ [--profile editable|runtime] runtime writes GLB + sibling metadata JSONkiln import <asset.zip|asset.glb> [--collection project] [--name <name>]kiln view [collection-directory|asset.glb|asset.zip] [--port 4318][--collection project --asset <id> --revision <revision>]@@ -29755,6 +29960,7 @@ var init_asset_cli = __esm(() => {init_program_store();init_registry2();init_cli_output();+ init_asset_export();init_local_runtime();init_cli_render_mode();init_asset_viewer();@@ -29768,13 +29974,13 @@ import { resolve as resolvePath } from "node:path";// src/direct-entry.tsimport { realpathSync } from "node:fs";-import { resolve } from "node:path";+import { resolve as resolve2 } from "node:path";import { fileURLToPath } from "node:url";function isDirectEntry(moduleUrl) {if (!process.argv[1])return false;try {- return realpathSync(resolve(process.argv[1])) === realpathSync(fileURLToPath(moduleUrl));+ return realpathSync(resolve2(process.argv[1])) === realpathSync(fileURLToPath(moduleUrl));} catch {return false;}diff --git a/dist/mcp-server.mjs b/dist/mcp-server.mjsindex 17cedcf6..9f0252c4 100644--- a/dist/mcp-server.mjs+++ b/dist/mcp-server.mjs@@ -117,6 +117,101 @@ var init_assets = __esm(() => {allowedFiles = new Set(["asset.glb", "source.kiln.js", "preview.png"]);});+// src/asset-export.ts+async function sha256(bytes) {+ const digest = await crypto.subtle.digest("SHA-256", Uint8Array.from(bytes));+ return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;+}+function validateMetadataFileName(name) {+ if (name.length > 200 || !/^[a-z0-9][a-z0-9._-]*\.kiln-metadata\.json$/i.test(name) || /^(con|prn|aux|nul|com[0-9]|lpt[0-9])\./i.test(name))+ throw new Error("Runtime metadata filename must be a portable sibling *.kiln-metadata.json filename");+}+async function exportAssetGlb(record, options = {}) {+ const profile = options.profile ?? "editable";+ if (profile !== "editable" && profile !== "runtime")+ throw new Error("Unknown export profile");+ validateRecordShape(record);+ const bytes = record.files["asset.glb"];+ if (profile === "editable")+ return { profile, glb: bytes };+ const name = options.metadataFileName ?? "runtime.kiln-metadata.json";+ validateMetadataFileName(name);+ for (const [file, data] of Object.entries(record.files)) {+ if (await sha256(data) !== record.manifest.files[file].sha256)+ throw new Error(`Asset integrity mismatch: ${file}`);+ }+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ let end = 12;+ while (end < bytes.length) {+ if (end + 8 > bytes.length)+ throw new Error("Invalid GLB chunk header");+ const length = view.getUint32(end, true);+ if (length % 4 || end + 8 + length > bytes.length)+ throw new Error("Invalid GLB chunk length");+ end += 8 + length;+ }+ const jsonEnd = 20 + view.getUint32(12, true);+ const json = JSON.parse(decoder.decode(bytes.subarray(20, jsonEnd)));+ if (!object(json) || !object(json.asset) || json.asset.version !== "2.0")+ throw new Error("Invalid glTF asset");+ const asset = json.asset;+ if (owns(asset, "extras") && !object(asset.extras))+ throw new Error("Cannot add provenance to non-object asset extras");+ const extras = asset.extras ?? {};+ if (owns(extras, "kilnProvenanceV1"))+ throw new Error("Asset extras already contain kilnProvenanceV1; export from the canonical revision");+ const scenes = [];+ if (json.scenes !== undefined && !Array.isArray(json.scenes))+ throw new Error("Invalid glTF scenes");+ for (const [index, scene] of (json.scenes ?? []).entries()) {+ if (!object(scene) || !object(scene.extras) || !owns(scene.extras, "kilnReviewClipsV1"))+ continue;+ const review = scene.extras.kilnReviewClipsV1;+ if (!object(review) || review.version !== 1 || !Array.isArray(review.clips))+ throw new Error("Unsupported scenes[].extras.kilnReviewClipsV1");+ scenes.push({ index, kilnReviewClipsV1: review });+ delete scene.extras.kilnReviewClipsV1;+ }+ const metadata = {+ version: "kiln.runtime-metadata.v1",+ source: {+ assetId: record.manifest.assetId,+ revisionId: record.manifest.revisionId,+ glbSha256: record.manifest.files["asset.glb"].sha256,+ ...record.manifest.files["source.kiln.js"] ? { sourceSha256: record.manifest.files["source.kiln.js"].sha256 } : {}+ },+ scenes+ };+ const metadataBytes = encoder.encode(JSON.stringify(metadata));+ asset.extras = {+ ...extras,+ kilnProvenanceV1: {+ version: "kiln.provenance.v1",+ profile: "runtime",+ metadata: { uri: name, sha256: await sha256(metadataBytes) }+ }+ };+ const jsonBytes = encoder.encode(JSON.stringify(json));+ const length = Math.ceil(jsonBytes.length / 4) * 4;+ const result = new Uint8Array(20 + length + bytes.length - jsonEnd);+ if (result.length > ASSET_LIMIT || metadataBytes.length > ASSET_LIMIT)+ throw new Error("Runtime export exceeds 64 MiB");+ result.set(bytes.subarray(0, 20));+ const header = new DataView(result.buffer);+ header.setUint32(8, result.length, true);+ header.setUint32(12, length, true);+ result.fill(32, 20, 20 + length);+ result.set(jsonBytes, 20);+ result.set(bytes.subarray(jsonEnd), 20 + length);+ return { profile, glb: result, metadata: { name, bytes: metadataBytes } };+}+var encoder, decoder, object = (value) => value !== null && typeof value === "object" && !Array.isArray(value), owns = (value, key) => Object.hasOwn(value, key);+var init_asset_export = __esm(() => {+ init_assets();+ encoder = new TextEncoder;+ decoder = new TextDecoder;+});+// src/views/background.tsvar GRID_BACKGROUND_RGB, GRID_BACKGROUND_HEX = "#1a1a1a";var init_background = __esm(() => {@@ -10551,7 +10646,7 @@ function verifyResourcePayload(descriptor, payload) {if (!Number.isSafeInteger(pixels) || pixels > TEXTURE_RESOLVER_LIMITS_V1.maxPixels) {throw new ApprovedTextureResourceUnavailableError(descriptor.id, `pixel limit is ${TEXTURE_RESOLVER_LIMITS_V1.maxPixels}; received ${pixels}`);}- const hash = sha256(bytes);+ const hash = sha2562(bytes);if (hash !== descriptor.contentHash) {throw new ApprovedTextureResourceUnavailableError(descriptor.id, `content hash ${hash} does not match the pinned ${descriptor.contentHash}`);}@@ -10742,7 +10837,7 @@ function collectMaterialResourceProvenance(root) {});return [...records.values()].sort((a, b) => `${a.resourceId}:${a.usage}`.localeCompare(`${b.resourceId}:${b.usage}`));}-var TEXTURE_RESOLVER_LIMITS_V1, ApprovedTextureResourceUnavailableError, EMBEDDED_RESOURCE_BASE64, isApprovedId = (value) => APPROVED_TEXTURE_RESOURCE_IDS.includes(value), bytesFromBase64 = (value) => new Uint8Array(Buffer.from(value, "base64")), sha256 = (bytes) => createHash3("sha256").update(bytes).digest("hex"), DEFAULT_APPROVED_TEXTURE_CACHE, materialTextures = (material) => {+var TEXTURE_RESOLVER_LIMITS_V1, ApprovedTextureResourceUnavailableError, EMBEDDED_RESOURCE_BASE64, isApprovedId = (value) => APPROVED_TEXTURE_RESOURCE_IDS.includes(value), bytesFromBase64 = (value) => new Uint8Array(Buffer.from(value, "base64")), sha2562 = (bytes) => createHash3("sha256").update(bytes).digest("hex"), DEFAULT_APPROVED_TEXTURE_CACHE, materialTextures = (material) => {const standard = material;const candidates = [standard.map,@@ -26152,7 +26247,8 @@ var init_measurement = __esm(() => {// src/assets-resources.tsvar exports_assets_resources = {};__export(exports_assets_resources, {- assetLinks: () => assetLinks+ assetLinks: () => assetLinks,+ runtimeAssetLinks: () => runtimeAssetLinks});function assetLinks(collection, manifest) {const manifestBytes = new TextEncoder().encode(JSON.stringify(manifest, null, 2)).byteLength;@@ -26171,9 +26267,26 @@ function assetLinks(collection, manifest) {function assetMime2(name) {return name.endsWith(".glb") ? "model/gltf-binary" : name.endsWith(".png") ? "image/png" : name.endsWith(".zip") ? "application/zip" : name.endsWith(".json") ? "application/json" : "text/javascript";}+async function runtimeAssetLinks(collection, record) {+ const output = await exportAssetGlb(record, { profile: "runtime" });+ if (output.profile !== "runtime")+ throw new Error("Expected runtime export");+ return [+ { name: "runtime.glb", bytes: output.glb },+ { name: output.metadata.name, bytes: output.metadata.bytes }+ ].map(({ name, bytes }) => ({+ type: "resource_link",+ name,+ uri: `kiln://assets/${collection}/${record.manifest.assetId}/${record.manifest.revisionId}/${name}`,+ mimeType: assetMime2(name),+ size: bytes.length,+ annotations: { audience: ["user"], priority: name.endsWith(".glb") ? 0.9 : 0.3 }+ }));+}var audiences, priorities;var init_assets_resources = __esm(() => {init_assets();+ init_asset_export();audiences = {"asset.glb": ["user"],"preview.png": ["user"],@@ -26479,11 +26592,12 @@ function localAssetLibrary(env = process.env) {// src/assets-resources.tsinit_assets();+init_asset_export();function assetMime(name) {return name.endsWith(".glb") ? "model/gltf-binary" : name.endsWith(".png") ? "image/png" : name.endsWith(".zip") ? "application/zip" : name.endsWith(".json") ? "application/json" : "text/javascript";}async function readAssetResource(library, uri) {- const match = /^kiln:\/\/assets\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/(asset\.glb|source\.kiln\.js|preview\.png|manifest\.json|editable\.zip)$/.exec(uri);+ const match = /^kiln:\/\/assets\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/(asset\.glb|runtime\.glb|runtime\.kiln-metadata\.json|source\.kiln\.js|preview\.png|manifest\.json|editable\.zip)$/.exec(uri);if (!match)throw new Error("Unknown asset resource");const collection = match[1];@@ -26491,6 +26605,16 @@ async function readAssetResource(library, uri) {const revision = match[3];const name = match[4];const record = await library.read(collection, asset, revision);+ if (name === "runtime.glb" || name === "runtime.kiln-metadata.json") {+ const output = await exportAssetGlb(record, { profile: "runtime" });+ if (output.profile !== "runtime")+ throw new Error("Expected runtime export");+ return {+ bytes: name === "runtime.glb" ? output.glb : output.metadata.bytes,+ mimeType: assetMime(name),+ name+ };+ }const bytes = name === "editable.zip" ? encodeAssetBundle([record]) : name === "manifest.json" ? new TextEncoder().encode(JSON.stringify(record.manifest, null, 2)) : record.files[name];if (!bytes)throw new Error("Asset file unavailable");@@ -28396,6 +28520,9 @@ function createKilnAssetDefs(context) {limit: z4.number().int().min(1).max(50).default(20)});const exportInput = z4.object(assetSelector);+ const profileExportInput = exportInput.extend({+ profile: z4.enum(["editable", "runtime"]).default("editable").describe("editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.")+ });const importInput = z4.object({...assetSelector,sourceCollection: assetSelector.collection@@ -28542,10 +28669,24 @@ function createKilnAssetDefs(context) {},{name: "kiln_export",- description: "Get exact GLB, source, preview, and manifest descriptors for one saved revision. Their resource URIs remain readable through resources/read, and configured hosts may also return download URLs including a portable editable ZIP. No binary bytes are placed in tool text.",- inputSchema: exportInput,+ description: "Export one saved revision. Default editable returns exact GLB, source, preview, and manifest descriptors; configured hosts may include portable editable ZIP download URLs. Opt-in runtime returns a standalone GLB plus a versioned metadata sidecar, moving only Kiln review clips out of GLB extras while preserving native animation and application metadata. Resource URIs remain readable through resources/read. Canonical revisions never change; no binary bytes are placed in tool text.",+ inputSchema: profileExportInput,run: async (raw) => {- const input = exportInput.parse(raw);+ const input = profileExportInput.parse(raw);+ if (input.profile === "runtime") {+ const record = await library().read(input.collection, input.assetId, input.revisionId);+ return {+ ok: true,+ profile: input.profile,+ collection: input.collection,+ asset: {+ assetId: input.assetId,+ revisionId: input.revisionId,+ name: record.manifest.name+ },+ resources: await (await Promise.resolve().then(() => (init_assets_resources(), exports_assets_resources))).runtimeAssetLinks(input.collection, record)+ };+ }return links(input.collection, (await library().read(input.collection, input.assetId, input.revisionId)).manifest);}},@@ -29603,7 +29744,7 @@ function createKilnMcpServer(context = {}, options = {}) {server.registerResource("asset-file", new ResourceTemplate("kiln://assets/{collection}/{asset}/{revision}/{file}", {list: undefined}), {- description: "Exact saved GLB, editable source, preview, manifest, or portable bundle."+ description: "Saved GLB/source/preview/manifest/bundle, or derived runtime GLB and metadata sidecar."}, async (uri) => {const file = await readAssetResource(context.assetLibrary, uri.href);return {diff --git a/docs/collections.md b/docs/collections.mdindex c006ee2a..be3b5c72 100644--- a/docs/collections.md+++ b/docs/collections.md@@ -102,6 +102,7 @@ fallback, not the normal workflow.node kiln.mjs export ASSET_ID REVISION_ID --out workbench.zipnode kiln.mjs export ASSET_ID REVISION_ID --format glb --out workbench.glbnode kiln.mjs export ASSET_ID REVISION_ID --format source --out workbench.kiln.js+node kiln.mjs export ASSET_ID REVISION_ID --profile runtime --out workbench-runtime.glbnode kiln.mjs import workbench.zip --collection librarynode kiln.mjs asset ASSET_ID REVISION_ID --collection library --restore```@@ -112,6 +113,13 @@ Source is capped at 1 MiB; normal evaluator limits can be lower. Bundles are boufilenames are allowlisted and hashes are verified on import/read. GLBs must embedresources, rather than fetch remote URLs when viewed.+The default `editable` profile preserves these exact saved files. Opt-in `runtime`+writes a standalone GLB plus `workbench-runtime.kiln-metadata.json`, moving only+Kiln's animation review extras into a hash-linked sidecar. Native playback needs no+sidecar. It does not reduce geometry or draw calls, and it never changes the canonical+revision. See [export profiles](export-profiles.md) for CLI/MCP/library usage, provenance,+paired-write behavior and limitations. Viewer download buttons retain editable behavior.+Imports preserve original IDs and parent references, even when an ancestor was notincluded. Importing the same revision twice is harmless; a conflicting identity isrejected. Each revision is committed atomically; a multi-revision import may havediff --git a/docs/engine-handoff.md b/docs/engine-handoff.mdindex a661c0c9..3b2b03d0 100644--- a/docs/engine-handoff.md+++ b/docs/engine-handoff.md@@ -5,6 +5,12 @@ CLI/MCP workflow first; choosing Blender or Unity does not require an exporter sThe experimental Three.js exporter is included in builds containing this integration,but older installed releases do not gain it by setting an environment variable.+For delivery files, see [editable and runtime export profiles](export-profiles.md).+Converter selection applies when generating a GLB; the delivery profile applies to+an already-saved revision. Keep an editable ZIP for authoring and compare runtime+delivery when duplicate review data makes an animated GLB larger. Either converter+works with either delivery profile; neither choice automatically enables compression.+## Choose the import route| Destination | Start here | Check in the destination |diff --git a/docs/evaluation/export-profiles.md b/docs/evaluation/export-profiles.mdnew file mode 100644index 00000000..fe098ee8--- /dev/null+++ b/docs/evaluation/export-profiles.md@@ -0,0 +1,121 @@+# Export profile qualification, 2026-09-15++Scope: ordinary local asset generation, saved revisions, export delivery and native+glTF playback. No Tier 2 harness runs, model/provider calls, deployment, compression,+or changes to the exporter backend were used.++## Reproduce++Use the supported Bun 1.4.2, Node 22.23.2 and npm 12.0.2 toolchain:++```sh+bun install --frozen-lockfile+bun run build:runtime+node scripts/dogfood-export-profiles.mjs+# Optionally add a real local, embedded-PNG GLB as a second fixture:+node scripts/dogfood-export-profiles.mjs /absolute/path/to/asset.glb+```++The script creates a fresh temporary asset workspace against the checkout's built+runtime and leaves its outputs plus `export-profile-receipt.json` there. It prints+that path. The built `kiln_workspace` stdio MCP must answer a capabilities request+before source generation proceeds. This is deterministic source authoring through+the normal tools, not a model capability evaluation.++The small fixture has textured armor and a named articulated pivot. Its source is+retained, rendered, saved, exported as the default editable ZIP, and restored. Runtime+exports then exercise:++- Actual CLI paired files, default/explicit editable preservation, refused overwrites,+ binary-only import, refused source restore and refused second runtime transformation.+- Actual built MCP descriptors and `resources/read` bytes, with verified sizes/hashes.+- Actual built local viewer HTTP GLB/sidecar delivery, compared to those MCP bytes.+- Exact native JSON semantics outside the owned review field/provenance link, and exact+ bytes of every post-JSON chunk, including mesh/animation/texture BIN data.+- Three.js r186 `GLTFLoader` with real Sharp-decoded PNGs and native `AnimationMixer`+ playback. No sidecar is supplied to the loader; resource resolution rejects network access.+- Exact before/after node transforms at five times in every clip, canonical revision+ files unchanged, and Khronos glTF validation.++## Observed results++Windows x64, Node 22.23.2, Bun 1.4.2, npm 12.0.2, Three.js 0.186.0. Both fixtures+passed the complete script, with zero Khronos errors and zero warnings.++Offline gates passed: frozen install, toolchain, skills, typecheck, lint, runtime+bundle rebuild, 1,953 tests (4 existing skips), and 45 render-service tests. Coverage+passed at 95.40% functions and 92.88% lines, above unchanged ratchets. The package+smoke installed the actual tarball without development dependencies and exercised+CLI/workspace/MCP/edit/worker flows. The new `@kiln/engine/asset-export` TypeScript+entry also resolved from that installation under Bun.++| Fixture | Canonical GLB | Runtime GLB | Sidecar | Native clips / tracks | Compared poses | Decoded PNGs |+| --- | ---: | ---: | ---: | ---: | ---: | ---: |+| Generated demonstrator | 7,240 B | 7,188 B | 616 B | 1 / 1 | 5 | 1 |+| Jaeger v4, local real asset | 3,771,340 B | 2,102,176 B | 1,669,629 B | 16 / 359 | 80 | 8 |++The Jaeger **GLB alone** is 44.26% smaller: 1,669,164 fewer bytes. Its complete+GLB-plus-sidecar pair is 3,771,805 B, which is **465 B larger** than the canonical+GLB. The benefit is loading only the runtime GLB in an application and retaining+the review sidecar separately. No draw-call, triangle, texture-memory, or FPS reduction+is claimed. A small/static asset may get a slightly larger GLB.++Canonical fixture hashes:++- Generated demonstrator: `sha256:c0252c00f7c845766e00b2cec2ce390780aa1414305637755197bd53ecad1d7f`.+- Jaeger v4: `sha256:14155efa3ebef47839b70632c0b185557d743abcb99d00e2fa093ba75e3553e0`.++Runtime hashes depend on the saved asset/revision IDs and selected metadata filename.+Repeated export of the same revision and filename is byte-deterministic. The external+fixture is user-owned and is not included in this repository.++## Regression boundaries++Focused tests cover missing review metadata, multiple scenes, preserved custom/node+extras, immutable input bytes, unsupported owned metadata, malformed chunk lengths,+file integrity, unsafe sibling filenames, preexisting provenance, native animation+playback, CLI/MCP profile selection and resource delivery. Paired-write tests cover+partial staging failures, rollback after a later publish fails, existing destination+preservation and distinct output paths. Default generation, save, render and editable+export behavior continues through the ordinary full suite.++This establishes these local generation/export flows and sampled native poses. It does+not establish compatibility with every glTF consumer, GPU visual equivalence, or scene+performance. Arbitrary extras are preserved, not privacy-scrubbed. A process crash can+leave a complete orphan sidecar; the paired publication is not a power-loss transaction.++## Integration with the community exporter++PR #115 merged as `e1f1e3d6274ab0212c82b72333278548827d10f4`. The export-profile+candidate was combined with that main commit in an isolated worktree. The changelog+retained both entries, and every runtime bundle was rebuilt from the combined source.+No source-code conflicts were present. The final #115 documentation update produced+the same combined source and CLI/MCP/worker bundle hashes as the tested runtime.++Toolchain, skills, typecheck, lint and the combined engine suite passed: 1,977 tests,+four existing skips, no failures. A fresh package installation passed its CLI, workspace,+MCP, worker, source-edit and textured experimental-exporter checks. The ordinary+generation/export script passed separately with `KILN_GLTF_EXPORTER=legacy` and+`KILN_GLTF_EXPORTER=three`, including exact native JSON/BIN, decoded PNGs, standalone+playback and CLI/MCP/HTTP delivery.++The full Jaeger source was also replayed through the experimental exporter in a separate+asset workspace. Both native animation batches combined on their asserted identical+graph, and all 226 asset checks passed. Its runtime derivative passed the same delivery+script with 16 clips, 359 tracks, eight decoded PNGs and 80 sampled poses, with zero+Khronos errors or warnings. This replay produced a 3,771,324-byte canonical GLB and a+2,102,160-byte runtime GLB, plus a 1,669,629-byte sidecar.++An additional combined skin/morph fixture retained material extensions, double-sided+surfaces, vertex colors and sampled deformed vertices through runtime export, both+before and after full geometry optimization. Native JSON and BIN were unchanged outside+the documented metadata fields. Khronos reported no errors; the fixture's three existing+skin warnings were identical before and after delivery. Full optimization removed unused+UV channels before delivery, as expected; the runtime profile introduced no such change.++These features act at separate boundaries. The converter selects how source becomes a+canonical GLB; the delivery profile derives files from a saved revision. The established+converter and editable delivery remain the defaults. Runtime delivery neither enables nor+qualifies the experimental converter. Its native-canvas requirement, unsupported UV shear+cases and consumer-extension limits remain described in the+[community-exporter guide](../community-exporter.md).diff --git a/docs/export-profiles.md b/docs/export-profiles.mdnew file mode 100644index 00000000..ae515579--- /dev/null+++ b/docs/export-profiles.md@@ -0,0 +1,214 @@+# Editable and runtime exports++Kiln keeps the saved revision as the canonical asset. Choose a delivery profile when+exporting it; changing the profile never rebuilds the asset or changes its collection.++| Profile | Output | Use |+| --- | --- | --- |+| `editable` (default) | Existing exact GLB, source, preview, manifest, or editable ZIP | Continue authoring, inspect build/review records, archive or share source |+| `runtime` (opt in) | Derived standalone GLB and a versioned metadata JSON sidecar | Deliver a smaller GLB to an application while retaining traceability |++`editable` describes the export policy, not a promise that an imported GLB has source.+A binary-only saved revision remains binary-only. Keep the editable ZIP when source+is available: a runtime sidecar is **not** a replacement for it.++## Which option should I use?++- **Continue editing or share a rebuildable asset:** keep the default `editable`+ profile and export its ZIP. Export an editable GLB when you need the exact saved GLB.+- **Load an animated asset in a game or web scene:** try `runtime`. Kiln moves its+ duplicate review tracks out of the GLB, reducing the data the application loads.+ Compare the actual sizes; a static asset may gain nothing. Keep the sidecar for+ traceability and keep the editable ZIP for future authoring.+- **Need additional glTF feature preservation:** separately compare the experimental+ Three.js converter described in the [engine handoff guide](engine-handoff.md).+ Preserve the baseline and check the result in the destination importer.++### Converter and delivery profile are separate settings++| Setting | When it applies | Default | Optional choice | Why it exists |+| --- | --- | --- | --- | --- |+| GLB converter | Source render/build | Established converter (`legacy`) | Experimental Three.js converter (`three`) | Compare preservation of features such as skin/morph data, vertex colors, extra UV sets and material extensions |+| Export profile | Delivery of an already-saved revision | `editable` | `runtime` | Keep exact authoring artifacts or externalize duplicate review data for application loading |++The converter is selected through the host's `KILN_GLTF_EXPORTER` environment or the+render library option. The delivery profile is selected through `kiln_export`, CLI+`export --profile`, or the asset-export library. Either converter can produce a saved+asset for either delivery profile. Changing the environment during an export does+not rebuild the saved GLB; create and save a new render when comparing converters.++The defaults preserve established workflows and complete review records. Runtime is+opt in because moving review data changes its location and adds a companion file.+The Three.js converter is experimental because native installation requirements,+unsupported UV transforms and destination feature support still need qualification.+Neither setting automatically enables mesh merging, geometry simplification, Draco,+Meshopt or KTX2 compression. Those require separate choices and validation.++## CLI++From an asset workspace, using the IDs returned by `save` or `assets`:++```sh+# Existing behavior: full editable ZIP, with byte-identical saved files.+node kiln.mjs export ASSET_ID REVISION_ID --out mech-editable.zip++# Explicit editable GLB: exact saved GLB bytes.+node kiln.mjs export ASSET_ID REVISION_ID --profile editable --format glb --out mech-editable.glb++# Runtime defaults to GLB; writes BOTH files below.+node kiln.mjs export ASSET_ID REVISION_ID --profile runtime --out mech.glb+# mech.glb+# mech.kiln-metadata.json+```++Runtime requires GLB format and an output ending in `.glb`. Bundle/source formats+use `editable`. Use a portable filename stem containing ASCII letters, digits,+periods, underscores or hyphens, beginning with a letter or digit. The generated+sidecar filename must be at most 200 characters; Windows device names are rejected.+Directory paths may be absolute, but **only the sibling filename** enters provenance.++Exports refuse to overwrite either destination. Runtime stages both complete files,+then publishes the sidecar before the GLB using exclusive hard links on the destination+filesystem. A caught failure rolls back files owned by that call and preserves existing+files. Filesystems must support hard links. This is not a crash/power-loss transaction:+an interrupted process can leave a complete orphan sidecar. Remove that orphan or choose+fresh output names before retrying. A partial GLB is never published by this path.++## MCP++```js+kiln_export({ collection: "project", assetId, revisionId, profile: "runtime" })+```++The shared tool registry accepts `editable` (default) or `runtime`. Runtime returns+descriptors for `runtime.glb` and `runtime.kiln-metadata.json`, including byte sizes+and `kiln://assets/...` resource URIs. Read them through MCP `resources/read`.+These resources are derived from the pinned revision on demand, without persisting+a new revision. The local viewer host also serves those resource filenames through+its existing `/files/` endpoint. Existing viewer download buttons retain editable behavior.++Runtime results do not reuse configured canonical download URLs: those would deliver+the wrong GLB. Client support for saving MCP resources varies. Use the local CLI pair+when the client cannot save them. No binary data is put into tool text.++## TypeScript library++```ts+import { exportAssetGlb } from '@kiln/engine/asset-export';++const record = await library.read('project', assetId, revisionId);+const output = await exportAssetGlb(record, {+ profile: 'runtime',+ metadataFileName: 'mech.kiln-metadata.json',+});+if (output.profile === 'runtime') {+ // Save output.glb as mech.glb and output.metadata.bytes under output.metadata.name.+ // The helper performs no filesystem writes or network requests.+}+```++Omitting `profile` returns the exact canonical GLB bytes. Runtime verifies the saved+file inventory and hashes, validates the GLB chunk table, and returns deterministic+bytes for the same record and sibling filename. It does not serialize through a new+glTF exporter or decode/re-encode textures.++## What runtime changes++Only `scenes[].extras.kilnReviewClipsV1` is moved into the JSON sidecar. It contains+Kiln's authored animation review vocabulary, including advisory tracks that might not+have valid native glTF targets. Native `animations` remain authoritative for playback.+The sidecar retains each source scene index and its original review object.++The profile preserves glTF hierarchy, node names, sockets, transforms, mesh topology,+materials, textures, skins, morph targets, native animation channels, and application+extras. Every chunk after JSON, including the BIN chunk, is copied byte for byte.+JSON values are preserved outside the named review field and the added provenance+record. Existing metadata is **not** generally scrubbed, so user-authored extras can+still contain information the author put there. The new provenance fields introduce+no local paths, source text, build paths or provider information.++Assets with no review clips still receive the provenance link and an empty sidecar+scene list; their GLB can grow slightly. This is not geometry optimization, compression,+mesh merging, texture compression, or an FPS improvement. Measure actual delivery size+and target-scene performance separately.++## Pointer and hash contract++The runtime GLB contains this record in `asset.extras.kilnProvenanceV1`:++```json+{+ "version": "kiln.provenance.v1",+ "profile": "runtime",+ "metadata": {+ "uri": "mech.kiln-metadata.json",+ "sha256": "sha256:<64 lowercase hexadecimal characters>"+ }+}+```++The sidecar uses version `kiln.runtime-metadata.v1`:++```json+{+ "version": "kiln.runtime-metadata.v1",+ "source": {+ "assetId": "a_example",+ "revisionId": "r_example",+ "glbSha256": "sha256:<canonical GLB hash>",+ "sourceSha256": "sha256:<source file hash, when available>"+ },+ "scenes": [+ { "index": 0, "kilnReviewClipsV1": { "version": 1, "clips": [] } }+ ]+}+```++The pointer hash covers the **exact UTF-8 sidecar bytes**, not reserialized JSON. The+sidecar points back to the canonical input GLB hash, not the derived runtime GLB hash,+so there is no circular hash dependency. IDs and hashes let a tool locate and verify+the corresponding editable revision; they are integrity/provenance data, not signatures+or authenticated authorship. The sidecar deliberately does not embed the full manifest,+source or build record.++The URI is informational, not a glTF buffer/image URI. Kiln does not automatically+fetch it or execute its contents. Standard glTF playback works without the sidecar,+including offline or after downloading only the GLB. A tool that explicitly reads it+should verify the byte hash and version before using the data. Deploy both files together+to retain the review provenance; keep the filename or regenerate the export.++An existing `asset.extras.kilnProvenanceV1`, or non-object `asset.extras`, causes runtime+export to fail instead of overwriting data. This also rejects applying runtime twice.+Export again from the canonical saved revision. An already-runtime GLB can still be+copied with the editable/default byte-preserving profile, but that does not restore+source or missing review metadata. Unknown versions of the owned review field fail+explicitly rather than being stripped.++## Boundaries++Draft renders, `renderGLB`, `kiln_render`, `save`, collection files, editable bundles,+review tooling, and current exporter backend defaults are unchanged. Use canonical+assets for Kiln's complete review vocabulary; runtime GLBs retain only native playback+unless a separate consumer explicitly uses the sidecar. This feature is independent+of exporter backend qualification and optional geometry/texture compression.++## Agent delivery checklist++1. Read the request and select the profile for the actual delivery. Use the normal+ converter unless the task calls for an explicit experimental comparison. Report+ the converter actually used; changing a setting alone is not evidence of a rebuild.+2. Save the accepted `programRef` with `kiln_save`, and retain its exact collection,+ asset ID and revision ID. Export that pinned revision. An existing imported GLB+ does not acquire editable source through either profile.+3. Keep the editable ZIP when source is available. For runtime delivery, save the+ GLB and the named sidecar without renaming or reserializing the sidecar. The CLI+ writes the pair; MCP resource delivery depends on the host's download support.+4. Verify that the runtime GLB loads and its native animations play independently.+ Verify the sidecar filename and byte hash when checking provenance. Use the+ canonical asset for Kiln's full review workflow; standard loaders do not fetch+ the sidecar or restore missing source.+5. Report the files, measured sizes, checks performed and remaining limits. A smaller+ GLB does not establish lower draw calls, texture memory or higher frame rate.++[Qualification results and repeatable local dogfood](https://github.com/matthew-kissinger/kiln/blob/main/docs/evaluation/export-profiles.md)+cover generated source, CLI/MCP/HTTP delivery, native playback and a full Jaeger asset.diff --git a/docs/tools.md b/docs/tools.mdindex 9a5a0f4e..0f6dc5a1 100644--- a/docs/tools.md+++ b/docs/tools.md@@ -1767,7 +1767,7 @@ Present one exact saved revision. Supporting MCP App clients show an interactive## kiln_export-Get exact GLB, source, preview, and manifest descriptors for one saved revision. Their resource URIs remain readable through resources/read, and configured hosts may also return download URLs including a portable editable ZIP. No binary bytes are placed in tool text.+Export one saved revision. Default editable returns exact GLB, source, preview, and manifest descriptors; configured hosts may include portable editable ZIP download URLs. Opt-in runtime returns a standalone GLB plus a versioned metadata sidecar, moving only Kiln review clips out of GLB extras while preserving native animation and application metadata. Resource URIs remain readable through resources/read. Canonical revisions never change; no binary bytes are placed in tool text.<details><summary>Input JSON Schema</summary>@@ -1791,12 +1791,22 @@ Get exact GLB, source, preview, and manifest descriptors for one saved revision."revisionId": {"type": "string","pattern": "^[a-z][a-z0-9_-]{0,79}$"+ },+ "profile": {+ "default": "editable",+ "description": "editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.",+ "type": "string",+ "enum": [+ "editable",+ "runtime"+ ]}},"required": ["collection","assetId",- "revisionId"+ "revisionId",+ "profile"],"additionalProperties": false}diff --git a/package.json b/package.jsonindex 506ff4c1..0e1e01ea 100644--- a/package.json+++ b/package.json@@ -19,6 +19,7 @@"exports": {"./assets": "./src/assets.ts","./assets/node": "./src/assets-node.ts",+ "./asset-export": "./src/asset-export.ts",".": "./src/cli.ts","./agent": "./src/agent/index.ts","./tools": "./src/tools/registry.ts",diff --git a/scripts/dogfood-export-profiles.mjs b/scripts/dogfood-export-profiles.mjsnew file mode 100644index 00000000..a795aef0--- /dev/null+++ b/scripts/dogfood-export-profiles.mjs@@ -0,0 +1,347 @@+#!/usr/bin/env node+// Ordinary local source -> render -> save -> export proof. No provider or Tier 2 calls.+import assert from 'node:assert/strict';+import { spawn, spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import { mkdtemp, readFile, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { AnimationMixer, DataTexture, RGBAFormat, LoadingManager, LoopOnce } from 'three';+import sharp from 'sharp';+import { validateBytes } from 'gltf-validator';++const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');+const workspace = await mkdtemp(join(tmpdir(), 'kiln-export-dogfood-'));+const receipt = {+ version: 1,+ node: process.version,+ runtimeBuild: JSON.parse(await readFile(join(repo, 'dist/build.json'), 'utf8')),+ workspace,+ checks: [],+ assets: [],+};+const sha = (bytes) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;+const env = {+ ...process.env,+ KILN_RENDER: 'cpu',+ KILN_PROGRAM_STORE: join(workspace, '.kiln/programs'),+ KILN_COLLECTIONS: JSON.stringify({ project: join(workspace, 'assets/kiln') }),+};+function command(args, ok = true) {+ const result = spawnSync(process.execPath, args, {+ cwd: workspace,+ env,+ encoding: 'utf8',+ windowsHide: true,+ timeout: 180000,+ });+ if (ok) assert.equal(result.status, 0, `${args.join(' ')}\n${result.stderr}\n${result.stdout}`);+ else assert.notEqual(result.status, 0, 'Expected command rejection');+ return result.stdout;+}+const cli = (...args) => command([join(workspace, 'kiln.mjs'), ...args]);+const jsonChunk = (bytes) => JSON.parse(bytes.subarray(20, 20 + bytes.readUInt32LE(12)).toString());+const binTail = (bytes) => bytes.subarray(20 + bytes.readUInt32LE(12));+const proof = (name) => {+ receipt.checks.push(name);+ console.log(name);+};++async function checkHttpResources(asset, expected) {+ const child = spawn(process.execPath, [join(workspace, 'kiln.mjs'), 'view', '--port', '0'], {+ cwd: workspace,+ env,+ windowsHide: true,+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ try {+ const url = await new Promise((done, fail) => {+ let output = '';+ const timer = setTimeout(() => fail(new Error('Viewer did not start')), 15000);+ child.once('error', (error) => {+ clearTimeout(timer);+ fail(error);+ });+ child.once('exit', (code) => {+ clearTimeout(timer);+ fail(new Error(`Viewer exited ${code}`));+ });+ child.stdout.on('data', (data) => {+ output += data;+ const match = output.match(/http:\/\/127\.0\.0\.1:\d+\//);+ if (match) {+ clearTimeout(timer);+ done(match[0]);+ }+ });+ });+ for (const [name, bytes] of expected) {+ const response = await fetch(+ `${url}files/project/${asset.assetId}/${asset.revisionId}/${name}?download`,+ );+ assert.equal(response.status, 200);+ assert.deepEqual(Buffer.from(await response.arrayBuffer()), bytes);+ }+ } finally {+ child.kill();+ }+ proof('built local viewer HTTP runtime GLB and sidecar endpoints return exact MCP bytes');+}++async function loadOffline(bytes) {+ const json = jsonChunk(bytes);+ const binary = binTail(bytes).subarray(8);+ const decoded = [];+ for (const image of json.images ?? []) {+ assert.equal(image.mimeType, 'image/png');+ const view = json.bufferViews[image.bufferView];+ const encoded = binary.subarray(view.byteOffset ?? 0, (view.byteOffset ?? 0) + view.byteLength);+ const { data, info } = await sharp(encoded, { failOn: 'warning' })+ .ensureAlpha()+ .raw()+ .toBuffer({ resolveWithObject: true });+ decoded.push({ data, info, sha256: sha(data) });+ }+ const manager = new LoadingManager();+ manager.setURLModifier(() => {+ throw new Error('External fetch attempted');+ });+ const loader = new GLTFLoader(manager);+ loader.register(() => ({+ name: 'DOGFOOD_DECODED_PNG',+ loadTexture(index) {+ const image = decoded[json.textures[index].source];+ const texture = new DataTexture(image.data, image.info.width, image.info.height, RGBAFormat);+ texture.flipY = false;+ texture.needsUpdate = true;+ return Promise.resolve(texture);+ },+ }));+ return {+ loaded: await loader.parseAsync(Uint8Array.from(bytes).buffer, ''),+ images: decoded.map(({ sha256, info }) => ({ sha256, width: info.width, height: info.height })),+ };+}++async function checkExport(asset, label) {+ const revisionPath = join(workspace, 'assets/kiln', asset.assetId, 'revisions', asset.revisionId);+ const canonical = await readFile(join(revisionPath, 'asset.glb'));+ const manifestBefore = await readFile(join(revisionPath, 'manifest.json'));+ const outputPath = join(workspace, `${label}.glb`);+ cli('export', asset.assetId, asset.revisionId, '--out', outputPath, '--profile', 'runtime');+ const runtime = await readFile(outputPath);+ const sidecar = await readFile(join(workspace, `${label}.kiln-metadata.json`));+ const before = jsonChunk(canonical),+ after = jsonChunk(runtime);+ assert.equal(after.asset.extras.kilnProvenanceV1.metadata.sha256, sha(sidecar));+ assert.equal(after.asset.extras.kilnProvenanceV1.metadata.uri, `${label}.kiln-metadata.json`);+ assert.equal(JSON.parse(sidecar).source.glbSha256, sha(canonical));+ assert.deepEqual(binTail(runtime), binTail(canonical));+ delete after.asset.extras.kilnProvenanceV1;+ if (!before.asset.extras) delete after.asset.extras;+ for (const scene of before.scenes ?? []) if (scene.extras) delete scene.extras.kilnReviewClipsV1;+ assert.deepEqual(after, before);+ const [base, derived] = await Promise.all([loadOffline(canonical), loadOffline(runtime)]);+ assert.deepEqual(derived.images, base.images);+ assert.deepEqual(+ derived.loaded.animations.map((clip) => clip.name),+ base.loaded.animations.map((clip) => clip.name),+ );+ const snapshot = (scene) => {+ const result = [];+ scene.traverse((node) =>+ result.push([+ node.name,+ ...node.position.toArray(),+ ...node.quaternion.toArray(),+ ...node.scale.toArray(),+ ]),+ );+ return result;+ };+ let poses = 0;+ for (let i = 0; i < base.loaded.animations.length; i++) {+ const mixers = [base, derived].map(({ loaded }) => {+ const mixer = new AnimationMixer(loaded.scene);+ const action = mixer.clipAction(loaded.animations[i]);+ action.setLoop(LoopOnce, 1);+ action.clampWhenFinished = true;+ action.play();+ return mixer;+ });+ for (const fraction of [0, 0.25, 0.5, 0.75, 1]) {+ for (const mixer of mixers) mixer.setTime(base.loaded.animations[i].duration * fraction);+ assert.deepEqual(snapshot(derived.loaded.scene), snapshot(base.loaded.scene));+ poses++;+ }+ for (const mixer of mixers) mixer.stopAllAction();+ }+ const validator = await validateBytes(new Uint8Array(runtime), { maxIssues: 100 });+ assert.equal(validator.issues.numErrors, 0, JSON.stringify(validator.issues));+ cli(+ 'export',+ asset.assetId,+ asset.revisionId,+ '--out',+ join(workspace, `${label}-editable.glb`),+ '--format',+ 'glb',+ '--profile',+ 'editable',+ );+ assert.deepEqual(await readFile(join(workspace, `${label}-editable.glb`)), canonical);+ command(+ [+ join(workspace, 'kiln.mjs'),+ 'export',+ asset.assetId,+ asset.revisionId,+ '--out',+ outputPath,+ '--profile',+ 'runtime',+ ],+ false,+ );+ assert.deepEqual(await readFile(outputPath), runtime);+ assert.deepEqual(await readFile(join(revisionPath, 'asset.glb')), canonical);+ assert.deepEqual(await readFile(join(revisionPath, 'manifest.json')), manifestBefore);+ const imported = JSON.parse(cli('import', outputPath, '--name', 'Runtime binary only')).assets[0];+ assert.equal(imported.editable, false);+ command(+ [join(workspace, 'kiln.mjs'), 'asset', imported.assetId, imported.revisionId, '--restore'],+ false,+ );+ command(+ [+ join(workspace, 'kiln.mjs'),+ 'export',+ imported.assetId,+ imported.revisionId,+ '--out',+ join(workspace, `${label}-twice.glb`),+ '--profile',+ 'runtime',+ ],+ false,+ );+ receipt.assets.push({+ label,+ canonicalBytes: canonical.length,+ runtimeBytes: runtime.length,+ sidecarBytes: sidecar.length,+ canonicalSha256: sha(canonical),+ runtimeSha256: sha(runtime),+ sidecarSha256: sha(sidecar),+ clips: base.loaded.animations.length,+ tracks: base.loaded.animations.reduce((n, clip) => n + clip.tracks.length, 0),+ comparedPoses: poses,+ decodedImages: derived.images,+ validatorErrors: validator.issues.numErrors,+ validatorWarnings: validator.issues.numWarnings,+ });+ proof(+ `${label}: exact native JSON/BIN, decoded PNGs, all sampled animation poses, standalone load without sidecar, canonical unchanged, exclusive exports, binary-only import`,+ );+ return { runtime, sidecar };+}++let client;+try {+ command([join(repo, 'scripts/create-workspace.mjs'), workspace, '--harness', 'codex']);+ await readFile(join(workspace, 'START.md'));+ await readFile(join(workspace, 'skills/kiln-author-asset/SKILL.md'));+ const transport = new StdioClientTransport({+ command: process.execPath,+ args: [join(repo, 'dist/mcp-server.mjs')],+ cwd: workspace,+ env,+ stderr: 'pipe',+ });+ client = new Client({ name: 'kiln_workspace', version: '1' });+ await client.connect(transport);+ const call = async (name, args) => {+ const result = await client.callTool({ name, arguments: args }, undefined, { timeout: 180000 });+ assert.notEqual(result.isError, true, JSON.stringify(result.content));+ const text = result.content.find((block) => block.type === 'text').text;+ try {+ return JSON.parse(text);+ } catch {+ return { text };+ }+ };+ await call('kiln_list_primitives', { capabilities: true });+ proof('fresh generated workspace reaches its built-runtime kiln_workspace MCP');+ const source = `const meta = { name: 'Export Profile Demonstrator', category: 'prop' };+async function build() {+ const root = createRoot('Demonstrator');+ const map = proceduralTexture({schemaVersion:2,size:64,usage:'albedo',name:'Paint',layers:[{op:'solid',color:0x60758d},{op:'noise',colorA:0x475468,colorB:0x99a5b4,scale:12,octaves:2,seed:9,opacity:0.25,blend:'overlay'}]});+ const paint = pbrMaterial({albedo:map,roughness:0.6,metalness:0.1});+ createPart('Base',boxGeo(1,0.2,1),paint,{parent:root,position:[0,0.1,0]});+ const arm = createPivot('Arm',[0,0.25,0],root);+ createPart('ArmArmor',boxGeo(0.25,1,0.25),paint,{parent:arm,position:[0,0.5,0]});+ return root;+}+function animate() {return [createClip('Swing',2,[rotationTrack('Joint_Arm',[{time:0,rotation:[0,0,-25]},{time:1,rotation:[0,0,25]},{time:2,rotation:[0,0,-25]}])])];}+`;+ await writeFile(join(workspace, 'demonstrator.kiln.js'), source, { flag: 'wx' });+ const ref = cli('source', 'demonstrator.kiln.js').match(/p_[a-f0-9]+/)[0];+ const rendered = await call('kiln_render', { programRef: ref });+ assert.equal(rendered.ok, true);+ const saved = await call('kiln_save', { programRef: ref, name: 'Export Profile Demonstrator' });+ assert.equal(saved.asset.editable, true);+ const asset = saved.asset;+ cli(+ 'export',+ asset.assetId,+ asset.revisionId,+ '--out',+ join(workspace, 'demonstrator-editable.zip'),+ );+ const restored = JSON.parse(cli('asset', asset.assetId, asset.revisionId, '--restore'));+ assert.equal(restored.programRef, ref);+ proof(+ 'new textured articulated source renders, saves, exports default editable ZIP and restores exact source',+ );+ await checkExport(asset, 'demonstrator');+ const exported = await call('kiln_export', {+ assetId: asset.assetId,+ revisionId: asset.revisionId,+ profile: 'runtime',+ });+ const files = new Map();+ for (const link of exported.resources) {+ const result = await client.readResource({ uri: link.uri });+ const content = result.contents[0];+ const bytes = content.blob ? Buffer.from(content.blob, 'base64') : Buffer.from(content.text);+ assert.equal(bytes.length, link.size);+ files.set(link.name, bytes);+ }+ assert.equal(+ jsonChunk(files.get('runtime.glb')).asset.extras.kilnProvenanceV1.metadata.sha256,+ sha(files.get('runtime.kiln-metadata.json')),+ );+ proof('built MCP runtime descriptors deliver hash-matching GLB and metadata bytes');+ await checkHttpResources(asset, files);+ const fixture = process.argv[2];+ if (fixture) {+ const original = await readFile(resolve(fixture));+ const imported = JSON.parse(cli('import', resolve(fixture), '--name', 'External real asset'))+ .assets[0];+ await checkExport(imported, 'external-asset');+ assert.deepEqual(await readFile(resolve(fixture)), original);+ }+ receipt.status = 'passed';+} catch (error) {+ receipt.status = 'failed';+ receipt.error = String(error.stack ?? error);+ throw error;+} finally {+ await client?.close();+ await writeFile(join(workspace, 'export-profile-receipt.json'), JSON.stringify(receipt, null, 2));+ console.log(`Receipt: ${join(workspace, 'export-profile-receipt.json')}`);+}diff --git a/skills/kiln-author-asset/SKILL.md b/skills/kiln-author-asset/SKILL.mdindex 690d87d3..f4fff021 100644--- a/skills/kiln-author-asset/SKILL.md+++ b/skills/kiln-author-asset/SKILL.md@@ -28,6 +28,8 @@ Inspect the actual images. Check silhouette, proportion, orientation, attachment## Revise and deliver+Read the [export profile guide](references/export-profiles.md) when choosing delivery files. Keep the default editable ZIP for continued authoring; use the opt-in runtime GLB and metadata sidecar for application delivery when its measured size benefit is useful. Converter selection happens during rendering, while the delivery profile applies to a saved revision. Report the actual choices and preserve the canonical source; neither option establishes scene performance.+Read a bounded source region with `kiln_source({ programRef, query: "dimensionOrPart" })`. Copy an exact anchor into `kiln_edit`, batch related replacements, and continue with its new `programRef`. Rendering is on by default; `capture` can keep the relevant framing. An applied edit can still fail to build, so inspect `render.ok` separately.When the collection tools are available, use them for delivery. A finished asset is not delivered until its accepted final reference is saved. The user chooses the destination when they name one. Call `kiln_assets({ action: "collections" })` to resolve available IDs when more than one collection is configured or the request mentions a destination. Use `project` only as the fallback when the user gave no destination; use `library` for an explicitly requested cross-workspace library. Then call `kiln_save({ programRef, name, collection, brief, description, attribution: { model, harness } })`. Record the actual model and harness when known, and omit unknown attribution rather than guessing. Saving creates the durable asset record and returns the asset ID, revision ID, and download resources for its exact GLB, source, preview, and ZIP bundle. Return those links to the user using the host's resource/download interface; do not transcribe binary data.diff --git a/skills/kiln-author-asset/references/engine-handoff.md b/skills/kiln-author-asset/references/engine-handoff.mdindex a661c0c9..3b2b03d0 100644--- a/skills/kiln-author-asset/references/engine-handoff.md+++ b/skills/kiln-author-asset/references/engine-handoff.md@@ -5,6 +5,12 @@ CLI/MCP workflow first; choosing Blender or Unity does not require an exporter sThe experimental Three.js exporter is included in builds containing this integration,but older installed releases do not gain it by setting an environment variable.+For delivery files, see [editable and runtime export profiles](export-profiles.md).+Converter selection applies when generating a GLB; the delivery profile applies to+an already-saved revision. Keep an editable ZIP for authoring and compare runtime+delivery when duplicate review data makes an animated GLB larger. Either converter+works with either delivery profile; neither choice automatically enables compression.+## Choose the import route| Destination | Start here | Check in the destination |diff --git a/skills/kiln-author-asset/references/export-profiles.md b/skills/kiln-author-asset/references/export-profiles.mdnew file mode 100644index 00000000..ae515579--- /dev/null+++ b/skills/kiln-author-asset/references/export-profiles.md@@ -0,0 +1,214 @@+# Editable and runtime exports++Kiln keeps the saved revision as the canonical asset. Choose a delivery profile when+exporting it; changing the profile never rebuilds the asset or changes its collection.++| Profile | Output | Use |+| --- | --- | --- |+| `editable` (default) | Existing exact GLB, source, preview, manifest, or editable ZIP | Continue authoring, inspect build/review records, archive or share source |+| `runtime` (opt in) | Derived standalone GLB and a versioned metadata JSON sidecar | Deliver a smaller GLB to an application while retaining traceability |++`editable` describes the export policy, not a promise that an imported GLB has source.+A binary-only saved revision remains binary-only. Keep the editable ZIP when source+is available: a runtime sidecar is **not** a replacement for it.++## Which option should I use?++- **Continue editing or share a rebuildable asset:** keep the default `editable`+ profile and export its ZIP. Export an editable GLB when you need the exact saved GLB.+- **Load an animated asset in a game or web scene:** try `runtime`. Kiln moves its+ duplicate review tracks out of the GLB, reducing the data the application loads.+ Compare the actual sizes; a static asset may gain nothing. Keep the sidecar for+ traceability and keep the editable ZIP for future authoring.+- **Need additional glTF feature preservation:** separately compare the experimental+ Three.js converter described in the [engine handoff guide](engine-handoff.md).+ Preserve the baseline and check the result in the destination importer.++### Converter and delivery profile are separate settings++| Setting | When it applies | Default | Optional choice | Why it exists |+| --- | --- | --- | --- | --- |+| GLB converter | Source render/build | Established converter (`legacy`) | Experimental Three.js converter (`three`) | Compare preservation of features such as skin/morph data, vertex colors, extra UV sets and material extensions |+| Export profile | Delivery of an already-saved revision | `editable` | `runtime` | Keep exact authoring artifacts or externalize duplicate review data for application loading |++The converter is selected through the host's `KILN_GLTF_EXPORTER` environment or the+render library option. The delivery profile is selected through `kiln_export`, CLI+`export --profile`, or the asset-export library. Either converter can produce a saved+asset for either delivery profile. Changing the environment during an export does+not rebuild the saved GLB; create and save a new render when comparing converters.++The defaults preserve established workflows and complete review records. Runtime is+opt in because moving review data changes its location and adds a companion file.+The Three.js converter is experimental because native installation requirements,+unsupported UV transforms and destination feature support still need qualification.+Neither setting automatically enables mesh merging, geometry simplification, Draco,+Meshopt or KTX2 compression. Those require separate choices and validation.++## CLI++From an asset workspace, using the IDs returned by `save` or `assets`:++```sh+# Existing behavior: full editable ZIP, with byte-identical saved files.+node kiln.mjs export ASSET_ID REVISION_ID --out mech-editable.zip++# Explicit editable GLB: exact saved GLB bytes.+node kiln.mjs export ASSET_ID REVISION_ID --profile editable --format glb --out mech-editable.glb++# Runtime defaults to GLB; writes BOTH files below.+node kiln.mjs export ASSET_ID REVISION_ID --profile runtime --out mech.glb+# mech.glb+# mech.kiln-metadata.json+```++Runtime requires GLB format and an output ending in `.glb`. Bundle/source formats+use `editable`. Use a portable filename stem containing ASCII letters, digits,+periods, underscores or hyphens, beginning with a letter or digit. The generated+sidecar filename must be at most 200 characters; Windows device names are rejected.+Directory paths may be absolute, but **only the sibling filename** enters provenance.++Exports refuse to overwrite either destination. Runtime stages both complete files,+then publishes the sidecar before the GLB using exclusive hard links on the destination+filesystem. A caught failure rolls back files owned by that call and preserves existing+files. Filesystems must support hard links. This is not a crash/power-loss transaction:+an interrupted process can leave a complete orphan sidecar. Remove that orphan or choose+fresh output names before retrying. A partial GLB is never published by this path.++## MCP++```js+kiln_export({ collection: "project", assetId, revisionId, profile: "runtime" })+```++The shared tool registry accepts `editable` (default) or `runtime`. Runtime returns+descriptors for `runtime.glb` and `runtime.kiln-metadata.json`, including byte sizes+and `kiln://assets/...` resource URIs. Read them through MCP `resources/read`.+These resources are derived from the pinned revision on demand, without persisting+a new revision. The local viewer host also serves those resource filenames through+its existing `/files/` endpoint. Existing viewer download buttons retain editable behavior.++Runtime results do not reuse configured canonical download URLs: those would deliver+the wrong GLB. Client support for saving MCP resources varies. Use the local CLI pair+when the client cannot save them. No binary data is put into tool text.++## TypeScript library++```ts+import { exportAssetGlb } from '@kiln/engine/asset-export';++const record = await library.read('project', assetId, revisionId);+const output = await exportAssetGlb(record, {+ profile: 'runtime',+ metadataFileName: 'mech.kiln-metadata.json',+});+if (output.profile === 'runtime') {+ // Save output.glb as mech.glb and output.metadata.bytes under output.metadata.name.+ // The helper performs no filesystem writes or network requests.+}+```++Omitting `profile` returns the exact canonical GLB bytes. Runtime verifies the saved+file inventory and hashes, validates the GLB chunk table, and returns deterministic+bytes for the same record and sibling filename. It does not serialize through a new+glTF exporter or decode/re-encode textures.++## What runtime changes++Only `scenes[].extras.kilnReviewClipsV1` is moved into the JSON sidecar. It contains+Kiln's authored animation review vocabulary, including advisory tracks that might not+have valid native glTF targets. Native `animations` remain authoritative for playback.+The sidecar retains each source scene index and its original review object.++The profile preserves glTF hierarchy, node names, sockets, transforms, mesh topology,+materials, textures, skins, morph targets, native animation channels, and application+extras. Every chunk after JSON, including the BIN chunk, is copied byte for byte.+JSON values are preserved outside the named review field and the added provenance+record. Existing metadata is **not** generally scrubbed, so user-authored extras can+still contain information the author put there. The new provenance fields introduce+no local paths, source text, build paths or provider information.++Assets with no review clips still receive the provenance link and an empty sidecar+scene list; their GLB can grow slightly. This is not geometry optimization, compression,+mesh merging, texture compression, or an FPS improvement. Measure actual delivery size+and target-scene performance separately.++## Pointer and hash contract++The runtime GLB contains this record in `asset.extras.kilnProvenanceV1`:++```json+{+ "version": "kiln.provenance.v1",+ "profile": "runtime",+ "metadata": {+ "uri": "mech.kiln-metadata.json",+ "sha256": "sha256:<64 lowercase hexadecimal characters>"+ }+}+```++The sidecar uses version `kiln.runtime-metadata.v1`:++```json+{+ "version": "kiln.runtime-metadata.v1",+ "source": {+ "assetId": "a_example",+ "revisionId": "r_example",+ "glbSha256": "sha256:<canonical GLB hash>",+ "sourceSha256": "sha256:<source file hash, when available>"+ },+ "scenes": [+ { "index": 0, "kilnReviewClipsV1": { "version": 1, "clips": [] } }+ ]+}+```++The pointer hash covers the **exact UTF-8 sidecar bytes**, not reserialized JSON. The+sidecar points back to the canonical input GLB hash, not the derived runtime GLB hash,+so there is no circular hash dependency. IDs and hashes let a tool locate and verify+the corresponding editable revision; they are integrity/provenance data, not signatures+or authenticated authorship. The sidecar deliberately does not embed the full manifest,+source or build record.++The URI is informational, not a glTF buffer/image URI. Kiln does not automatically+fetch it or execute its contents. Standard glTF playback works without the sidecar,+including offline or after downloading only the GLB. A tool that explicitly reads it+should verify the byte hash and version before using the data. Deploy both files together+to retain the review provenance; keep the filename or regenerate the export.++An existing `asset.extras.kilnProvenanceV1`, or non-object `asset.extras`, causes runtime+export to fail instead of overwriting data. This also rejects applying runtime twice.+Export again from the canonical saved revision. An already-runtime GLB can still be+copied with the editable/default byte-preserving profile, but that does not restore+source or missing review metadata. Unknown versions of the owned review field fail+explicitly rather than being stripped.++## Boundaries++Draft renders, `renderGLB`, `kiln_render`, `save`, collection files, editable bundles,+review tooling, and current exporter backend defaults are unchanged. Use canonical+assets for Kiln's complete review vocabulary; runtime GLBs retain only native playback+unless a separate consumer explicitly uses the sidecar. This feature is independent+of exporter backend qualification and optional geometry/texture compression.++## Agent delivery checklist++1. Read the request and select the profile for the actual delivery. Use the normal+ converter unless the task calls for an explicit experimental comparison. Report+ the converter actually used; changing a setting alone is not evidence of a rebuild.+2. Save the accepted `programRef` with `kiln_save`, and retain its exact collection,+ asset ID and revision ID. Export that pinned revision. An existing imported GLB+ does not acquire editable source through either profile.+3. Keep the editable ZIP when source is available. For runtime delivery, save the+ GLB and the named sidecar without renaming or reserializing the sidecar. The CLI+ writes the pair; MCP resource delivery depends on the host's download support.+4. Verify that the runtime GLB loads and its native animations play independently.+ Verify the sidecar filename and byte hash when checking provenance. Use the+ canonical asset for Kiln's full review workflow; standard loaders do not fetch+ the sidecar or restore missing source.+5. Report the files, measured sizes, checks performed and remaining limits. A smaller+ GLB does not establish lower draw calls, texture memory or higher frame rate.++[Qualification results and repeatable local dogfood](https://github.com/matthew-kissinger/kiln/blob/main/docs/evaluation/export-profiles.md)+cover generated source, CLI/MCP/HTTP delivery, native playback and a full Jaeger asset.diff --git a/skills/kiln-qa-asset/SKILL.md b/skills/kiln-qa-asset/SKILL.mdindex 4e73e12d..e1c72111 100644--- a/skills/kiln-qa-asset/SKILL.md+++ b/skills/kiln-qa-asset/SKILL.md@@ -10,6 +10,8 @@ Match the checks to the requested delivery. A source build, an image review, a G## Before integration+Read the [export profile guide](references/export-profiles.md) when reviewing delivery files. Verify the selected converter separately from the editable/runtime profile. Runtime GLBs must preserve native playback without the sidecar; provenance checks use the sidecar filename and exact byte hash. Keep the canonical editable asset for source and full Kiln review data, and measure actual loading and rendering performance separately.+Read validation/build findings and export warnings. `kiln_validate` only checks source; render and inspect the actual geometry when that is the task. Choose broad or part-specific views that reveal the suspected defect. Copy the returned `programRef` exactly for every view, whether it is a short `p_` handle or a full SHA-256 reference; request source text only when a repair needs it. A handle identifies a revision in its store; use full source and artifact hashes for integrity evidence.Distinguish expected open sheets from invalid solid topology. `geometryDiagnostics` reports boundary edges, non-manifold edges, orientation conflicts and degenerates; it does not prove absence of self-intersection. A capped loft, shell-like surface, or sampled field is not automatically a manufacturing-grade solid.diff --git a/skills/kiln-qa-asset/references/engine-handoff.md b/skills/kiln-qa-asset/references/engine-handoff.mdindex a661c0c9..3b2b03d0 100644--- a/skills/kiln-qa-asset/references/engine-handoff.md+++ b/skills/kiln-qa-asset/references/engine-handoff.md@@ -5,6 +5,12 @@ CLI/MCP workflow first; choosing Blender or Unity does not require an exporter sThe experimental Three.js exporter is included in builds containing this integration,but older installed releases do not gain it by setting an environment variable.+For delivery files, see [editable and runtime export profiles](export-profiles.md).+Converter selection applies when generating a GLB; the delivery profile applies to+an already-saved revision. Keep an editable ZIP for authoring and compare runtime+delivery when duplicate review data makes an animated GLB larger. Either converter+works with either delivery profile; neither choice automatically enables compression.+## Choose the import route| Destination | Start here | Check in the destination |diff --git a/skills/kiln-qa-asset/references/export-profiles.md b/skills/kiln-qa-asset/references/export-profiles.mdnew file mode 100644index 00000000..ae515579--- /dev/null+++ b/skills/kiln-qa-asset/references/export-profiles.md@@ -0,0 +1,214 @@+# Editable and runtime exports++Kiln keeps the saved revision as the canonical asset. Choose a delivery profile when+exporting it; changing the profile never rebuilds the asset or changes its collection.++| Profile | Output | Use |+| --- | --- | --- |+| `editable` (default) | Existing exact GLB, source, preview, manifest, or editable ZIP | Continue authoring, inspect build/review records, archive or share source |+| `runtime` (opt in) | Derived standalone GLB and a versioned metadata JSON sidecar | Deliver a smaller GLB to an application while retaining traceability |++`editable` describes the export policy, not a promise that an imported GLB has source.+A binary-only saved revision remains binary-only. Keep the editable ZIP when source+is available: a runtime sidecar is **not** a replacement for it.++## Which option should I use?++- **Continue editing or share a rebuildable asset:** keep the default `editable`+ profile and export its ZIP. Export an editable GLB when you need the exact saved GLB.+- **Load an animated asset in a game or web scene:** try `runtime`. Kiln moves its+ duplicate review tracks out of the GLB, reducing the data the application loads.+ Compare the actual sizes; a static asset may gain nothing. Keep the sidecar for+ traceability and keep the editable ZIP for future authoring.+- **Need additional glTF feature preservation:** separately compare the experimental+ Three.js converter described in the [engine handoff guide](engine-handoff.md).+ Preserve the baseline and check the result in the destination importer.++### Converter and delivery profile are separate settings++| Setting | When it applies | Default | Optional choice | Why it exists |+| --- | --- | --- | --- | --- |+| GLB converter | Source render/build | Established converter (`legacy`) | Experimental Three.js converter (`three`) | Compare preservation of features such as skin/morph data, vertex colors, extra UV sets and material extensions |+| Export profile | Delivery of an already-saved revision | `editable` | `runtime` | Keep exact authoring artifacts or externalize duplicate review data for application loading |++The converter is selected through the host's `KILN_GLTF_EXPORTER` environment or the+render library option. The delivery profile is selected through `kiln_export`, CLI+`export --profile`, or the asset-export library. Either converter can produce a saved+asset for either delivery profile. Changing the environment during an export does+not rebuild the saved GLB; create and save a new render when comparing converters.++The defaults preserve established workflows and complete review records. Runtime is+opt in because moving review data changes its location and adds a companion file.+The Three.js converter is experimental because native installation requirements,+unsupported UV transforms and destination feature support still need qualification.+Neither setting automatically enables mesh merging, geometry simplification, Draco,+Meshopt or KTX2 compression. Those require separate choices and validation.++## CLI++From an asset workspace, using the IDs returned by `save` or `assets`:++```sh+# Existing behavior: full editable ZIP, with byte-identical saved files.+node kiln.mjs export ASSET_ID REVISION_ID --out mech-editable.zip++# Explicit editable GLB: exact saved GLB bytes.+node kiln.mjs export ASSET_ID REVISION_ID --profile editable --format glb --out mech-editable.glb++# Runtime defaults to GLB; writes BOTH files below.+node kiln.mjs export ASSET_ID REVISION_ID --profile runtime --out mech.glb+# mech.glb+# mech.kiln-metadata.json+```++Runtime requires GLB format and an output ending in `.glb`. Bundle/source formats+use `editable`. Use a portable filename stem containing ASCII letters, digits,+periods, underscores or hyphens, beginning with a letter or digit. The generated+sidecar filename must be at most 200 characters; Windows device names are rejected.+Directory paths may be absolute, but **only the sibling filename** enters provenance.++Exports refuse to overwrite either destination. Runtime stages both complete files,+then publishes the sidecar before the GLB using exclusive hard links on the destination+filesystem. A caught failure rolls back files owned by that call and preserves existing+files. Filesystems must support hard links. This is not a crash/power-loss transaction:+an interrupted process can leave a complete orphan sidecar. Remove that orphan or choose+fresh output names before retrying. A partial GLB is never published by this path.++## MCP++```js+kiln_export({ collection: "project", assetId, revisionId, profile: "runtime" })+```++The shared tool registry accepts `editable` (default) or `runtime`. Runtime returns+descriptors for `runtime.glb` and `runtime.kiln-metadata.json`, including byte sizes+and `kiln://assets/...` resource URIs. Read them through MCP `resources/read`.+These resources are derived from the pinned revision on demand, without persisting+a new revision. The local viewer host also serves those resource filenames through+its existing `/files/` endpoint. Existing viewer download buttons retain editable behavior.++Runtime results do not reuse configured canonical download URLs: those would deliver+the wrong GLB. Client support for saving MCP resources varies. Use the local CLI pair+when the client cannot save them. No binary data is put into tool text.++## TypeScript library++```ts+import { exportAssetGlb } from '@kiln/engine/asset-export';++const record = await library.read('project', assetId, revisionId);+const output = await exportAssetGlb(record, {+ profile: 'runtime',+ metadataFileName: 'mech.kiln-metadata.json',+});+if (output.profile === 'runtime') {+ // Save output.glb as mech.glb and output.metadata.bytes under output.metadata.name.+ // The helper performs no filesystem writes or network requests.+}+```++Omitting `profile` returns the exact canonical GLB bytes. Runtime verifies the saved+file inventory and hashes, validates the GLB chunk table, and returns deterministic+bytes for the same record and sibling filename. It does not serialize through a new+glTF exporter or decode/re-encode textures.++## What runtime changes++Only `scenes[].extras.kilnReviewClipsV1` is moved into the JSON sidecar. It contains+Kiln's authored animation review vocabulary, including advisory tracks that might not+have valid native glTF targets. Native `animations` remain authoritative for playback.+The sidecar retains each source scene index and its original review object.++The profile preserves glTF hierarchy, node names, sockets, transforms, mesh topology,+materials, textures, skins, morph targets, native animation channels, and application+extras. Every chunk after JSON, including the BIN chunk, is copied byte for byte.+JSON values are preserved outside the named review field and the added provenance+record. Existing metadata is **not** generally scrubbed, so user-authored extras can+still contain information the author put there. The new provenance fields introduce+no local paths, source text, build paths or provider information.++Assets with no review clips still receive the provenance link and an empty sidecar+scene list; their GLB can grow slightly. This is not geometry optimization, compression,+mesh merging, texture compression, or an FPS improvement. Measure actual delivery size+and target-scene performance separately.++## Pointer and hash contract++The runtime GLB contains this record in `asset.extras.kilnProvenanceV1`:++```json+{+ "version": "kiln.provenance.v1",+ "profile": "runtime",+ "metadata": {+ "uri": "mech.kiln-metadata.json",+ "sha256": "sha256:<64 lowercase hexadecimal characters>"+ }+}+```++The sidecar uses version `kiln.runtime-metadata.v1`:++```json+{+ "version": "kiln.runtime-metadata.v1",+ "source": {+ "assetId": "a_example",+ "revisionId": "r_example",+ "glbSha256": "sha256:<canonical GLB hash>",+ "sourceSha256": "sha256:<source file hash, when available>"+ },+ "scenes": [+ { "index": 0, "kilnReviewClipsV1": { "version": 1, "clips": [] } }+ ]+}+```++The pointer hash covers the **exact UTF-8 sidecar bytes**, not reserialized JSON. The+sidecar points back to the canonical input GLB hash, not the derived runtime GLB hash,+so there is no circular hash dependency. IDs and hashes let a tool locate and verify+the corresponding editable revision; they are integrity/provenance data, not signatures+or authenticated authorship. The sidecar deliberately does not embed the full manifest,+source or build record.++The URI is informational, not a glTF buffer/image URI. Kiln does not automatically+fetch it or execute its contents. Standard glTF playback works without the sidecar,+including offline or after downloading only the GLB. A tool that explicitly reads it+should verify the byte hash and version before using the data. Deploy both files together+to retain the review provenance; keep the filename or regenerate the export.++An existing `asset.extras.kilnProvenanceV1`, or non-object `asset.extras`, causes runtime+export to fail instead of overwriting data. This also rejects applying runtime twice.+Export again from the canonical saved revision. An already-runtime GLB can still be+copied with the editable/default byte-preserving profile, but that does not restore+source or missing review metadata. Unknown versions of the owned review field fail+explicitly rather than being stripped.++## Boundaries++Draft renders, `renderGLB`, `kiln_render`, `save`, collection files, editable bundles,+review tooling, and current exporter backend defaults are unchanged. Use canonical+assets for Kiln's complete review vocabulary; runtime GLBs retain only native playback+unless a separate consumer explicitly uses the sidecar. This feature is independent+of exporter backend qualification and optional geometry/texture compression.++## Agent delivery checklist++1. Read the request and select the profile for the actual delivery. Use the normal+ converter unless the task calls for an explicit experimental comparison. Report+ the converter actually used; changing a setting alone is not evidence of a rebuild.+2. Save the accepted `programRef` with `kiln_save`, and retain its exact collection,+ asset ID and revision ID. Export that pinned revision. An existing imported GLB+ does not acquire editable source through either profile.+3. Keep the editable ZIP when source is available. For runtime delivery, save the+ GLB and the named sidecar without renaming or reserializing the sidecar. The CLI+ writes the pair; MCP resource delivery depends on the host's download support.+4. Verify that the runtime GLB loads and its native animations play independently.+ Verify the sidecar filename and byte hash when checking provenance. Use the+ canonical asset for Kiln's full review workflow; standard loaders do not fetch+ the sidecar or restore missing source.+5. Report the files, measured sizes, checks performed and remaining limits. A smaller+ GLB does not establish lower draw calls, texture memory or higher frame rate.++[Qualification results and repeatable local dogfood](https://github.com/matthew-kissinger/kiln/blob/main/docs/evaluation/export-profiles.md)+cover generated source, CLI/MCP/HTTP delivery, native playback and a full Jaeger asset.diff --git a/src/asset-cli.test.ts b/src/asset-cli.test.tsindex ea181e40..f872f2af 100644--- a/src/asset-cli.test.ts+++ b/src/asset-cli.test.ts@@ -1,6 +1,6 @@import { expect, test } from 'bun:test';import { spawnSync } from 'node:child_process';-import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { mkdtemp, readFile, rm, readdir } from 'node:fs/promises';import { join, resolve } from 'node:path';import { tmpdir } from 'node:os';import { decodeAssetBundle } from './assets';@@ -49,6 +49,69 @@ test('CLI saves, exports, imports, and restores a revision across independent stexpect(JSON.parse(restored.stdout).programRef).toMatch(/^p_/);expect(run('second', ['import', file]).status).toBe(0);expect(JSON.parse(run('second', ['assets']).stdout).assets.length).toBe(1);+ const canonical = decodeAssetBundle(new Uint8Array(await readFile(file)))[0]!.files[+ 'asset.glb'+ ]!;+ const editable = join(root, 'editable.glb');+ expect(+ run('first', [+ 'export',+ asset.assetId,+ asset.revisionId,+ '--out',+ editable,+ '--format',+ 'glb',+ '--profile',+ 'editable',+ ]).status,+ ).toBe(0);+ expect(new Uint8Array(await readFile(editable))).toEqual(Uint8Array.from(canonical));+ const runtime = join(root, 'runtime.glb');+ expect(+ run('first', [+ 'export',+ asset.assetId,+ asset.revisionId,+ '--out',+ runtime,+ '--profile',+ 'runtime',+ ]).status,+ ).toBe(0);+ const metadata = JSON.parse(await readFile(join(root, 'runtime.kiln-metadata.json'), 'utf8'));+ expect(metadata.version).toBe('kiln.runtime-metadata.v1');+ expect(metadata.source.revisionId).toBe(asset.revisionId);+ const runtimeBefore = await readFile(runtime);+ expect(+ run('first', [+ 'export',+ asset.assetId,+ asset.revisionId,+ '--out',+ runtime,+ '--profile',+ 'runtime',+ ]).status,+ ).toBe(1);+ expect(await readFile(runtime)).toEqual(runtimeBefore);+ for (const flags of [+ ['--profile', 'unknown'],+ ['--profile', 'runtime', '--format', 'bundle'],+ ['--profile', 'runtime', '--format', 'source'],+ ]) {+ expect(+ run('first', [+ 'export',+ asset.assetId,+ asset.revisionId,+ '--out',+ join(root, 'bad.glb'),+ ...flags,+ ]).status,+ ).toBe(1);+ }+ expect(await readdir(root)).not.toContain('bad.glb');} finally {await rm(root, { recursive: true, force: true });}diff --git a/src/asset-cli.ts b/src/asset-cli.tsindex 1f75687d..07c476a6 100644--- a/src/asset-cli.ts+++ b/src/asset-cli.ts@@ -6,7 +6,8 @@ import { ASSET_LIMIT, assetIdSchema, decodeAssetBundle, encodeAssetBundle } fromimport { localProgramStore } from './program-store-node';import { programRefPattern, retainProgram } from './program-store';import { createKilnProgramToolRegistry } from './tools/registry';-import { prepareDestination } from './cli-output';+import { prepareDestination, writeNewDestinationsAtomic } from './cli-output';+import { exportAssetGlb } from './asset-export';import { createPackagedLocalToolContext } from './local-runtime';import { buildRenderPort, resolveRenderMode } from './cli-render-mode';import { startAssetViewer } from './asset-viewer';@@ -21,6 +22,7 @@ ASSETS & VIEWERkiln assets [--collection project] list saved revisions (JSON)kiln asset <id> <revision> [--collection project] [--restore]kiln export <id> <revision> --out asset.zip [--format bundle|glb|source]+ [--profile editable|runtime] runtime writes GLB + sibling metadata JSONkiln import <asset.zip|asset.glb> [--collection project] [--name <name>]kiln view [collection-directory|asset.glb|asset.zip] [--port 4318][--collection project --asset <id> --revision <revision>]@@ -46,6 +48,7 @@ export async function assetMain(argv: readonly string[]): Promise<number> {'tag','out','format',+ 'profile','port','render',]);@@ -154,8 +157,28 @@ export async function assetMain(argv: readonly string[]): Promise<number> {} else console.log(JSON.stringify(record.manifest, null, 2));} else {if (!flags.out) throw new Error('export requires --out');- const format = flags.format ?? 'bundle';+ const profile = flags.profile ?? 'editable';+ if (profile !== 'editable' && profile !== 'runtime')+ throw new Error('Unknown export profile');+ const format = flags.format ?? (profile === 'runtime' ? 'glb' : 'bundle');if (!['bundle', 'glb', 'source'].includes(format)) throw new Error('Unknown export format');+ if (profile === 'runtime') {+ if (format !== 'glb')+ throw new Error('Runtime profile requires GLB format; use editable for source or bundle');+ const destination = resolve(flags.out);+ if (!destination.toLowerCase().endsWith('.glb'))+ throw new Error('Runtime output must end in .glb');+ const metadataFileName = `${basename(destination).slice(0, -4)}.kiln-metadata.json`;+ const output = await exportAssetGlb(record, { profile, metadataFileName });+ if (output.profile !== 'runtime') throw new Error('Expected runtime export');+ const metadataPath = resolve(dirname(destination), output.metadata.name);+ await writeNewDestinationsAtomic([+ { path: metadataPath, data: output.metadata.bytes },+ { path: destination, data: output.glb },+ ]);+ console.log(`Saved ${destination}\nSaved ${metadataPath}`);+ return 0;+ }const bytes =format === 'bundle'? encodeAssetBundle([record])diff --git a/src/asset-export.test.ts b/src/asset-export.test.tsnew file mode 100644index 00000000..67d51371--- /dev/null+++ b/src/asset-export.test.ts@@ -0,0 +1,227 @@+import { expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { exportAssetGlb } from './asset-export';+import type { AssetRecord } from './assets';+import { renderGLB } from './render';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { AnimationMixer, LoadingManager, LoopOnce } from 'three';++const sha = (bytes: Uint8Array) => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;+function glb(json: unknown, tail = new Uint8Array([4, 0, 0, 0, 0x42, 0x49, 0x4e, 0, 1, 2, 3, 4])) {+ const text = new TextEncoder().encode(JSON.stringify(json));+ const length = Math.ceil(text.length / 4) * 4;+ const bytes = new Uint8Array(20 + length + tail.length);+ const view = new DataView(bytes.buffer);+ [0x46546c67, 2, bytes.length, length, 0x4e4f534a].forEach((n, i) => {+ view.setUint32(i * 4, n, true);+ });+ bytes.fill(32, 20, 20 + length);+ bytes.set(text, 20);+ bytes.set(tail, 20 + length);+ return bytes;+}+function json(bytes: Uint8Array) {+ return JSON.parse(+ new TextDecoder().decode(+ bytes.subarray(20, 20 + new DataView(bytes.buffer, bytes.byteOffset).getUint32(12, true)),+ ),+ );+}+function record(bytes: Uint8Array): AssetRecord {+ return {+ manifest: {+ version: 'kiln.asset.v1',+ assetId: 'a_test',+ revisionId: 'r_test',+ name: 'Test',+ tags: [],+ createdAt: '2026-09-15T00:00:00.000Z',+ editable: false,+ files: { 'asset.glb': { bytes: bytes.length, sha256: sha(bytes) as `sha256:${string}` } },+ },+ files: { 'asset.glb': bytes },+ };+}+const review = { version: 1, clips: [{ name: 'Open', duration: 1, tracks: [] }] };+const fixture = () =>+ record(+ glb({+ asset: { version: '2.0', extras: { application: 'keep' } },+ scenes: [+ { nodes: [0], extras: { kilnReviewClipsV1: review, custom: [1, 2] } },+ { extras: { kilnReviewClipsV1: review } },+ ],+ nodes: [{ name: 'Socket', extras: { kilnReviewClipsV1: 'not scene-owned', socket: true } }],+ animations: [{ name: 'Open', channels: [], samplers: [] }],+ buffers: [{ byteLength: 4 }],+ }),+ );++test('editable default preserves exact canonical bytes, including review metadata', async () => {+ const source = fixture();+ expect(await exportAssetGlb(source)).toEqual({+ profile: 'editable',+ glb: source.files['asset.glb']!,+ });+ expect(await exportAssetGlb(source, { profile: 'editable' })).toEqual(+ await exportAssetGlb(source),+ );+});++test('runtime externalizes only owned scene review data, preserving JSON semantics and binary bytes', async () => {+ const source = fixture();+ const before = source.files['asset.glb']!.slice();+ const output = await exportAssetGlb(source, {+ profile: 'runtime',+ metadataFileName: 'mech.kiln-metadata.json',+ });+ expect(output.profile).toBe('runtime');+ if (output.profile !== 'runtime') throw new Error('wrong profile');+ const meta = JSON.parse(new TextDecoder().decode(output.metadata.bytes));+ expect(meta).toEqual({+ version: 'kiln.runtime-metadata.v1',+ source: { assetId: 'a_test', revisionId: 'r_test', glbSha256: sha(before) },+ scenes: [+ { index: 0, kilnReviewClipsV1: review },+ { index: 1, kilnReviewClipsV1: review },+ ],+ });+ const actual = json(output.glb);+ expect(actual.asset.extras.kilnProvenanceV1).toEqual({+ version: 'kiln.provenance.v1',+ profile: 'runtime',+ metadata: { uri: 'mech.kiln-metadata.json', sha256: sha(output.metadata.bytes) },+ });+ delete actual.asset.extras.kilnProvenanceV1;+ const expected = json(before);+ for (const scene of expected.scenes) delete scene.extras.kilnReviewClipsV1;+ expect(actual).toEqual(expected);+ expect(output.glb.slice(-12)).toEqual(before.slice(-12));+ expect(source.files['asset.glb']).toEqual(before);+ expect(+ await exportAssetGlb(source, {+ profile: 'runtime',+ metadataFileName: 'mech.kiln-metadata.json',+ }),+ ).toEqual(output);+});++test('runtime handles assets without review clips and includes verified source hash without source or build paths', async () => {+ const source = record(glb({ asset: { version: '2.0' }, scenes: [{ extras: 'custom scalar' }] }));+ const code = new TextEncoder().encode('source deliberately stays in the editable bundle');+ source.files['source.kiln.js'] = code;+ source.manifest.editable = true;+ source.manifest.files['source.kiln.js'] = {+ bytes: code.length,+ sha256: sha(code) as `sha256:${string}`,+ };+ source.manifest.build = {+ engine: 'C:\\private\\engine',+ options: {},+ warnings: [],+ rebuild: 'engine-required',+ };+ const output = await exportAssetGlb(source, { profile: 'runtime' });+ if (output.profile !== 'runtime') throw new Error('wrong profile');+ const meta = JSON.parse(new TextDecoder().decode(output.metadata.bytes));+ expect(meta.scenes).toEqual([]);+ expect(meta.source.sourceSha256).toBe(sha(code));+ expect(new TextDecoder().decode(output.metadata.bytes)).not.toContain('private');+ expect(json(output.glb).scenes[0].extras).toBe('custom scalar');+});++test('runtime refuses collisions and repeat transformation instead of overwriting provenance', async () => {+ for (const extras of [{ kilnProvenanceV1: 'application-owned' }, 'scalar', null]) {+ await expect(+ exportAssetGlb(record(glb({ asset: { version: '2.0', extras } })), { profile: 'runtime' }),+ ).rejects.toThrow('extras');+ }+ const output = await exportAssetGlb(fixture(), { profile: 'runtime' });+ await expect(exportAssetGlb(record(output.glb), { profile: 'runtime' })).rejects.toThrow(+ 'kilnProvenanceV1',+ );+ expect((await exportAssetGlb(record(output.glb))).glb).toEqual(output.glb);+});++test('runtime rejects unsafe sidecar names and unsupported owned metadata without mutation', async () => {+ for (const name of [+ '../meta.json',+ 'C:\\secret.json',+ 'https://example.com/a.json',+ '/meta.json',+ 'a%2Fb.kiln-metadata.json',+ 'a?b.kiln-metadata.json',+ 'CON.kiln-metadata.json',+ ]) {+ await expect(+ exportAssetGlb(fixture(), { profile: 'runtime', metadataFileName: name }),+ ).rejects.toThrow('filename');+ }+ for (const value of [null, {}, { version: 2, clips: [] }, { version: 1, clips: 'bad' }]) {+ await expect(+ exportAssetGlb(+ record(+ glb({ asset: { version: '2.0' }, scenes: [{ extras: { kilnReviewClipsV1: value } }] }),+ ),+ { profile: 'runtime' },+ ),+ ).rejects.toThrow('kilnReviewClipsV1');+ }+});++test('runtime validates integrity and the entire chunk table before returning output', async () => {+ const source = fixture();+ source.manifest.files['asset.glb']!.sha256 = `sha256:${'0'.repeat(64)}`;+ await expect(exportAssetGlb(source, { profile: 'runtime' })).rejects.toThrow('integrity');+ for (const tail of [+ new Uint8Array([1]),+ new Uint8Array([8, 0, 0, 0, 0x42, 0x49, 0x4e, 0]),+ new Uint8Array([1, 0, 0, 0, 0x42, 0x49, 0x4e, 0, 1]),+ ]) {+ await expect(+ exportAssetGlb(record(glb({ asset: { version: '2.0' } }, tail)), { profile: 'runtime' }),+ ).rejects.toThrow('chunk');+ }+});++test('generated runtime GLB loads and plays native animation with no sidecar or network access', async () => {+ const rendered = await renderGLB(`+ const meta = { name: 'Export proof', category: 'prop' };+ function build() {+ const root = createRoot('Proof');+ const arm = createPivot('Arm', [0, 0.5, 0], root);+ createPart('Armor', boxGeo(0.2, 1, 0.2), gameMaterial(0x668899), { parent: arm, position: [0, 0.5, 0] });+ return root;+ }+ function animate() { return [createClip('swing', 1, [rotationTrack('Joint_Arm', [{time: 0, rotation: [0, 0, 0]}, {time: 1, rotation: [0, 0, 70]}])])]; }+ `);+ const output = await exportAssetGlb(record(rendered.glb), { profile: 'runtime' });+ const manager = new LoadingManager();+ manager.setURLModifier(() => {+ throw new Error('Unexpected external resource request');+ });+ const baseline = await new GLTFLoader(manager).parseAsync(+ Uint8Array.from(rendered.glb).buffer,+ '',+ );+ const runtime = await new GLTFLoader(manager).parseAsync(Uint8Array.from(output.glb).buffer, '');+ expect(runtime.animations.map((clip) => clip.name)).toEqual(['swing']);+ expect(runtime.animations[0]!.tracks.map((track) => track.name)).toEqual(+ baseline.animations[0]!.tracks.map((track) => track.name),+ );+ const mixers = [baseline, runtime].map((loaded) => {+ const mixer = new AnimationMixer(loaded.scene);+ const action = mixer.clipAction(loaded.animations[0]!);+ action.setLoop(LoopOnce, 1);+ action.clampWhenFinished = true;+ action.play();+ return mixer;+ });+ for (const time of [0, 0.1, 0.5, 0.9, 1]) {+ for (const mixer of mixers) mixer.setTime(time);+ const before = baseline.scene.getObjectByName('Joint_Arm')!;+ const after = runtime.scene.getObjectByName('Joint_Arm')!;+ expect(after.quaternion.toArray()).toEqual(before.quaternion.toArray());+ if (time > 0) expect(Math.abs(after.quaternion.z)).toBeGreaterThan(0);+ }+});diff --git a/src/asset-export.ts b/src/asset-export.tsnew file mode 100644index 00000000..52d43276--- /dev/null+++ b/src/asset-export.ts@@ -0,0 +1,136 @@+/** Saved-asset delivery profiles. No renderer, filesystem, or network dependencies. */+import { ASSET_LIMIT, validateRecordShape, type AssetRecord } from './assets';++export type AssetExportProfile = 'editable' | 'runtime';+export interface AssetGlbExportOptions {+ /** Editable is the byte-preserving default. Runtime externalizes review-only data. */+ profile?: AssetExportProfile;+ /** A portable sibling filename, not a path or URL. Used only by runtime. */+ metadataFileName?: string;+}+export type AssetGlbExport =+ | { profile: 'editable'; glb: Uint8Array }+ | { profile: 'runtime'; glb: Uint8Array; metadata: { name: string; bytes: Uint8Array } };++export interface RuntimeMetadataV1 {+ version: 'kiln.runtime-metadata.v1';+ source: {+ assetId: string;+ revisionId: string;+ glbSha256: string;+ sourceSha256?: string;+ };+ scenes: { index: number; kilnReviewClipsV1: Record<string, unknown> }[];+}++const encoder = new TextEncoder();+const decoder = new TextDecoder();+const object = (value: unknown): value is Record<string, unknown> =>+ value !== null && typeof value === 'object' && !Array.isArray(value);+const owns = (value: object, key: string) => Object.hasOwn(value, key);++async function sha256(bytes: Uint8Array): Promise<string> {+ const digest = await crypto.subtle.digest('SHA-256', Uint8Array.from(bytes));+ return `sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')}`;+}++/** Validate before creating any output directories or writing any bytes. */+export function validateMetadataFileName(name: string): void {+ if (+ name.length > 200 ||+ !/^[a-z0-9][a-z0-9._-]*\.kiln-metadata\.json$/i.test(name) ||+ /^(con|prn|aux|nul|com[0-9]|lpt[0-9])\./i.test(name)+ )+ throw new Error(+ 'Runtime metadata filename must be a portable sibling *.kiln-metadata.json filename',+ );+}++/**+ * Derive a delivery GLB from a saved revision, never changing the canonical record.+ * The sidecar is informational: neither this helper nor standard glTF loaders fetch+ * it. Only the exact owned scene review field is moved; application extras survive.+ */+export async function exportAssetGlb(+ record: AssetRecord,+ options: AssetGlbExportOptions = {},+): Promise<AssetGlbExport> {+ const profile = options.profile ?? 'editable';+ if (profile !== 'editable' && profile !== 'runtime') throw new Error('Unknown export profile');+ validateRecordShape(record);+ const bytes = record.files['asset.glb']!;+ if (profile === 'editable') return { profile, glb: bytes };+ const name = options.metadataFileName ?? 'runtime.kiln-metadata.json';+ validateMetadataFileName(name);+ for (const [file, data] of Object.entries(record.files)) {+ if ((await sha256(data)) !== record.manifest.files[file]!.sha256)+ throw new Error(`Asset integrity mismatch: ${file}`);+ }++ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ let end = 12;+ while (end < bytes.length) {+ if (end + 8 > bytes.length) throw new Error('Invalid GLB chunk header');+ const length = view.getUint32(end, true);+ if (length % 4 || end + 8 + length > bytes.length) throw new Error('Invalid GLB chunk length');+ end += 8 + length;+ }+ const jsonEnd = 20 + view.getUint32(12, true);+ const json: unknown = JSON.parse(decoder.decode(bytes.subarray(20, jsonEnd)));+ if (!object(json) || !object(json.asset) || json.asset.version !== '2.0')+ throw new Error('Invalid glTF asset');+ const asset = json.asset;+ if (owns(asset, 'extras') && !object(asset.extras))+ throw new Error('Cannot add provenance to non-object asset extras');+ const extras = (asset.extras ?? {}) as Record<string, unknown>;+ if (owns(extras, 'kilnProvenanceV1'))+ throw new Error(+ 'Asset extras already contain kilnProvenanceV1; export from the canonical revision',+ );+ const scenes: RuntimeMetadataV1['scenes'] = [];+ if (json.scenes !== undefined && !Array.isArray(json.scenes))+ throw new Error('Invalid glTF scenes');+ for (const [index, scene] of ((json.scenes ?? []) as unknown[]).entries()) {+ if (!object(scene) || !object(scene.extras) || !owns(scene.extras, 'kilnReviewClipsV1'))+ continue;+ const review = scene.extras.kilnReviewClipsV1;+ if (!object(review) || review.version !== 1 || !Array.isArray(review.clips))+ throw new Error('Unsupported scenes[].extras.kilnReviewClipsV1');+ scenes.push({ index, kilnReviewClipsV1: review });+ delete scene.extras.kilnReviewClipsV1;+ }+ const metadata: RuntimeMetadataV1 = {+ version: 'kiln.runtime-metadata.v1',+ source: {+ assetId: record.manifest.assetId,+ revisionId: record.manifest.revisionId,+ glbSha256: record.manifest.files['asset.glb']!.sha256,+ ...(record.manifest.files['source.kiln.js']+ ? { sourceSha256: record.manifest.files['source.kiln.js'].sha256 }+ : {}),+ },+ scenes,+ };+ const metadataBytes = encoder.encode(JSON.stringify(metadata));+ asset.extras = {+ ...extras,+ kilnProvenanceV1: {+ version: 'kiln.provenance.v1',+ profile: 'runtime',+ metadata: { uri: name, sha256: await sha256(metadataBytes) },+ },+ };+ const jsonBytes = encoder.encode(JSON.stringify(json));+ const length = Math.ceil(jsonBytes.length / 4) * 4;+ const result = new Uint8Array(20 + length + bytes.length - jsonEnd);+ if (result.length > ASSET_LIMIT || metadataBytes.length > ASSET_LIMIT)+ throw new Error('Runtime export exceeds 64 MiB');+ result.set(bytes.subarray(0, 20));+ const header = new DataView(result.buffer);+ header.setUint32(8, result.length, true);+ header.setUint32(12, length, true);+ result.fill(32, 20, 20 + length);+ result.set(jsonBytes, 20);+ result.set(bytes.subarray(jsonEnd), 20 + length);+ return { profile, glb: result, metadata: { name, bytes: metadataBytes } };+}diff --git a/src/assets-resources.ts b/src/assets-resources.tsindex fb1bba2a..ebd14506 100644--- a/src/assets-resources.ts+++ b/src/assets-resources.ts@@ -1,4 +1,10 @@-import { encodeAssetBundle, type AssetLibrary, type AssetManifest } from './assets';+import {+ encodeAssetBundle,+ type AssetLibrary,+ type AssetManifest,+ type AssetRecord,+} from './assets';+import { exportAssetGlb } from './asset-export';export interface AssetLink {type: 'resource_link';@@ -68,12 +74,32 @@ export function assetMime(name: string): string {? 'application/json': 'text/javascript';}++/** Derived resources are deterministic, read-only, and never replace a saved revision. */+export async function runtimeAssetLinks(+ collection: string,+ record: AssetRecord,+): Promise<AssetLink[]> {+ const output = await exportAssetGlb(record, { profile: 'runtime' });+ if (output.profile !== 'runtime') throw new Error('Expected runtime export');+ return [+ { name: 'runtime.glb', bytes: output.glb },+ { name: output.metadata.name, bytes: output.metadata.bytes },+ ].map(({ name, bytes }) => ({+ type: 'resource_link',+ name,+ uri: `kiln://assets/${collection}/${record.manifest.assetId}/${record.manifest.revisionId}/${name}`,+ mimeType: assetMime(name),+ size: bytes.length,+ annotations: { audience: ['user'], priority: name.endsWith('.glb') ? 0.9 : 0.3 },+ }));+}export async function readAssetResource(library: AssetLibrary,uri: string,): Promise<{ bytes: Uint8Array; mimeType: string; name: string }> {const match =- /^kiln:\/\/assets\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/(asset\.glb|source\.kiln\.js|preview\.png|manifest\.json|editable\.zip)$/.exec(+ /^kiln:\/\/assets\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/([a-z][a-z0-9_-]{0,79})\/(asset\.glb|runtime\.glb|runtime\.kiln-metadata\.json|source\.kiln\.js|preview\.png|manifest\.json|editable\.zip)$/.exec(uri,);if (!match) throw new Error('Unknown asset resource');@@ -82,6 +108,15 @@ export async function readAssetResource(const revision = match[3]!;const name = match[4]!;const record = await library.read(collection, asset, revision);+ if (name === 'runtime.glb' || name === 'runtime.kiln-metadata.json') {+ const output = await exportAssetGlb(record, { profile: 'runtime' });+ if (output.profile !== 'runtime') throw new Error('Expected runtime export');+ return {+ bytes: name === 'runtime.glb' ? output.glb : output.metadata.bytes,+ mimeType: assetMime(name),+ name,+ };+ }const bytes =name === 'editable.zip'? encodeAssetBundle([record])diff --git a/src/assets-tools.test.ts b/src/assets-tools.test.tsindex c31d71a1..af9c0841 100644--- a/src/assets-tools.test.ts+++ b/src/assets-tools.test.ts@@ -134,6 +134,43 @@ test('MCP saves an editable revision, exposes exact downloadable bytes, and restrevisionId: verbose.revisionId,});expect(JSON.stringify(exported).length).toBeLessThan(6000);+ const runtime = await client.callTool({+ name: 'kiln_export',+ arguments: {+ collection: 'project',+ assetId: data.asset.assetId,+ revisionId: data.asset.revisionId,+ profile: 'runtime',+ },+ });+ expect(runtime.isError).not.toBe(true);+ const runtimePayload = JSON.parse(+ (runtime.content as { type: string; text?: string }[]).find((block) => block.type === 'text')!+ .text!,+ );+ expect(runtimePayload.profile).toBe('runtime');+ const runtimeLinks = runtime.content.filter((block) => block.type === 'resource_link') as {+ type: string;+ name: string;+ uri: string;+ size: number;+ }[];+ expect(runtimeLinks.map((link) => link.name)).toEqual([+ 'runtime.glb',+ 'runtime.kiln-metadata.json',+ ]);+ expect(runtimePayload.downloadUrls).toBeUndefined();+ for (const descriptor of runtimeLinks) {+ const resource = await client.readResource({ uri: descriptor.uri });+ const file = resource.contents[0]!;+ const bytes = 'blob' in file ? Buffer.from(file.blob, 'base64') : Buffer.from(file.text);+ expect(bytes.length).toBe(descriptor.size);+ if (descriptor.name.endsWith('.json'))+ expect(JSON.parse(bytes.toString()).source.revisionId).toBe(data.asset.revisionId);+ }+ expect(await assetLibrary.read('project', data.asset.assetId, data.asset.revisionId)).toEqual(+ record,+ );} finally {await client.close();await server.close();diff --git a/src/cli-output.test.ts b/src/cli-output.test.tsindex 410c21c8..e5c9050c 100644--- a/src/cli-output.test.ts+++ b/src/cli-output.test.ts@@ -13,7 +13,7 @@ import {} from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { writeDestinationAtomic } from './cli-output';+import { writeDestinationAtomic, writeNewDestinationsAtomic } from './cli-output';async function fixture(run: (directory: string) => Promise<void>) {const directory = await mkdtemp(join(tmpdir(), 'kiln-output-'));@@ -114,3 +114,63 @@ it.skipIf(process.platform === 'win32')(expect((await readdir(directory)).sort()).toEqual(['link.glb', 'target.glb']);}),);++it('publishes an exclusive sidecar and GLB only after complete staging', () =>+ fixture(async (directory) => {+ const sidecar = join(directory, 'nested', 'asset.json');+ const glb = join(directory, 'nested', 'asset.glb');+ async function* staged() {+ expect(await readdir(join(directory, 'nested'))).not.toContain('asset.json');+ yield Buffer.from('complete GLB');+ }+ await writeNewDestinationsAtomic([+ { path: sidecar, data: 'metadata' },+ { path: glb, data: staged() },+ ]);+ expect(await readFile(sidecar, 'utf8')).toBe('metadata');+ expect(await readFile(glb, 'utf8')).toBe('complete GLB');+ expect((await readdir(join(directory, 'nested'))).sort()).toEqual(['asset.glb', 'asset.json']);+ await expect(+ writeNewDestinationsAtomic([+ { path: sidecar, data: 'replacement' },+ { path: glb, data: 'replacement' },+ ]),+ ).rejects.toThrow();+ expect(await readFile(glb, 'utf8')).toBe('complete GLB');+ }));++it('rolls back only owned published outputs when the later exclusive publish fails', () =>+ fixture(async (directory) => {+ const sidecar = join(directory, 'asset.json');+ const glb = join(directory, 'asset.glb');+ await writeFile(glb, 'existing GLB');+ await expect(+ writeNewDestinationsAtomic([+ { path: sidecar, data: 'metadata' },+ { path: glb, data: 'new GLB' },+ ]),+ ).rejects.toThrow();+ expect(await readFile(glb, 'utf8')).toBe('existing GLB');+ expect(await readdir(directory)).toEqual(['asset.glb']);+ }));++it('does not publish either output after a partial staging write fails', () =>+ fixture(async (directory) => {+ async function* interrupted() {+ yield Buffer.from('partial');+ throw new Error('interrupted');+ }+ await expect(+ writeNewDestinationsAtomic([+ { path: join(directory, 'asset.json'), data: 'metadata' },+ { path: join(directory, 'asset.glb'), data: interrupted() },+ ]),+ ).rejects.toThrow('interrupted');+ expect(await readdir(directory)).toEqual([]);+ await expect(+ writeNewDestinationsAtomic([+ { path: join(directory, 'same'), data: 'a' },+ { path: join(directory, 'same'), data: 'b' },+ ]),+ ).rejects.toThrow('distinct');+ }));diff --git a/src/cli-output.ts b/src/cli-output.tsindex 5fa01833..e89bc749 100644--- a/src/cli-output.ts+++ b/src/cli-output.ts@@ -3,6 +3,7 @@ import type { Stats } from 'node:fs';import {chmod,lstat,+ link,mkdir,open,realpath,@@ -11,7 +12,7 @@ import {unlink,writeFile,} from 'node:fs/promises';-import { dirname, join } from 'node:path';+import { dirname, join, resolve } from 'node:path';/*** Prepare the directories leading to a CLI destination.@@ -70,3 +71,55 @@ export async function writeDestinationAtomic(await unlink(temporary).catch(() => {});}}++/**+ * Stage an exclusive multi-file export, then publish in order (sidecar before GLB).+ * Hard links publish complete bytes without replacing existing files. A caught+ * failure rolls back this call's outputs. This is not a crash/power-loss transaction;+ * an interrupted process can leave a complete orphan sidecar, never a partial GLB.+ */+export async function writeNewDestinationsAtomic(+ outputs: { path: string; data: Parameters<typeof writeFile>[1] }[],+): Promise<void> {+ const paths = outputs.map(({ path }) => {+ const absolute = resolve(path);+ return process.platform === 'win32' ? absolute.toLowerCase() : absolute;+ });+ if (new Set(paths).size !== paths.length) throw new Error('Export destinations must be distinct');+ const staged: { path: string; temporary: string; published: boolean }[] = [];+ try {+ for (const { path, data } of outputs) {+ await prepareDestination(path);+ const temporary = join(dirname(path), `.kiln-write-${randomUUID()}.tmp`);+ const file = await open(temporary, 'wx');+ staged.push({ path, temporary, published: false });+ try {+ await writeFile(file, data);+ } finally {+ await file.close();+ }+ }+ for (const output of staged) {+ await link(output.temporary, output.path);+ output.published = true;+ }+ } catch (error) {+ for (const output of staged.filter((item) => item.published).reverse()) {+ // An unrelated writer may have replaced an output since our publish. Never+ // remove it: only unlink the inode still shared with our staging file.+ try {+ const [destination, temporary] = await Promise.all([+ lstat(output.path),+ lstat(output.temporary),+ ]);+ if (destination.dev === temporary.dev && destination.ino === temporary.ino)+ await unlink(output.path);+ } catch {+ /* Preserve the original failure; leave an undeletable complete file. */+ }+ }+ throw error;+ } finally {+ await Promise.all(staged.map(({ temporary }) => unlink(temporary).catch(() => {})));+ }+}diff --git a/src/mcp-server.ts b/src/mcp-server.tsindex ad6fc729..bc732d72 100644--- a/src/mcp-server.ts+++ b/src/mcp-server.ts@@ -246,7 +246,8 @@ export function createKilnMcpServer(list: undefined,}),{- description: 'Exact saved GLB, editable source, preview, manifest, or portable bundle.',+ description:+ 'Saved GLB/source/preview/manifest/bundle, or derived runtime GLB and metadata sidecar.',},async (uri) => {const file = await readAssetResource(context.assetLibrary!, uri.href);diff --git a/src/tools/registry.ts b/src/tools/registry.tsindex 981f4161..52a5bcd6 100644--- a/src/tools/registry.ts+++ b/src/tools/registry.ts@@ -2467,6 +2467,14 @@ export function createKilnAssetDefs(context: KilnToolContext): KilnToolDef[] {limit: z.number().int().min(1).max(50).default(20),});const exportInput = z.object(assetSelector);+ const profileExportInput = exportInput.extend({+ profile: z+ .enum(['editable', 'runtime'])+ .default('editable')+ .describe(+ 'editable preserves canonical source/GLB/build resources. runtime returns a standalone GLB and versioned review-metadata sidecar; no source bundle or geometry optimization.',+ ),+ });const importInput = z.object({...assetSelector,sourceCollection: assetSelector.collection,@@ -2636,10 +2644,27 @@ export function createKilnAssetDefs(context: KilnToolContext): KilnToolDef[] {{name: 'kiln_export',description:- 'Get exact GLB, source, preview, and manifest descriptors for one saved revision. Their resource URIs remain readable through resources/read, and configured hosts may also return download URLs including a portable editable ZIP. No binary bytes are placed in tool text.',- inputSchema: exportInput,+ 'Export one saved revision. Default editable returns exact GLB, source, preview, and manifest descriptors; configured hosts may include portable editable ZIP download URLs. Opt-in runtime returns a standalone GLB plus a versioned metadata sidecar, moving only Kiln review clips out of GLB extras while preserving native animation and application metadata. Resource URIs remain readable through resources/read. Canonical revisions never change; no binary bytes are placed in tool text.',+ inputSchema: profileExportInput,run: async (raw) => {- const input = exportInput.parse(raw);+ const input = profileExportInput.parse(raw);+ if (input.profile === 'runtime') {+ const record = await library().read(input.collection, input.assetId, input.revisionId);+ return {+ ok: true,+ profile: input.profile,+ collection: input.collection,+ asset: {+ assetId: input.assetId,+ revisionId: input.revisionId,+ name: record.manifest.name,+ },+ resources: await (await import('../assets-resources')).runtimeAssetLinks(+ input.collection,+ record,+ ),+ };+ }return links(input.collection,(await library().read(input.collection, input.assetId, input.revisionId)).manifest,